@usine/server 0.4.1-next.264.gfdecd7e → 0.4.1-next.265.g59d6496
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 +2 -0
- package/dist/http.d.ts.map +1 -1
- package/dist/http.js +2 -0
- package/dist/http.js.map +1 -1
- package/dist/up.d.ts.map +1 -1
- package/dist/up.js +3 -1
- package/dist/up.js.map +1 -1
- package/dist/web/assets/_agent-_6-dDU4o.js +1 -0
- package/dist/web/assets/_label-B2hIQTiP.js +1 -0
- package/dist/web/assets/_loop-DvEDblaI.js +1 -0
- package/dist/web/assets/_name-CGGRdFfK.js +1 -0
- package/dist/web/assets/_name-DXMuBR5m.js +1 -0
- package/dist/web/assets/_name-Jq31XnPR.js +1 -0
- package/dist/web/assets/_name-z-THY2_h.js +2 -0
- package/dist/web/assets/{_number-CpU9ru_u.js → _number-DPBp5g17.js} +1 -1
- package/dist/web/assets/_number-DdeVk37S.js +1 -0
- package/dist/web/assets/_number-Jq31XnPR.js +1 -0
- package/dist/web/assets/_run-CdbRrREt.js +5 -0
- package/dist/web/assets/_run-Jq31XnPR.js +1 -0
- package/dist/web/assets/_worker-Kb3E2cex.js +1 -0
- package/dist/web/assets/action-BbYQzHVY.js +1 -0
- package/dist/web/assets/agents-aKrqbR-m.js +1 -0
- package/dist/web/assets/agents-ySzr8fy8.js +1 -0
- package/dist/web/assets/code-block-CjNdHwJz.js +4 -0
- package/dist/web/assets/collapsible-iYmFtriP.js +1 -0
- package/dist/web/assets/drawer-jppXFu1P.js +1 -0
- package/dist/web/assets/dropdown-menu-CFZLqcex.js +1 -0
- package/dist/web/assets/edit-and-retry-DE8DjLVA.js +1 -0
- package/dist/web/assets/{error-alert-hABzwCSY.js → error-alert-BVIxPJFU.js} +1 -1
- package/dist/web/assets/{file-error-B5tv6DhJ.js → file-error-DhZlb2_Y.js} +1 -1
- package/dist/web/assets/heading-D62nMA3C.js +1 -0
- package/dist/web/assets/{history-PYEz5wbe.js → history-DkNNnV6Y.js} +1 -1
- package/dist/web/assets/identity-DlGZ_gKf.js +1 -0
- package/dist/web/assets/index-B3ZB08sw.css +2 -0
- package/dist/web/assets/index-BdDPka5v.js +10 -0
- package/dist/web/assets/{label-badge-JdNthOHh.js → label-badge-d6omX3Kx.js} +1 -1
- package/dist/web/assets/labels-B7V9VhjQ.js +1 -0
- package/dist/web/assets/list-CMj9dgxo.js +1 -0
- package/dist/web/assets/loops-w6ia_oEU.js +1 -0
- package/dist/web/assets/mark-B8EExm_5.js +1 -0
- package/dist/web/assets/model-0V8C6gKN.js +1 -0
- package/dist/web/assets/moves-B2I_hBZb.js +1 -0
- package/dist/web/assets/{not-found-D7GT8Sj7.js → not-found-hL2Tp5vW.js} +1 -1
- package/dist/web/assets/outcome-xmjRsDh1.js +5 -0
- package/dist/web/assets/{overview-C73v5kbv.js → overview-BixI1Gdc.js} +1 -1
- package/dist/web/assets/{page-C47YAWAl.js → page-BLxt7Xfg.js} +1 -1
- package/dist/web/assets/pull-request-marks-BIB-F5Bo.js +1 -0
- package/dist/web/assets/repositories-DhkeCOwR.js +1 -0
- package/dist/web/assets/route-D0B3Tsri.js +1 -0
- package/dist/web/assets/route-NFcp08tu.js +1 -0
- package/dist/web/assets/{routes-g6SHTgCO.js → routes-BHwcH9Lh.js} +17 -17
- package/dist/web/assets/routes-Jq31XnPR.js +1 -0
- package/dist/web/assets/run-again-DSDtftlB.js +1 -0
- package/dist/web/assets/{section-BZs0sQLB.js → section-BP8TxDno.js} +1 -1
- package/dist/web/assets/section-D4djNiAN.js +24 -0
- package/dist/web/assets/settings-0NNJ2XzL.js +1 -0
- package/dist/web/assets/{sortable.esm-Lp8AM6j2.js → sortable.esm-JyniDt4R.js} +1 -1
- package/dist/web/assets/strings-BeaABxX0.js +311 -0
- package/dist/web/assets/{strings-Bexnszes.js → strings-Bs2WdZYo.js} +1 -1
- package/dist/web/assets/tasks-Jq31XnPR.js +1 -0
- package/dist/web/assets/tasks-x2oa1Rt3.js +1 -0
- package/dist/web/assets/usage-C27cuo6g.js +1 -0
- package/dist/web/assets/useAnchoredPopupScrollLock-DEVFEHhP.js +1 -0
- package/dist/web/assets/usePositioner-BeAdUrxb.js +1 -0
- package/dist/web/assets/useScrollLock-77tiYKUD.js +1 -0
- package/dist/web/assets/workers-jjiTPmGP.js +1 -0
- package/dist/web/index.html +10 -19
- package/package.json +9 -9
- package/dist/web/assets/Match-BsHjCE-9.js +0 -1
- package/dist/web/assets/_agent-CK1JZbEZ.js +0 -1
- package/dist/web/assets/_label-CkDrdgxa.js +0 -1
- package/dist/web/assets/_loop-DLKJmqFq.js +0 -1
- package/dist/web/assets/_name--06G9LKw.js +0 -1
- package/dist/web/assets/_name-BzeOsU08.js +0 -1
- package/dist/web/assets/_name-CCrJHJTI.js +0 -1
- package/dist/web/assets/_name-LWtfT5Eq.js +0 -2
- package/dist/web/assets/_number-BzeOsU08.js +0 -1
- package/dist/web/assets/_number-n4iejSEq.js +0 -1
- package/dist/web/assets/_run-BzeOsU08.js +0 -1
- package/dist/web/assets/_run-CHrGLkXR.js +0 -5
- package/dist/web/assets/_worker-BvlkSKMd.js +0 -1
- package/dist/web/assets/action-DQzkdVHs.js +0 -1
- package/dist/web/assets/actions-CG0hkpe7.js +0 -1
- package/dist/web/assets/agents-CgWsAMoz.js +0 -1
- package/dist/web/assets/agents-D3eAK_60.js +0 -1
- package/dist/web/assets/code-block-Y9Y-8fHK.js +0 -4
- package/dist/web/assets/collapsible-BKcakxvM.js +0 -1
- package/dist/web/assets/drawer-ClcvABkO.js +0 -1
- package/dist/web/assets/dropdown-menu-BHKHYfLs.js +0 -1
- package/dist/web/assets/edit-and-retry-DZ5FH7N6.js +0 -1
- package/dist/web/assets/heading-zIOXe3qT.js +0 -1
- package/dist/web/assets/index-C_S4sA5L.css +0 -2
- package/dist/web/assets/index-Dki55xSv.js +0 -10
- package/dist/web/assets/labels-Dr9t-xYj.js +0 -1
- package/dist/web/assets/lazyRouteComponent-BnRF0Crs.js +0 -1
- package/dist/web/assets/list-NcxSR9Ja.js +0 -1
- package/dist/web/assets/loops-DI4kElkX.js +0 -1
- package/dist/web/assets/mark-uyeJ8aPC.js +0 -1
- package/dist/web/assets/model-87X7P9Uh.js +0 -1
- package/dist/web/assets/moves-DS1ecXd6.js +0 -1
- package/dist/web/assets/outcome-DvqnSso3.js +0 -5
- package/dist/web/assets/preload-helper-BLdHbfdN.js +0 -1
- package/dist/web/assets/pull-request-marks-B4f7z4xa.js +0 -1
- package/dist/web/assets/queries-BZMW2wiD.js +0 -1
- package/dist/web/assets/queries-oea_Y4on.js +0 -1
- package/dist/web/assets/repositories-CZBhubWh.js +0 -1
- package/dist/web/assets/route-BtU2HI1M.js +0 -1
- package/dist/web/assets/route-CD6OvH-7.js +0 -1
- package/dist/web/assets/route-status-DGpeFNCC.js +0 -1
- package/dist/web/assets/routes-BzeOsU08.js +0 -1
- package/dist/web/assets/run-again-DPa5c27z.js +0 -1
- package/dist/web/assets/section-eyIYzZrG.js +0 -24
- package/dist/web/assets/settings-DusVdmgP.js +0 -1
- package/dist/web/assets/skeleton-87E84B2f.js +0 -1
- package/dist/web/assets/strings-DXB6PB2g.js +0 -311
- package/dist/web/assets/tasks-BzeOsU08.js +0 -1
- package/dist/web/assets/tasks-ClShPUFW.js +0 -1
- package/dist/web/assets/usage-BMYuEDo9.js +0 -1
- package/dist/web/assets/use-open-run-B8nD_BT1.js +0 -1
- package/dist/web/assets/useAnchoredPopupScrollLock-NN99o6YU.js +0 -1
- package/dist/web/assets/useSelector-CRBsgquS.js +0 -1
- package/dist/web/assets/useSuspenseQuery-DbhQN-t-.js +0 -1
- package/dist/web/assets/visuallyHidden-BUGCJ1D9.js +0 -1
- package/dist/web/assets/workers-CDWbu1Tb.js +0 -1
|
@@ -1,311 +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,v=()=>{_++};function ee(e){return typeof e==`string`}function te(e){return typeof e==`number`}function ne(e){return typeof e==`boolean`}function re(e){return typeof e==`bigint`}function ie(e){return typeof e==`symbol`}function ae(e){return ee(e)||te(e)||ie(e)}function oe(e){return typeof e==`function`}function se(e){return e!==void 0}function ce(e){return e!=null}function le(e){return!1}function ue(e){return!0}function de(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function fe(e){return typeof e==`object`&&!!e||oe(e)}var pe=r(2,(e,t)=>fe(e)&&t in e),me=r(2,(e,t)=>pe(e,`_tag`)&&e._tag===t);function he(e){return e instanceof Error}function ge(e){return pe(e,Symbol.iterator)||ee(e)}var _e=`~effect/Hash`,ve=e=>{switch(typeof e){case`number`:return we(e);case`bigint`:return Te(e.toString(10));case`string`:return Te(e);case`function`:case`object`:if(e===null)break;if(e instanceof Date)return Number.isNaN(e.getTime())?Te(`Invalid Date`):Te(e.toISOString());if(e instanceof RegExp)return Te(e.toString());{if(h.has(e))return ye(e);let t=Pe.get(e);if(t!==void 0)return t;if(Fe.has(e))return v(),Te(`[Circular]`);Fe.add(e);let n=_,r;try{r=`~effect/Hash`in e?e[_e]():typeof e==`function`?ye(e):e instanceof DataView?ke(g(e)):Array.isArray(e)||ArrayBuffer.isView(e)?ke(e):e instanceof Map?Ae(e):e instanceof Set?Me(e):De(e)}finally{Fe.delete(e)}return n===_&&Pe.set(e,r),r}}return Se(be(Te(String(e))))},ye=e=>(Ne.has(e)||Ne.set(e,Se(Math.random()*4294967296|0)),Ne.get(e)),be=e=>(e^=e>>>16,e=Math.imul(e,2246822507),e^=e>>>13,e=Math.imul(e,3266489909),e^e>>>16),xe=r(2,(e,t)=>be(Math.imul(e,2654435761)+Math.imul(t,2246822507))),Se=e=>e&3221225471|e>>>1&1073741824,Ce=new DataView(new ArrayBuffer(8)),we=e=>{let t=e|0;return t===e?Se(t):(Ce.setFloat64(0,e===e?e:NaN),Se(xe(Ce.getInt32(0),Ce.getInt32(4))))},Te=e=>{let t=5381,n=e.length;for(;n;)t=t*33^e.charCodeAt(--n);return Se(t)},Ee=(e,t)=>{let n=12289;for(let r of t)n^=xe(ve(r),ve(e[r]));return Se(n)},De=e=>Ee(e,m(e)),Oe=(e,t)=>n=>{let r=e;for(let e of n)r^=t(e);return Se(r)},ke=e=>{let t=6151;for(let n of e)t=xe(t,ve(n));return Se(t)},Ae=Oe(Te(`Map`),([e,t])=>xe(ve(e),ve(t))),je=Te(`Set`),Me=Oe(je,e=>xe(je,ve(e))),Ne=new WeakMap,Pe=new WeakMap,Fe=new WeakSet,Ie=`~effect/Equal`;function Le(){return arguments.length===1?e=>Re(e,arguments[0]):Re(arguments[0],arguments[1])}function Re(e,t){if(e===t)return!0;if(e==null||t==null)return!1;let n=typeof e;return n===typeof t?n===`number`&&e!==e&&t!==t?!0:n!==`object`&&n!==`function`||h.has(e)||h.has(t)?!1:ze(e,t):!1}function ze(e,t){let n=Ve.length;for(let r=n;r-->0;)if(Ve[r]===e&&He[r]===t)return!0;if(n)return Be(e,t);let r=Ue.get(e);r||Ue.set(e,r=new WeakMap);let i=r.get(t);return i===void 0&&r.set(t,i=Be(e,t)),i}function Be(e,t){Ve.push(e),He.push(t);try{return We(e,t)}finally{Ve.pop(),He.pop()}}var Ve=[],He=[],Ue=new WeakMap;function We(e,t){if(ve(e)!==ve(t))return!1;if(e instanceof Date){if(!(t instanceof Date))return!1;let n=e.getTime(),r=t.getTime();return n===r||Number.isNaN(n)&&Number.isNaN(r)}if(e instanceof RegExp)return t instanceof RegExp&&e.toString()===t.toString();let n=Ze(e);if(n!==Ze(t)||typeof e==`function`&&!n)return!1;if(n)return e[Ie](t);if(Array.isArray(e))return!Array.isArray(t)||e.length!==t.length?!1:Ge(e,t);if(ArrayBuffer.isView(e)){let n=e instanceof DataView;return!ArrayBuffer.isView(t)||e.byteLength!==t.byteLength||n!==t instanceof DataView?!1:n?Ke(g(e),g(t)):Ke(e,t)}return e instanceof Map?!(t instanceof Map)||e.size!==t.size?!1:Je(e,t,Ye,Xe):e instanceof Set?!(t instanceof Set)||e.size!==t.size?!1:Je(e,t,ve,Re):qe(e,t)}function Ge(e,t){for(let n=0;n<e.length;n++)if(!Re(e[n],t[n]))return!1;return!0}function Ke(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function qe(e,t){let n=m(e),r=m(t);if(n.size!==r.size)return!1;for(let i of n)if(!r.has(i)||!Re(e[i],t[i]))return!1;return!0}function Je(e,t,n,r){let i=new Map,a=0;for(let e of t){let t=n(e),r=i.get(t);r?r.push(e):i.set(t,[e]),a++}outer:for(let t of e){let e=i.get(n(t));if(e){for(let n=0;n<e.length;n++)if(r(t,e[n])){e[n]=e[e.length-1],e.pop(),a--;continue outer}}return!1}return a===0}var Ye=e=>ve(e[0]),Xe=(e,t)=>Re(e[0],t[0])&&Re(e[1],t[1]),Ze=e=>pe(e,Ie),Qe=()=>Le,$e=Symbol.for(`~effect/Redactable`),et=e=>pe(e,$e);function tt(e){return et(e)?nt(e):e}function nt(e){return e[$e](globalThis[`~effect/Fiber/currentFiber`]?.context??at)}var rt=`~effect/Fiber/currentFiber`,it=new Map,at={"~effect/Context":{},base:it,depth:0,mapUnsafe:it,pipe(){return e(this,arguments)}};function ot(e,t){let n=t?.space??0,r=new WeakSet,i=n?typeof n==`number`?` `.repeat(n):n:``,a=e=>i.repeat(e),o=(e,t)=>{let n=e?.constructor;return n&&n!==Object.prototype.constructor&&n.name?`${n.name}(${t})`:t},s=e=>{try{return Reflect.ownKeys(e)}catch{return[`[ownKeys threw]`]}};function c(e,t=0){try{return l(e,t)}catch{return(typeof e==`object`&&e||typeof e==`function`)&&r.delete(e),`[inspection threw]`}}function l(e,n=0){if(typeof e==`string`)return JSON.stringify(e);if(typeof e==`number`||e==null||typeof e==`boolean`||typeof e==`symbol`)return String(e);if(typeof e==`bigint`)return String(e)+`n`;if(typeof e==`object`||typeof e==`function`){if(r.has(e))return st;r.add(e);let l;if($e in e)l=c(nt(e),n);else if(Array.isArray(e))l=!i||e.length<=1?`[${e.map(e=>c(e,n)).join(`,`)}]`:`[\n${a(n+1)}${e.map(e=>c(e,n+1)).join(`,
|
|
2
|
-
`+a(n+1))}\n${a(n)}]`;else if(e instanceof Date)l=ut(e);else if(!t?.ignoreToString&&pe(e,`toString`)&&typeof e.toString==`function`&&e.toString!==Object.prototype.toString&&e.toString!==Array.prototype.toString){let t=dt(e);l=e instanceof Error&&e.cause!==void 0?`${t} (cause: ${c(e.cause,n)})`:t}else if(Symbol.iterator in e)l=`${e.constructor.name}(${c(Array.from(e),n)})`;else{let t=s(e);if(!i||t.length<=1){let r=`{${t.map(t=>`${ct(t)}:${c(ft(e,t),n)}`).join(`,`)}}`;l=o(e,r)}else{let r=`{\n${t.map(t=>`${a(n+1)}${ct(t)}: ${c(ft(e,t),n+1)}`).join(`,
|
|
3
|
-
`)}\n${a(n)}}`;l=o(e,r)}}return r.delete(e),l}return String(e)}return c(e,0)}var st=`[Circular]`;function ct(e){return typeof e==`string`?JSON.stringify(e):String(e)}function lt(e){return e.map(e=>`[${ct(e)}]`).join(``)}function ut(e){try{return e.toISOString()}catch{return`Invalid Date`}}function dt(e){try{let t=e.toString();return typeof t==`string`?t:String(t)}catch{return`[toString threw]`}}function ft(e,t){try{return e[t]}catch{return`[property access threw]`}}function pt(e,t){let n=[];return JSON.stringify(e,function(e,t){let r=Object.getOwnPropertyDescriptor(this,e)?.value,i=pe(r,$e)?tt(r):tt(t);if(typeof i==`bigint`)return ot(i);if(typeof i!=`object`||!i)return i;let a=i instanceof Error&&!pe(i,`toJSON`)?{...i,name:i.name,message:i.message}:i;for(;n.length>0&&n[n.length-1]!==this;)n.pop();if(n.includes(i))return;if(n.push(i),a!==i&&n.push(a),!mt(a)||ht(a))return a;let o=new Proxy(a,{get(e,t){let n=Reflect.get(e,t,e);return Object.getOwnPropertyDescriptor(e,t)?.get===void 0?n:tt(n)}});return n.push(o),o},t?.space)??`null`}function mt(e){for(let t of Object.getOwnPropertyNames(e))if(Object.getOwnPropertyDescriptor(e,t)?.get!==void 0)return!0;return!1}function ht(e){for(let t of[Number.prototype.valueOf,Boolean.prototype.valueOf,String.prototype.valueOf])try{return Reflect.apply(t,e,[]),!0}catch{}return!1}var gt=Symbol.for(`nodejs.util.inspect.custom`),_t=e=>{try{return e=tt(e),pe(e,`toJSON`)&&oe(e.toJSON)&&e.toJSON.length===0?e.toJSON():Array.isArray(e)?e.map(_t):e}catch{return`[toJSON threw]`}},vt=(e,t=2)=>{if(typeof e==`string`)return e;try{return typeof e==`object`?pt(e,{space:t}):ot(e,{space:t})}catch{return String(e)}},yt={toJSON(){return _t(this)},[gt](){return this.toJSON()},toString(){return ot(this.toJSON())}},bt=class{[gt](){return this.toJSON()}toString(){return ot(this.toJSON())}},xt=(()=>{let e=Object.getOwnPropertyDescriptor(Error,`stackTraceLimit`);return e===void 0?Object.isExtensible(Error):Object.hasOwn(e,`writable`)?e.writable===!0:e.set!==void 0})(),St=()=>Error.stackTraceLimit,Ct=e=>{xt&&(Error.stackTraceLimit=e)},wt=class{constructor(e){this.value=e,this.done=!1}next(e){return this.done?(this.value=e,this):(this.done=!0,{value:this.value,done:!1})}},Tt=(()=>{let e=`~effect/Utils/internal`,t={[e]:e=>e()},n={[e]:e=>{try{return e()}finally{}}},r=St();if(r===0)return n[e];Ct(2);let i=t[e](()=>Error());return Ct(r),i.stack?.includes(e)===!0?t[e]:n[e]})();function Et(e,t,n){t===`__proto__`?Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0}):e[t]=n}function Dt(e,t){if(!Object.hasOwn(t,`__proto__`))Object.assign(e,t);else for(let n of Reflect.ownKeys(t))Object.prototype.propertyIsEnumerable.call(t,n)&&Et(e,n,t[n])}var Ot=`~effect/Effect`,kt=`~effect/Exit`,At={_A:i,_E:i,_R:i},jt=`${Ot}/identifier`,Mt=`${Ot}/args`,Nt=`${Ot}/evaluate`,Pt=`${Ot}/successCont`,Ft=`${Ot}/failureCont`,It=`${Ot}/ensureCont`,Lt=Symbol.for(`effect/Effect/Yield`),Rt={pipe(){return e(this,arguments)},toJSON(){return{...this}},toString(){return ot(this.toJSON(),{ignoreToString:!0,space:2})},[gt](){return this.toJSON()}},zt={[Ot]:At,...Rt,[Symbol.iterator](){return new wt(this)},toJSON(){return{_id:`Effect`,op:this[jt],...`~effect/Effect/args`in this?{args:this[Mt]}:void 0}}},Bt=e=>pe(e,Ot),Vt=e=>pe(e,kt),Ht=`~effect/Cause`,Ut=`~effect/Cause/Reason`,Wt=e=>pe(e,Ht),Gt=e=>pe(e,Ut),Kt=class{constructor(e){this[Ht]=Ht,this.reasons=e}pipe(){return e(this,arguments)}toJSON(){return{_id:`Cause`,reasons:this.reasons.map(e=>e.toJSON())}}toString(){return`Cause(${ot(this.reasons)})`}[gt](){return this.toJSON()}[Ie](e){return Wt(e)&&this.reasons.length===e.reasons.length&&this.reasons.every((t,n)=>Le(t,e.reasons[n]))}[_e](){return ke(this.reasons)}},qt=new WeakMap,Jt=class{[Ut];annotations;_tag;constructor(e,t,n){if(this[Ut]=Ut,this._tag=e,t!==Yt&&typeof n==`object`&&n&&t.size>0){let e=qt.get(n);e&&(t=new Map([...e,...t])),qt.set(n,t)}this.annotations=t}annotate(e,t){if(e.mapUnsafe.size===0)return this;let n=new Map(this.annotations);e.mapUnsafe.forEach((e,r)=>{t?.overwrite!==!0&&n.has(r)||n.set(r,e)});let r=Object.assign(Object.create(Object.getPrototypeOf(this)),this);return r.annotations=n,r}pipe(){return e(this,arguments)}toString(){return ot(this)}[gt](){return this.toString()}},Yt=new Map,Xt=class extends Jt{constructor(e,t=Yt){super(`Fail`,t,e),this.error=e}toString(){return`Fail(${ot(this.error)})`}toJSON(){return{_tag:`Fail`,error:this.error}}[Ie](e){return sn(e)&&Le(this.error,e.error)&&Le(this.annotations,e.annotations)}[_e](){return xe(Te(this._tag))(xe(ve(this.error))(ve(this.annotations)))}},Zt=e=>new Kt(e),Qt=(e,t)=>{let n=new Map,r=[];for(let i of e.concat(t)){let e=ve(i),t=n.get(e);if(t===void 0)n.set(e,[i]);else if(t.some(e=>Le(e,i)))continue;else t.push(i);r.push(i)}return r},$t=r(2,(e,t)=>{if(e.reasons.length===0)return t;if(t.reasons.length===0)return e;let n=new Kt(Qt(e.reasons,t.reasons));return Le(e,n)?e:n}),en=(e,t)=>{let n=e.reasons.slice();for(let e of t.reasons)ln(e)&&!n.some(t=>ln(t)&&t.fiberId===e.fiberId&&t.annotations===e.annotations)&&n.push(e);return n.length===e.reasons.length?e:new Kt(n)},tn=new Kt([]),nn=e=>new Kt([new Xt(e)]),rn=class extends Jt{constructor(e,t=Yt){super(`Die`,t,e),this.defect=e}toString(){return`Die(${ot(this.defect)})`}toJSON(){return{_tag:`Die`,defect:this.defect}}[Ie](e){return cn(e)&&Le(this.defect,e.defect)&&Le(this.annotations,e.annotations)}[_e](){return xe(Te(this._tag))(xe(ve(this.defect))(ve(this.annotations)))}},an=e=>new Kt([new rn(e)]),on=r(e=>Wt(e[0]),(e,t,n)=>t.mapUnsafe.size===0?e:new Kt(e.reasons.map(e=>e.annotate(t,n)))),sn=e=>e._tag===`Fail`,cn=e=>e._tag===`Die`,ln=e=>e._tag===`Interrupt`;function un(e){return yn(`Effect.evaluate: Not implemented`)}var dn=e=>({...zt,[jt]:e.op,[Nt]:e[`~effect/Effect/evaluate`]??un,[Pt]:e[Pt],[Ft]:e[Ft],[It]:e[It]}),fn=e=>{let t=dn(e),n=function(e){this[Mt]=e};return n.prototype=t,function(e){return new n(e)}},pn=e=>{let t={[kt]:kt,_tag:e.op,get[e.prop](){return this[Mt]},...dn(e),toString(){return`${e.op}(${ot(this[Mt])})`},toJSON(){return{_id:`Exit`,_tag:e.op,[e.prop]:this[Mt]}},[Ie](e){return Vt(e)&&e._tag===this._tag&&Le(this[`~effect/Effect/args`],e[`~effect/Effect/args`])},[_e](){return xe(Te(e.op),ve(this[Mt]))}},n=function(e){this[Mt]=e};return n.prototype=t,function(e){return new n(e)}},mn=pn({op:`Success`,prop:`value`,[Nt](e){let t=e.getCont(Pt);return t?t[Pt](this[Mt],e,this):e.yieldWith(this)}}),hn={key:`effect/Cause/StackTrace`},gn={key:`effect/Cause/InterruptorStackTrace`},_n=pn({op:`Failure`,prop:`cause`,[Nt](e){let t=this[Mt],n=!1;e.cache.stackFrame&&(t=on(t,{mapUnsafe:new Map([[hn.key,e.cache.stackFrame]])}),n=!0);let r=e.getCont(Ft),i=e._interruptedCause;if(i&&e.interruptible){let a=!1;for(;r&&e.interruptible;)a||=jt in r,r=e.getCont(Ft);a&&(t=Zt(t.reasons.filter(e=>e._tag!==`Fail`))),t=en(t,i),n=!0}return r?r[Ft](t,e,n?void 0:this):e.yieldWith(n?_n(t):this)}}),vn=e=>_n(nn(e)),yn=e=>_n(an(e)),bn=fn({op:`WithFiber`,[Nt](e){return this[Mt](e)}}),xn=function(){class e extends globalThis.Error{}let t=dn({op:`YieldableError`,[Nt](){return vn(this)}});return delete t.toString,Object.assign(e.prototype,t),e}(),Sn=function(){let e=Symbol.for(`effect/Data/Error/plainArgs`);return class extends xn{constructor(t){super(t?.message,t?.cause?{cause:t.cause}:void 0),t&&(Dt(this,t),Object.defineProperty(this,e,{value:t,enumerable:!1}))}toJSON(){return{...this[e],...this}}}}(),Cn=e=>{class t extends Sn{_tag=e}return t.prototype.name=e,t},wn=`~effect/Cause/NoSuchElementError`,Tn=class extends Cn(`NoSuchElementError`){[wn]=wn;constructor(e){super({message:e})}},En=`~effect/Cause/Done`,Dn=e=>pe(e,En),On={[En]:En,_tag:`Done`,value:void 0},kn=e=>e===void 0?On:{[En]:En,_tag:`Done`,value:e},An=vn(On),jn=e=>e===void 0?An:vn(kn(e)),Mn=e=>dn({op:e.label,[Nt]:e.evaluate}),Nn=e=>(t,n)=>t===n||e(t,n),Pn=(e,t)=>e===t,Fn=()=>Pn;function In(e){return Nn((t,n)=>{if(t.length!==n.length)return!1;for(let r=0;r<t.length;r++)if(!e[r](t[r],n[r]))return!1;return!0})}function Ln(e){return Nn((t,n)=>{if(t.length!==n.length)return!1;for(let r=0;r<t.length;r++)if(!e(t[r],n[r]))return!1;return!0})}var Rn=`~effect/Option`,zn={[Rn]:{_A:e=>e},...Rt,[Symbol.iterator](){return new wt(this)}},Bn=Object.defineProperty(Object.assign(Object.create(zn),{_tag:`Some`,_op:`Some`,[Ie](e){return Un(e)&&Gn(e)&&Le(this.value,e.value)},[_e](){return xe(ve(this._tag))(ve(this.value))},toString(){return`some(${ot(this.value)})`},toJSON(){return{_id:`Option`,_tag:this._tag,value:_t(this.value)}}}),"valueOrUndefined",{get(){return this.value}}),Vn=ve(`None`),Hn=Object.assign(Object.create(zn),{_tag:`None`,_op:`None`,valueOrUndefined:void 0,[Ie](e){return Un(e)&&Wn(e)},[_e](){return Vn},toString(){return`none()`},toJSON(){return{_id:`Option`,_tag:this._tag}}}),Un=e=>pe(e,Rn),Wn=e=>e._tag===`None`,Gn=e=>e._tag===`Some`,Kn=Object.create(Hn),qn=function(e){this.value=e};qn.prototype=Bn;var Jn=e=>new qn(e),Yn=`~effect/Result`,Xn={[Yn]:{_A:e=>e,_E:e=>e},...Rt,[Symbol.iterator](){return new wt(this)}},Zn=Object.assign(Object.create(Xn),{_tag:`Success`,_op:`Success`,[Ie](e){return $n(e)&&tr(e)&&Le(this.success,e.success)},[_e](){return xe(ve(this._tag))(ve(this.success))},toString(){return`success(${ot(this.success)})`},toJSON(){return{_id:`Result`,_tag:this._tag,value:_t(this.success)}}}),Qn=Object.assign(Object.create(Xn),{_tag:`Failure`,_op:`Failure`,[Ie](e){return $n(e)&&er(e)&&Le(this.failure,e.failure)},[_e](){return xe(ve(this._tag))(ve(this.failure))},toString(){return`failure(${ot(this.failure)})`},toJSON(){return{_id:`Result`,_tag:this._tag,failure:_t(this.failure)}}}),$n=e=>pe(e,Yn),er=e=>e._tag===`Failure`,tr=e=>e._tag===`Success`,nr=function(e){this.failure=e};nr.prototype=Qn;var rr=e=>new nr(e),ir=function(e){this.success=e};ir.prototype=Zn;var ar=e=>new ir(e),or=r(2,(e,t)=>Wn(e)?rr(t()):ar(e.value));function sr(e){return(t,n)=>t===n?0:e(t,n)}var cr=sr((e,t)=>e<t?-1:1),lr=sr((e,t)=>globalThis.Number.isNaN(e)&&globalThis.Number.isNaN(t)?0:globalThis.Number.isNaN(e)?-1:globalThis.Number.isNaN(t)?1:e<t?-1:1);function ur(e){return sr((t,n)=>e(n,t))}function dr(e){let t=Array.from(e);return sr((e,n)=>{let r=0;for(let i of t)if(r=i(e,n),r!==0)return r;return r})}var fr=r(2,(e,t)=>sr((n,r)=>e(t(n),t(r)))),pr=e=>r(2,(t,n)=>e(t,n)===-1),mr=e=>r(2,(t,n)=>e(t,n)===1),hr=e=>r(2,(t,n)=>e(t,n)!==1),gr=e=>r(2,(t,n)=>e(t,n)!==-1),y=()=>Kn,b=Jn,_r=Un,x=Wn,S=Gn,vr=r(2,(e,{onNone:t,onSome:n})=>x(e)?t():n(e.value)),yr=r(2,(e,t)=>x(e)?t():e.value),br=r(2,(e,t)=>x(e)?t():e),xr=e=>{let t=y();for(t of e)if(S(t))return t;return t},Sr=e=>e==null?y():b(e),Cr=e=>e===void 0?y():b(e),wr=e=>e===null?y():b(e),C=yr(c),Tr=yr(l),Er=e=>(...t)=>{try{return b(e(...t))}catch{return y()}},Dr=r(2,(e,t)=>{if(S(e))return e.value;throw t()}),Or=r(2,(e,t)=>x(e)?y():b(t(e.value))),kr=r(2,(e,t)=>x(e)?y():t(e.value)),Ar=kr(i),jr=e=>{if(Symbol.iterator in e){let t=[];for(let n of e){if(x(n))return y();t.push(n.value)}return b(t)}let t={};for(let n of Object.keys(e)){let r=e[n];if(x(r))return y();Et(t,n,r.value)}return b(t)},Mr=e=>x(e)?[]:[e.value],Nr=r(2,(e,t)=>x(e)?y():t(e.value)?b(e.value):y()),Pr=r(2,(e,t)=>t(e)?b(e):y()),Fr=(e=>r(2,(t,n)=>!x(t)&&e(t.value,n)))(Qe()),Ir=r(2,(e,t)=>!x(e)&&t(e.value)),Lr=`~effect/Context/Service`,Rr=function(){function e(){}let t=e;Object.setPrototypeOf(t,zr);let n=(e,n)=>(t.key=e,n?.defaultValue&&(t[Vr]=Vr,t.defaultValue=n.defaultValue),n?.make&&(t.make=n.make),n?.fiberCached&&Br.add(e),t);return arguments.length>0?n(arguments[0],arguments[1]):n},zr={[Lr]:Lr,...Mn({label:`Service`,evaluate(e){return mn(ui(e.context,this))}}),toJSON(){return{_id:`Service`,key:this.key}},of(e){return e},context(e){return ii(this,e)},use(e){return bn(t=>e(ui(t.context,this)))},useSync(e){return bn(t=>mn(e(ui(t.context,this))))}},Br=new Set,Vr=`~effect/Context/Reference`,Hr=`~effect/Context`,Ur=8,Wr=8,Gr=(e,t,n,r)=>{let i=Object.create(Qr);return i.cacheRoot=e??i,i.base=t,i.overlay=n,i.depth=r,i._flat=void 0,i.baseHits=0,i},Kr=(e,t)=>{t&&(Kr(e,t.parent),e.set(t.key,t.value))},qr=e=>{if(e._flat)return e._flat;if(!e.overlay)return e._flat=e.base;let t=new Map(e.base);return Kr(t,e.overlay),e._flat=t},Jr=(e,t)=>{let n=new Map(e.mapUnsafe);return t(n),Zr(n)},Yr=Symbol(),Xr=(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)?Yr:(n.overlay&&++n.baseHits>=n.base.size&&n.baseHits>=Wr&&(n.base=qr(n),n.overlay=void 0,n.depth=0),r)},Zr=e=>Gr(void 0,e,void 0,0),Qr={get mapUnsafe(){return qr(this)},...Rt,[Hr]:{_Services:e=>e},toJSON(){return{_id:`Context`,services:Array.from(this.mapUnsafe).map(([e,t])=>({key:e,value:t}))}},[Ie](e){if(!ei(e))return!1;let t=this.mapUnsafe,n=e.mapUnsafe;if(t.size!==n.size)return!1;for(let[e,r]of t)if(!n.has(e)||!Le(r,n.get(e)))return!1;return!0},[_e](){return we(this.mapUnsafe.size)}},$r=(e,t)=>e.cacheRoot===t.cacheRoot,ei=e=>pe(e,Hr),ti=e=>!!e[Vr],ni=()=>ri,ri=Zr(new Map),ii=(e,t)=>Zr(new Map([[e.key,t]])),ai=r(3,(e,t,n)=>oi(e,t.key,n)),oi=(e,t,n)=>{let r=e,i=Br.has(t)?void 0:r.cacheRoot;if(r.depth>=Ur){let e=new Map(r._flat??r.base);return r._flat||Kr(e,r.overlay),e.set(t,n),Gr(i,e,void 0,0)}return Gr(i,r.base,{key:t,value:n,parent:r.overlay},r.depth+1)},si=r(2,(e,t)=>ci(e,t.key)),ci=(e,t)=>{let n=Xr(e,t);return n===Yr?void 0:n},li=r(2,(e,t)=>{let n=Xr(e,t.key);if(n===Yr){if(ti(t))return fi(t);throw pi(t)}return n}),ui=li,di=`~effect/Context/defaultValue`,fi=e=>di in e?e[di]:e[di]=e.defaultValue(),pi=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},mi=r(2,(e,t)=>{let n=Xr(e,t.key);return n===Yr?ti(t)?b(fi(t)):y():b(n)}),hi=r(2,(e,t)=>e.mapUnsafe.size===0?t:t.mapUnsafe.size===0?e:Jr(e,e=>t.mapUnsafe.forEach((t,n)=>e.set(n,t)))),gi=(...e)=>{let t=new Map;for(let n=0;n<e.length;n++)e[n].mapUnsafe.forEach((e,n)=>{t.set(n,e)});return Zr(t)},_i=(...e)=>t=>{if(e.length<=1){let n=new Map;if(e.length===1){let r=e[0].key,i=Xr(t,r);i!==Yr&&n.set(r,i)}return Zr(n)}let n=new Set(e.map(e=>e.key));return Jr(t,e=>e.forEach((t,r)=>{n.has(r)||e.delete(r)}))},vi=Rr,yi=e=>e.length>0,bi=e=>e>0?Math.floor(e):0,xi=e=>Math.max(1,bi(e)),Si=ar,Ci=rr,wi=or,Ti=e=>{if(oe(e))try{return Si(e())}catch(e){return Ci(e)}try{return Si(e.try())}catch(t){return Ci(e.catch(t))}},Ei=$n,Di=er,Oi=tr,ki=r(2,(e,t)=>Oi(e)?Si(t(e.success)):e),Ai=r(2,(e,{onFailure:t,onSuccess:n})=>Di(e)?t(e.failure):n(e.success)),ji=r(2,(e,t)=>{if(Oi(e))return e.success;throw t(e.failure)})(i),Mi=e=>{if(Symbol.iterator in e){let t=[];for(let n of e){if(Di(n))return n;t.push(n.success)}return Si(t)}let t={};for(let n of Object.keys(e)){let r=e[n];if(Di(r))return r;Et(t,n,r.success)}return Si(t)},Ni=(...e)=>e,Pi=In,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=yi,Xi=yi;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)?y():b(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 b(r)}else if(S(i))return i}return y()}),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(;yi(a);){let[e,n]=t(a);i.push(e),a=n}return i}return[]}),ca=r(2,(e,t)=>{let n=xi(t);return n>=e.length?[la(e),[]]:[Ki(e.slice(1,n),ta(e)),e.slice(n)]}),la=e=>e.slice(),ua=r(2,(e,t)=>{let n=Wi(e);return Xi(n)?sa(n,ca(t)):[]}),da=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}),fa=(e,t)=>{let n=ve(t),r=e.get(n);if(r===void 0)return e.set(n,[t]),!0;for(let e of r)if(Le(e,t))return!1;return r.push(t),!0},pa=()=>[],ma=e=>[e],ha=r(2,(e,t)=>e.map(t)),ga=e=>{let t=[];for(let n of e)S(n)&&t.push(n.value);return t},_a=Ln,va=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}),ya=e=>{let t=Wi(e);if(t.length<2)return[...t];let n=new Map,r=[];for(let e of t)fa(n,e)&&r.push(e);return r},ba=`~effect/Duration`,xa=BigInt(0),Sa=BigInt(1),Ca=BigInt(2),wa=BigInt(10),Ta=BigInt(1e3),Ea=BigInt(1e6),Da=BigInt(1e9),Oa=BigInt(6e10),ka=BigInt(36e11),Aa=BigInt(864e11),ja=BigInt(6048e11),Ma=e=>BigInt(Math.sign(e)*Math.round(Math.abs(e))),Na=e=>Number.isInteger(e)?BigInt(e)*Ea:Ma(e*1e6),Pa=e=>Ja(Number.isFinite(e)?Ma(e):e),Fa=(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},Ia=(e,t)=>{let n=e.indexOf(`.`);if(n===-1)return BigInt(e)*t;let r=e[0]===`-`,i=e.slice(n+1),a=wa**BigInt(i.length),o=(BigInt(e.slice(+!!r,n))*a+BigInt(i))*t;return La(r?-o:o,a)},La=(e,t)=>{let n=e<xa?-e:e,r=n/t+(n%t*Ca>=t?Sa:xa);return e<xa?-r:r},Ra=(e,t)=>{let n=Number(e)*t;if(!Number.isFinite(n))return Ja(n);let r=Ia(e,BigInt(t)*Ea);return Ja(Number.isInteger(n)&&BigInt(n)*Ea===r?n:r)},za=/^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/,Ba=e=>{switch(typeof e){case`number`:return eo(e);case`bigint`:return $a(e);case`string`:{if(e===`Infinity`)return Za;if(e===`-Infinity`)return Qa;let t=za.exec(e);if(!t)break;let[n,r,i]=t;if(i===`nano`||i===`nanos`)return $a(Ia(r,Sa));if(i===`micro`||i===`micros`)return $a(Ia(r,Ta));switch(i){case`milli`:case`millis`:return Ra(r,1);case`second`:case`seconds`:return Ra(r,1e3);case`minute`:case`minutes`:return Ra(r,6e4);case`hour`:case`hours`:return Ra(r,36e5);case`day`:case`days`:return Ra(r,864e5);case`week`:case`weeks`:return Ra(r,6048e5)}break}case`object`:{if(e===null)break;if(ba in e)return e;if(Array.isArray(e)){if(e.length!==2||!e.every(te))return Ua(e);if(Number.isNaN(e[0])||Number.isNaN(e[1]))return Xa;if(e[0]===-1/0||e[1]===-1/0)return Qa;if(e[0]===1/0||e[1]===1/0)return Za;let t=e[0]*1e9+e[1];return Number.isFinite(t)&&Number.isInteger(e[0])&&Number.isInteger(e[1])?Ja(BigInt(e[0])*Da+BigInt(e[1])):Pa(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 Ja(n);let e=Ha(t);return e===void 0||BigInt(n)*Ea===e?Ja(n):Ja(e)}let r=n*1e6+(t.microseconds??0)*1e3+(t.nanoseconds??0),i=Number.isFinite(r)?Ha(t):void 0;return i===void 0?Pa(r):Ja(i)}}return Ua(e)},Va=e=>!e||Number.isInteger(e),Ha=e=>{if(!Va(e.weeks)||!Va(e.days)||!Va(e.hours)||!Va(e.minutes)||!Va(e.seconds)||!Va(e.milliseconds)||!Va(e.microseconds)||!Va(e.nanoseconds))return;let t=xa;return e.weeks&&(t+=BigInt(e.weeks)*ja),e.days&&(t+=BigInt(e.days)*Aa),e.hours&&(t+=BigInt(e.hours)*ka),e.minutes&&(t+=BigInt(e.minutes)*Oa),e.seconds&&(t+=BigInt(e.seconds)*Da),e.milliseconds&&(t+=BigInt(e.milliseconds)*Ea),e.microseconds&&(t+=BigInt(e.microseconds)*Ta),e.nanoseconds&&(t+=BigInt(e.nanoseconds)),t},Ua=e=>{throw Error(`Invalid Input: ${e}`)},Wa={_tag:`Millis`,millis:0},Ga={_tag:`Infinity`},Ka={_tag:`NegativeInfinity`},qa={[ba]:ba,[_e](){switch(this.value._tag){case`Millis`:return ve(Na(this.value.millis));case`Nanos`:return ve(this.value.nanos);default:return De(this.value)}},[Ie](e){return Ya(e)&&co(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)}},Ja=e=>{let t=Object.create(qa);return t.value=typeof e==`number`?isNaN(e)||e===0||Object.is(e,-0)?Wa:Number.isFinite(e)?Number.isInteger(e)?{_tag:`Millis`,millis:e}:{_tag:`Nanos`,nanos:Na(e)}:e>0?Ga:Ka:e===xa?Wa:{_tag:`Nanos`,nanos:e},t},Ya=e=>pe(e,ba),Xa=Ja(0),Za=Ja(1/0),Qa=Ja(-1/0),$a=e=>Ja(e),eo=e=>Ja(e),to=e=>Ja(e*1e3),no=e=>Ja(e*6e4),ro=e=>ao(Ba(e),{onMillis:i,onNanos:e=>Fa(e,1e6),onInfinity:()=>1/0,onNegativeInfinity:()=>-1/0}),io=e=>{let t=Ba(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 Na(t.value.millis)}},ao=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)()}}),oo=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(io(e),t.value.nanos):n.onNanos(e.value.nanos,io(t))),so=(e,t)=>oo(e,t,{onMillis:(e,t)=>e===t,onNanos:(e,t)=>e===t,onInfinity:(e,t)=>e.value._tag===t.value._tag}),co=r(2,(e,t)=>so(e,t)),lo=e=>t=>!Di(e(t)),uo=e=>t=>t.has(e)?Si(t):Ci(t),fo=r(2,(e,t)=>n=>{let r=e(n);return Di(r)?r:t(r.success)}),po=vi(`effect/Scheduler`,{fiberCached:!0,defaultValue:()=>new vo}),mo=e=>{let t=!1;return Promise.resolve().then(()=>{t||e()}),()=>{t=!0}},ho=`setImmediate`in globalThis?e=>{let t=globalThis.setImmediate(e);return()=>globalThis.clearImmediate(t)}:e=>{let t=setTimeout(e,0);return()=>clearTimeout(t)},go=e=>{try{return ho(e)}catch{return mo(e)}},_o=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}},vo=class{executionMode;setImmediate;constructor(e=`async`,t){this.executionMode=e,this.setImmediate=t??(e===`sync`?mo:go)}shouldYield(e){return e.currentOpCount>=e.cache.maxOpsBeforeYield}makeDispatcher(){return new yo(this.setImmediate)}},yo=class{tasks=new _o;running=void 0;setImmediate;constructor(e=go){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()}},bo=vi(`effect/Scheduler/MaxOpsBeforeYield`,{fiberCached:!0,defaultValue:()=>2048}),xo=vi(`effect/Scheduler/PreventSchedulerYield`,{fiberCached:!0,defaultValue:()=>!1}),So=class extends n{constructor(e){super(),e&&Dt(this,e)}},Co=e=>class extends So{_tag=e},wo=Cn,To=`~effect/encoding/EncodingError`,Eo=class extends wo(`EncodingError`){[To]=To},Do=e=>Io(typeof e==`string`?Po.encode(e):e),Oo=e=>{switch(e){case 16:return Mo();case 32:return No();default:{let t=``;for(let n=e>>>3;n>0;n--)t+=jo();return t}}},ko=Uint8Array.from(`0123456789abcdef`,e=>e.charCodeAt(0)),Ao=()=>Math.random()*4294967296>>>0,jo=()=>{let e=Ao();return String.fromCharCode(ko[e>>>28],ko[e>>>24&15],ko[e>>>20&15],ko[e>>>16&15],ko[e>>>12&15],ko[e>>>8&15],ko[e>>>4&15],ko[e&15])},Mo=()=>{let e=Ao(),t=Ao();return String.fromCharCode(ko[e>>>28],ko[e>>>24&15],ko[e>>>20&15],ko[e>>>16&15],ko[e>>>12&15],ko[e>>>8&15],ko[e>>>4&15],ko[e&15],ko[t>>>28],ko[t>>>24&15],ko[t>>>20&15],ko[t>>>16&15],ko[t>>>12&15],ko[t>>>8&15],ko[t>>>4&15],ko[t&15])},No=()=>{let e=Ao(),t=Ao(),n=Ao(),r=Ao();return String.fromCharCode(ko[e>>>28],ko[e>>>24&15],ko[e>>>20&15],ko[e>>>16&15],ko[e>>>12&15],ko[e>>>8&15],ko[e>>>4&15],ko[e&15],ko[t>>>28],ko[t>>>24&15],ko[t>>>20&15],ko[t>>>16&15],ko[t>>>12&15],ko[t>>>8&15],ko[t>>>4&15],ko[t&15],ko[n>>>28],ko[n>>>24&15],ko[n>>>20&15],ko[n>>>16&15],ko[n>>>12&15],ko[n>>>8&15],ko[n>>>4&15],ko[n&15],ko[r>>>28],ko[r>>>24&15],ko[r>>>20&15],ko[r>>>16&15],ko[r>>>12&15],ko[r>>>8&15],ko[r>>>4&15],ko[r&15])},Po=new TextEncoder,Fo=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`)),Io=e=>{let t=``;for(let n=0;n<e.length;n++)t+=Fo[e[n]];return t},Lo=`effect/Tracer/ParentSpan`,Ro=class extends Rr()(Lo,{fiberCached:!0}){},zo=e=>e,Bo=vi(`effect/Tracer/DisablePropagation`,{defaultValue:s}),Vo=vi(`effect/Tracer/CurrentTraceLevel`,{defaultValue:()=>`Info`}),Ho=vi(`effect/Tracer/MinimumTraceLevel`,{defaultValue:()=>`All`}),Uo=`effect/Tracer`,Wo=zo({span:e=>new Go(e)}),Go=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??=Tr(this.parent)?.traceId??Oo(32)}get spanId(){return this._spanId??=Oo(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)}},Ko=`effect/Metric/FiberRuntimeMetrics`,qo=vi(`effect/References/CurrentStackFrame`,{fiberCached:!0,defaultValue:l}),Jo=vi(`effect/References/TracerEnabled`,{fiberCached:!0,defaultValue:o}),Yo=vi(`effect/References/TracerTimingEnabled`,{defaultValue:o}),Xo=vi(`effect/References/TracerSpanAnnotations`,{defaultValue:()=>({})}),Zo=vi(`effect/References/TracerSpanLinks`,{defaultValue:()=>[]}),Qo=vi(`effect/References/CurrentLogAnnotations`,{defaultValue:()=>({})}),$o=vi(`effect/References/CurrentLogLevel`,{fiberCached:!0,defaultValue:()=>`Info`}),es=vi(`effect/References/MinimumLogLevel`,{fiberCached:!0,defaultValue:()=>`Info`}),ts=vi(`effect/References/CurrentLogSpans`,{defaultValue:()=>[]}),ns=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:is(()=>n.stack)}},rs=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}},is=rs(3),as=class extends Jt{constructor(e,t=Yt){super(`Interrupt`,t,`Interrupted`),this.fiberId=e}toString(){return`Interrupt(${this.fiberId})`}toJSON(){return{_tag:`Interrupt`,fiberId:this.fiberId}}[Ie](e){return ln(e)&&this.fiberId===e.fiberId&&this.annotations===e.annotations}[_e](){return Te(`${this._tag}:${this.fiberId}`)}},os=e=>new as(e),ss=e=>new Kt([new as(e)]),cs=e=>e.reasons.some(sn),ls=e=>{for(let t=0;t<e.reasons.length;t++){let n=e.reasons[t];if(n._tag===`Fail`)return Si(n.error)}return Ci(e)},us=e=>e.reasons.some(cn),ds=e=>us(e)&&cs(e)?Zt(e.reasons.map(e=>e._tag===`Fail`&&!Dn(e.error)?new rn(e.error,e.annotations):e)):e,fs=e=>us(e)?Ci(ds(e)):ls(e),ps=e=>{let t=e.reasons.find(cn);return t?Si(t.defect):Ci(e)},ms=e=>e.reasons.some(ln),hs=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?Si(t):Ci(e)},gs=e=>e.reasons.length>0&&e.reasons.every(ln),_s=r(2,(e,t)=>{let n=!1,r=e.reasons.map(e=>sn(e)?(n=!0,new Xt(t(e.error),e.annotations)):e);return n?Zt(r):e}),vs=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},ys=(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(bs(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=Ts(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(bs(i,r[0].annotations,t))}}finally{i!==0&&Ct(i)}return n},bs=(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(xs(e),{cause:i!==void 0&&!r.has(i)?bs(i,void 0,void 0,r):void 0}),typeof e.name==`string`&&(a.name=e.name),typeof e.stack==`string`)a.stack=Cs(e.stack,a,t);else{let e=`${a.name}: ${a.message}`;a.stack=t?ws(e,t):e}n?.includeCauseInStack&&(a.stack=Os(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?ws(n,t):n}return a},xs=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)},Ss=/\((.*)\)/g,Cs=(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?ws(a.join(`
|
|
8
|
-
`),n):a.join(`
|
|
9
|
-
`)},ws=(e,t)=>{let n=t?.get(hn.key);return n&&(e=`${e}\n${Es(n)}`),e},Ts=(e,t)=>{let n=[`${e.name}: ${e.message}`];for(let e of t){let t=e.fiberId===void 0?`unknown`:`#${e.fiberId}`,r=e.annotations.get(gn.key);n.push(` at fiber (${t})`),r&&n.push(Es(r))}return n.join(`
|
|
10
|
-
`)},Es=e=>{let t=[],n=e,r=0;for(;n&&r<10;){let e=n.stack();if(e){let r=e.matchAll(Ss),i=!1;for(let[,e]of r)i=!0,t.push(` at ${n.name} (${e})`);i||t.push(` at ${n.name} (${e.replace(/^at /,``)})`)}else t.push(` at ${n.name}`);n=n.parent,r++}return t.join(`
|
|
11
|
-
`)},Ds=e=>ys(e).map(Os).join(`
|
|
12
|
-
`),Os=e=>e.cause?`${e.stack} {\n${ks(e.cause,` `)}\n}`:e.stack,ks=(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${ks(e.cause,`${t} `)}\n${t}}`),r},As=`~effect/Fiber`,js={_A:i,_E:i},Ms={id:0},Ns=(()=>{try{return globalThis.process?.getBuiltinModule?.(`node:async_hooks`)?.AsyncResource}catch{return}})(),Ps=()=>Ns===void 0?void 0:new Ns(`effect/Fiber`),Fs=()=>globalThis[rt],Is=class{constructor(e,t=!0){this.setContext(e),this.id=++Ms.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[As](){return js}get currentDispatcher(){return this._dispatcher??=this.cache.scheduler.makeDispatcher()}getRef(e){return ui(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=ss(e);this.cache.stackFrame&&(n=on(n,ii(hn,this.cache.stackFrame))),t&&(n=on(n,t)),this._interruptedCause=this._interruptedCause?en(this._interruptedCause,n):n,this.interruptible&&(this._running?this._deferredInterrupt=!0:this.evaluate(Ys(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=Ps();return}let n=Bs.interruptChildren&&Bs.interruptChildren(this);if(n!==void 0)return this.evaluate(Rc(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=ni()}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=Ys(this._interruptedCause)),this.currentOpCount++;let e=this.cache;if(!r&&!e.preventYield&&e.scheduler.shouldYield(this)){r=!0;let e=i;i=Rc(ec,()=>e)}if(i=e.tracerContext?e.tracerContext(i,this):i[Nt](this),i===Lt){let e=this._yielded;if(`~effect/Exit`in e)return this._deferredInterrupt=!1,this._yielded=void 0,e;if(this._deferredInterrupt){this._yielded=void 0,e();continue}return Lt}}catch(e){if(!pe(i,`~effect/Effect/evaluate`))return yn(`Fiber.runLoop: Not a valid effect: ${String(i)}`);i=yn(e)}}finally{this._running=n,globalThis[rt]=t}}getCont(e){if(this._deferredInterrupt)return this._deferredInterrupt=!1,Rs;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&zs-1))return mn(e);let t=this.getCont(Pt);return t?t[Pt](e,this):this.yieldWith(mn(e))}yieldWith(e){return this._yielded=e,Lt}children(){return this._children??=new Set}pipe(){return e(this,arguments)}setContext(e){let t=this.context;if(this.context=e,t!==void 0&&$r(t,e))return;let n=e.cacheRoot,r=n._fiberCache??=Ls(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}},Ls=e=>{let t=ci(e,Uo);return{scheduler:ui(e,po),tracer:t,tracerContext:t?t.context:void 0,tracerEnabled:ui(e,Jo),span:ci(e,Lo),logLevel:ui(e,$o),minimumLogLevel:ui(e,es),stackFrame:ui(e,qo),runtimeMetrics:ci(e,Ko),maxOpsBeforeYield:ui(e,bo),preventYield:ui(e,xo)}},Rs={[Pt](e,t){return Ys(t._interruptedCause)},[Ft](e,t){return Ys(t._interruptedCause)}},zs=32,Bs={interruptChildren:void 0},Vs=e=>{if(!e.cache.stackFrame)return;let t=new Map;return t.set(gn.key,e.cache.stackFrame),Zr(t)},Hs=e=>{let t=e;return t._exit?Js(t._exit):uc(n=>t._exit?n(Js(t._exit)):Zs(e.addObserver(e=>n(Js(e)))))},Us=e=>uc(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(Js(r))}return a(),Zs(()=>i?.())}),Ws=e=>{let t=e;return t._exit?t._exit:uc(n=>t._exit?n(t._exit):Zs(e.addObserver(n)))},Gs=e=>bn(t=>Ks(e,t.id)),Ks=r(e=>pe(e[0],As),(e,t,n)=>bn(r=>{let i=Vs(r);return i=i&&n?hi(i,n):i??n,e.interruptUnsafe(t,i),Fc(Hs(e))})),qs=e=>bn(t=>{let n=Vs(t),r=pa();for(let i of e)i.interruptUnsafe(t.id,n),r.push(i);return Fc(Us(r))}),Js=mn,Ys=_n,Xs=vn,Zs=fn({op:`Sync`,[Nt](e){let t=this[Mt](),n=e.getCont(Pt);return n?n[Pt](t,e):e.yieldWith(mn(t))}}),Qs=fn({op:`Suspend`,[Nt](e){return this[Mt]()}}),$s=Ai({onFailure:Xs,onSuccess:Js}),ec=fn({op:`Yield`,[Nt](e){let t=!1;return e.currentDispatcher.scheduleTask(()=>{t||e.evaluate(Zc)},this[`~effect/Effect/args`]??0),e.yieldWith(()=>{t=!0})}})(0),tc=Js(y()),nc=e=>Qs(()=>Ys(e())),rc=e=>yn(e),ic=Js(void 0),ac=e=>{let t=typeof e==`function`?e:e.try,n=typeof e==`function`?e=>new kd(e,`An error occurred in Effect.try`):e.catch;return Qs(()=>{try{return Js(t())}catch(e){return Xs(n(e))}})},oc=e=>cc(function(t,n){e(n).then(e=>t(Js(e)),e=>t(rc(e)))},e.length!==0),sc=e=>{let t=typeof e==`function`?e:e.try,n=typeof e==`function`?e=>new kd(e,`An error occurred in Effect.tryPromise`):e.catch;return cc(function(e,r){let i=e=>Qs(()=>{try{return Xs(Tt(()=>n(e)))}catch(e){return rc(e)}});try{t(r).then(t=>e(Js(t)),t=>e(i(t)))}catch(t){e(i(t))}},t.length!==0)},cc=function(){let e=dn({op:`Async`,[Nt](e){let t=!1,n=!1,r=this.withSignal?new AbortController:void 0,i=this.register.call(e.cache.scheduler,r=>{t||(t=!0,n?e.evaluate(r):n=r)},r?.signal);return n===!1?(n=!0,e.yieldWith(()=>{t=!0}),r===void 0&&i===void 0||e._stack.push(lc(()=>(t=!0,r?.abort(),i??Zc))),Lt):n}}),t=function(e,t){this.register=e,this.withSignal=t};return t.prototype=e,function(e,n){return new t(e,n)}}(),lc=fn({op:`AsyncFinalizer`,[It](e){e.interruptible&&(e.interruptible=!1,e._stack.push(wu))},[Ft](e,t){return ms(e)?Rc(Jl(_n(e),this[Mt]()),()=>Ys(e)):Ys(e)}}),uc=e=>cc(e,e.length>=2),dc=uc(u),fc=(...e)=>{if(e.length===1){let t=e[0];return Qs(()=>bc(t()))}let[t,n]=e;return Qs(()=>bc(n.call(t.self)))},pc=(e,...t)=>{let n=t.length===0?function(){return Qs(()=>bc(e.apply(this,arguments)))}:function(){let n=Qs(()=>bc(e.apply(this,arguments)));for(let e=0;e<t.length;e++)n=t[e](n,...arguments);return n};return mc(e.length,n)},mc=(e,t)=>Object.defineProperty(t,"length",{value:e,configurable:!0}),hc=rs(2),gc=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)=>_c(t,r,i,a,e,n):_c(t,arguments[0],i,Array.prototype.slice.call(arguments,1),e,n)},_c=(e,t,n,r,i,a)=>{let o=typeof t==`function`?t:r.shift().bind(t.self),s=`${e} (definition)`,c=n?hc(()=>n.stack):l;return mc(o.length,function(...t){let n=Qs(()=>{let e=o.apply(this,arguments);return Bt(e)?e:bc(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)),al(i?ld(e,a,e=>ud(n,e)):n,qo,t=>({name:e,stack:d?hc(()=>d.stack):l,parent:{name:s,stack:c,parent:t}}))})},vc=(e,...t)=>mc(e.length,t.length===0?function(){return yc(()=>e.apply(this,arguments))}:function(){let n=yc(()=>e.apply(this,arguments));for(let e of t)n=e(n,...arguments);return n}),yc=e=>{try{let t=e(),n;for(;;){let r=t.next(n);if(r.done)return Js(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 Qs(()=>n?(n=!1,Rc(r.value,e=>bc(t,e))):Qs(()=>bc(e())))}}}}catch(e){return rc(e)}},bc=function(){let e=dn({op:`Iterator`,[Pt](e,t){let n=this.iterator;for(;;){let r=n.next(e);if(r.done)return Js(r.value);if(!zc(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)}}(),xc=r(2,(e,t)=>new wc(e,Tc,Js(t))),Sc=function(e){return e._stack.push(this),this[Mt]},Cc=dn({op:`OnSuccess`,[Nt]:Sc}),wc=function(e,t,n){this[Mt]=e,this[Pt]=t,this.payload=n};wc.prototype=Cc;var Tc=function(){return this.payload},Ec=function(e,t){return t.succeedWith(this.payload)},Dc=(()=>{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})(),Oc=function(e,t){let n=this.payload;return t.succeedWith(Dc?n(e):Tt(()=>n(e)))},kc=function(e){let t=this.payload;return t(e)},Ac=function(e){let t=this.payload;return new wc(t(e),Ec,e)},jc=function(e){return new wc(this.payload,Ec,e)},Mc=e=>Hc(e,b),Nc=r(2,(e,t)=>new wc(e,Bt(t)?Tc:kc,t)),Pc=r(2,(e,t)=>new wc(e,Bt(t)?jc:Ac,t)),Fc=e=>new wc(e,Tc,Zc),Ic=(e,t)=>bn(n=>{let r=new Set;return uu(n,()=>r.size===0?void 0:qs(r)),uc(i=>{let a=!1,o=0;for(let s of e){if(a)break;let e=o++,c=Bu(n,s,!0,!0,!1);r.add(c),c.addObserver(o=>{r.delete(c);let s=!a;a=!0,i(o),s&&t?.onWinner&&t.onWinner({fiber:c,index:e,parentFiber:n})})}})}),Lc=r(e=>Bt(e[1]),(e,t,n)=>Ic([e,t],n)),Rc=r(2,(e,t)=>new wc(e,kc,t)),zc=e=>e[kt]!==void 0,Bc=r(2,(e,t)=>zc(e)?e._tag===`Success`?t(e.value):e:Rc(e,t)),Vc=e=>Rc(e,i),Hc=r(2,(e,t)=>new wc(e,Oc,t)),Uc=r(2,(e,t)=>zc(e)?Qc(e,t):Hc(e,t)),Wc=r(2,(e,t)=>zc(e)?$c(e,t):El(e,t)),Gc=r(2,(e,t)=>zc(e)?el(e,t):Dl(e,t)),Kc=e=>_n(ss(e)),qc=e=>e._tag===`Success`,Jc=e=>e._tag===`Failure`,Yc=e=>e._tag===`Failure`?Si(e.cause):Ci(e),Xc=e=>e._tag===`Failure`&&ms(e.cause),Zc=mn(void 0),Qc=r(2,(e,t)=>e._tag===`Success`?mn(t(e.value)):e),$c=r(2,(e,t)=>e._tag===`Success`?e:_n(_s(e.cause,t))),el=r(2,(e,t)=>e._tag===`Success`?mn(t.onSuccess(e.value)):_n(_s(e.cause,t.onFailure))),tl=r(2,(e,t)=>qc(e)?t:e),nl=e=>{let t=[];for(let n of e)n._tag===`Failure`&&t.push(...n.cause.reasons);return t.length===0?Zc:_n(Zt(t))},rl=e=>bn(t=>Js(mi(t.context,e))),il=r(2,(e,t)=>bn(n=>{let r=n.context,i=t(r);return r===i||(n.setContext(i),uu(n,()=>{n.setContext(r)})),e})),al=r(3,(e,t,n)=>il(e,e=>{let r=li(e,t),i=n(r);return r===i?e:ai(e,t,i)})),ol=()=>sl,sl=bn(e=>Js(e.context)),cl=e=>bn(t=>e(t.context)),ll=r(2,(e,t)=>zc(e)?e:il(e,hi(t))),ul=function(){return arguments.length===1?r(2,(e,t)=>dl(e,arguments[0],t)):r(3,(e,t,n)=>dl(e,t,n)).apply(this,arguments)},dl=(e,t,n)=>il(e,ai(t,n)),fl=r(e=>Bt(e[0]),(e,t)=>ju({while:o,body:a(t?.disableYield?e:Rc(e,e=>ec)),step:u})),pl=r(2,(e,t)=>new hl(e,t.length===1?t:e=>t(e))),ml=dn({op:`OnFailure`,[Nt]:Sc}),hl=function(e,t){this[Mt]=e,this[Ft]=t};hl.prototype=ml;var gl=r(3,(e,t,n)=>pl(e,e=>{let r=t(e);return Di(r)?Ys(r.failure):n(r.success,e)})),_l=r(2,(e,t)=>gl(e,fs,e=>t(e))),vl=r(2,(e,t)=>gl(e,ps,t)),yl=r(2,(e,t)=>pl(e,e=>Nc(t(e),Ys(e)))),bl=r(3,(e,t,n)=>pl(e,e=>{let r=t(e);return Di(r)?Ys(e):Nc(n(r.success,e),Ys(e))})),xl=r(2,(e,t)=>bl(e,ls,e=>t(e))),Sl=r(e=>Bt(e[0]),(e,t,n,r)=>pl(e,e=>{let i=fs(e);return Di(i)?Ys(i.failure):t(i.success)?n(i.success):r?r(i.success):Ys(e)})),Cl=r(e=>Bt(e[0]),(e,t,n,r)=>pl(e,e=>{let i=fs(e);if(Di(i))return Ys(i.failure);let a=t(i.success);return Di(a)?r?r(a.failure):Ys(e):n(a.success)})),wl=r(e=>Bt(e[0]),(e,t,n,r)=>Sl(e,Array.isArray(t)?e=>pe(e,`_tag`)&&t.includes(e._tag):me(t),n,r)),Tl=r(e=>Bt(e[0]),(e,t,n)=>{let r;return Cl(e,e=>(r??=Object.keys(t),pe(e,`_tag`)&&ee(e._tag)&&r.includes(e._tag)?Si(e):Ci(e)),e=>t[e._tag](e),n)}),El=r(2,(e,t)=>pl(e,e=>Ys(_s(e,t)))),Dl=r(2,(e,t)=>Ml(e,{onFailure:e=>Ys(_s(e,t.onFailure)),onSuccess:e=>Zs(()=>t.onSuccess(e))})),Ol=e=>_l(e,rc),kl=r(e=>Bt(e[0]),(e,t)=>{if(!t?.log)return Ll(e,{onFailure:e=>ic,onSuccess:e=>ic});let n=Rd(t.log===!0?void 0:t.log);return Ml(e,{onFailure(e){let r=fs(e);return Di(r)?Ys(r.failure):t.message===void 0?n(e):n(t.message,e)},onSuccess:e=>ic})}),Al=e=>Rl(e,{onFailure:y,onSuccess:b}),jl=e=>zl(e,{onFailure:Ci,onSuccess:Si}),Ml=r(2,(e,t)=>new Pl(e,t.onSuccess.length===1?t.onSuccess:e=>t.onSuccess(e),t.onFailure.length===1?t.onFailure:e=>t.onFailure(e))),Nl=dn({op:`OnSuccessAndFailure`,[Nt]:Sc}),Pl=function(e,t,n){this[Mt]=e,this[Pt]=t,this[Ft]=n};Pl.prototype=Nl;var Fl=function(e,t){let n=this.payload;return t.succeedWith(Dc?n.onSuccess(e):Tt(()=>n.onSuccess(e)))},Il=((e,t)=>{let n=dn({op:e,[Nt]:Sc,[Pt]:Fl,[Ft]:t}),r=function(e,t){this[Mt]=e,this.payload=t};return r.prototype=n,r})(`Match`,function(e,t){let n=fs(e);if(Di(n))return Ys(n.failure);let r=this.payload;return t.succeedWith(Dc?r.onFailure(n.success):Tt(()=>r.onFailure(n.success)))}),Ll=r(2,(e,t)=>Ml(e,{onFailure:e=>{let n=fs(e);return Di(n)?Ys(n.failure):t.onFailure(n.success)},onSuccess:t.onSuccess})),Rl=r(2,(e,t)=>new Il(e,t)),zl=r(2,(e,t)=>{if(zc(e)){if(e._tag===`Success`)return mn(t.onSuccess(e.value));let n=fs(e.cause);return Di(n)?_n(n.failure):mn(t.onFailure(n.success))}return Rl(e,t)}),Bl=e=>zc(e)?mn(e):Vl(e),Vl=fn({op:`Exit`,[Nt](e){return e._stack.push(this),this[Mt]},[Pt](e,t,n){return t.succeedWith(n??mn(e))},[Ft](e,t,n){return t.succeedWith(n??_n(e))}}),Hl=`~effect/Scope`,Ul=`~effect/Scope/Closeable`,Wl=Rr(`effect/Scope`),Gl=(e,t)=>bn(n=>(Du(n),Kl(e,t)??ic)),Kl=(e,t)=>{let n=e.state;if(n._tag===`Closed`||(e.state={_tag:`Closed`,exit:t},e.parent!==void 0&&eu(e.parent,e),n._tag===`Empty`))return;if(n.finalizer!==void 0)return ql(n.finalizer,t);let r=n.finalizers;return r.size===1?ql(r.values().next().value,t):Yl(e,r,t)},ql=(e,t)=>{try{return e(t)}catch(e){return yn(e)}},Jl=(e,t)=>qc(e)?t:pl(t,t=>Ys(ds($t(e.cause,t)))),Yl=pc(function*(e,t,n){let r=[],i=[],a=Array.from(t),o=Fs();for(let t=a.length-1;t>=0;t--){let[s,c]=a[t];e.strategy===`sequential`?r.push(yield*Bl(ql(c,n))):s!==o&&i.push(Bu(o,ql(c,n),!0,!0,`inherit`))}return i.length>0&&(r=yield*Us(i)),yield*nl(r)}),Xl=(e,t)=>{let n=nu(t,e);return e.state._tag===`Closed`?(n.state=e.state,n):($l(e,n,e=>Gl(n,e)),n)},Zl=(e,t)=>Qs(()=>e.state._tag===`Closed`?t(e.state.exit):($l(e,{},t),ic)),Ql=(e,t)=>Zl(e,a(t)),$l=(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)}},eu=(e,t)=>{if(e.state._tag!==`Open`)return;let n=e.state;n.finalizerKey===t?e.state=ru:n.finalizers!==void 0&&(n.finalizers.delete(t),n.finalizers.size===0&&(e.state=ru))},tu=e=>nu(e,void 0),nu=(e=`sequential`,t)=>({[Ul]:Ul,[Hl]:Hl,strategy:e,parent:t,state:ru}),ru={_tag:`Empty`},iu=Wl,au=ul(Wl),ou=e=>Qs(()=>{let t=tu();return du(e(t),e=>Qs(()=>Kl(t,e)??ic))}),su=(e,t,n)=>cl(r=>ku(i=>Rc(iu,a=>Pc(n?.interruptible?i(e):e,e=>Zl(a,n=>ll(t(e,n),r)))))),cu=function(){let e=dn({op:`OnExit`,[Nt](e){return e._stack.push(this),this.effect},[It](e){e.interruptible&&this.interruptible!==!0&&(e._stack.push(wu),e.interruptible=!1)},[Pt](e,t,n){n??=mn(e);let r;try{r=this.onExit(n)}catch(e){r=yn(e)}return r?Rc(r,e=>n):n},[Ft](e,t,n){n??=_n(e);let r;try{r=this.onExit(n)}catch(e){r=yn(e)}return r?Rc(Jl(n,r),e=>n):n}}),t=function(e,t,n){this.effect=e,this.onExit=t,this.interruptible=n};return t.prototype=e,t}(),lu=(e,t,n)=>new cu(e,t,n),uu=(e,t)=>{e._stack.push(new cu(void 0,t,void 0))},du=r(2,lu),fu=r(2,(e,t)=>du(e,e=>t)),pu=r(3,(e,t,n)=>du(e,e=>{let r=t(e);return Di(r)?ic:n(r.success,e)})),mu=r(2,(e,t)=>pu(e,Yc,t)),hu=r(3,(e,t,n)=>du(e,e=>{if(e._tag!==`Failure`)return ic;let r=t(e.cause);return Di(r)?ic:n(r.success,e.cause)})),gu=r(2,(e,t)=>hu(hs,t)(e)),_u=(e,t,n)=>ku(r=>Rc(e,e=>lu(Qs(()=>r(t(e))),t=>n(e,t),!0))),vu=a(1/0),yu=(e,t)=>{let n=0,r,i,a=(e,t)=>(t.awaiters++,uu(e,()=>{if(!(--t.awaiters>0||t.done))return i===t&&(i=void 0),Gs(t.fiber)}),Ws(t.fiber));return[bn(o=>{if(i!==void 0)return o===i.fiber?Ws(i.fiber):a(o,i);if(r!==void 0&&(n===1/0||o.getRef(hd).currentTimeMillisUnsafe()<n))return r;r=void 0;let s=o.getRef(hd),c={fiber:new Is(o.context),awaiters:0,done:!1};i=c;let l=a(o,c);return c.fiber.evaluate(lu(e,e=>{if(c.done=!0,i!==c||(i=void 0,Xc(e)))return;let a=t(e);n=a===1/0?1/0:s.currentTimeMillisUnsafe()+a,r=e})),c.fiber._exit??l}),Zs(()=>{i=void 0,r=void 0})]},bu=e=>Zs(()=>yu(e,vu)[0]),xu=bn(e=>Ys(ss(e.id))),Su=e=>bn(t=>(t.interruptible&&(t.interruptible=!1,t._stack.push(wu)),e)),Cu=fn({op:`SetInterruptible`,[It](e){if(e.interruptible=this[Mt],e._interruptedCause&&e.interruptible)return()=>Ys(e._interruptedCause)}}),wu=Cu(!0),Tu=Cu(!1),Eu=e=>{if(e.interruptible=!0,e._stack.push(Tu),e._interruptedCause)return Ys(e._interruptedCause)},Du=e=>{let t=e;t.interruptible&&(t.interruptible=!1,t._stack.push(wu))},Ou=e=>bn(t=>t.interruptible?e:Eu(t)??e),ku=e=>bn(t=>t.interruptible?(t.interruptible=!1,t._stack.push(wu),e(Ou)):e(i)),Au=(e,t)=>ge(e)?t?.mode===`result`?Mu(e,jl,t):Mu(e,i,t):t?.discard?t.mode===`result`?Mu(Object.values(e),jl,t):Mu(Object.values(e),i,t):Qs(()=>Hc(Mu(Object.entries(e),([e,n])=>Hc(t?.mode===`result`?jl(n):n,t=>[e,t]),{concurrency:t?.concurrency}),Object.fromEntries)),ju=fn({op:`While`,[Pt](e,t){return this[Mt].step(e),this[`~effect/Effect/args`].while()?(t._stack.push(this),this[Mt].body()):Zc},[Nt](e){return this[`~effect/Effect/args`].while()?(e._stack.push(this),this[Mt].body()):Zc}}),Mu=r(e=>typeof e[1]==`function`,(e,t,n)=>Qs(()=>{let r=Pu(n?.concurrency);if(r===1)return Nu(e,t,n);let i=Wi(e),a=i.length;if(a===0)return n?.discard?ic:Js([]);let o=n?.discard?void 0:Array(a),s=Ru({f:t,out:o},i,{concurrency:r});return s?xc(s,o):Js(o)})),Nu=(e,t,n)=>Qs(()=>{let r=n?.discard?void 0:[],i=e[Symbol.iterator](),a=i.next(),o=0;return xc(ju({while:()=>!a.done,body:()=>t(a.value,o++),step:e=>{r&&r.push(e),a=i.next()}}),r)}),Pu=e=>e===`unbounded`?1/0:Math.max(1,e??1),Fu=()=>e=>{let t=e.onItem,n=e.step,r=(e,t,r,a,o)=>Rc(Bl(o),o=>n(e,t[r],o,r)??i(e,t,r+1,a)??ic),i=(e,i,a=0,o=i.length)=>{for(;a<o;a++){let s=i[a],c=t(e,s,a);if(!zc(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},Iu=e=>{let t=e.onItem,n=e.step;return(e,r,i)=>{let a=0,o=i.end??r.length,s=i.concurrency,c=!1,l,u,d,f,p,m=e=>{let t=yn(e);return f=t,c=!0,u&&u.size>0?Rc(Su(qs(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(zc(g)){if(f=n(e,o,g,a),f)break}else if(l){p=void 0;let t=Bu(l,g,!0,!0,`inherit`);if(t._exit){if(f=n(e,o,t._exit,a),f)break;continue}u.add(t);let r=a;if(t.addObserver(a=>{u.delete(t);try{if(f){if(a._tag===`Failure`){let e=a.cause.reasons.filter(e=>e._tag!==`Interrupt`);if(e.length>0){let t=Zt(e);f=_n(f._tag===`Failure`?ds($t(f.cause,t)):t)}}}else{let t=n(e,o,a,r);t&&(f=t,h())}if(i){let e=h();e&&d(e)}else c&&u.size===0&&d(f??ic)}catch(e){d(m(e))}}),u.size<s)continue;i=!0,a++;return}else return uc(e=>{l=Fs(),u=new Set,p=g,d=e;let t;try{t=h()}catch(t){return e(m(t))}return t?e(t):Qs(()=>(f??=Zc,Rc(u?qs(u):ic,()=>f?._tag===`Failure`?f:ic)))})}if(c=!0,f){if(u&&u.size>0){let e=Vs(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(ic);else return Zc}};return h()}},Lu=()=>e=>Iu(e),Ru=Iu({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)}}),zu=r(e=>ge(e[0])&&!Bt(e[0]),(e,t,n)=>Hc(Mu(e,(e,n)=>{let r=t(e,n);return typeof r==`boolean`?Js(r?b(e):y()):Hc(r,t=>t?b(e):y())},n),ga)),Bu=(e,t,n=!1,r=!1,i=!1)=>{let a=e,o=i===`inherit`?a.interruptible:!i,s=new Is(a.context,o);return r||(a.children().add(s),s._parent=a),n?s.evaluate(t):(s._asyncContext=Ps(),a.currentDispatcher.scheduleTask(()=>s.evaluate(t),0)),s},Vu=e=>()=>bn(t=>t===e?ic:Gs(e)),Hu=r(e=>Bt(e[0]),(e,t,n)=>bn(r=>{let i=t.state._tag===`Closed`?new Is(r.context):Bu(r,e,n?.startImmediately,!0,n?.uninterruptible);return i._exit||(t.state._tag===`Closed`?i.interruptUnsafe(r.id,Vs(r)):($l(t,i,Vu(i)),i.addObserver(()=>eu(t,i)))),Js(i)})),Uu=r(e=>Bt(e[0]),(e,t)=>Rc(iu,n=>Hu(e,n,t))),Wu=e=>(t,n)=>{let r=new Is(n?.scheduler?ai(e,po,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},Gu=r(2,(e,t)=>e._exit?e:t.state._tag===`Closed`?(e.interruptUnsafe(e.id),e):(eu(t,e),$l(t,e,Vu(e)),e.addObserver(()=>eu(t,e)),e)),Ku=Wu(ni()),qu=e=>{let t=Wu(e);return(e,n)=>{let r=t(e,n);return new Promise(e=>{r.addObserver(t=>e(t))})}},Ju=(e=>{let t=qu(e);return(e,n)=>t(e,n).then(e=>{if(e._tag===`Failure`)throw vs(e.cause);return e.value})})(ni()),Yu=e=>{let t=Wu(e);return e=>{if(zc(e))return e;let n=new vo(`sync`),r=t(e,{scheduler:n});return r._dispatcher?.flush(),r._exit??yn(new Dd(r))}},Xu=Yu(ni()),Zu=(e=>{let t=Yu(e);return e=>{let n=t(e);if(n._tag===`Failure`)throw vs(n.cause);return n.value}})(ni()),Qu=Js(!0),$u=Js(!1),ed=class{waiters=[];scheduled=void 0;_isOpen;constructor(e){this._isOpen=e}scheduleUnsafe(e){if(this.waiters.length===0)return Qu;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=[],Qu}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](Zc)};flushWaiters(){let e=this.waiters;this.waiters=[],this.flushScheduled();for(let t=0;t<e.length;t++)e[t](Zc)}open=bn(e=>this._isOpen?$u:(this._isOpen=!0,this.scheduleUnsafe(e)));release=bn(e=>this._isOpen?$u:this.scheduleUnsafe(e));openUnsafe(){return!this._isOpen&&(this._isOpen=!0,this.flushWaiters(),!0)}await=uc(e=>this._isOpen?e(ic):(this.waiters.push(e),Zs(()=>{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=Zs(()=>this.closeUnsafe());whenOpen=e=>Rc(this.await,()=>e);isOpen(){return this._isOpen}},td=e=>new ed(e??!1),nd=BigInt(0),rd={_tag:`Span`,spanId:`noop`,traceId:`noop`,sampled:!1,status:{_tag:`Ended`,startTime:nd,endTime:nd,exit:Zc},attributes:new Map,links:[],kind:`internal`,attribute(){},event(){},end(){},addLinks(){}},id=e=>Object.assign(Object.create(rd),e),ad=e=>e?ui(e.annotations,Bo)?e._tag===`Span`?ad(Tr(e.parent)):y():b(e):y(),od=(e,t,n)=>{let r=!e.cache.tracerEnabled||n?.annotations&&ui(n.annotations,Bo),i=n?.parent===void 0?n?.root?y():ad(e.cache.span):b(n.parent),a;if(r)a=id({name:t,parent:i,annotations:ai(n?.annotations??ni(),Bo,!0)});else{let r=e.cache.tracer??Wo,o=e.getRef(hd),s=e.getRef(Yo),c=e.getRef(Xo),l=e.getRef(Zo),u=n?.level??e.getRef(Vo),d=n?.links===void 0?l.length===0?[]:l.slice():[...l,...n.links];a=r.span({name:t,parent:i,annotations:n?.annotations??ni(),links:d,startTime:s?o.currentTimeNanosUnsafe():nd,kind:n?.kind??`internal`,root:n?.root??!1,sampled:n?.sampled??(S(i)&&i.value.sampled===!1?!1:!jd(e.getRef(Ho),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},sd=(e,t)=>(t=typeof t==`function`?t:l,al(qo,n=>({name:e,stack:t,parent:n}))),cd=(e,t,n,r)=>Zs(()=>{e.status._tag!==`Ended`&&e.end(r?n.currentTimeNanosUnsafe():nd,t)}),ld=(e,...t)=>{let n=t.length===1?void 0:t[0],r=t[t.length-1];return bn(t=>{let i=od(t,e,n),a=t.getRef(hd),o=t.getRef(Yo);return uu(t,e=>cd(i,e,a,o)),r(i)})},ud=ul(Ro),dd=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=ns(n),r=sd(t.name,n?.captureStackTrace)),e?ud(r(arguments[0]),t):e=>ud(r(e),t)},fd=function(){let e=typeof arguments[0]!=`string`,t=e?arguments[1]:arguments[0],n=ns(arguments[2]);if(e){let e=arguments[0];return ld(t,arguments[2],t=>dd(e,t,n))}let r=typeof arguments[1]==`function`?arguments[1]:void 0,i=r?void 0:arguments[1];return(e,...a)=>ld(t,r?r(...a):i,t=>dd(e,t,n))},pd=(...e)=>bn(t=>{let n=t.currentSpanLocal;if(n){if(e.length===1)for(let[t,r]of Object.entries(e[0]))n.attribute(t,r);else n.attribute(e[0],e[1])}return ic}),md=bn(e=>{let t=e.currentSpanLocal;return t?Js(t):Xs(new Tn)}),hd=vi(`effect/Clock`,{defaultValue:()=>new _d}),gd=2**31-1,_d=class{currentTimeMillisUnsafe(){return Date.now()}currentTimeMillis=Zs(()=>this.currentTimeMillisUnsafe());currentTimeNanosUnsafe(){return bd()}currentTimeNanos=Zs(()=>this.currentTimeNanosUnsafe());monotonicTimeNanosUnsafe(){return yd()}monotonicTimeNanos=Zs(()=>this.monotonicTimeNanosUnsafe());sleep(e){return this.sleepMillis(ro(e))}sleepMillis(e){return e<=0?ec:Number.isFinite(e)?uc(t=>{let n=e>gd?this.sleepMillis(e-gd):ic,r=setTimeout(()=>t(n),Math.min(e,gd));return Zs(()=>clearTimeout(r))}):dc}},vd=BigInt(1e6),yd=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())*vd;return e>t&&(t=e),t}}(),bd=function(){let e=BigInt(1e9),t;return()=>{let n=yd(),r=BigInt(Date.now())*vd;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}}(),xd=e=>bn(t=>e(t.getRef(hd))),Sd=e=>xd(t=>t.sleep(Ba(e))),Cd=xd(e=>e.currentTimeMillis),wd=`~effect/Cause/IllegalArgumentError`,Td=class extends Cn(`IllegalArgumentError`){[wd]=wd;constructor(e){super({message:e})}},Ed=`~effect/Cause/AsyncFiberError`,Dd=class extends Cn(`AsyncFiberError`){[Ed]=Ed;constructor(e){super({message:`An asynchronous Effect was executed with Effect.runSync`,fiber:e})}},Od=`~effect/Cause/UnknownError`,kd=class extends Cn(`UnknownError`){[Od]=Od;constructor(e,t){super({message:t,cause:e})}},Ad=vi(`effect/Console`,{defaultValue:()=>globalThis.console}),jd=mr(fr(lr,e=>{switch(e){case`All`:return-(2**53-1);case`Fatal`:return 5e4;case`Error`:return 4e4;case`Warn`:return 3e4;case`Info`:return 2e4;case`Debug`:return 1e4;case`Trace`:return 0;case`None`:return 2**53-1}})),Md=vi(`effect/Logger/CurrentLoggers`,{defaultValue:()=>new Set([Vd,Hd])}),Nd=vi(`effect/Logger/LogToStderr`,{defaultValue:s}),Pd={"~effect/Logger":{_Message:i,_Output:i},pipe(){return e(this,arguments)}},Fd=e=>{let t=Object.create(Pd);return t.log=e,t},Id=e=>e.replace(/[\s="]/g,`_`),Ld=(e,t)=>`${Id(e[0])}=${t-e[1]}ms`,Rd=e=>(...t)=>{let n;for(let e=0,r=t.length;e<r;e++){let r=t[e];Wt(r)&&(n?t.splice(e,1):t=t.slice(0,e).concat(t.slice(e+1)),n=n?Zt(n.reasons.concat(r.reasons)):r,e--)}return n===void 0&&(n=tn),bn(r=>{let i=e??r.cache.logLevel;if(jd(r.cache.minimumLogLevel,i))return ic;let a=r.getRef(hd),o=r.getRef(Md);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 ic})},zd={bold:`1`,red:`31`,green:`32`,yellow:`33`,blue:`34`,cyan:`36`,white:`37`,gray:`90`,black:`30`,bgBrightRed:`101`};zd.gray,zd.blue,zd.green,zd.yellow,zd.red,zd.bgBrightRed,zd.black;var Bd=e=>`${e.getHours().toString().padStart(2,`0`)}:${e.getMinutes().toString().padStart(2,`0`)}:${e.getSeconds().toString().padStart(2,`0`)}.${e.getMilliseconds().toString().padStart(3,`0`)}`,Vd=Fd(({cause:e,date:t,fiber:n,logLevel:r,message:i})=>{let a=Array.isArray(i)?i.slice():[i];e.reasons.length>0&&a.push(Ds(e));let o=t.getTime(),s=n.getRef(ts),c=``;for(let e of s)c+=` ${Ld(e,o)}`;let l=n.getRef(Qo);Object.keys(l).length>0&&a.push(l);let u=n.getRef(Ad);(n.getRef(Nd)?u.error:u.log)(`[${Bd(t)}] ${r.toUpperCase()} (#${n.id})${c}:`,...a)}),Hd=Fd(({cause:e,fiber:t,logLevel:n,message:r})=>{let i=t.getRef(hd),a=t.getRef(Qo),o=t.cache.span;if(o===void 0||o._tag===`ExternalSpan`)return;let s={};for(let[e,t]of Object.entries(a))Et(s,e,t);s[`effect.fiberId`]=t.id,s[`effect.logLevel`]=n.toUpperCase(),e.reasons.length>0&&(s[`effect.cause`]=Ds(e)),o.event(vt(Array.isArray(r)&&r.length===1?r[0]:r),i.currentTimeNanosUnsafe(),s)}),Ud=Wt,Wd=Gt,Gd=sn,Kd=Zt,qd=nn,Jd=an,Yd=e=>new Xt(e),Xd=e=>new rn(e),Zd=os,Qd=gs,$d=_s,ef=$t,tf=vs,nf=ms,rf=hs,af=Ds,of=Dn,sf=jn,cf=Td,lf=mn,uf=_n,df=vn,ff=Zc,pf=qc,mf=Jc,hf={"~effect/Deferred":{_A:i,_E:i},pipe(){return e(this,arguments)}},gf=function(){this.resumes=void 0,this.effect=void 0};gf.prototype=hf;var _f=()=>new gf,vf=()=>Zs(()=>_f()),yf=e=>uc(t=>e.effect?t(e.effect):(e.resumes??=[],e.resumes.push(t),Zs(()=>{let n=e.resumes;if(n===void 0)return;let r=n.indexOf(t);r>=0&&n.splice(r,1)}))),bf=r(2,(e,t)=>Zs(()=>wf(e,t))),xf=e=>Zs(()=>Sf(e)),Sf=e=>e.effect!==void 0,Cf=r(2,(e,t)=>bf(e,mn(t))),wf=(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},Tf=r(2,(e,t)=>ku(n=>Rc(Bl(n(e)),e=>bf(t,e)))),Ef=Yo,Df=Wl,Of=tu,kf=au,Af=Zl,jf=Ql,Mf=Xl,Nf=Gl,Pf=`~effect/Layer`,Ff=`~effect/Layer/MemoMap`,If=(e,t)=>{let n={observers:0,deferred:_f(),scope:Of(),finalizer:r=>Qs(()=>--n.observers>0?ic:(e.map.delete(t),Nf(n.scope,r)))};return n},Lf=(e,t)=>t.state._tag!==`Closed`&&(e.observers++,$l(t,{},e.finalizer),!0),Rf={[Pf]:{_ROut:i,_E:i,_RIn:i},pipe(){return e(this,arguments)}},zf=e=>{let t=Object.create(Rf);return t.build=e,t},Bf=e=>zf((t,n)=>{let r=Mf(n);return du(e(t,r),e=>e._tag===`Failure`?Nf(r,e):ic)}),Vf=e=>{let t=Bf((n,r)=>n.getOrElseMemoize(t,r,e));return t},Hf=class{get[Ff](){return Ff}parent;constructor(e){this.parent=e}map=new Map;get(e,t){let n=this.map.get(e);return n?(Lf(n,t),n.deferred.effect??yf(n.deferred)):this.parent?.get(e,t)}getOrElseMemoize(e,t,n){return Qs(()=>{let r;return lu(Qs(()=>{let i=this.get(e,t);if(i)return i;let a=If(this,e);return Lf(a,t)?(r=a.deferred,this.map.set(e,a),n(this,a.scope)):n(this,t)}),e=>{r&&wf(r,e)})})}},Uf=()=>new Hf,Wf=e=>new Hf(e),Gf=class e extends Rr()(`effect/Layer/CurrentMemoMap`){static forkOrCreate(t){let n=si(t,e);return n?Wf(n):Uf()}},Kf=r(3,(e,t,n)=>ul(Hc(Qs(()=>e.build(t,n)),ai(Gf,t)),Gf,t)),qf=r(2,(e,t)=>bn(n=>Kf(e,Gf.forkOrCreate(n.context),t))),Jf=function(){return arguments.length===1?e=>Yf(ii(arguments[0],e)):Yf(ii(arguments[0],arguments[1]))},Yf=e=>zf(a(Js(e))),Xf=function(){return arguments.length===1?e=>Zf(arguments[0],e):Zf(arguments[0],arguments[1])},Zf=(e,t)=>Qf(Hc(t,t=>ii(e,t))),Qf=e=>Vf((t,n)=>kf(e,n)),$f=e=>Qf(xc(e,ni())),ep=(e,t,n)=>{let r=Mf(n,`parallel`);return Mu(e,e=>e.build(t,Mf(r,`sequential`)),{concurrency:e.length}).pipe(Hc(e=>gi(...e)))},tp=(...e)=>Vf((t,n)=>ep(e,t,n)),np=(e,t,n)=>Vf((r,i)=>Rc(Array.isArray(t)?ep(t,r,i):t.build(r,i),t=>e.build(r,i).pipe(ll(t),Hc(e=>n(e,t))))),rp=r(2,(e,t)=>np(e,t,i)),ip=r(2,(e,t)=>np(e,t,(e,t)=>hi(t,e))),ap=hd,op=Cd,sp=`~effect/DateTime`,cp=`~effect/DateTime/TimeZone`,lp={[sp]:sp,pipe(){return e(this,arguments)},[gt](){return this.toString()},toJSON(){return Hp(this).toJSON()}},up={...lp,_tag:`Utc`,[_e](){return we(this.epochMilliseconds)},[Ie](e){return gp(e)&&e._tag===`Utc`&&this.epochMilliseconds===e.epochMilliseconds},toString(){return`DateTime.Utc(${Hp(this).toJSON()})`}},dp={...lp,_tag:`Zoned`,[_e](){return xe(we(this.epochMilliseconds))(ve(this.zone))},[Ie](e){return gp(e)&&e._tag===`Zoned`&&this.epochMilliseconds===e.epochMilliseconds&&Le(this.zone,e.zone)},toString(){return`DateTime.Zoned(${fm(this)})`}},fp={[cp]:cp,[gt](){return this.toString()}},pp={...fp,_tag:`Named`,[_e](){return Te(`Named:${this.id}`)},[Ie](e){return vp(e)&&e._tag===`Named`&&this.id===e.id},toString(){return`TimeZone.Named(${this.id})`},toJSON(){return{_id:`TimeZone`,_tag:`Named`,id:this.id}}},mp={...fp,_tag:`Offset`,[_e](){return Te(`Offset:${this.offset}`)},[Ie](e){return vp(e)&&e._tag===`Offset`&&this.offset===e.offset},toString(){return`TimeZone.Offset(${Gp(this.offset)})`},toJSON(){return{_id:`TimeZone`,_tag:`Offset`,offset:this.offset}}},hp=(e,t,n)=>{let r=Object.create(dp);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},gp=e=>pe(e,sp),_p=e=>gp(e[0]),vp=e=>pe(e,cp),yp=e=>vp(e)&&e._tag===`Named`,bp=e=>e._tag===`Utc`,xp=e=>e._tag===`Zoned`,Sp=e=>{let t=Object.create(up);return t.epochMilliseconds=e,Object.defineProperty(t,"partsUtc",{value:void 0,enumerable:!1,writable:!0}),t},Cp=e=>{let t=e.getTime();if(Number.isNaN(t))throw new cf(`Invalid date`);return Sp(t)},wp=e=>{if(gp(e))return e;if(e instanceof Date)return Cp(e);if(typeof e==`object`){if(`epochMilliseconds`in e)return Cp(new Date(e.epochMilliseconds));let t=new Date(0);return Zp(t,e),Cp(t)}return typeof e==`string`&&!Tp(e)?Cp(new Date(e+`Z`)):Cp(new Date(e))},Tp=e=>/Z|GMT|[+-]\d{2}$|[+-]\d{2}:?\d{2}$|\]$/.test(e)||/z$|gmt$/i.test(e),Ep=-864e13+432e5,Dp=864e13-504e5,Op=(e,t)=>{let n=t?.timeZone;if(n===void 0&&gp(e)&&xp(e))return e;let r=wp(e);if(r.epochMilliseconds<Ep||r.epochMilliseconds>Dp)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=Lp(new Date(r.epochMilliseconds).getTimezoneOffset()*-60*1e3);else if(vp(n))i=n;else if(typeof n==`number`)i=Lp(n);else{let e=Bp(n);if(x(e))throw new cf(`Invalid time zone: ${n}`);i=e.value}return t?.adjustForTimeZone===!0?$p(r.epochMilliseconds,i,t?.disambiguation??`compatible`):hp(r.epochMilliseconds,i,r.partsUtc)},kp=Er(wp),Ap=Hc(op,Sp),jp=e=>Sp(e.epochMilliseconds),Mp=r(_p,(e,t,n)=>n?.adjustForTimeZone===!0?$p(e.epochMilliseconds,t,n?.disambiguation??`compatible`):hp(e.epochMilliseconds,t,e.partsUtc)),Np=new Map,Pp={day:`numeric`,month:`numeric`,year:`numeric`,era:`short`,hour:`numeric`,minute:`numeric`,second:`numeric`,timeZoneName:`longOffset`,fractionalSecondDigits:3,hourCycle:`h23`},Fp=e=>{let t=e.resolvedOptions().timeZone,n=Np.get(t);if(n!==void 0)return n;let r=Object.create(pp);return r.id=t,r.format=e,Np.set(t,r),r},Ip=e=>{let t=Np.get(e);if(t!==void 0)return t;try{let t=Fp(new Intl.DateTimeFormat(`en-US`,{...Pp,timeZone:e}));return Np.set(e,t),t}catch{throw new cf(`Invalid time zone: ${e}`)}},Lp=e=>{let t=Object.create(mp);return t.offset=e,t},Rp=Er(Ip),zp=/^(?:GMT)?[+-]/,Bp=e=>{if(zp.test(e)){let t=tm(e);return t===null?y():b(Lp(t))}return Rp(e)},Vp=r(_p,(e,t,n)=>Or(Rp(t),t=>Mp(e,t,n))),Hp=e=>new Date(e.epochMilliseconds),Up=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},Wp=e=>Up(e).getTime()-qp(e),Gp=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`)}`},Kp=e=>Gp(Wp(e)),qp=e=>e.epochMilliseconds,Jp=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()}),Yp=e=>e._tag===`Utc`?Xp(e):(e.partsAdjusted===void 0&&(e.partsAdjusted=om(e,Jp)),e.partsAdjusted),Xp=e=>(e.partsUtc===void 0&&(e.partsUtc=sm(e,Jp)),e.partsUtc),Zp=(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)},Qp=864e5,$p=(e,t,n)=>{if(t._tag===`Offset`)return hp(e-t.offset,t);let r=nm(e-Qp,e,t),i=nm(e+Qp,e,t);if(r===i)return hp(e-r,t);let a=r<i,o=r-i;if(a){if(nm(e-i,e,t)===i)return hp(e-i,t);let a=hp(e-r,t);if(e!==Up(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 hp(e-i,t);case`compatible`:case`later`:return a}return a}if(nm(e-r,e,t)===r){if(n===`earlier`||n===`compatible`||nm(e-r+o,e+o,t)===r)return hp(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 hp(e-i,t)},em=/([+-])(\d{2}):?(\d{2})$/,tm=e=>{let t=em.exec(e);if(t===null)return null;let[,n,r,i]=t;return(n===`+`?1:-1)*(Number(r)*60+Number(i))*60*1e3},nm=(e,t,n)=>{let r=n.format.formatToParts(e).find(e=>e.type===`timeZoneName`)?.value??``;if(r===`GMT`)return 0;let i=tm(r);return i===null?Wp(hp(t,n)):i},rm=r(_p,(e,t,n)=>{if(e._tag===`Utc`){let n=Hp(e);return t(n),Sp(n.getTime())}let r=Up(e),i=new Date(r.getTime());return t(i),$p(i.getTime(),e.zone,n?.disambiguation??`compatible`)}),im=r(2,(e,t)=>am(e,e=>{let n=new Date(e);return t(n),n.getTime()})),am=r(2,(e,t)=>{let n=t(qp(e));return e._tag===`Utc`?Sp(n):hp(n,e.zone)}),om=r(2,(e,t)=>t(Up(e))),sm=r(2,(e,t)=>t(Hp(e))),cm=r(2,(e,t)=>{let n=im(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:rm(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)}})}),lm=r(2,(e,t)=>{let n={};for(let e in t)n[e]=-1*t[e];return cm(e,n)}),um=e=>Hp(e).toISOString(),dm=e=>{let t=Up(e);return e._tag===`Utc`?t.toISOString():`${t.toISOString().slice(0,-1)}${Kp(e)}`},fm=e=>e.zone._tag===`Offset`?dm(e):`${dm(e)}[${e.zone.id}]`;globalThis.Number;var pm=lr;globalThis.String;var mm=e=>e.toLowerCase(),hm=e=>e.length>0,gm=`~effect/Cron`;function _m(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 vm={[gm]:gm,[Ie](e){return ym(e)&&Lm(this,e)},[_e](){return d(ve(this.tz),xe(ve(this.and)),xe(ke(Wi(this.seconds))),xe(ke(Wi(this.minutes))),xe(ke(Wi(this.hours))),xe(ke(Wi(this.days))),xe(ke(Wi(this.months))),xe(ke(Wi(this.weekdays))))},toObject(){return _m(this)},toString(){return`Cron(${ot(_m(this))})`},toJSON(){let e=_m(this);return e._id=`Cron`,e},[gt](){return this.toJSON()},pipe(){return e(this,arguments)}},ym=e=>pe(e,gm),bm=e=>{let t=Object.create(vm);t.seconds=Sm.seconds(e.seconds??[0]),t.minutes=Sm.minutes(e.minutes),t.hours=Sm.hours(e.hours),t.days=Sm.days(e.days),t.months=Sm.months(e.months),t.weekdays=Sm.weekdays(e.weekdays),t.and=e.and===!0,t.tz=Cr(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:wm.next.second(n),minute:wm.next.minute(r),hour:wm.next.hour(i),day:wm.next.day(a),month:wm.next.month(o),weekday:wm.next.weekday(s)},t.prev={second:wm.prev.second(n),minute:wm.prev.minute(r),hour:wm.prev.hour(i),day:wm.prev.day(a),month:wm.prev.month(o),weekday:wm.prev.weekday(s)},t},xm=(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,pm))},Sm={seconds:xm(`seconds`,0,59),minutes:xm(`minutes`,0,59),hours:xm(`hours`,0,23),days:xm(`days`,1,31),months:xm(`months`,1,12),weekdays:xm(`weekdays`,0,7,e=>e===7?0:e)},Cm=(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},wm={prev:{second:Cm(60,`prev`),minute:Cm(60,`prev`),hour:Cm(24,`prev`),day:Cm(32,`prev`),month:Cm(13,`prev`),weekday:Cm(7,`prev`)},next:{second:Cm(60,`next`),minute:Cm(60,`next`),hour:Cm(24,`next`),day:Cm(32,`next`),month:Cm(13,`next`),weekday:Cm(7,`next`)}},Tm=`~effect/Cron/CronParseError`,Em=class extends wo(`CronParseError`){[Tm]=Tm},Dm=(e,t)=>{let n=e.trim().split(/\s+/).filter(hm);if(n.length!==5&&n.length!==6)return Ci(new Em({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||vp(t)?Si(t):wi(Bp(t),()=>new Em({message:`Invalid time zone in cron expression`,input:t})),seconds:Wm(r,Rm),minutes:Wm(i,zm),hours:Wm(a,Bm),days:Wm(o,Vm),months:Wm(s,Hm),weekdays:Wm(c,Um)}).pipe(ki(({tz:e,seconds:t,minutes:n,hours:r,days:i,months:a,weekdays:o})=>bm({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})))},Om=(e,t)=>ji(Dm(e,t)),km=(e,t)=>{let n=Op(t,{timeZone:Tr(e.tz)}).pipe(Yp);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)},Am=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth()+1,0)).getUTCDate(),jm=(e,t)=>Nm(e,t,`next`),Mm=(e,t)=>Nm(e,t,`prev`),Nm=(e,t,n)=>{let r=Tr(e.tz),i=Op(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&&yp(r)&&r.id===`UTC`,p=f?u:e=>{let t=Op(e,{timeZone:i.zone,adjustForTimeZone:!0,disambiguation:a?`later`:void 0}).pipe(Up),n=e.getTime()-t.getTime();(a?n!==0:n>0)&&e.setTime(a?t.getTime():e.getTime()+n)},m=a||f?s:e=>Op(e,{timeZone:i.zone,adjustForTimeZone:!0}).epochMilliseconds<=i.epochMilliseconds;return Hp(rm(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=Am(t)-e+l.day}else r=!a&&n>Am(t)?Am(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=Am(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`)}))},Pm=Nn((e,t)=>Le(e.tz,t.tz)&&e.and===t.and&&Im(e.seconds,t.seconds)&&Im(e.minutes,t.minutes)&&Im(e.hours,t.hours)&&Im(e.days,t.days)&&Im(e.months,t.months)&&Im(e.weekdays,t.weekdays)),Fm=Ln(Fn()),Im=(e,t)=>Fm(Wi(e),Wi(t)),Lm=r(2,(e,t)=>Pm(e,t)),Rm={min:0,max:59},zm={min:0,max:59},Bm={min:0,max:23},Vm={min:1,max:31},Hm={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}},Um={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}},Wm=(e,t)=>{let n=new Set,r=e.split(`,`),i=Gm(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:Gm(a);if(c!==void 0){if(!Number.isInteger(c))return Ci(new Em({message:`Expected step value to be a positive integer`,input:e}));if(c<1)return Ci(new Em({message:`Expected step value to be greater than 0`,input:e}));if(c>t.max)return Ci(new Em({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]=Km(o,t.aliases);if(!Number.isInteger(n))return Ci(new Em({message:`Expected a positive integer`,input:e}));if(n<t.min||n>t.max)return Ci(new Em({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 Ci(new Em({message:`Expected a positive integer`,input:e}));if(r<t.min||r>t.max)return Ci(new Em({message:`Expected a value between ${t.min} and ${t.max}`,input:e}));if(n>r)return Ci(new Em({message:`Invalid value range`,input:e}));for(let e=n;e<=r;e+=c??1)s(e)}}}return Si({values:n,wildcard:a})},Gm=e=>{let t=e.indexOf(`/`);if(t!==-1){let n=e.slice(t+1);return[e.slice(0,t),Jm.test(n)?Number(n):NaN]}return[e,void 0]},Km=(e,t)=>{let n=e.indexOf(`-`);return n===-1?[qm(e,t),void 0]:[qm(e.slice(0,n),t),qm(e.slice(n+1),t)]};function qm(e,t){return t?.[mm(e)]??(Jm.test(e)?Number(e):NaN)}var Jm=/^\d+$/,Ym=r(2,(e,t)=>gl(e,$m,e=>t(e))),Xm=e=>e.reasons.some(Zm),Zm=e=>e._tag===`Fail`&&of(e.error),Qm=e=>{let t,n=!1;for(let r of e.reasons)Zm(r)?t??=r.error:r._tag!==`Interrupt`&&(n=!0);return t===void 0?Ci(e):n?Ci(Kd(e.reasons.filter(e=>!Zm(e)))):Si(t)},$m=e=>{let t=Qm(e);return Di(t)?t:Si(t.success.value)},eh=e=>{let t=Qm(e);return Di(t)?uf(t.failure):lf(t.success.value)},th=r(2,(e,t)=>Ml(e,{onSuccess:t.onSuccess,onFailure:e=>{let n=Qm(e);return Di(n)?t.onFailure(n.failure):t.onDone(n.success.value)}})),nh=`~effect/Schedule`,rh=vi(`effect/Schedule/CurrentMetadata`,{defaultValue:a({input:void 0,output:void 0,duration:Xa,attempt:0,start:0,now:0,elapsed:0,elapsedSincePrevious:0})}),ih={[nh]:{_Out:i,_In:i,_Env:i},pipe(){return e(this,arguments)}},ah=e=>pe(e,nh),oh=e=>{let t=Object.create(ih);return t.step=e,t},sh=()=>{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}}},ch=e=>oh(Hc(e,e=>{let t=sh();return(n,r)=>e(t(n,r))})),lh=e=>pl(e.step,e=>Js(()=>Ys(e))),uh=e=>xd(t=>Hc(lh(e),e=>{let n=sh();return r=>Qs(()=>{let i=t.currentTimeMillisUnsafe();return Rc(e(i,r),([e,t])=>{let a=n(i,r);return a.output=e,a.duration=t,xc(Sd(t),a)})})})),dh=(e,t=2)=>{let n=ro(Ba(e));return ch(Js(e=>{let r=eo(n*t**(e.attempt-1));return Js([r,r])}))},fh=e=>oh(Hc(lh(e),e=>(t,n)=>th(e(t,n),{onSuccess:e=>Js([n,e[1]]),onFailure:Ys,onDone:()=>sf(n)}))),ph=e=>{let t=Ba(e);return ch(Js(e=>Js([e.attempt-1,t])))},mh=r(2,(e,t)=>oh(Hc(lh(e),e=>{let n=sh();return(r,i)=>Rc(e(r,i),e=>{let[a,o]=e,s=t({...n(r,i),output:a,duration:o});return Rc(Bt(s)?s:Js(s),t=>t?Js(e):sf(a))})}))),hh=ph(Xa),gh=(e,t,n)=>ou(r=>Rc(n?.local?Kf(t,Uf(),r):qf(t,r),t=>ll(e,t))),_h=r(e=>Bt(e[0]),(e,t,n)=>ei(t)?ll(e,t):gh(e,Array.isArray(t)?tp(...t):t,n)),vh=r(3,(e,t,n)=>Rc(uh(t),t=>{let r=rh.defaultValue(),i,a=gl(Qs(()=>ul(e,rh,r)),fs,e=>(i=e,Rc(t(e),e=>(r=e,a))));return Ym(a,e=>Tt(()=>n(i,e)))})),yh=r(2,(e,t)=>vh(e,typeof t==`function`?t(i):ah(t)?t:xh(t),Xs)),bh=fh(hh),xh=e=>{let t=e.schedule?fh(e.schedule):bh;return e.while&&(t=mh(t,({input:t})=>{let n=e.while(t);return Bt(n)?n:Js(n)})),e.until&&(t=mh(t,({input:t})=>{let n=e.until(t);return Bt(n)?Hc(n,e=>!e):Js(!n)})),e.times!==void 0&&(t=mh(t,({attempt:t})=>Js(t<=e.times))),t},Sh=`~effect/MutableHashMap`,Ch={[Sh]:Sh,[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)}},wh=()=>{let e=Object.create(Ch);return e.backing=new Map,e.buckets=new Map,e},Th=r(2,(e,t)=>{if(e.backing.has(t))return b(e.backing.get(t));if(Eh(t))return y();let n=ve(t),r=e.buckets.get(n);return r===void 0?y():Dh(e,r,t)}),Eh=e=>typeof e!=`object`&&typeof e!=`function`,Dh=(e,t,n)=>{for(let r=0,i=t.length;r<i;r++)if(Le(n,t[r])){let n=t[r];return b(e.backing.get(n))}return y()},Oh=r(2,(e,t)=>S(Th(e,t))),kh=r(3,(e,t,n)=>{if(e.backing.has(t)||Eh(t))return e.backing.set(t,n),e;let r=ve(t),i=e.buckets.get(r);if(i===void 0)return e.buckets.set(r,[t]),e.backing.set(t,n),e;let a=Ah(i,t);return a===void 0&&(i.push(t),a=t),e.backing.set(a,n),e}),Ah=(e,t)=>{for(let n=0,r=e.length;n<r;n++)if(Le(t,e[n]))return e[n]},jh=r(2,(e,t)=>{if(Eh(t))return e.backing.delete(t),e;let n=ve(t),r=e.buckets.get(n);if(r===void 0)return e;for(let n=0,i=r.length;n<i;n++){let i=r[n];if(i===t||Le(t,i)){e.backing.delete(i),r.splice(n,1);break}}return r.length===0&&e.buckets.delete(n),e}),Mh=Bt,Nh=Au,Ph=Mu,Fh=oc,Ih=sc,w=Js,Lh=tc,Rh=Qs,zh=Zs,Bh=ic,Vh=uc,Hh=dc,T=fc,Uh=Xs,Wh=Ys,Gh=nc,Kh=rc,qh=ac,Jh=bn,Yh=$s,E=Rc,Xh=Vc,Zh=Nc,Qh=Pc,$h=jl,eg=Al,tg=Bl,ng=Hc,rg=xc,ig=Mc,ag=Fc,og=_l,sg=wl,cg=Tl,lg=pl,ug=vl,dg=El,fg=Ol,pg=xl,mg=yl,hg=yh,gg=kl,_g=Sd,vg=Ic,yg=Lc,bg=zu,xg=Rl,Sg=Ml,Cg=ol,wg=cl,Tg=_h,Eg=ll,Dg=rl,Og=il,kg=ul,Ag=su,jg=_u,Mg=fu,Ng=mu,Pg=lu,Fg=du,Ig=bu,Lg=xu,Rg=gu,zg=Su,Bg=ku,Vg=fl,D=pd,Hg=md,Ug=ld,Wg=fd,Gg=dd,Kg=Hu,qg=Uu,Jg=Ku,Yg=Wu,Xg=Ju,Zg=Zu,Qg=Xu,$g=pc,O=gc,e_=Rd(`Warn`),t_=Rd(`Error`),k=Rd(`Info`),A=Rd(`Debug`),n_=Uc,r_=Wc,i_=Gc,a_=Bc,o_=vc,s_=`~effect/BigDecimal`,c_={[s_]:s_,[_e](){let e=g_(this);return xe(Te(String(e.value)),we(e.scale))},[Ie](e){return l_(e)&&x_(this,e)===0},toString(){return`BigDecimal(${C_(this)})`},toJSON(){return{_id:`BigDecimal`,value:String(this.value),scale:this.scale}},[gt](){return this.toJSON()},pipe(){return e(this,arguments)}},l_=e=>pe(e,s_),u_=(e,t)=>{if(!Number.isSafeInteger(t))throw RangeError(`Scale must be a safe integer, got ${t}`);let n=Object.create(c_);return n.value=e,n.scale=t,n},d_=(e,t)=>{let n=u_(e,t);return n.normalized=n,n},f_=BigInt(0),p_=BigInt(1),m_=BigInt(10),h_=d_(f_,0),g_=e=>{if(e.normalized===void 0){if(e.value===f_)e.normalized=h_;else{let t=`${e.value}`,n=t.length;for(;t[n-1]===`0`;)n--;e.normalized=d_(BigInt(t.slice(0,n)),e.scale-(t.length-n))}}return e.normalized},__=100,v_=[p_],y_=(e,t)=>e===t?0:e<t?-1:1,b_=(e,t)=>{let n=`${e.value<f_?-e.value:e.value}`,r=`${t.value<f_?-t.value:t.value}`,i=BigInt(n.length-r.length)-BigInt(e.scale)+BigInt(t.scale);if(i!==f_)return i<f_?-1:1;let a=Math.max(n.length,r.length);return cr(n.padEnd(a,`0`),r.padEnd(a,`0`))},x_=(e,t)=>{if(e.scale===t.scale)return y_(e.value,t.value);let n=S_(e),r=S_(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>__)return n===-1?b_(t,e):b_(e,t);let o=v_[a]??=m_**BigInt(a);return i>0?y_(e.value,t.value*o):y_(e.value*o,t.value)},S_=e=>e.value===f_?0:e.value<f_?-1:1,C_=e=>{let t=g_(e);if(Math.abs(t.scale)>=16)return w_(t);let n=t.value<f_,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},w_=e=>{if(T_(e))return`0e+0`;let t=g_(e),n=`${t.value}`,r=t.value<f_?2:1,i=n.slice(0,r),a=n.slice(r),o=a.length-t.scale;return`${i}${a===``?``:`.${a}`}e${o>=0?`+`:``}${o}`},T_=e=>e.value===f_,E_=globalThis.BigInt,D_=e=>e>E_(2**53-1)||e<E_(-(2**53-1))?y():b(Number(e)),O_=BigInt(1),k_=BigInt(1e3),A_=BigInt(1024),j_=[{symbol:`B`,factor:O_,names:[`B`,`byte`,`bytes`]},{symbol:`kB`,factor:k_,names:[`kB`,`kilobyte`,`kilobytes`]},{symbol:`MB`,factor:k_**BigInt(2),names:[`MB`,`megabyte`,`megabytes`]},{symbol:`GB`,factor:k_**BigInt(3),names:[`GB`,`gigabyte`,`gigabytes`]},{symbol:`TB`,factor:k_**BigInt(4),names:[`TB`,`terabyte`,`terabytes`]},{symbol:`PB`,factor:k_**BigInt(5),names:[`PB`,`petabyte`,`petabytes`]},{symbol:`EB`,factor:k_**BigInt(6),names:[`EB`,`exabyte`,`exabytes`]},{symbol:`ZB`,factor:k_**BigInt(7),names:[`ZB`,`zettabyte`,`zettabytes`]},{symbol:`YB`,factor:k_**BigInt(8),names:[`YB`,`yottabyte`,`yottabytes`]},{symbol:`RB`,factor:k_**BigInt(9),names:[`RB`,`ronnabyte`,`ronnabytes`]},{symbol:`QB`,factor:k_**BigInt(10),names:[`QB`,`quettabyte`,`quettabytes`]}],M_=[j_[0],{symbol:`KiB`,factor:A_,names:[`KiB`,`kibibyte`,`kibibytes`]},{symbol:`MiB`,factor:A_**BigInt(2),names:[`MiB`,`mebibyte`,`mebibytes`]},{symbol:`GiB`,factor:A_**BigInt(3),names:[`GiB`,`gibibyte`,`gibibytes`]},{symbol:`TiB`,factor:A_**BigInt(4),names:[`TiB`,`tebibyte`,`tebibytes`]},{symbol:`PiB`,factor:A_**BigInt(5),names:[`PiB`,`pebibyte`,`pebibytes`]},{symbol:`EiB`,factor:A_**BigInt(6),names:[`EiB`,`exbibyte`,`exbibytes`]},{symbol:`ZiB`,factor:A_**BigInt(7),names:[`ZiB`,`zebibyte`,`zebibytes`]},{symbol:`YiB`,factor:A_**BigInt(8),names:[`YiB`,`yobibyte`,`yobibytes`]}];[...j_,...M_.slice(1)];var N_=D_,P_=e=>Dr(N_(e),()=>Error(`ByteSize exceeds Number.MAX_SAFE_INTEGER: ${e}`)),F_=gp,I_=bp,L_=Cp,R_=wp,z_=kp,B_=Ap,V_=jp,H_=Rp,U_=Vp,W_=Hp,G_=Up,K_=qp,q_=lm,J_=um,Y_=fm,X_=e=>Q_(typeof e==`string`?$_.encode(e):e),Z_=e=>{let t=ev(e),n=t.length;if(n%4!=0)return Ci(new Eo({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 Ci(new Eo({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=rv(t.charCodeAt(e))<<18|rv(t.charCodeAt(e+1))<<12|rv(t.charCodeAt(e+2))<<6|rv(t.charCodeAt(e+3));r[i]=n>>16,r[i+1]=n>>8&255,r[i+2]=n&255}return Si(r)}catch(e){return Ci(new Eo({kind:`Decode`,module:`Base64`,input:t,message:e instanceof Error?e.message:`Invalid input`}))}},Q_=e=>{let t=e.length,n=``,r=2;for(;r<t;r+=3)n+=tv[e[r-2]>>2],n+=tv[(e[r-2]&3)<<4|e[r-1]>>4],n+=tv[(e[r-1]&15)<<2|e[r]>>6],n+=tv[e[r]&63];return r===t+1&&(n+=tv[e[r-2]>>2],n+=tv[(e[r-2]&3)<<4],n+=`==`),r===t&&(n+=tv[e[r-2]>>2],n+=tv[(e[r-2]&3)<<4|e[r-1]>>4],n+=tv[(e[r-1]&15)<<2],n+=`=`),n},$_=new TextEncoder,ev=e=>e.replace(/[\n\r]/g,``),tv=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,nv=new Uint8Array(123).fill(255);for(let e=0;e<64;e++)nv[tv.charCodeAt(e)]=e;nv[61]=0;var rv=e=>{if(e>=nv.length||nv[e]===255)throw TypeError(`Invalid character ${String.fromCharCode(e)}`);return nv[e]},iv=`~effect/http/Cookies`,av=`~effect/http/Cookies/Cookie`,ov={[iv]:iv,...yt,toJSON(){return{_id:`effect/Cookies`,cookies:zi(this.cookies,e=>e.toJSON())}},pipe(){return e(this,arguments)}},sv=e=>{let t=Object.create(ov);return t.cookies=e,t},cv=e=>{let t={};for(let n of e)Et(t,n.name,n);return sv(t)},lv=e=>{let t=typeof e==`string`?[e]:e,n=[];for(let e of t){let t=uv(e.trim());t&&n.push(t)}return cv(n)};function uv(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(!dv.test(r))return;let i=t[0].slice(n+1),a=pv(i);if(t.length===1)return Object.assign(Object.create(fv),{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=to(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(fv),{name:r,value:a,valueEncoded:i,options:Object.keys(o).length>0?o:void 0})}var dv=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,fv={[av]:av,...yt,toJSON(){return{_id:`effect/Cookies/Cookie`,name:this.name,value:this.value,options:this.options}}},pv=e=>{try{return decodeURIComponent(e)}catch{return e}},mv=new WeakMap,hv=e=>{if(mv.has(e))return mv.get(e);throw Error(`Unable to get redacted value`+(e.label?` with label: "${e.label}"`:``))},gv=`~effect/Redacted`,_v=e=>pe(e,gv),vv=(e,t)=>{let n=Object.create(yv);return t?.label&&(n.label=t.label),mv.set(n,e),n},yv={[gv]:{_A:e=>e},label:void 0,...Rt,toJSON(){return this.toString()},toString(){return`<redacted${ee(this.label)?`:`+this.label:``}>`},[_e](){return ve(mv.get(this))},[Ie](e){return _v(e)&&Le(mv.get(this),mv.get(e))}},bv=hv,xv=e=>Nn((t,n)=>e(bv(t),bv(n))),Sv=Symbol.for(`~effect/http/Headers`),Cv=Object.defineProperties(Object.create(null),{[Sv]:{value:Sv},[$e]:{value(e){return Nv(this,ui(e,Fv))}},toJSON:{value(){return tt(this)}},[Ie]:{value(e){return Tv(this,e)}},[_e]:{value(){return De(this)}},toString:{value:yt.toString},[gt]:{value:yt[gt]}}),wv=e=>Object.assign(Object.create(Cv),e),Tv=Hi(Fn()),Ev=Object.create(Cv),Dv=e=>{if(e===void 0)return Ev;if(Symbol.iterator in e){let t=Object.create(Cv);for(let[n,r]of e)t[n.toLowerCase()]=r;return t}let t=Object.create(Cv);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},Ov=e=>Object.setPrototypeOf(e,Cv),kv=r(3,(e,t,n)=>{let r=wv(e);return r[t.toLowerCase()]=n,r}),Av=r(2,(e,t)=>wv({...e,...Dv(t)})),jv=r(2,(e,t)=>{let n=wv(e);return Object.assign(n,t),n}),Mv=r(2,(e,t)=>{let n=wv(e);return delete n[t.toLowerCase()],n}),Nv=r(2,(e,t)=>{let n={...e},r=t=>{if(typeof t==`string`){let r=t.toLowerCase();r in e&&(n[r]=vv(e[r]))}else for(let r in e)r.search(t)!==-1&&(n[r]=vv(e[r]))};if(Array.isArray(t))for(let e=0;e<t.length;e++)r(t[e]);else r(t);return n}),Pv=(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},Fv=vi(`effect/Headers/CurrentRedactedNames`,{defaultValue:()=>[`authorization`,`cookie`,`set-cookie`,`x-api-key`]}),Iv=e=>typeof e==`string`?e:bv(e),Lv=`~effect/http/UrlParams`,Rv=e=>pe(e,Lv),zv={...Rt,[Lv]:Lv,[Symbol.iterator](){return this.params[Symbol.iterator]()},[$e](e){return{_id:`UrlParams`,params:Object.fromEntries(Qv(this,ui(e,cy)))}},toJSON(){return tt(this)},[Ie](e){return Wv(this,e)},[_e](){return ke(this.params.flat())}},Bv=e=>{let t=Object.create(zv);return t.params=e,t},Vv=e=>{if(Rv(e))return e;let t=Hv(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 Bv(n)},Hv=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,Uv(r[t])]);else if(typeof r==`object`&&r&&!_v(r)){let t=Hv(r);for(let[r,i]of t)n.push([[e,...typeof r==`string`?[r]:r],i])}else r!==void 0&&n.push([e,Uv(r)]);return n},Uv=e=>_v(e)?e:String(e),Wv=Nn((e,t)=>Gv(e.params,t.params)),Gv=_a(Pi([Fn(),Qe()])),Kv=Bv([]),qv=r(2,(e,t)=>Bv(t(e.params))),Jv=r(2,(e,t)=>{let n=Vv(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 Bv(n)}),Yv=r(2,(e,t)=>qv(e,Ji(Vv(t).params))),Xv=e=>new URLSearchParams(Vv(e).params.map(([e,t])=>[e,Iv(t)])).toString(),Zv=e=>{let t={};for(let[n,r]of e.params){let e=Iv(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},Qv=r(2,(e,t)=>{let n=Array.isArray(t)?t:[t];return e.params.map(([e,t])=>[e,typeof t==`string`&&$v(e,n)?vv(t):t])}),$v=Pv,ey=(e,t=sy())=>{e.includes(`@`)&&(e=iy(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)+ay(e.slice(n+1,i),t)+e.slice(i)},ty=/^(?:(https?|ftp|wss?):[/\\]*|[a-z][a-z\d+.-]*:\/\/|[/\\]{2,})/i,ny=/[/\\?#]/,ry=/[/?#]/,iy=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=ty.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?ny:ry),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])},ay=(e,t)=>e.split(`&`).map(e=>{let n=e.indexOf(`=`);return n!==-1&&$v(oy(e.slice(0,n)),t)?e.slice(0,n+1)+`REDACTED`:e}).join(`&`),oy=e=>{if(!e.includes(`%`)&&!e.includes(`+`))return e;try{return decodeURIComponent(e.replace(/\+/g,` `))}catch{return e}},sy=()=>ui(globalThis[`~effect/Fiber/currentFiber`]?.context??ni(),cy),cy=vi(`effect/http/UrlParams/CurrentRedactedNames`,{defaultValue:()=>[`AWSAccessKeyId`,`Signature`,`sig`,`X-Goog-Signature`]});function ly(e){return e.checks?e.checks[e.checks.length-1].annotations:e.annotations}function uy(e){return t=>ly(t)?.[e]}var dy=`~structural`,fy=`~sentinels`,py=`~constructor`,my=f(e=>{let t=ly(e)?.identifier;return typeof t==`string`?t:e.getExpected(my)}),hy=Symbol(),gy=lf,_y=gy(hy),vy=gy(hy),yy=e=>e===hy?y():b(e),by=e=>e._tag===`None`?_y:gy(e.value),xy=`~effect/SchemaIssue/Issue`;function Sy(e){return pe(e,xy)&&e[xy]===xy}function Cy(e){return Object.hasOwn(e,`input`)}var wy=class{[xy]=xy;constructor(e,t){t?.reportInput===!0&&e!==hy&&(this.input=e)}},Ty=class extends wy{_tag=`Filter`;filter;issue;constructor(e,t,n,r){super(n,r),this.filter=e,this.issue=t}},Ey=class extends wy{_tag=`Encoding`;ast;issue;constructor(e,t,n,r){super(n,r),this.ast=e,this.issue=t}},Dy=class extends wy{_tag=`Pointer`;path;issue;constructor(e,t){super(),this.path=e,this.issue=t}},Oy=class extends wy{_tag=`MissingKey`;annotations;constructor(e){super(),this.annotations=e}},ky=class extends wy{_tag=`UnexpectedKey`;ast;constructor(e,t,n){super(t,n),this.ast=e}},Ay=class extends wy{_tag=`Composite`;ast;issues;constructor(e,t,n,r){super(n,r),this.ast=e,this.issues=t}},jy=class extends wy{_tag=`InvalidType`;ast;constructor(e,t,n){super(t,n),this.ast=e}},My=class extends wy{_tag=`InvalidValue`;annotations;constructor(e,t,n){super(t,n),this.annotations=e}};function Ny(e,t,n,r,i){return new Ay(e,[new Dy([t],n)],r,i)}var Py=class extends wy{_tag=`Forbidden`;annotations;constructor(e,t,n){super(t,n),this.annotations=e}},Fy=class extends wy{_tag=`AnyOf`;ast;issues;constructor(e,t,n,r){super(n,r),this.ast=e,this.issues=t}},Iy=class extends wy{_tag=`OneOf`;ast;successes;constructor(e,t,n,r){super(n,r),this.ast=e,this.successes=t}};function Ly(e,t,n){if(Sy(e))return e;if(typeof e==`string`)return new My({message:e},t,n);let r=typeof e.issue==`string`?new My({message:e.issue},t,n):e.issue;return new Dy(e.path,r)}function Ry(e,t,n){if(e!==void 0)return typeof e==`boolean`?e?void 0:new My(void 0,t,n):Ly(e,t,n)}function zy(e,t,n,r){return Array.isArray(t)?Xi(t)?t.length===1?Ly(t[0],n,r):new Ay(e,ha(t,e=>Ly(e,n,r)),n,r):void 0:Ry(t,n,r)}var By=e=>{let t=Qy(e);if(t!==void 0)return t;switch(e._tag){case`InvalidType`:return Gy(my(e.ast),e);case`InvalidValue`:{let t=Wy(e);if(t!==void 0)return Gy(t,e);let n=Uy(e);return n===void 0?`Expected a valid value`:`Invalid data ${n}`}case`MissingKey`:return`Missing key`;case`UnexpectedKey`:{let t=Uy(e);return t===void 0?`Expected no excess property`:`Unexpected key with value ${t}`}case`Forbidden`:return`Forbidden operation`;case`OneOf`:{let t=Uy(e);return t===void 0?`Expected exactly one member to match`:`Expected exactly one member to match the input ${t}`}}},Vy=e=>Qy(e)??Qy(e.issue);function Hy(e){return t=>({issues:qy(t,[],e?.leafHook??By,e?.checkHook??Vy)})}function Uy(e){return Cy(e)?ot(e.input):void 0}function Wy(e){let t=e.annotations?.expected;return typeof t==`string`?t:void 0}function Gy(e,t){let n=Uy(t);return n===void 0?`Expected ${e}`:`Expected ${e}, got ${n}`}function Ky(e,t){let n=t(e);if(n!==void 0||e.issue._tag!==`InvalidValue`)return n;let r=Wy(e.issue);return r===void 0?Gy(Jy(e.filter),e):Gy(r,e.issue)}function qy(e,t,n,r,i){switch(e._tag){case`Filter`:return qy(e.issue,t,n,r,i??Ky(e,r));case`Encoding`:return qy(e.issue,t,n,r,i);case`Pointer`:return qy(e.issue,[...t,...e.path],n,r,i);case`Composite`:case`AnyOf`:return e._tag===`Composite`||e.issues.length>0?e.issues.flatMap(e=>qy(e,t,n,r,i)):[{path:t,message:i??Qy(e)??Gy(my(e.ast),e)}];default:return[{path:t,message:i??n(e)}]}}function Jy(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=>Jy(e)).join(` & `)}}function Yy(){return e=>Zy(e,``)}var Xy=Yy();function Zy(e,t,n){let r;switch(e._tag){case`Filter`:return Zy(e.issue,t,n??Ky(e,Vy));case`Encoding`:return Zy(e.issue,t,n);case`Pointer`:return Zy(e.issue,t+lt(e.path),n);case`Composite`:case`AnyOf`:if(e._tag===`Composite`||e.issues.length>0)return e.issues.map(e=>Zy(e,t,n)).join(`
|
|
14
|
-
`);r=n??Qy(e)??Gy(my(e.ast),e);break;default:r=n??By(e)}return t?`${r}\n at ${t}`:r}function Qy(e){if(e._tag===`Pointer`||e._tag===`Composite`)return;if(e._tag===`Encoding`)return Qy(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 $y(e){let t;for(let n of e.reasons){if(!Gd(n)||!Sy(n.error))return;t??=n.error}return t}function eb(e,t){let n=$y(e);if(n===void 0)throw Error(t,{cause:e});return n}var tb=e=>Object.assign(Object.create(t),e);function nb(e){return ub((t,n)=>Uh(e(t,n)))}function rb(e){return nb((t,n)=>{let r={message:e(t)};return S(t)?new Py(r,t.value,n):new Py(r)})}var ib=rb(()=>`Encoding is not supported`),ab=tb({_tag:`Passthrough`});function ob(){return ab}function sb(e){return tb({_tag:`Transform`,transform:e})}function cb(e){return tb({_tag:`TransformEffect`,transform:e})}function lb(e){return tb({_tag:`TransformOptional`,transform:e})}function ub(e){return tb({_tag:`TransformOptionalEffect`,transform:e})}function db(){return lb(()=>y())}function fb(e){return ub(t=>{let n=Nr(t,se);return S(n)?w(n):n_(e,b)})}function pb(){return sb(globalThis.String)}function mb(){return sb(globalThis.Number)}function hb(){return cb((e,t)=>{try{return w(globalThis.BigInt(e))}catch{return Uh(new My({expected:`a value that can be converted to a bigint`},e,t))}})}function gb(e){return cb((t,n)=>qh({try:()=>JSON.parse(t,e?.reviver),catch:()=>new My({expected:`a valid JSON string`},t,n)}))}function _b(e){return cb((t,n)=>qh({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 My({expected:`a JSON-serializable value`},t,n)}))}function vb(){return sb(X_)}function yb(){return cb((e,t)=>r_(Yh(Z_(e)),()=>new My({expected:`a valid Base64 string`},e,t)))}var bb=class extends n{_tag=`Middleware`;decode;encode;constructor(e,t){super(),this.decode=e,this.encode=t}flip(){return new bb(this.encode,this.decode)}},xb=`~effect/SchemaTransformation/Transformation`,Sb=class extends n{[xb]=xb;_tag=`Transformation`;decode;encode;constructor(e,t){super(),this.decode=e,this.encode=t}flip(){return new Sb(this.encode,this.decode)}};function Cb(e){return pe(e,xb)&&e[xb]===xb}var wb=e=>Cb(e)?e:new Sb(e.decode,e.encode);function Tb(e){return new Sb(cb(e.decode),cb(e.encode))}function Eb(e){return new Sb(sb(e.decode),sb(e.encode))}function Db(e){return new Sb(lb(e.decode),lb(e.encode))}var Ob=new Sb(ob(),ob());function kb(){return Ob}var Ab=new Sb(mb(),pb()),jb=new Sb(hb(),pb()),Mb=e=>de(e)&&typeof e.message==`string`,Nb=e=>{let t=Object.hasOwn(e,`cause`)?Error(e.message,{cause:Lb(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},Pb=e=>{try{let t=pt(e);return t===void 0?ot(e):JSON.parse(t)}catch{return ot(e)}},Fb=(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},Ib=e=>{let t=new WeakSet,n=r=>{if(he(r)){if(t.has(r))return`[Circular]`;t.add(r);let i=Fb(r,e,n);return t.delete(r),i}return Pb(r)};return n},Lb=e=>Mb(e)?Nb(e):e,Rb=e=>Eb({decode:Lb,encode:Ib(e)});function zb(){return Eb({decode:wr,encode:C})}function Bb(){return Db({decode:b,encode:Ar})}var Vb=Tb({decode:(e,t)=>URL.canParse(e)?w(new URL(e)):Uh(new My({expected:`a valid URL string`},e,t)),encode:e=>w(e.href)}),Hb=new Sb(yb(),vb());function Ub(e){return new Sb(gb(e??{}),_b(e))}function Wb(e){return t=>t._tag===e}var Gb=Wb(`Declaration`),Kb=Wb(`Null`),qb=Wb(`Void`),Jb=Wb(`Never`),Yb=Wb(`Literal`),Xb=Wb(`UniqueSymbol`),Zb=Wb(`Arrays`),Qb=Wb(`Objects`),$b=Wb(`Union`),ex=Wb(`Suspend`),tx=class{to;transformation;constructor(e,t){this.to=e,this.transformation=t}},nx={},rx=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}},ix=`~effect/Schema`,ax=class{[ix]=ix;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}>`}},ox=class extends ax{_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===hy)return _y;e??=this.run(this.typeParameters);try{return e(t,this,n)}catch(e){return Kh(e)}}}_rebuild(e,t,n,r,i){let a=jS(this.typeParameters,e);return a===this.typeParameters&&t===this.checks&&n===this.encodingChecks&&r===this.run&&i===this.encodingRun?this:new ox(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>`}},sx=new class extends ax{_tag=`Null`;getParser(){return YS(this,null)}getExpected(){return`null`}},cx=class extends ax{_tag=`Undefined`;getParser(){return YS(this,void 0)}toCodecJson(){return yS(this,[lx])}getExpected(){return`undefined`}},lx=new tx(sx,new Sb(sb(()=>void 0),sb(()=>null))),ux=new cx,dx=new class extends ax{_tag=`Void`;getParser(){let e=gy(void 0);return t=>t===hy?_y:e}toCodecJson(){return yS(this,[lx])}getExpected(){return`void`}},fx=new class extends ax{_tag=`Never`;getParser(){return XS(this,le)}getExpected(){return`never`}},px=new class extends ax{_tag=`Unknown`;getParser(){return XS(this,ue)}getExpected(){return`unknown`}},mx=class extends ax{_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 YS(this,this.literal)}matchPart(e,t){return e===globalThis.String(this.literal)?this.literal:void 0}toCodecJson(){return typeof this.literal==`bigint`?hx(this):this}toCodecStringTree(){return typeof this.literal==`string`?this:hx(this)}getExpected(){return typeof this.literal==`string`?JSON.stringify(this.literal):globalThis.String(this.literal)}};function hx(e){let t=globalThis.String(e.literal);return yS(e,[new tx(new mx(t),new Sb(sb(()=>e.literal),sb(()=>t)))])}var gx=new class extends ax{_tag=`String`;getParser(){return XS(this,ee)}matchPart(e,t){let n=this.checks;return n&&!t.disableChecks&&cC(n,e,void 0,this,t)?void 0:e}getExpected(){return`string`}},_x=class extends ax{_tag=`Number`;getParser(){return XS(this,te)}matchKey(e,t){return this._match(eC,e,t)}matchPart(e,t){return this._match($S,e,t)}_match(e,t,n){if(!e.test(t))return;let r=globalThis.Number(t);return n.disableChecks||!this.checks?r:cC(this.checks,r,void 0,this,n)?void 0:r}toCodecJson(){return this.checks&&(vx(this.checks,`effect/schema/isFinite`)||vx(this.checks,`effect/schema/isInt`))?this:yS(this,[mS])}toCodecStringTree(){return this.toCodecJson()===this?yS(this,[rC]):yS(this,[iC])}getExpected(){return`number`}};function vx(e,t){return e.some(e=>e.annotations?.representation?.id===t||e._tag===`FilterGroup`&&vx(e.checks,t))}var yx=new _x,bx=new class extends ax{_tag=`Boolean`;getParser(){return XS(this,ne)}getExpected(){return`boolean`}},xx=new class extends ax{_tag=`BigInt`;getParser(){return XS(this,re)}matchPart(e,t){if(!aC.test(e))return;let n=globalThis.BigInt(e);return t.disableChecks||!this.checks?n:cC(this.checks,n,void 0,this,t)?void 0:n}toCodecStringTree(){return yS(this,[sC])}getExpected(){return`bigint`}},Sx=class extends ax{_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(BS(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(BS(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 ky(n,t[o],i),a=new Dy([o],r);if(i.errors===`all`)e.issues?e.issues.push(a):e.issues=[a];else return Uh(new Ay(n,[a],t,i))}return e.issues?Uh(new Ay(n,e.issues,t,i)):gy(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:Pu(t.concurrency),f=d===1?Tx(i,e,0,u):Ex(i,e,{concurrency:d,end:u});if(!f)return c(i);if(zc(f))return a_(f,()=>c(i));let p=!0;return Rh(()=>p?(p=!1,E(f,()=>c(i))):l(e,t))};return(e,a)=>{if(e===hy)return _y;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)):Uh(new jy(n,e,a))}catch(e){return Kh(e)}}}_rebuild(e,t,n){let r=jS(this.elements,e),i=jS(this.rest,e);return r===this.elements&&i===this.rest&&t===this.checks&&n===this.encodingChecks?this:new Sx(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 Cx(e,t,n,r){if(n._tag===`Failure`)return Dx(e,e.ast,r,n);let i=n===vy?t:n[Mt];if(i!==hy)e.output[r]=i;else{let t=e.getParser(e.tailThreshold,r);if(BS(t.ast))return;let n=new Dy([r],new Oy(t.ast.context?.annotations));if(e.options.errors===`all`)e.issues?e.issues.push(n):e.issues=[n];else return df(new Ay(e.ast,[n],e.input,e.options))}}var wx={onItem(e,t,n){let r=n<e.len?t:hy;return e.getParser(e.tailThreshold,n).parser(r,e.options)},step:Cx},Tx=Fu()(wx),Ex=Lu()(wx),Dx=(e,t,n,r)=>{if(r.cause.reasons.length===0)return r;let i=$y(r.cause);if(i===void 0)return uf($d(r.cause,r=>new Ay(t,[new Dy([n],r)],e.input,e.options)));let a=new Dy([n],i);if(e.options.errors===`all`)e.issues?e.issues.push(a):e.issues=[a];else return df(new Ay(t,[a],e.input,e.options))},Ox=`[+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:[Ee][+-]?\\d+)?`;function kx(e,t,n=nx){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(ZS(GS(t)))}var Ax=class{name;type;constructor(e,t){this.name=e,this.type=t}};function jx(e){switch(e._tag){case`String`:case`Number`:case`Symbol`:case`TemplateLiteral`:return!0;case`Union`:return e.types.every(jx);default:return!1}}function Mx(e){let t=xS(e);switch(t._tag){case`String`:case`Number`:case`Symbol`:case`TemplateLiteral`:return!0;case`Union`:return t.types.every(Mx);default:return!1}}function Nx(e){return jx(e)&&Mx(e)}var Px=class{parameter;type;constructor(e,t){if(!Nx(e))throw Error(`Invalid index signature parameter ${e._tag}`);if(this.parameter=e,this.type=t,BS(t)&&!JS(t))throw Error("Cannot use `Schema.optionalKey` with index signatures, use `Schema.optional` instead.")}},Fx=class extends ax{_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 XS(n,ce);let a,o,s=()=>(a||(a=n.propertySignatures.map(e=>({parser:t(e.type),name:e.name,type:e.type})),o=i?n.indexSignatures.map(n=>({is:n,parserKey:e(ZS(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 Dx(t,n,i,s)??ff;let c=s===vy?o:s[Mt];if(a!==hy&&c!==hy){if(r&&(e.has(i)||e.has(typeof a==`number`?globalThis.String(a):a)))return ff;Et(t.out,a,c)}return ff},c=(e,r,i,a)=>{if(!a){let t=i.parserKey(r,e.options);if(!zc(t))return E(tg(t),t=>c(e,r,i,t));a=t}if(a._tag===`Failure`)return Dx(e,n,r,a)??ff;let o=a===vy?r:a[Mt],s=e.input[r],l=i.parserValue(s,e.options);return zc(l)?t(e,r,o,s,l):E(tg(l),n=>t(e,r,o,s,n))},l=(e,n,r)=>{let i=e.input[n],a=r.parserValue(i,e.options);return zc(a)?t(e,n,n,i,a):E(tg(a),r=>t(e,n,n,i,r))},u=i?Lu()({onItem:(e,[t,n])=>n.is.parameter===gx?l(e,t,n):c(e,t,n),step:(e,t,n)=>n._tag===`Failure`?n:void 0}):void 0;return o_(function*(t,d){if(t===hy)return hy;if(typeof t!=`object`||!t||Array.isArray(t))return yield*Uh(new jy(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:Pu(d.concurrency),v=i&&g?n.indexSignatures.map(e=>kx(f,e.parameter,d)):void 0;if(g){let r=v?new Set(e):e;if(v)for(let e of v)for(let t of e)r.add(t);let i=Reflect.ownKeys(f);for(let e=0;e<i.length;e++){let a=i[e];if(!r.has(a)&&Object.prototype.propertyIsEnumerable.call(f,a)){let e=new ky(n,f[a],d),r=new Dy([a],e);if(h){m.issues?m.issues.push(r):m.issues=[r];continue}return yield*Uh(new Ay(n,[r],t,d))}}}if(r){let e=_===1?Rx(m,a):zx(m,a,{concurrency:_});e&&(yield*e)}if(i&&_===1)for(let e=0;e<i;e++){let t=o[e],n=t.is.parameter===gx?l:c,r=v?.[e]??(t.is.parameter===gx?Object.keys(f):kx(f,t.is.parameter,d));for(let e=0;e<r.length;e++){let i=n(m,r[e],t);if(!zc(i))yield*i;else if(i._tag===`Failure`)return yield*i}}else if(u){let e=pa();for(let t=0;t<i;t++){let n=o[t],r=v?.[t]??(n.is.parameter===gx?Object.keys(f):kx(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*Uh(new Ay(n,m.issues,t,d)):p})};if(i)return c();let l,u=(e,t,n)=>{let r=a[t];return E(tg(n),n=>{let i={...e,out:{...e.out}},o=Ix(i,r,n);if(o)return o;let s=()=>gy(i.out),c=Rx(i,a.slice(t+1));return c?a_(c,s):s()})};return(e,t)=>{if(e===hy)return _y;if(t.errors===`all`||t.onExcessProperty!==void 0||t.concurrency!==void 0&&Pu(t.concurrency)!==1)return(l??=c())(e,t);if(typeof e!=`object`||!e||Array.isArray(e))return Uh(new jy(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=Qx(i,s),l=c?i[s]:hy,d=n.parser(l,t);if(!zc(d))return u(o,e,d);if(d===vy){c&&Et(a,s,l);continue}let f=Ix(o,n,d);if(f)return f}}catch(e){return Kh(e)}return gy(a)}}_rebuild(e,t,n,r){let i=jS(this.propertySignatures,t=>{let n=e(t.type);return n===t.type?t:new Ax(t.name,n)}),a=jS(this.indexSignatures,n=>{let r=t(n.parameter),i=e(n.type);return r===n.parameter&&i===n.type?n:new Px(r,i)});return i===this.propertySignatures&&a===this.indexSignatures&&n===this.checks&&r===this.encodingChecks?this:new Fx(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 Ix(e,t,n){if(n._tag===`Failure`)return Dx(e,e.ast,t.name,n);if(n===vy)return;let r=n[Mt];if(r!==hy)Et(e.out,t.name,r);else if(delete e.out[t.name],!BS(t.type)){let n=new Dy([t.name],new Oy(t.type.context?.annotations));if(e.options.errors===`all`){e.issues?e.issues.push(n):e.issues=[n];return}return df(new Ay(e.ast,[n],e.input,e.options))}}var Lx={onItem(e,t){if(!Qx(e.input,t.name))return t.parser(hy,e.options);let n=e.input[t.name];return Et(e.out,t.name,n),t.parser(n,e.options)},step:Ix},Rx=Fu()(Lx),zx=Lu()(Lx);function Bx(e,t){return e?t?[...e,...t]:e:t}function Vx(e,t,n){return new Fx(Reflect.ownKeys(e).map(t=>new Ax(t,e[t].ast)),[],n,t)}function Hx(e){return e.ast}function Ux(e,t=void 0){return new Sx(!1,e.map(e=>e.ast),[],void 0,t)}function Wx(e,t,n){return new eS(e.map(Hx),t,void 0,n)}function Gx(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=Bx(i,e.checks)}return new Fx(n,r,void 0,i)}var Kx=p(e=>{for(;;){if(ex(e))return px;let t=e.encoding;if(!t)return e.recur?.(Kx,i)??e;if(t.some(e=>e.transformation._tag===`Middleware`&&e.transformation.decode!==i))return px;e=t[t.length-1].to}});function qx(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(qx)));default:return[`null`,`undefined`,`string`,`number`,`boolean`,`symbol`,`bigint`,`object`,`array`,`function`]}}function Jx(e){switch(e._tag){default:return[];case`Declaration`:{let t=e.annotations?.[fy];return Array.isArray(t)?t:[]}case`Objects`:return e.propertySignatures.flatMap(e=>{let t=e.type;if(!BS(t)){if(Yb(t))return[{key:e.name,literal:t.literal}];if(Xb(t))return[{key:e.name,literal:t.symbol}]}return[]});case`Arrays`:return e.elements.flatMap((e,t)=>{if(!BS(e)){if(Yb(e))return[{key:t,literal:e.literal}];if(Xb(e))return[{key:t,literal:e.symbol}]}return[]});case`Union`:{if(e.types.length===0)return[];let t=e.types.map(e=>Jx(Kx(e)));return t[0].filter(e=>t.every(t=>t.some(t=>t.key===e.key&&t.literal===e.literal)))}case`Suspend`:return Jx(e.thunk())}}var Yx=new WeakMap,Xx=Object.freeze([]),Zx=e=>e===null?`null`:Array.isArray(e)?`array`:typeof e,Qx=(e,t)=>t===`__proto__`?Object.hasOwn(e,t):t in e;function $x(e){let t=Yx.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=Kx(c);if(Jb(l))continue;if(Yb(l)||Xb(l)){a??=new Map;let e=Yb(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=Jx(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=qx(l);for(let n of e)(i[n]??=[]).push(t)}}let c={},l=e=>c[e]??=Object.freeze(i?.[e]??Xx);if(o&&a)a.forEach(Object.freeze),t=e=>a.get(e)??Xx;else if(n?.size===1&&!i){let[r,[i]]=n.entries().next().value,a=new Map;for(let[e,t]of i)a.set(e,Object.freeze(Array.from(t)));let o=Object.freeze(e.map((e,t)=>t));t=(e,t)=>{if(fe(e)){let n=Qx(e,r)?e[r]:void 0;if(n!==void 0)return a.get(n)??Xx;if(t)return o}return Xx}}else if(n){let e;for(let t of n)(!e||t[1][0].size>e[1][0].size)&&t[1][1].size===r&&(e=t);t=(t,r)=>{let a=Zx(t);if(!fe(t))return l(a);let o=new Set(i?.[a]),s;if(e){let[n,[i]]=e,c=Qx(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=Qx(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=Qx(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(Zx(e));return a?t.filter(t=>s[t]===void 0||s[t]===e):t};return Yx.set(e,t),t}var eS=class extends ax{_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===hy)return _y;let i=(o??=$x(n.types))(e,r);if(i.length===0)return Uh(new Fy(n,[],e,t));if(i.length===1){let r=a(i[0])(e,t);return r._tag===`Success`?r:zc(r)?tS(n,r.cause,e,t):nS(n,r,e,t)}return rS(n,a,i,e,t)}}_rebuild(e,t,n){let r=jS(this.types,e);return r===this.types&&t===this.checks&&n===this.encodingChecks?this:new eS(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=GS(t);switch(n._tag){case`Arrays`:{let t=n.elements.filter(Yb);if(t.length>0)return`${sS(n.isMutable)}[ ${t.map(t=>e(t)+cS(t.context?.isOptional)).join(`, `)}, ... ]`;break}case`Objects`:{let t=n.propertySignatures.filter(e=>Yb(e.type));if(t.length>0)return`{ ${t.map(t=>`${sS(t.type.context?.isMutable)}${ct(t.name)}${cS(t.type.context?.isOptional)}: ${e(t.type)}`).join(`, `)}, ... }`;break}}return e(n)});return Array.from(new Set(n)).join(` | `)}};function tS(e,t,n,r){let i=$y(t);return i?df(new Fy(e,[i],n,r)):uf(t)}function nS(e,t,n,r){return lg(t,t=>tS(e,t,n,r))}function rS(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=aS(a,n);if(!o)return a.out?a.out:Uh(new Fy(e,a.issues??[],r,i));if(zc(o))return iS(o,a);let s=!0;return Rh(()=>s?(s=!1,iS(o,a)):rS(e,t,n,r,i))}function iS(e,t){return a_(e,e=>t.out===vy?w(t.input):t.out?t.out:Uh(new Fy(t.ast,t.issues??[],t.input,t.options)))}var aS=Fu()({onItem(e,t){return e.parser(t)(e.input,e.options)},step(e,t,n){if(n._tag===`Failure`){let t=$y(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]),df(new Iy(e.ast,e.successes,e.input,e.options));if(e.out=n,e.successes)e.successes.push(e.ast.types[t]);else return ff}}}),oS=new eS([new mx(`Infinity`),new mx(`-Infinity`),new mx(`NaN`)]);function sS(e){return e?``:`readonly `}function cS(e){return e?`?`:``}var lS=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 lS(this.run,{...this.annotations,...e},this.aborted)}abort(){return new lS(this.run,this.annotations,!0)}and(e,t){return new uS([this,e],t)}},uS=class extends n{_tag=`FilterGroup`;checks;annotations;constructor(e,t=void 0){super(),this.checks=e,this.annotations=t}annotate(e){return new uS(this.checks,{...this.annotations,...e})}and(e,t){return new uS([this,e],t)}};function dS(e,t,n=!1){return new lS((t,n,r)=>zy(n,e(t,n,r),t,r),t,n)}function fS(e){return dS(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 pS=wS(yx,[fS()]),mS=new tx(new eS([pS,oS]),new Sb(mb(),sb(e=>globalThis.Number.isFinite(e)?e:globalThis.String(e))));function hS(e,t){let n=new globalThis.RegExp(e),r={source:n.source,flags:n.flags};return dS(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 gS=new WeakMap;function _S(e,t){let n=Object.assign(Object.create(Object.getPrototypeOf(e)),e,t);return Reflect.ownKeys(t).every(e=>e===`context`||e===`encoding`)&&gS.set(n,vS(e)),n}function vS(e){let t=gS.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 gS.set(e,n),n}function yS(e,t){return e.encoding===t?e:_S(e,{encoding:t})}function bS(e,t){if(e.context===t)return e;let n=vS(e);return n.context===t&&n.encoding===e.encoding?n:_S(e,{context:t})}function xS(e){return e.encoding?xS(e.encoding[e.encoding.length-1].to):e}function SS(e,t){if(e.checks){let n=e.checks[e.checks.length-1];return CS(e,qi(e.checks.slice(0,-1),n.annotate(t)))}return _S(e,{annotations:{...e.annotations,...t}})}function CS(e,t){if(e._tag===`Suspend`&&t)throw Error(`Cannot add checks to Suspend`);return e.checks===t?e:_S(e,{checks:t})}function wS(e,t){return CS(e,Bx(e.checks,t))}function TS(e,t){let n=t(e.to);return n===e.to?e:new tx(n,e.transformation)}function ES(e,t){let n=e,r=n[n.length-1],i=TS(r,t);return i===r?e:qi(e.slice(0,e.length-1),i)}function DS(e){return t=>t.encoding?yS(t,ES(t.encoding,e)):t}function OS(e,t){return DS(e=>bS(e,t))(e)}function kS(e,t){function n(r){if(r.encoding){let e=r.encoding[r.encoding.length-1];return t?.stopAt?.(e)?r:yS(r,ES(r.encoding,n))}return e(r)}return p(n)}function AS(e,t,n){let r=new tx(e,t);return yS(n,n.encoding?[...n.encoding,r]:[r])}function jS(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 MS(e,t){return bS(e,e.context?new rx(e.context.isOptional,e.context.isMutable,e.context.constructorDefault,{...e.context.annotations,...t}):new rx(!1,!1,void 0,t))}var NS=p(e=>PS(bS(e,e.context?e.context.isOptional===!1?new rx(!0,e.context.isMutable,e.context.constructorDefault,e.context.annotations):e.context:new rx(!0,!1)))),PS=DS(NS),FS=f(e=>NS(new eS([e,ux])));function IS(e,t){return bS(e,e.context?new rx(e.context.isOptional,e.context.isMutable,t,e.context.annotations):new rx(!1,!1,t))}function LS(e,t,n){return AS(e,n,t)}function RS(e){let t=[],n=[];function r(e){switch(e._tag){case`Literal`:ae(e.literal)&&!t.includes(e.literal)&&t.push(e.literal);return;case`UniqueSymbol`:t.includes(e.symbol)||t.push(e.symbol);return;case`Never`:return;case`Union`:for(let t=0;t<e.types.length;t++)r(e.types[t]);return;default:n.push(e)}}return r(e),{literals:t,parameters:n}}function zS(e,t){let{literals:n,parameters:r}=RS(e);return new Fx(n.map(e=>new Ax(e,t)),r.map(e=>new Px(e,t)))}function BS(e){return e.context?.isOptional??!1}function VS(e){return e.annotations?.[`~structural`]===!0||e._tag===`FilterGroup`&&e.checks.every(VS)}function HS(e){function t(e){return VS(e)?[e]:e._tag===`FilterGroup`?e.checks.flatMap(t):[]}let n=e.flatMap(t);return Yi(n)?n:void 0}function US(e){let t=!0;function n(e){return t=t&&!e.encoding&&!ex(e),t&&`recur`in e&&e.recur(n),e}return`recur`in e&&e.recur(n),t}var WS=p(e=>{let t=vS(e);if(t!==e){let n=WS(t);return n===t&&e.encoding===void 0?e:bS(n,e.context)}let n=`recur`in e?e.recur(WS):e;if(`encodingChecks`in n&&n.encodingChecks){let t=US(e)?n.encodingChecks:Zb(n)||Qb(n)||Gb(n)&&n.typeParameters.length>0?HS(n.encodingChecks):void 0;return _S(n,{encodingChecks:void 0,checks:Bx(n.checks,t)})}return n}),GS=p(e=>WS(qS(e)));function KS(e,t){let n=t,r=n.length,i=n[r-1],a=[new tx(qS(yS(e,void 0)),n[0].transformation.flip())];for(let e=1;e<r;e++)a.unshift(new tx(qS(n[e-1].to),n[e].transformation.flip()));let o=qS(i.to);return o.encoding?yS(o,[...o.encoding,...a]):yS(o,a)}var qS=f(e=>{if(e.encoding)return KS(e,e.encoding);let t=vS(e);if(t!==e){let n=qS(t);return n===t?e:bS(n,e.context)}return`flip`in e?e.flip(qS):`recur`in e?e.recur(qS):e});function JS(e){switch(e._tag){case`Undefined`:return!0;case`Union`:return e.types.some(JS);default:return!1}}function YS(e,t){let n=t===0?vy:gy(t);return(r,i)=>r===hy?_y:r===t?n:Uh(new jy(e,r,i))}function XS(e,t){return(n,r)=>n===hy?_y:t(n)?vy:Uh(new jy(e,n,r))}var ZS=kS(e=>{switch(e._tag){default:return e;case`Number`:return e.toCodecStringTree();case`Union`:return e.recur(ZS)}}),QS=kS(e=>{switch(e._tag){default:return e;case`Symbol`:case`UniqueSymbol`:return e.toCodecStringTree();case`Union`:return e.recur(QS)}}),$S=new globalThis.RegExp(`^${Ox}$`),eC=new globalThis.RegExp(`^(?:${Ox}|Infinity|-Infinity|NaN)$`);function tC(e){return hS($S,{expected:`a string representing a finite number`,representation:{id:`effect/schema/isStringFinite`,payload:null},toJsonSchema:()=>({pattern:$S.source}),...e})}var nC=wS(gx,[tC()]),rC=new tx(nC,Ab),iC=new tx(new eS([nC,oS]),Ab),aC=new globalThis.RegExp(`^-?\\d+$`);function oC(e){return hS(aC,{expected:`a string representing a bigint`,representation:{id:`effect/schema/isStringBigInt`,payload:null},toJsonSchema:()=>({pattern:aC.source}),...e})}var sC=new tx(wS(gx,[oC({expected:`a string representing a bigint`})]),jb);function cC(e,t,n,r,i){for(let a=0;a<e.length;a++){let o=e[a];if(o._tag===`FilterGroup`){if(n=cC(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 Ty(o,e,t,i);if(n?n.push(r):n=[r],i.errors!==`all`||o.aborted)return n}}}return n}function lC(e){if(!Gb(e))return;let t=e.annotations?.[py];return oe(t)?t(e.typeParameters):void 0}var uC=ly,dC=uy;function fC(e){return e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&globalThis.Number.isFinite(e)}function pC(e){return e===void 0||typeof e==`string`}function mC(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 hC(e){return mC(e,fC)}var gC=new ox([],()=>(e,t,n)=>hC(e)?vy:Uh(new jy(t,e,n)),{representation:{id:`effect/schema/Json`,payload:null},expected:`JSON value`,toCodecJson:()=>void 0,toCodecStringTree:()=>bC}),_C=new tx(gC,kb()),vC=new tx(new eS([new Sx(!1,[],[gC]),new Fx([],[new Px(gx,gC)])]),kb());function yC(e){return mC(e,pC)}var bC=new tx(new ox([],()=>(e,t,n)=>yC(e)?vy:Uh(new jy(t,e,n)),{expected:`StringTree`,toCodecStringTree:()=>void 0}),kb()),xC=(e,t,n)=>e===vy?n(t):a_(e,n);function SC(e){let t=CC(e);return(e,n,r)=>{try{return t(e,n,r)}catch(e){return Kh(e)}}}function CC(e){if(e._tag===`Middleware`)return(t,n,r)=>wC(t===vy?e.decode(gy(yy(n)),r):e.decode(n_(t,yy),r));let t=e.decode;switch(t._tag){case`Passthrough`:return(e,t)=>e===vy?gy(t):e;case`Transform`:{let e=e=>e===hy?_y:gy(t.transform(e));return(t,n)=>xC(t,n,e)}case`TransformOptional`:{let e=e=>by(t.transform(yy(e)));return(t,n)=>xC(t,n,e)}case`TransformEffect`:return(e,n,r)=>xC(e,n,e=>e===hy?_y:t.transform(e,r));case`TransformOptionalEffect`:return(e,n,r)=>xC(e,n,e=>wC(t.transform(yy(e),r)))}}var wC=e=>a_(e,by),TC=(e,t,n,r)=>lg(r,r=>Gh(()=>$d(r,r=>new Ey(e,r,t,n))));function EC(e,t){let n=SC(e.link.transformation),r;return(i,a)=>{if(i===hy)return _y;if(e.isConstructed(i))return vy;let o=(r??=t(e.link.to))(i,a);return n(o,i,a)}}function DC(e,t){let n=e.context.constructorDefault;return(r,i)=>{if(r!==hy&&r!==void 0)return t(r,i);let a=n;if(zc(a)&&a._tag===`Success`){let e=t(a[Mt],i);return e===vy?a:e}return a_(TC(e,r,i,a),e=>{let n=t(e,i);return n===vy?gy(e):n})}}function OC(e,t){let n=t(e);return e.context?.constructorDefault===void 0?n:DC(e,n)}function kC(e,t,n,r,i){if(e._tag===`Declaration`)for(let n of e.typeParameters)t(n);let a=n?lC(e):void 0,o=a?EC(a,t):r??e.getParser(t,n),s=e.checks,c=e.encoding,l=c?.map(e=>SC(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(zc(r)){if(r._tag===`Success`){let i=r===vy?t:r[Mt];if(t!==hy&&i!==hy){let i=cC(u,t,void 0,e,n);i&&(r=Uh(new Ay(e,i,t,n)))}}}else r=E(r,r=>{if(t!==hy&&r!==hy){let r=cC(u,t,void 0,e,n);if(r)return Uh(new Ay(e,r,t,n))}return w(r)})}if(s&&!n.disableChecks){if(zc(r)){if(r._tag===`Success`){let i=r===vy?t:r[Mt];if(i===hy)return r;let a=cC(s,i,void 0,e,n);a&&(r=Uh(new Ay(e,a,i,n)))}}else r=E(r,t=>{if(t!==hy){let r=cC(s,t,void 0,e,n);if(r)return Uh(new Ay(e,r,t,n))}return w(t)})}return r}catch(e){return Kh(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=a_(o,e=>{let n=t(e,r);return n===vy?gy(e):n})}if(o._tag===`Success`){let e=o[Mt],t=p(e,r);return t===vy?o:t}return o=TC(e,n,r,o),a_(o,e=>{let t=p(e,r);return t===vy?gy(e):t})}:p}var AC=Symbol(),jC=new WeakMap,MC=e=>IC(e).parser,NC=e=>IC(e).makeEffect,PC=e=>OC(e,NC),FC=class{ast;constructor(e){this.ast=e}get decodeEffect(){return this.cachedDecodeEffect??=kC(this.ast,MC)}get parser(){return this.decodeEffect}get makeEffect(){return this.cachedMakeEffect??=kC(this.ast,NC,PC)}};function IC(e){let t=jC.get(e);if(t!==void 0)return t;let n=new FC(e);return jC.set(e,n),n}function LC(e){let t=e.ast,n;return(e,r)=>(n??=ZC(rw,WS(t)))(e,r?.disableChecks?r?.parseOptions?{...r.parseOptions,disableChecks:!0}:{disableChecks:!0}:r?.parseOptions)}function RC(e){let t=LC(e);return(e,n)=>{let r=Qg(t(e,n));return pf(r)?b(r.value):(eb(r.cause,`Option adapter can only return none for schema issues`),y())}}function zC(e){return tw(WS(e.ast))}function BC(e){return HC(e.ast)}function VC(e){{let t=QC(YC(e));return e=>{let n=t(e,nx);return pf(n)?!0:(eb(n.cause,`Type guard adapter can only return false for schema issues`),!1)}}}function HC(e){let t=WS(e),n=e=>(n=VC(t),n(e));return e=>n(e)}function UC(e,t){let n=YC(e.ast);return t===void 0?n:(e,r)=>n(e,qC(t,r))}function WC(e,t){return $C(UC(e,t))}var GC=WC;function KC(e,t){let n=YC(qS(e.ast));return t===void 0?n:(e,r)=>n(e,qC(t,r))}var qC=(e,t)=>t?{...e,...t}:e,JC=e=>e===hy?Uh(new My):w(e);function YC(e){return ZC(nw,e)}function XC(e,t){return e===vy?w(t):zc(e)?e[`~effect/Effect/args`]===hy?JC(hy):e:a_(e,JC)}function ZC(e,t){let n;return(r,i)=>{let a=(n??=e(t))(r,i??nx);return a===vy?w(r):zc(a)?a[`~effect/Effect/args`]===hy?JC(hy):a:a_(a,JC)}}function QC(e){return(t,n)=>Qg(e(t,n))}function $C(e){let t=QC(e);return(e,n)=>{let r=t(e,n);return pf(r)?b(r.value):(eb(r.cause,`Option adapter can only return none for schema issues`),y())}}function ew(e,t){let n=Qg(e);if(pf(n))return n.value;let r=eb(n.cause,t);throw Error(`Schema validation failed`,{cause:r})}function tw(e){let t,n;return(r,i)=>{t??=IC(e);let a=i?.disableChecks?i.parseOptions?{...i.parseOptions,disableChecks:!0}:{disableChecks:!0}:i?.parseOptions??nx,o=t.make;if(o!==void 0&&r!==hy){let e;try{e=o(r,a)}catch(e){throw eb(Jd(e),`Constructor adapter can only throw schema issues`),e}if(e!==AC&&e!==hy)return e}return ew(XC((n??=t.makeEffect)(r,a),r),`Constructor adapter can only throw schema issues`)}}var nw=e=>IC(e).parser,rw=e=>IC(e).makeEffect,iw=`~effect/Schema/Schema`,aw=Symbol(),ow={[iw]:iw,get make(){let e=zC(this);return Object.defineProperty(this,"make",{value:e,enumerable:!0}),e},get makeEffect(){let e=LC(this);return Object.defineProperty(this,"makeEffect",{value:e,enumerable:!0}),e},get makeOption(){let e=RC(this);return Object.defineProperty(this,"makeOption",{value:e,enumerable:!0}),e},pipe(){return e(this,arguments)},annotate(e){return this.rebuild(SS(this.ast,e))},annotateKey(e){return this.rebuild(MS(this.ast,e))},check(...e){return this.rebuild(wS(this.ast,e))},rebuild(e){return sw(e,this[aw])}};function sw(e,t){function n(){}let r=Object.setPrototypeOf(n,ow);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[aw]=t,r.ast=e,r}function cw(e){return sw(lw(e.ast),{schema:e})}var lw=kS(e=>{let t=vS(e);if(t!==e){let n=lw(t);if(n===t)return e;if(n.encoding===void 0)return bS(n,e.context)}let n=mw(e,lw),r=e.context;return n===e||r===void 0?n:OS(n,uw(r))});function uw(e){return e.constructorDefault===void 0?e:new rx(e.isOptional,e.isMutable,void 0,e.annotations)}function dw(e){if(e.propertySignatures.some(e=>typeof e.name!=`string`))throw new globalThis.Error(`Objects property names must be strings`,{cause:e})}function fw(e){return t=>{let n=[...t].sort((t,n)=>e(GS(t))-e(GS(n)));return n.some((e,n)=>e!==t[n])?n:t}}var pw=fw(e=>{switch(e._tag){case`BigInt`:case`Symbol`:case`UniqueSymbol`:return 0;default:return 1}});function mw(e,t){switch(e._tag){case`Declaration`:{let n=e.annotations?.toCodecJson??e.annotations?.toCodec;if(!oe(n))return yS(e,[_C]);let r=n(e.typeParameters.map(e=>sw(GS(e))));return r===void 0?e:yS(e,[TS(r,t)])}case`Unknown`:return yS(e,[_C]);case`ObjectKeyword`:return yS(e,[vC]);case`Undefined`:case`Void`:case`Literal`:case`Number`:return e.toCodecJson();case`UniqueSymbol`:case`Symbol`:case`BigInt`:return e.toCodecStringTree();case`Objects`:return dw(e),e.recur(t,QS);case`Union`:{let n=pw(e.types);return n===e.types?e.recur(t):new eS(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 hw(e){return sw(xw(e.ast),{schema:e})}var gw=fw(e=>{switch(e._tag){case`Null`:case`Boolean`:case`Number`:case`BigInt`:case`Symbol`:case`UniqueSymbol`:return 0;default:return 1}});function _w(e,t,n){switch(e._tag){case`Declaration`:{let r=e.typeParameters.map(e=>sw(t(GS(e)))),i=e.annotations?.toCodecStringTree;if(oe(i)){let n=i(r);return n===void 0?e:yS(e,[TS(n,t)])}let a=e.annotations?.toCodecJson,o=oe(a)?a(r):void 0,s=o===void 0?e.annotations?.toCodec:void 0,c=o??(oe(s)?s(r):void 0);return c===void 0?n(e):yS(e,[TS(c,t)])}case`Null`:return yS(e,[vw]);case`Boolean`:return yS(e,[yw]);case`Unknown`:case`ObjectKeyword`:return yS(e,[bC]);case`Enum`:case`Number`:case`Literal`:case`UniqueSymbol`:case`Symbol`:case`BigInt`:return e.toCodecStringTree();case`Objects`:return dw(e),e.recur(t,QS);case`Union`:{let n=gw(e.types);return n===e.types?e.recur(t):new eS(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 vw=new tx(new mx(`null`),new Sb(sb(()=>null),sb(()=>`null`))),yw=new tx(new eS([new mx(`true`),new mx(`false`)]),new Sb(sb(e=>e===`true`),pb())),bw=new Sb(sb(e=>typeof e==`string`?[e]:e),ob()),xw=kS(e=>{let t=_w(e,xw,e=>{throw new globalThis.Error(`Missing structural codec for StringTree`,{cause:e})});return t!==e&&e.context!==void 0?OS(t,uw(e.context)):t},{stopAt:e=>e.transformation===bw});function Sw(e){return pf(e)?e.value:{issues:[{message:af(e.cause)}]}}function Cw(e,t){let n=UC(e),r={errors:`all`,...t?.parseOptions},i=Hy(t);return ww(e,{validate:e=>{let t=new vo(`sync`),a=Jg(xg(n(e,r),{onFailure:i,onSuccess:e=>({value:e})}),{scheduler:t});a.currentDispatcher?.flush();let o=a.pollUnsafe();return o?Sw(o):new Promise(e=>{a.addObserver(t=>{e(Sw(t))})})}})}function ww(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 Tw=r(2,(e,t)=>({...e,...t})),Ew=r(2,(e,t)=>Ow(e,(e,n)=>[Object.hasOwn(t,e)?t[e]:e,n])),Dw=e=>e;function Ow(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 kw=`~effect/Schema/SchemaError`;function Aw(e){return pe(e,`~effect/Schema/SchemaError`)&&e[`~effect/Schema/SchemaError`]===`~effect/Schema/SchemaError`}({...yt}),{...yt},{...yt},{...yt},{...yt},{...yt},{...yt},{...yt};var jw=iw;function Mw(){return(e,t,n)=>Zw(new ox(e.map(Hx),e=>t(e.map(e=>Zw(e))),n))}function Nw(e,t){return Mw()([],()=>(t,n,r)=>e(t)?w(t):Uh(new jy(n,t,r)),t)}var Pw=class extends wo(`SchemaError`){[kw]=kw;constructor(e){let t=St();Ct(0);try{super({issue:e})}finally{Ct(t)}}get message(){return Xy(this.issue)}toJSON(){return{_tag:this._tag,message:this.message}}[gt](){return this.toJSON()}toString(){return`SchemaError(${this.message})`}};function Fw(e){return Aw(e)}function Iw(e){return zc(e)?Lw(e):lg(e,e=>Gh(()=>$d(e,e=>new Pw(e))))}function Lw(e){return pf(e)?e:uf($d(e.cause,e=>new Pw(e)))}function Rw(e,t){let n;for(let r of e.reasons){if(!Gd(r)||!Fw(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 zw(e){let t=Qg(e);if(pf(t))return t.value;throw Rw(t.cause,`Sync adapter can only throw schema errors`)}function Bw(e,t){return Cw(e,t)}var Vw=BC;function Hw(e,t){let n=UC(e,t);return(e,t)=>Iw(n(e,t))}var Uw=Hw,Ww=WC,Gw=GC;function Kw(e,t){let n=Hw(e,t);return(e,t)=>zw(n(e,t))}function qw(e,t){let n=KC(e,t);return(e,t)=>Iw(n(e,t))}var Jw=qw;function Yw(e,t){let n=qw(e,t);return(e,t)=>zw(n(e,t))}var Xw=Yw,Zw=sw;function Qw(e){return pe(e,jw)&&e[jw]===jw}var $w=Dw(e=>Zw(NS(e.ast),{schema:e})),eT=Dw(e=>{let t=xT(e);return Zw(FS(e.ast),{schema:t})}),tT=Dw(e=>Zw(WS(e.ast),{schema:e})),nT=Dw(e=>Zw(GS(e.ast),{schema:e}));function rT(e){let t=Zw(new mx(e),{literal:e,transform(n){return t.pipe(ST(rT(n),{decode:sb(()=>n),encode:sb(()=>e)}))}});return t}var iT=Zw(fx),aT=Zw(px),oT=Zw(sx),sT=Zw(ux),j=Zw(gx),cT=Zw(yx),lT=Zw(bx),uT=Zw(xx),dT=Zw(dx);function fT(e,t){return Zw(e,{fields:t,mapFields(e,t){let n=e(this.fields);return fT(Vx(n,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function M(e){return fT(Vx(e,void 0),e)}var pT=e=>typeof e==`symbol`?e:globalThis.String(e);function mT(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=nT(t.fields[o]),c=Object.hasOwn(e,o),l=c?e[o]:o,u=pT(l);if(a.has(u))throw new globalThis.Error(`Duplicate encoded keys: ${ct(l)}`);a.add(u),Et(n,l,s),c&&(r[o]=l,i[l]=o)}return M(n).pipe(ST(t,Eb({decode:Ew(i),encode:Ew(r)})))}}function hT(e,t){return Zw(zS(e.ast,t.ast),{key:e,value:t})}function gT(e,t){return Zw(Gx(e.ast,t.map(Hx)),{schema:e,records:t})}function _T(e,t){return Zw(e,{elements:t,mapElements(e,t){let n=e(this.elements);return _T(Ux(n,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function vT(e){return _T(Ux(e),e)}var N=Dw(e=>Zw(new Sx(!1,[],[e.ast]),{value:e})),yT=Dw(e=>Zw(new Sx(!1,[e.ast],[e.ast]),{value:e}));function bT(e,t){return Zw(e,{members:t,mapMembers(e,t){let n=e(this.members);return bT(Wx(n,this.ast.options,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function P(e,t){return bT(Wx(e,t,void 0),e)}function F(e){let t=e.map(rT);return Zw(Wx(t,void 0,void 0),{literals:e,members:t,mapMembers(e){return P(e(this.members))},pick(e){return F(e)},transform(e){return P(t.map((t,n)=>t.transform(e[n])))}})}var I=Dw(e=>P([e,oT])),xT=Dw(e=>P([e,sT]));function L(e){return t=>Zw(t.ast,{schema:t,identifier:e})}function ST(e,t){return n=>Zw(LS(n.ast,e.ast,t?wb(t):kb()),{from:n,to:e})}function CT(){return(e,t)=>MT()(e,{decode:t,encode:ib})}function wT(e,t){return n=>t?ST(n,t)(e):ST(n)(e)}function TT(e){return t=>Zw(IS(t.ast,e),{schema:t})}function ET(e){return zc(e)&&e._tag===`Success`?e:lg(e,e=>Gh(()=>$d(e,e=>e.issue)))}function DT(e,t){let n=t?.encodingStrategy===`omit`?db():ob();return t=>$w(nT(t)).pipe(ST(t,{decode:fb(ET(e)),encode:n}))}function OT(e,t){return n=>tT(n).pipe(DT(e,t),wT($w(n)))}function kT(e){return rT(e).pipe(TT(w(e)))}function AT(e,t){return M({_tag:kT(e),...t})}function jT(e,t){return Nw(t=>t instanceof e,t)}function MT(){return(e,t)=>new tx(e.ast,wb(t))}var NT=dS;function PT(e,t){let n=e.source,r=e.flags,i=/^[dg]*uy?$/.test(r),a=r===``?`new RegExp(${ot(n)})`:`new RegExp(${ot(n)}, ${ot(r)})`;return hS(e,{toJsonSchema:()=>i?{pattern:r.endsWith(`y`)?`^(?:${n})`:n}:[{},!0],toCode:()=>({runtime:`Schema.isPattern(${a})`}),...t})}var FT=Zw(pS),IT=fS;function LT(e){let t=mr(e.order),n=e.formatter??ot;return(r,i)=>NT(e=>t(e,r),{expected:`a value greater than ${n(r)}`,arbitraryConstraint:{order:e.order,minimum:r,exclusiveMinimum:!0},...e.annotate?.(r),...i})}function RT(e){let t=gr(e.order),n=e.formatter??ot;return(r,i)=>NT(e=>t(e,r),{expected:`a value greater than or equal to ${n(r)}`,arbitraryConstraint:{order:e.order,minimum:r},...e.annotate?.(r),...i})}function zT(e){let t=gr(e.order),n=mr(e.order),r=hr(e.order),i=pr(e.order),a=e.formatter??ot;return(o,s)=>{let c=o.exclusiveMinimum?n:t,l=o.exclusiveMaximum?i:r;return NT(e=>c(e,o.minimum)&&l(e,o.maximum),{expected:`a value between ${a(o.minimum)}${o.exclusiveMinimum?` (excluded)`:``} and ${a(o.maximum)}${o.exclusiveMaximum?` (excluded)`:``}`,arbitraryConstraint:{order:e.order,minimum:o.minimum,maximum:o.maximum,...o.exclusiveMinimum&&{exclusiveMinimum:!0},...o.exclusiveMaximum&&{exclusiveMaximum:!0}},...e.annotate?.(o),...s})}}function BT(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${ot(e)}`);return e}var VT=LT({order:lr,annotate:e=>({representation:{id:`effect/schema/isGreaterThan`,payload:{exclusiveMinimum:BT(e)}},toJsonSchema:()=>({exclusiveMinimum:e}),toCode:()=>({runtime:`Schema.isGreaterThan(${ot(e)})`})})}),HT=RT({order:lr,annotate:e=>({representation:{id:`effect/schema/isGreaterThanOrEqualTo`,payload:{minimum:BT(e)}},toJsonSchema:()=>({minimum:e}),toCode:()=>({runtime:`Schema.isGreaterThanOrEqualTo(${ot(e)})`})})}),UT=zT({order:lr,annotate:e=>{let t=e.exclusiveMinimum?!0:void 0,n=e.exclusiveMaximum?!0:void 0;return{representation:{id:`effect/schema/isBetween`,payload:{minimum:BT(e.minimum),maximum:BT(e.maximum),...t&&{exclusiveMinimum:t},...n&&{exclusiveMaximum:n}}},toJsonSchema:()=>({[t?`exclusiveMinimum`:`minimum`]:e.minimum,[n?`exclusiveMaximum`:`maximum`]:e.maximum}),toCode:()=>({runtime:`Schema.isBetween({ minimum: ${ot(e.minimum)}, maximum: ${ot(e.maximum)}, exclusiveMinimum: ${ot(t)}, exclusiveMaximum: ${ot(n)} })`})}}});function WT(e){return NT(e=>globalThis.Number.isSafeInteger(e),{expected:`an integer`,representation:{id:`effect/schema/isInt`,payload:null},toJsonSchema:()=>({type:`integer`,minimum:globalThis.Number.MIN_SAFE_INTEGER,maximum:globalThis.Number.MAX_SAFE_INTEGER}),toCode:()=>({runtime:`Schema.isInt()`}),arbitraryConstraint:{number:`integer`},...e})}var R=cT.check(WT());function GT(e,t){return e=YT(e),KT(e,Math.ceil(e/2),t)}function KT(e,t,n){return NT(t=>t.length>=e,{expected:`a value with a length of at least ${e}`,representation:{id:`effect/schema/isMinLength`,payload:{minLength:e}},toJsonSchema:({type:n})=>n===`string`?e<=1?{minLength:t}:[{minLength:t},!0]:n===`array`?{minItems:e}:n===void 0?[{minLength:t,minItems:e},!0]:[{},!0],toCode:()=>({runtime:`Schema.isMinLength(${e})`}),[dy]:!0,arbitraryConstraint:{minLength:e},...n})}function qT(e){return KT(1,1,e)}function JT(e,t){return e=YT(e),NT(t=>t.length<=e,{expected:`a value with a length of at most ${e}`,representation:{id:`effect/schema/isMaxLength`,payload:{maxLength:e}},toJsonSchema:({type:t})=>t===`string`?e===0?{maxLength:e}:[{maxLength:e},!0]:t===`array`?{maxItems:e}:t===void 0?[{maxLength:e,maxItems:e},!0]:[{},!0],toCode:()=>({runtime:`Schema.isMaxLength(${e})`}),[dy]:!0,arbitraryConstraint:{maxLength:e},...t})}function YT(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${e}`);return Math.max(0,Math.floor(e))}function XT(e){return NT(e=>ya(e).length===e.length,{expected:`an array with unique items`,representation:{id:`effect/schema/isUnique`,payload:null},toJsonSchema:()=>({uniqueItems:!0}),toCode:()=>({runtime:`Schema.isUnique()`}),arbitraryConstraint:{uniqueBy:i},...e})}var z=j.check(qT()),ZT=e=>+(e?.includeStack===!0)|(e?.excludeCause===!0?2:0),QT=e=>{switch(e){case 0:return;case 1:return{includeStack:!0};case 2:return{excludeCause:!0};case 3:return{includeStack:!0,excludeCause:!0}}},$T=[];function eE(e){let t=ZT(e),n=$T[t];if(n!==void 0)return n;let r=IE.pipe(ST(aT,Rb(QT(t))));return $T[t]=r,r}globalThis.RegExp;var tE=j.annotate({expected:`a string that will be decoded as a URL`}),nE=jT(globalThis.URL,{representation:{id:`effect/schema/URL`,payload:null},toCode:()=>({runtime:`Schema.URL`,Type:`globalThis.URL`}),expected:`URL`,toCodecJson:()=>MT()(tE,Vb)}),rE=tE.pipe(ST(nE,Vb)),iE=j.annotate({expected:`a string that will be decoded as JSON`,contentMediaType:`application/json`});function aE(e,t){return iE.pipe(ST(e,Ub(t)))}var oE=aE(aT);globalThis.File,globalThis.URLSearchParams;var sE=j.annotate({expected:`a string that will be decoded as a finite number`}).pipe(ST(FT,Ab)),cE=j.annotate({expected:`a base64 encoded string that will be decoded as Uint8Array`,format:`byte`,contentEncoding:`base64`}),lE=jT(globalThis.Uint8Array,{representation:{id:`effect/schema/Uint8Array`,payload:null},toCode:()=>({runtime:`Schema.Uint8Array`,Type:`globalThis.Uint8Array`}),expected:`Uint8Array`,toCodecJson:()=>MT()(cE,Hb)});function uE(e,t){return Zw(Mw()([e,t],([e,t])=>(n,r,i)=>{if(!Wd(n))return Uh(new jy(r,n,i));switch(n._tag){case`Fail`:return i_(UC(e)(n.error,i),{onSuccess:Yd,onFailure:e=>Ny(r,`error`,e,n,i)});case`Die`:return i_(UC(t)(n.defect,i),{onSuccess:Xd,onFailure:e=>Ny(r,`defect`,e,n,i)});case`Interrupt`:return w(n)}},{representation:{id:`effect/schema/CauseReason`,payload:null},toCode:({typeParameters:e})=>({runtime:`Schema.CauseReason(${e[0].runtime}, ${e[1].runtime})`,Type:`Cause.Failure<${e[0].Type}, ${e[1].Type}>`,importDeclarations:[`import * as Cause from "effect/Cause"`]}),expected:`Cause.Failure`,toCodec:([e,t])=>MT()(P([M({_tag:rT(`Fail`),error:e}),M({_tag:rT(`Die`),defect:t}),M({_tag:rT(`Interrupt`),fiberId:xT(FT)})]),Eb({decode:e=>{switch(e._tag){case`Fail`:return Yd(e.error);case`Die`:return Xd(e.defect);case`Interrupt`:return Zd(e.fiberId)}},encode:e=>{switch(e._tag){case`Fail`:return{_tag:`Fail`,error:e.error};case`Die`:return{_tag:`Die`,defect:e.defect};case`Interrupt`:return{_tag:`Interrupt`,fiberId:e.fiberId}}}}))}).ast,{error:e,defect:t})}function dE(e,t){return Zw(Mw()([e,t],([e,t])=>{let n=N(uE(e,t));return(e,t,r)=>Ud(e)?i_(UC(n)(e.reasons,r),{onSuccess:Kd,onFailure:n=>Ny(t,`reasons`,n,e,r)}):Uh(new jy(t,e,r))},{representation:{id:`effect/schema/Cause`,payload:null},toCode:({typeParameters:e})=>({runtime:`Schema.Cause(${e[0].runtime}, ${e[1].runtime})`,Type:`Cause.Cause<${e[0].Type}, ${e[1].Type}>`,importDeclarations:[`import * as Cause from "effect/Cause"`]}),expected:`Cause`,toCodec:([e,t])=>MT()(N(uE(e,t)),Eb({decode:Kd,encode:({reasons:e})=>e}))}).ast,{error:e,defect:t})}var fE=Tb({decode:(e,t)=>vr(z_(e),{onNone:()=>Uh(new My({expected:`a valid UTC DateTime string`},e,t)),onSome:e=>w(V_(e))}),encode:e=>w(J_(e))}),pE=-864e13,mE=864e13;function hE(e,t,n){let r=Math.max(t,e?.minimum===void 0?t:e.minimum.epochMilliseconds+ +(e.exclusiveMinimum===!0)),i=Math.min(n,e?.maximum===void 0?n:e.maximum.epochMilliseconds-+(e.exclusiveMaximum===!0));return r<=i?[r,i]:[t,n]}function gE(e,t){return R.check(UT({minimum:e,maximum:t}))}var _E=Nw(e=>F_(e)&&I_(e),{representation:{id:`effect/schema/DateTimeUtc`,payload:null},toCode:()=>({runtime:`Schema.DateTimeUtc`,Type:`DateTime.Utc`,importDeclarations:[`import * as DateTime from "effect/DateTime"`]}),expected:`DateTime.Utc`,toCodecArbitrary:({constraint:e})=>{let[t,n]=hE(e,pE,mE);return CT()(gE(t,n),sb(R_))},toCodecJson:()=>MT()(j,fE),toFormatter:()=>e=>e.toString()}),vE=j.annotate({expected:`a string that will be decoded as a DateTime.Utc`}).pipe(ST(_E,fE));function B(e){return Zw(Mw()([e],([e])=>(t,n,r)=>_r(t)?x(t)?Lh:i_(UC(e)(t.value,r),{onSuccess:b,onFailure:e=>Ny(n,`value`,e,t,r)}):Uh(new jy(n,t,r)),{representation:{id:`effect/schema/Option`,payload:null},toCode:({typeParameters:e})=>({runtime:`Schema.Option(${e[0].runtime})`,Type:`Option.Option<${e[0].Type}>`,importDeclarations:[`import * as Option from "effect/Option"`]}),expected:`Option`,toCodec:([e])=>MT()(P([M({_tag:rT(`Some`),value:e}),M({_tag:rT(`None`)})]),Eb({decode:e=>e._tag===`None`?y():b(e.value),encode:e=>S(e)?{_tag:`Some`,value:e.value}:{_tag:`None`}}))}).ast,{value:e})}function yE(e){return I(e).pipe(ST(B(tT(e)),zb()))}var bE=Nw(Rv,{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:()=>Wv,toCodec:()=>MT()(N(vT([j,j])),Eb({decode:Bv,encode:e=>e.params.map(([e,t])=>[e,Iv(t)])}))}).pipe(ST(hT(j,P([j,yT(j)])),Eb({decode:Zv,encode:Vv})));function xE(e){return $w(e).pipe(ST(B(tT(e)),Bb()))}function SE(e,t){let n=typeof t?.label==`string`?t.label:void 0,r=t?.disallowJsonEncode===!0,i=n===void 0?r?{disallowJsonEncode:!0}:void 0:r?{label:n,disallowJsonEncode:!0}:{label:n},a=n===void 0?void 0:UC(rT(n));return Zw(Mw()([e],([e])=>(t,n,r)=>_v(t)?a_(a===void 0?Bh:r_(a(t.label,r),e=>new Dy([`label`],e)),()=>i_(UC(e)(bv(t),r),{onSuccess:e=>vv(e,{label:t.label}),onFailure:()=>new Ay(n,[new Dy([`value`],new My(void 0,t,r))],t,r)})):Uh(new jy(n,t,r)),{representation:{id:`effect/schema/Redacted`,payload:i??null},toCode:({typeParameters:e})=>({runtime:i===void 0?`Schema.Redacted(${e[0].runtime})`:`Schema.Redacted(${e[0].runtime}, ${ot(i)})`,Type:`Redacted.Redacted<${e[0].Type}>`,importDeclarations:[`import * as Redacted from "effect/Redacted"`]}),expected:`Redacted`,toCodecJson:([e])=>MT()(e,{decode:sb(e=>vv(e,{label:n})),encode:r?rb(e=>`Cannot serialize Redacted`+(S(e)&&typeof e.value.label==`string`?` with label: "${e.value.label}"`:``)):sb(bv)}),toEquivalence:([e])=>xv(e)}).ast,{value:e})}function CE(e,t){return ST(SE(tT(e),{label:t?.label,disallowJsonEncode:t?.disallowEncode}),{decode:sb(e=>vv(e,{label:t?.label})),encode:t?.disallowEncode?rb(e=>`Cannot encode Redacted`+(S(e)&&typeof e.value.label==`string`?` with label: "${e.value.label}"`:``)):sb(bv)})(e)}var wE=globalThis.Symbol.for(`immer-draftable`),TE={};function EE(t,n,r,i,a){let o=AE(r,n,i),s=kE(n),c=class extends t{constructor(...[e,t]){let n=t?.[`~payload`],i=n?.token===TE?n.value:r.make(e??{},t);super(i,{...t,disableChecks:!0,"~payload":{token:TE,value:i}})}static[jw]=jw;get[s](){return s}static[wE]=!0;static identifier=n;static fields=r.fields;static get ast(){return o(this).ast}static pipe(){return e(this,arguments)}static rebuild(e){return o(this).rebuild(e)}static make(e,t){return zC(o(this))(e??{},t)}static makeOption(e,t){return RC(o(this))(e??{},t)}static makeEffect(e,t){return o(this).makeEffect(e??{},t)}static annotate(e){return this.rebuild(SS(this.ast,e))}static annotateKey(e){return this.rebuild(MS(this.ast,e))}static check(...e){return this.rebuild(wS(this.ast,e))}static extend(e){return(t,n)=>{let i=jE(t)?t:M(t),o={...r.fields,...i.fields},s=Vx(o,r.ast.checks,{identifier:e});return EE(this,e,fT(wS(s,i.ast.checks),o),n,a)}}static mapFields(e,t){return r.mapFields(e,t)}};return a!==void 0&&Object.assign(c.prototype,a(n)),c}function DE(e,t){return new e(t,{"~payload":{token:TE,value:t}})}function OE(e){return new Sb(sb(t=>DE(e,t)),ob())}function kE(e){return`~effect/Schema/Class/${e}`}function AE(e,t,n){let r;return i=>{if(r!==void 0)return r;let a=kE(t),o=e=>e instanceof i||pe(e,a),s=OE(i);return r=ST(Zw(new ox([e.ast],()=>(e,t,n)=>o(e)?w(e):Uh(new jy(t,e,n)),{identifier:t,[py]:([e])=>({isConstructed:o,link:new tx(e,s)}),toCodec:([e])=>new tx(e.ast,s),toEquivalence:([e])=>e,toFormatter:([e])=>t=>`${i.identifier}(${e(t)})`,[fy]:Jx(e.ast),...n})),s)(e)}}function jE(e){return Qw(e)}var V=e=>(t,n)=>EE(So,e,jE(t)?t:M(t),n,e=>({toString(){return`${e}(${ot({...this})})`}})),H=e=>(t,n,r)=>{let i=jE(n)?n.mapFields(e=>({_tag:kT(t),...e}),{unsafePreserveChecks:!0}):AT(t,n);return V(e??t)(i,r)},ME=e=>(t,n)=>EE(Sn,e,jE(t)?t:M(t),n,e=>({name:e})),NE=e=>(t,n,r)=>{let i=jE(n)?n.mapFields(e=>({_tag:kT(t),...e}),{unsafePreserveChecks:!0}):AT(t,n);return ME(e??t)(i,r)},PE=cw,FE=hw,IE=Zw(SS(gC,{toCode:()=>({runtime:`Schema.Json`,Type:`Schema.Json`})})),LE=hT(j,IE),RE=Hs,zE=Ws,BE=Gs,VE=Ks,HE=qs,UE=Gu,WE=td,GE=`~effect/MutableRef`,KE={[GE]:GE,...Rt,toJSON(){return{_id:`MutableRef`,current:_t(this.current)}}},qE=e=>{let t=Object.create(KE);return t.current=e,t},JE=r(2,(e,t)=>(e.current=t,e)),YE=Symbol.for(`effect/MutableList/Empty`),XE=()=>({head:void 0,tail:void 0,length:0}),ZE=e=>{let t=e.head;t.offset>=1024&&t===e.tail&&t.mutable&&(t.array.length-t.offset)*8<=t.offset&&(e.head=e.tail={array:t.array.slice(t.offset),mutable:!0,offset:0,next:void 0})},QE=()=>({array:[],mutable:!0,offset:0,next:void 0}),$E=(e,t)=>{e.tail?e.tail.mutable||(e.tail.next=QE(),e.tail=e.tail.next):e.head=e.tail=QE(),e.tail.array.push(t),e.length++},eD=e=>{e.head=e.tail=void 0,e.length=0},tD=e=>{if(!e.head)return YE;let t=e.head.array[e.head.offset];return e.head.mutable&&(e.head.array[e.head.offset]=void 0),e.head.offset++,e.length--,e.head.offset===e.head.array.length?e.head.next?e.head=e.head.next:eD(e):ZE(e),t},nD=`~effect/Queue`,rD=`~effect/Queue/Enqueue`,iD=`~effect/Queue/Dequeue`,aD={_A:i,_E:i},oD={[nD]:aD,[rD]:aD,[iD]:aD,...Rt,toJSON(){return{_id:`effect/Queue`,state:this.state._tag,size:_D(this)}}},sD=e=>bn(t=>{let n=Object.create(oD);return n.dispatcher=t.currentDispatcher,n.capacity=e?.capacity??1/0,n.strategy=e?.strategy??`suspend`,n.messages=XE(),n.scheduleRunning=!1,n.state={_tag:`Open`,takers:new Set,offers:new Set,awaiters:new Set},Js(n)}),cD=e=>sD({capacity:e}),lD=r(2,(e,t)=>Qs(()=>uD(e,t)?yD:e.state._tag===`Open`&&e.strategy===`suspend`?DD(e,t):vD)),uD=(e,t)=>e.state._tag===`Open`?e.messages.length>=e.capacity?e.strategy===`sliding`?(tD(e.messages),$E(e.messages,t),!0):e.capacity<=0&&e.state.takers.size>0&&($E(e.messages,t),SD(e),!0):($E(e.messages,t),CD(e),!0):!1,dD=r(2,(e,t)=>Zs(()=>fD(e,t))),fD=(e,t)=>{if(e.state._tag!==`Open`)return!1;let n=tl(_n(t),bD);return e.state.offers.size===0&&e.messages.length===0?(MD(e,n),!0):(e.state={...e.state,_tag:`Closing`,exit:n},CD(e),!0)},pD=e=>Zs(()=>mD(e)),mD=e=>{if(e.state._tag===`Done`)return!1;eD(e.messages);let t=e.state.offers;MD(e,e.state._tag===`Open`?xD:e.state.exit);for(let e of t)kD(e);return!0},hD=e=>wD(()=>gD(e)??Nc(ED(e,()=>TD(e,1)),hD(e))),gD=e=>{if(e.state._tag===`Done`)return e.state.exit;if(e.messages.length>0){let t=tD(e.messages);return jD(e),mn(t)}if(e.capacity<=0&&e.state.offers.size>0){let t=AD(e.state.offers);return jD(e),mn(t)}},_D=e=>e.state._tag===`Done`?0:e.messages.length,vD=mn(!1),yD=mn(!0),bD=vn(kn()),xD=Kc(),SD=e=>{if(e.state._tag!==`Done`&&e.state.takers.size!==0){for(let t of e.state.takers)if(t.ready()&&(e.state.takers.delete(t),t.resume(Zc),e.messages.length===0))break}},CD=e=>{e.scheduleRunning||e.state._tag===`Done`||e.state.takers.size===0||(e.scheduleRunning=!0,e.dispatcher.scheduleTask(()=>{e.scheduleRunning=!1,SD(e)},0))},wD=fn({op:`QueueTake`,[Nt](e){let t=this[Mt]();return Vt(t)?t[Nt](e):t}}),TD=(e,t)=>e.messages.length>=(e.state._tag===`Closing`?1:Math.min(t,e.capacity||1))||e.capacity<=0&&e.state._tag!==`Done`&&e.state.offers.size>0,ED=(e,t)=>uc(n=>{if(e.state._tag===`Done`)return n(e.state.exit);if(t())return n(Zc);let r={ready:t,resume:n};return e.state.takers.add(r),Zs(()=>{e.state._tag!==`Done`&&e.state.takers.delete(r)})}),DD=(e,t)=>uc(n=>uD(e,t)?n(yD):OD(e,{_tag:`Single`,message:t,resume:n})),OD=(e,t)=>{if(e.state._tag!==`Open`)return kD(t);let n=e.state.offers;return n.add(t),Zs(()=>{e.state._tag!==`Done`&&(n.delete(t),e.state._tag===`Closing`&&n.size===0&&e.messages.length===0&&MD(e,e.state.exit))})},kD=e=>e._tag===`Single`?e.resume(vD):e.resume(mn(e.remaining.slice(e.offset))),AD=e=>{let t=e.values().next().value;if(t._tag===`Single`)return e.delete(t),t.resume(yD),t.message;let n=t.remaining[t.offset++];return t.offset===t.remaining.length&&(e.delete(t),t.resume(mn([]))),n},jD=e=>{if(e.state._tag===`Done`)return Xm(e.state.exit.cause);if(e.state.offers.size===0)return e.state._tag===`Closing`&&e.messages.length===0&&(MD(e,e.state.exit),Xm(e.state.exit.cause));for(let t of e.state.offers){let n=e.capacity-e.messages.length;if(n<=0)break;if(t._tag===`Single`)$E(e.messages,t.message),e.state.offers.delete(t),t.resume(yD);else{for(;t.offset<t.remaining.length;t.offset++){if(n===0)return!1;$E(e.messages,t.remaining[t.offset]),n--}e.state.offers.delete(t),t.resume(mn([]))}let r=e.state;if(r._tag===`Done`)return Xm(r.exit.cause)}return!1},MD=(e,t)=>{if(e.state._tag===`Done`)return;let n=e.state;e.state={_tag:`Done`,exit:t};for(let e of n.takers)e.resume(t);n.takers.clear();for(let e of n.awaiters)e(t);n.awaiters.clear()},ND=e=>new FD(e),PD=(e,t,n)=>uc(r=>{if(e.free>=t)return r(n);let i=()=>{e.free<t||(e.waiters.delete(i),r(n))};return e.waiters.add(i),Zs(()=>{e.waiters.delete(i)})}),FD=class{waiters=new Set;taken=0;permits;constructor(e){this.permits=e}get free(){return this.permits-this.taken}take(e){let t=Qs(()=>this.free<e?PD(this,e,t):(this.taken+=e,Js(e)));return t}takeIfAvailable(e){return Qs(()=>this.free<e?Js(!1):(this.taken+=e,Js(!0)))}releaseUnsafe(e,t){return this.taken-=t,this.waiters.size>0&&e.currentDispatcher.scheduleTask(()=>{for(let e of this.waiters){if(this.free<=0)break;e()}},0),this.free}resize(e){return bn(t=>(this.permits=e,this.free<0||this.releaseUnsafe(t,0),ic))}release(e){return bn(t=>Js(this.releaseUnsafe(t,e)))}get releaseAll(){return bn(e=>Js(this.releaseUnsafe(e,this.taken)))}withPermits(e){return t=>ku(n=>{let r=Qs(()=>this.free<e?Rc(n(PD(this,e,ic)),()=>r):(this.taken+=e,lu(n(t),()=>{this.releaseUnsafe(Fs(),e)},!0)));return r})}withPermit=this.withPermits(1);withPermitsIfAvailable(e){return t=>ku(n=>this.free<e?tc:(this.taken+=e,lu(n(Mc(t)),()=>{this.releaseUnsafe(Fs(),e)},!0)))}},ID=e=>Zs(()=>new FD(e)),LD=`~effect/Channel`,RD=e=>pe(e,LD),zD={[LD]:{_Env:i,_InErr:i,_InElem:i,_OutErr:i,_OutElem:i},pipe(){return e(this,arguments)}},BD=e=>{let t=Object.create(zD);return t.transform=(t,n)=>lg(e(t,n),e=>w(Wh(e))),t},VD=(e,t)=>BD((n,r)=>E(WD(e)(n,r),e=>t(e,r))),HD=e=>BD((t,n)=>e),UD=e=>BD($g(function*(t,n){let r=Mf(n),i=e=>Nf(r,eh(e));return Ng(yield*Ng(e(t,n,r),i),i)})),WD=e=>e.transform,GD=e=>BD((t,n)=>Rh(()=>WD(e())(t,n))),KD=e=>HD(w(Uh(e))),qD=e=>HD(Wh(e)),JD=e=>qD(Jd(e)),YD=e=>BD((t,n)=>XD({scope:n,readable:e.evaluate(),onError:e.onError,releaseLockOnEnd:e.releaseLockOnEnd})),XD=e=>{let t=e.readable.getReader(),n=e.exit??qE(void 0),r=Rh(()=>n.current?n.current:Sg(Ih({try:()=>t.read(),catch:e.onError}),{onFailure:e=>n.current??Wh(e),onSuccess:({done:e,value:t})=>n.current?n.current:e?sf():w(ma(t))}));return rg(jf(e.scope,e.releaseLockOnEnd?zh(()=>t.releaseLock()):Fh(()=>t.cancel().catch(e=>t.closed.then(()=>Promise.reject(e),u))).pipe(Mg(zh(()=>t.releaseLock())))),r)},ZD=r(2,(e,t)=>VD(e,e=>zh(()=>{let n=0;return ng(e,e=>t(e,n++))}))),QD=e=>e===void 0||e!==`unbounded`&&e<=1,$D=r(e=>RD(e[0]),(e,t,n)=>QD(n?.concurrency)?eO(e,t):tO(e,t,n)),eO=(e,t)=>BD((n,r)=>{let i=0;return ng(WD(e)(n,r),E(e=>t(e,i++)))}),tO=(e,t,n)=>UD($g(function*(r,i,o){let s=0,c=yield*WD(e)(r,i),l=n.concurrency===`unbounded`?2**53-1:Math.min(n.concurrency,2**53-1),u=yield*cD(0);yield*jf(o,pD(u));let d=Yg(yield*Cg()),f=UE(o);if(n.unordered){let e=ND(l),n=a(e.release(1)),r=Sg({onFailure:e=>E(dD(u,e),n),onSuccess:e=>E(lD(u,e),n)});yield*e.take(1).pipe(E(()=>c),E(e=>{let n=s++;return f(d(r(Rh(()=>t(e,n))))),Bh}),Vg({disableYield:!0}),lg(t=>e.withPermits(l-1)(dD(u,t))),Kg(o))}else{let e=yield*cD(l-2);yield*jf(o,pD(e)),yield*hD(e).pipe(Xh,E(e=>lD(u,e)),Vg({disableYield:!0}),lg(e=>dD(u,e)),Kg(o));let n,r=e=>{e._tag!==`Success`&&(n=e.cause,fD(u,e.cause))};yield*c.pipe(E(i=>{if(n)return Wh(n);let a=s++,o=d(Rh(()=>t(i,a)));return f(o),o.addObserver(r),lD(e,zE(o))}),Vg({disableYield:!0}),lg(t=>lD(e,uf(t)).pipe(Zh(dD(e,t)))),Kg(o))}return hD(u)})),nO=e=>VD(e,e=>{let t,n=0;return w(Rh(function r(){if(t===void 0)return E(e,e=>{switch(e.length){case 0:return r();case 1:return w(e[0]);default:return t=e,w(e[n++])}});let i=t[n++];return n>=t.length&&(t=void 0,n=0),w(i)}))}),rO=r(2,(e,t)=>VD(e,e=>w(E(e,function n(r){let i=[];for(let e=0;e<r.length;e++)t(r[e])&&i.push(r[e]);return Xi(i)?w(i):E(e,n)})))),iO=r(2,(e,t)=>BD((n,r)=>{let i=Mf(r);return ng(WD(e)(n,i),e=>{let a=e.pipe(lg(e=>{if(Xm(e))return Wh(e);let o=i;return i=Mf(r),Nf(o,uf(e)).pipe(Zh(WD(t(e))(n,i)),E(e=>(a=e,e)))}));return Rh(()=>a)})})),aO=r(3,(e,t,n)=>iO(e,e=>{let r=t(e);return Di(r)?qD(r.failure):n(r.success,e)})),oO=r(2,(e,t)=>aO(e,fs,e=>t(e))),sO=r(e=>RD(e[0]),(e,t,n,r)=>oO(e,e=>t(e)?n(e):r?r(e):KD(e))),cO=r(2,(e,t)=>VD(e,e=>w(dg(e,e=>of(e)?e:t(e))))),lO=r(e=>RD(e[0])&&RD(e[1]),(e,t,n)=>UD($g(function*(r,i,a){let o=n?.haltStrategy??`both`,s=yield*cD(0);yield*jf(a,pD(s));let c=0;function l(e,t){if(c++,!Xm(t))return dD(s,t);switch(o){case`both`:return c===2?dD(s,t):Bh;case`left`:case`right`:return e===o?dD(s,t):Bh;case`either`:return dD(s,t)}}let u=(e,t,n)=>WD(t)(r,n).pipe(E(e=>e.pipe(E(e=>lD(s,e)),Vg)),Ng(t=>Pg(eh(t),e=>Nf(n,e)).pipe(Sg({onFailure:t=>l(e,t),onSuccess:()=>l(e,t)}))),Kg(a));return yield*u(`left`,e,Mf(a)),yield*u(`right`,t,Mf(a)),hD(s)}))),uO=(e,t)=>BD((n,r)=>zh(()=>{let r=new TextDecoder(e,t),i={stream:!0},a=n.pipe(ng(ha(e=>r.decode(e,i))),Ym(e=>{a=sf(e);let t=r.decode();return t.length>0?w(ma(t)):a}));return Rh(()=>a)})),dO=r(2,(e,t)=>BD((n,r)=>E(WD(e)(n,r),e=>WD(t)(e,r)))),fO=r(2,(e,t)=>lO(e,HD(w(E(t,sf))),{haltStrategy:`either`})),pO=r(2,(e,t)=>UD((n,r,i)=>Af(i,t).pipe(Zh(WD(e)(n,r))))),mO=r(2,(e,t)=>pO(e,e=>t)),hO=(e,t,n)=>Rh(()=>{let r=Of();return Ym(E(WD(e)(sf(),r),t),n||w).pipe(Fg(e=>Nf(r,e)))}),gO=r(2,(e,t)=>BD((n,r)=>ng(Eg(WD(e)(n,r),t),Eg(t)))),_O=r(2,(e,t)=>hO(e,e=>Vg(E(e,t),{disableYield:!0}))),vO=e=>Rh(()=>{let t=y();return hO(e,e=>e.pipe(ig,E(e=>(t=e,sf()))),()=>w(t))}),yO=(e,t)=>WD(e)(sf(),t),bO=(e,t)=>()=>{let n=Uw(yT(e),t);return BD((e,t)=>w(E(e,e=>n(e))))},xO=`~effect/Stream`,SO={_R:i,_E:i,_A:i},CO=function(e){this.channel=e};CO.prototype={[xO]:SO,pipe(){return e(this,arguments)}};var wO=e=>new CO(e),TO=`~effect/Stream`,EO=e=>pe(e,TO),DO=wO,OO=(e,t)=>DO(BD((n,r)=>E(yO(e.channel,r),e=>t(e,r)))),kO=e=>e.channel,AO=e=>{let t=DO(GD(()=>e().channel));return jO.set(t,e),t},jO=new WeakMap,MO=e=>DO(KD(e)),NO=e=>DO(JD(e)),PO=e=>DO(YD(e)),FO=r(2,(e,t)=>AO(()=>{let n=0;return DO(ZD(e.channel,ha(e=>t(e,n++))))})),IO=r(e=>EO(e[0]),(e,t,n)=>e.channel.pipe(nO,$D(t,n),ZD(ma),DO)),LO=r(2,(e,t)=>DO($D(e.channel,t))),RO=r(2,(e,t)=>DO(rO(kO(e),t))),zO=r(e=>EO(e[0]),(e,t,n,r)=>DO(sO(kO(e),t,e=>n(e).channel,r&&(e=>r(e).channel)))),BO=r(2,(e,t)=>DO(cO(e.channel,t))),VO=r(2,(e,t)=>DO(dO(e.channel,t))),HO=r(e=>EO(e[0]),(e,t)=>e.channel.pipe(dO(uO(t?.encoding)),DO)),UO=r(2,(e,t)=>DO(fO(e.channel,t))),WO=r(2,(e,t)=>DO(mO(e.channel,t))),GO=r(2,(e,t)=>DO(gO(e.channel,t))),KO=e=>ng(vO(e.channel),Or($i(0))),qO=r(e=>EO(e[0]),(e,t,n)=>{let r,i,a=!1,o=WE(!1),s=n?.signal,c=()=>i.interruptUnsafe();return new ReadableStream({start(n){i=Jg(Eg(_O(VD(e.channel,e=>w(o.whenOpen(e))),e=>zh(()=>{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(tf(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,Xg(ag(BE(i)))}},n?.strategy)}),JO=r(e=>EO(e[0]),(e,t)=>ng(Cg(),n=>qO(e,n,t))),YO=Rr(`effect/Crypto`),XO=`~effect/FiberMap`,ZO=e=>pe(e,XO),QO={[XO]:XO,[Symbol.iterator](){return this.state._tag===`Closed`?Li():this.state.backing[Symbol.iterator]()},...Rt,toJSON(){return{_id:`FiberMap`,state:this.state}}},$O=(e,t)=>{let n=Object.create(QO);return n.state={_tag:`Open`,backing:e,fibers:new Set},n.deferred=t,n},ek=()=>Ag(zh(()=>$O(wh(),_f())),e=>Rh(()=>{let t=e.state;return t._tag===`Closed`?Bh:(e.state={_tag:`Closed`},HE(t.fibers).pipe(Tf(e.deferred)))})),tk=-1,nk=lo(fo(rf,uo(tk))),rk=r(e=>ZO(e[0]),(e,t,n,r)=>{if(e.state._tag===`Closed`){n.interruptUnsafe(tk);return}let i=Th(e.state.backing,t);if(i._tag===`Some`){if(i.value===n)return;if(r?.onlyIfMissing===!0){n.interruptUnsafe(tk);return}}kh(e.state.backing,t,n),e.state.fibers.add(n),i._tag===`Some`&&i.value.interruptUnsafe(tk),n.addObserver(i=>{if(e.state._tag===`Closed`)return;e.state.fibers.delete(n);let a=Th(e.state.backing,t);S(a)&&n===a.value&&jh(e.state.backing,t),mf(i)&&(r?.propagateInterruption===!0?!nk(i.cause):!Qd(i.cause))&&wf(e.deferred,i)})}),ik=r(2,(e,t)=>e.state._tag===`Closed`?y():Th(e.state.backing,t)),ak=r(2,(e,t)=>Rh(()=>w(ik(e,t)))),ok=r(2,(e,t)=>e.state._tag!==`Closed`&&Oh(e.state.backing,t)),sk=r(2,(e,t)=>zh(()=>ok(e,t))),ck=r(2,(e,t)=>Rh(()=>{if(e.state._tag===`Closed`)return Bh;let n=Th(e.state.backing,t);return n._tag===`None`?Bh:VE(n.value,tk)})),lk=function(){let e;return()=>(e===void 0&&(e=Jg(Lg)),e)}(),uk=function(){let e=arguments[0];if(Mh(arguments[2]))return dk(e,arguments[1],arguments[2],arguments[3]);let t=arguments[1],n=arguments[2];return r=>dk(e,t,r,n)},dk=(e,t,n,r)=>Jh(i=>{if(e.state._tag===`Closed`)return Lg;if(r?.onlyIfMissing===!0&&ok(e,t))return zh(lk);let a=Bu(i,n,r?.startImmediately??!0,!0);return rk(e,t,a,r),w(a)}),fk=`~effect/Match/Matcher`,pk={[fk]:{_input:i,_filters:i,_remaining:i,_result:i,_return:i,_args:i},_tag:`TypeMatcher`,add(e){return mk(this.select,[...this.cases,e])},pipe(){return e(this,arguments)}};function mk(e,t){let n=Object.create(pk);return n.select=e,n.cases=t,n}var hk={[fk]:{_input:i,_filters:i,_result:i,_return:i,_flavor:i},_tag:`ValueMatcher`,add(e){return Oi(this.value)?this:e._tag===`When`&&e.guard(this.provided)===!0||e._tag===`Not`&&e.guard(this.provided)===!1?gk(this.provided,Si(e.evaluate(this.provided))):this},pipe(){return e(this,arguments)}};function gk(e,t){let n=Object.create(hk);return n.provided=e,n.value=t,n}var _k=(e,t)=>({_tag:`When`,guard:e,evaluate:t}),vk=e=>{if(typeof e==`function`)return e;if(Array.isArray(e)){let t=e.map(vk),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,vk(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},yk=e=>gk(e,Ci(e)),bk=r(2,(e,t)=>Ck(t)(mk(i,[]))(e)),xk=(e,t)=>n=>n.add(_k(vk(e),t)),Sk=e=>t=>{let n=_k(n=>n!=null&&Object.hasOwn(t,n[e]),n=>t[n[e]](n));return e=>e.add(n)},Ck=(e=>t=>{let n=Sk(e)(t);return e=>Dk(n(e))})(`_tag`),wk=e=>t=>{let n=Tk(t);return Ei(n)?n._tag===`Success`?n.success:e(n.failure):(...t)=>{let r=n(...t);return Oi(r)?r.success:e(r.failure,...t)}},Tk=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?Si(t.evaluate(r,...n)):Ci(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 Si(t.evaluate(r,...n))}return Ci(r)}},Ek=`effect/match/Match/exhaustive: absurd`,Dk=e=>{let t=Tk(e);if(Ei(t)){if(Oi(t))return t.success;throw Error(Ek)}return(...e)=>{let n=t(...e);if(Oi(n))return n.success;throw Error(Ek)}},Ok=yk,kk=bk,Ak=xk,jk=ee,Mk=te,Nk=ie,Pk=wk,Fk={"~effect/Ref":{_A:i},...Rt,toJSON(){return{_id:`Ref`,ref:this.ref}}},Ik=e=>{let t=Object.create(Fk);return t.ref=qE(e),t},Lk=e=>zh(()=>Ik(e)),Rk=e=>zh(()=>e.ref.current),zk=r(2,(e,t)=>zh(()=>JE(e.ref,t))),Bk=r(2,(e,t)=>zh(()=>{let[n,r]=t(e.ref.current);return e.ref.current=r,n})),Vk=r(2,(e,t)=>zh(()=>{e.ref.current=t(e.ref.current)})),Hk=r(2,(e,t)=>zh(()=>e.ref.current=t(e.ref.current))),Uk=r(2,(e,t)=>e===void 0?void 0:t(e)),Wk=`~effect/SynchronizedRef`,Gk={...Rt,[Wk]:Wk,toJSON(){return{_id:`SynchronizedRef`,value:this.backing.ref.current}}},Kk=e=>{let t=Object.create(Gk);return t.semaphore=ND(1),t.backing=Ik(e),t},qk=e=>zh(()=>Kk(e)),Jk=e=>e.backing.ref.current,Yk=r(2,(e,t)=>e.semaphore.withPermit(Rh(()=>ng(t(Jk(e)),([t,n])=>(e.backing.ref.current=n,t))))),Xk=j.check(PT(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u,{message:`Expected a full GitHub repo name (owner/name)`})).pipe(L(`RepositoryName`)),Zk=j.check(PT(/^[^\s-]\S*$/u,{message:`Expected a Git revision without whitespace or a leading dash`})).pipe(L(`RepositoryRevision`)),Qk=j.check(PT(/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/u,{message:`Expected a 40- or 64-character lowercase Git object ID`})).pipe(L(`CommitSha`)),$k=e=>e.replaceAll(/[^A-Za-z0-9_.-]/gu,`_`),eA=e=>{let t=e.indexOf(`/`);return{owner:e.slice(0,t),name:e.slice(t+1)}},tA=e=>e.toLowerCase(),nA=z.pipe(L(`EventId`)),rA=z.pipe(L(`DedupKey`)),iA=class extends V(`Event`)({id:nA,dedupKey:rA,payload:IE,receivedAt:_E}){},aA=z.pipe(L(`LoopName`)),oA=[`none`,`required`],sA=F(oA),cA=[`write`,`read`],lA=F(cA),uA=class extends H(`CancelReason/OperatorCanceled`)(`OperatorCanceled`,{}){},dA=class extends H(`CancelReason/Superseded`)(`Superseded`,{by:nA}){},fA=class extends H(`CancelReason/Revoked`)(`Revoked`,{}){},pA=P([uA,dA,fA]),mA=class extends H(`RunState/Pending`)(`Pending`,{}){},hA=class extends H(`RunState/Waiting`)(`Waiting`,{}){},gA=class extends H(`RunState/Queued`)(`Queued`,{}){},_A=class extends H(`RunState/Running`)(`Running`,{}){},vA=class extends H(`RunState/Succeeded`)(`Succeeded`,{}){},yA=class extends H(`RunState/Failed`)(`Failed`,{}){},bA=class extends H(`RunState/Canceled`)(`Canceled`,{reason:pA}){},xA=P([mA,hA,gA,_A]),SA=P([...xA.members,vA,yA,bA]),CA=P([mA,hA,gA]),wA=P([mA,gA]),TA=Vw(xA),EA=Vw(CA),DA=Vw(wA),OA=e=>({canApprove:e._tag===`Waiting`,canRetry:e._tag===`Failed`,canResolveFailure:e._tag===`Failed`,canCancel:TA(e),canRunAgain:e._tag===`Succeeded`||e._tag===`Canceled`}),kA=()=>(...e)=>e,AA=kA()(`Pending`,`Waiting`,`Queued`,`Running`),jA=kA()(`Pending`,`Waiting`,`Queued`,`Running`,`Succeeded`,`Failed`,`Canceled`),MA=kA()(`Pending`,`Waiting`,`Queued`),NA=e=>new hA,PA=e=>new gA,FA=e=>new _A,IA=e=>new vA,LA=e=>new yA,RA=e=>new _A,zA=e=>new bA({reason:new uA}),BA=(e,t)=>new bA({reason:new dA({by:t})}),VA=e=>new bA({reason:new fA}),HA=z.pipe(L(`RunId`)),UA=class extends V(`Run`)({id:HA,eventId:nA,loop:aA,state:SA,openedAt:_E}){},U=Symbol.for(`drizzle:entityKind`),WA=new WeakMap;function GA(e){let t=new Set;for(let n=e;n;n=Object.getPrototypeOf(n))U in n&&t.add(n[U]);return WA.set(e,t),t}var KA=Function.prototype[Symbol.hasInstance];function W(e,t){if(KA.call(t,e))return!0;if(typeof e!=`object`||!e)return!1;let n=Object.getPrototypeOf(e)?.constructor;return typeof n==`function`&&(WA.get(n)??GA(n)).has(t[U])}function qA(e){if(typeof e!=`object`||!e)return;let t=Object.getPrototypeOf(e)?.constructor;if(typeof t==`function`)return WA.get(t)??GA(t)}var JA=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}},YA=Symbol.for(`drizzle:Name`),XA=Symbol.for(`drizzle:Schema`),ZA=Symbol.for(`drizzle:Columns`),QA=Symbol.for(`drizzle:ExtraConfigColumns`),$A=Symbol.for(`drizzle:OriginalName`),ej=Symbol.for(`drizzle:BaseName`),tj=Symbol.for(`drizzle:CacheKey`),nj=Symbol.for(`drizzle:IsAlias`),rj=Symbol.for(`drizzle:Qualifier`),ij=Symbol.for(`drizzle:ExtraConfigBuilder`),aj=Symbol.for(`drizzle:IsDrizzleTable`),oj=class{static[U]=`Table`;static[Symbol.hasInstance](e){return W(e,this)}static Symbol={Name:YA,Schema:XA,OriginalName:$A,Columns:ZA,ExtraConfigColumns:QA,BaseName:ej,IsAlias:nj,ExtraConfigBuilder:ij,CacheKey:tj};[YA];[$A];[XA];[ZA];[QA];[ej];[tj];[nj]=!1;[aj]=!0;[ij]=void 0;constructor(e,t,n){this[YA]=this[$A]=e,this[XA]=t,this[ej]=n,this[tj]=t?`${t}.${e}`:e}};function sj(e){return e[YA]}var cj=Symbol.for(`drizzle:OriginalColumn`),lj=e=>e;lj.isNoop=!0;var uj=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=lj;mapToDriverValue=lj;postBuild(){return this}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!==`byDefault`}[cj](){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(`)},dj=Symbol.for(`drizzle:ViewBaseConfig`),fj=Symbol.for(`drizzle:IsDrizzleView`),pj=class{static[U]=`View`;static[Symbol.hasInstance](e){return W(e,this)}[dj];[fj]=!0;get[YA](){return this[dj].name}get[XA](){return this[dj].schema}get[nj](){return this[dj].isAlias}get[$A](){return this[dj].originalName}get[ZA](){return this[dj].selectedFields}constructor({name:e,schema:t,selectedFields:n,query:r}){this[dj]={name:e,originalName:e,schema:t,selectedFields:n,query:r,isExisting:!r,isAlias:!1}}},mj=class{static[U]=`Subquery`;static[Symbol.hasInstance](e){return W(e,this)}get[YA](){return this._.alias}get[XA](){}get[$A](){return this._.alias}get[nj](){return!1}get[ZA](){return this._.selectedFields}constructor(e,t,n,r=!1){this._={brand:`Subquery`,sql:e,selectedFields:t,alias:n,isWith:r}}},hj=class extends mj{static[U]=`WithSubquery`};function gj(e){return e!=null&&typeof e.getSQL==`function`}var _j=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=xj(f);if(Sj(f,p,q.string))i.sql+=f.value??``;else if(Sj(f,p,q.sql))this.collectSQL(f.queryChunks,t,n,r||f.shouldInlineParams,i,a,void 0);else if(Sj(f,p,q.name))i.sql+=s(f.value);else if(f!==void 0){if(Sj(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[oj.Symbol.Schema];i.sql+=f.isAlias?s(f.name):f.table[nj]||t===void 0?s(f.table[oj.Symbol.Name])+`.`+s(e):s(t)+`.`+s(f.table[oj.Symbol.Name])+`.`+s(e)}else if(Sj(f,p,q.param)){let e=f.value,o=xj(e);if(Sj(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&&xj(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(Sj(f,p,q.placeholder))i.sql+=c(n.value++,f),a.push(f);else if(Sj(f,p,q.table)){let e=f[oj.Symbol.Schema],t=f[oj.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[nj]?s(t):s(e)+`.`+s(t)}else if(Sj(f,p,q.view)){let e=f[dj].schema,t=f[dj].name;i.sql+=e===void 0||f[dj].isAlias?s(t):s(e)+`.`+s(t)}else if(Sj(f,p,q.aliased)&&f.fieldAlias!==void 0)i.sql+=(f.origin===void 0?``:s(f.origin)+`.`)+s(f.fieldAlias);else if(Sj(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&&xj(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=xj(d);f===q.other?this.collectBoundValue(d,o[u],c[u],t,n,r,i,a):Sj(d,f,q.string)?i.sql+=d.value??``:this.collectSQL([f===q.sql?d:new Dj(d,o[u])],t,n,r,i,a,void 0)}i.sql+=`)`}else if(Sj(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(gj(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)),xj(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},vj=new WeakMap,yj=Symbol(`drizzle:chunkKind`);function bj(e,t){let n=t.has(G[U])?q.string:t.has(_j[U])?q.sql:t.has(Cj[U])?q.name:t.has(uj[U])?q.column:t.has(Dj[U])?q.param:t.has(Aj[U])?q.placeholder:t.has(oj[U])?q.table:t.has(pj[U])?q.view:t.has(_j.Aliased[U])?q.aliased:t.has(mj[U])?q.subquery:t.has(Oj[U])?q.valueRows:q.other;return vj.set(e,n),n!==q.other&&Object.defineProperty(e.prototype,yj,{value:n}),n}function xj(e){if(typeof e!=`object`||!e)return q.other;let t=e[yj];if(t!==void 0)return t;let n=Object.getPrototypeOf(e)?.constructor;return typeof n==`function`?vj.get(n)??bj(n,qA(e)):q.other}function Sj(e,t,n){return t===n}var Cj=class{value;static[U]=`Name`;static[Symbol.hasInstance](e){return W(e,this)}brand;constructor(e){this.value=e}getSQL(){return new _j([this])}};function wj(e){return typeof e==`object`&&!!e&&`mapToDriverValue`in e&&typeof e.mapToDriverValue==`function`}var Tj={mapFromDriverValue:e=>e};Tj.mapFromDriverValue.isNoop=!0;var Ej={mapToDriverValue:e=>e};Ej.mapToDriverValue.isNoop=!0,{...Tj,...Ej};var Dj=class{value;encoder;codec;static[U]=`Param`;static[Symbol.hasInstance](e){return W(e,this)}brand;constructor(e,t=Ej,n){this.value=e,this.encoder=t,this.codec=n}getSQL(){return new _j([this])}},Oj=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=xj(o);r.push(s===q.sql||s===q.string?o:new Dj(o,t[a]))}return r.push(K[`)`]),new _j(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 _j(n)}(function(e){function t(){return new _j([])}e.empty=t;function n(e){return new _j(e)}e.fromList=n;function r(e){return new _j([new G(e)])}e.raw=r;function i(e,t){let{length:n}=e;if(t===void 0||n===0)return new _j(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 _j(r)}e.join=i;function a(e){return new Cj(e)}e.identifier=a;function o(e){return new Aj(e)}e.placeholder=o;function s(e,t){return new Dj(e,t)}e.param=s;function c(e){let t=kj(e);if(t.length)return J.raw(t)}e.comment=c})(J||={});function kj(e){let t=kj.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})(kj||={}),(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})(_j||={});var Aj=class{name;static[U]=`Placeholder`;static[Symbol.hasInstance](e){return W(e,this)}constructor(e){this.name=e}getSQL(){return new _j([this])}};function jj(e){let t=e.queryChunks,n;for(let e=0;e<t.length;++e){let r=t[e];W(r,uj)&&((n??=[...t])[e]=J.identifier(r.name))}if(!n)return e;let r=new _j(n);return r.decoder=e.decoder,r.shouldInlineParams=e.shouldInlineParams,r}function Mj(e,t){for(let n=0;n<e.length;++n){let r=e[n];switch(xj(r)){case q.table:t.add(r[tj]);break;case q.sql:Mj(r.queryChunks,t);break;case q.param:{let e=r.value;xj(e)===q.sql&&Mj(e.queryChunks,t);break}case q.subquery:Mj(r._.sql.queryChunks,t);break;case q.valueRows:Mj(r.cells,t);break;case q.other:case q.aliased:Array.isArray(r)?Mj(r,t):gj(r)&&Mj(r.getSQL().queryChunks,t)}}}uj.prototype.getSQL=function(){return new _j([this])},G.prototype.getSQL=function(){return new _j([this])},mj.prototype.getSQL=function(){return new _j([this])};function Nj(e,t){Object.defineProperty(e,rj,{get(){let e=t(this);return Object.defineProperty(this,rj,{value:e,enumerable:!1,configurable:!0,writable:!0}),e},configurable:!0})}function Pj(e,t){return new _j(e===void 0?[new Cj(t)]:[new Cj(e),K[`.`],new Cj(t)])}Nj(oj.prototype,e=>Pj(e[XA],e[YA])),Nj(pj.prototype,e=>Pj(e[dj].schema,e[dj].name)),Nj(mj.prototype,e=>new Cj(e._.alias));function Fj(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 Ij=Object.getPrototypeOf(()=>null).constructor;function Lj(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 Rj(e,t){let n=`\t"use strict";
|
|
19
|
-
const { columns } = this;
|
|
20
|
-
const { length } = rows;
|
|
21
|
-
const mapped = new Array(length);
|
|
22
|
-
${Lj(e,t)}
|
|
23
|
-
return mapped;
|
|
24
|
-
//# sourceURL=drizzle:jit-query-mapper`;return Object.assign(new Ij(`rows`,n).bind({columns:e}),{body:`function jitQueryMapper (rows) {\n${n}\n}`})}function zj(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?Fj(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 Bj(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,uj))r.push({path:s,field:o,fieldType:`Column`,codec:n?.get(o,`normalize`),arrayDimensions:o.dimensions,column:o});else if(W(o,_j)){let e=Vj(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,_j.Aliased)){let e=Vj(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,mj)){let e,t=Object.values(o._.selectedFields)[0],i;W(t,uj)?(e=t,i=t):W(t,_j)?(e=Vj(t),i=t.decoder):(e=Vj(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,oj)?Bj(o[oj.Symbol.Columns],s,n,r):Bj(o,s,n,r)}return r}function Vj(e){let{decoder:t}=e.getSQL();return Sj(t,xj(t),q.column)?t:void 0}function Hj(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 Uj(e){return e[oj.Symbol.Columns]}function Wj(e){let t=xj(e);return Sj(e,t,q.subquery)?e._.alias:Sj(e,t,q.view)?e[dj].name:Sj(e,t,q.sql)?void 0:e[oj.Symbol.IsAlias]?e[oj.Symbol.Name]:e[oj.Symbol.BaseName]}function Gj(e,t){return{name:typeof e==`string`&&e.length>0?e:``,config:typeof e==`object`?e:t}}typeof TextDecoder>`u`||new TextDecoder;function Kj(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 qj=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===cj&&!this.ignoreColumnAlias?()=>e:e[t]}},Jj=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=Sj(n,xj(n),q.column)?new Proxy(n,this.columnHandler??=new qj(this.view,this.ignoreColumnAlias)):gj(n)?n:new Proxy(n,this),r.set(n,i)),i}},Yj=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===rj)return this.qualifier??=J.identifier(this.alias);if(t===oj.Symbol.IsAlias)return!0;if(t===oj.Symbol.Name||this.replaceOriginalName&&t===oj.Symbol.OriginalName)return this.alias;if(t===oj.Symbol.Columns){let t=e[oj.Symbol.Columns];return t&&(Sj(e,xj(e),q.view)?this.aliasSelection(t,n):this.getProxiedColumns(t,n))}if(t===dj){let t=e[dj],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(Sj(r,xj(r),q.column)){let i=e[oj.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 qj(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 Jj(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}},Xj=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=xj(n);return Sj(n,a,q.column)?i=new Proxy(n,this.columnHandler??=new qj(this.subquery,!0)):Sj(n,a,q.aliased)?(i=n.clone(),i.isSelectionField=!0,i.origin=this.alias):i=n,r.set(n,i),i}},Zj=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===rj)return this.qualifier??=J.identifier(this.alias);if(t===oj.Symbol.IsAlias)return!0;if(t===oj.Symbol.Name)return this.alias;if(t===oj.Symbol.OriginalName)return e._.alias;if(t!==oj.Symbol.Schema)return t===`_`?this.config??={...e._,alias:this.alias,isWith:!0,selectedFields:this.aliasSelection(e,n)}:t===oj.Symbol.Columns?this.aliasSelection(e,n):e[t]}aliasSelection(e,t){return this.selection??=new Proxy(e._.selectedFields,new Xj(t,this.alias))}},Qj=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===cj?()=>e:e[t]}};function $j(e,t){return Sj(e,xj(e),q.subquery)?new Proxy(e,new Zj(t)):new Proxy(e,new Yj(t,!1,!1))}function eM(e){let t=e[oj.Symbol.Schema],n=J.identifier(e[oj.Symbol.OriginalName]);return t?J`${J.identifier(t)}.${n} ${e}`:J`${n} ${e}`}function tM(e,t){return new Proxy(e,new Qj(t))}uj.prototype.as=function(e){return tM(this,e)};function nM(e){return e[cj]()}var rM=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 iM(e,t){if(wj(t)&&!gj(e)){let n=xj(e);if(n!==q.param&&n!==q.placeholder&&n!==q.column&&n!==q.table&&n!==q.view)return new Dj(e,t)}return e}var aM=(e,t,n)=>new _j([e,t,iM(n,e)]),Y=(e,t)=>aM(e,K[` = `],t),oM=(e,t)=>aM(e,K[` <> `],t),sM=(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 _j(n)};function cM(...e){let t=e.filter(e=>e!==void 0);if(t.length!==0)return t.length===1?new _j(t):sM(t,K[`) and (`])}function lM(...e){let t=e.filter(e=>e!==void 0);if(t.length!==0)return t.length===1?new _j(t):sM(t,K[`) or (`])}function uM(e){if(e)return W(e,_j)?J`not (${e})`:J`not ${e}`}var dM=(e,t)=>aM(e,K[` > `],t),fM=(e,t)=>aM(e,K[` >= `],t),pM=(e,t)=>aM(e,K[` < `],t),mM=(e,t)=>aM(e,K[` <= `],t);function hM(e,t){return Array.isArray(t)?t.length===0?new _j([K[`1 = 0`]]):new _j([e,K[` in `],t.map(t=>iM(t,e))]):aM(e,K[` in `],t)}function gM(e,t){return Array.isArray(t)?t.length===0?new _j([K[`1 = 1`]]):new _j([e,K[` not in `],t.map(t=>iM(t,e))]):aM(e,K[` not in `],t)}function _M(e){return J`(${e} is null)`}function vM(e){return J`(${e} is not null)`}function yM(e){return J`exists ${e}`}function bM(e){return J`not exists ${e}`}function xM(e,t,n){return J`${e} between ${iM(t,e)} and ${iM(n,e)}`}function SM(e,t,n){return J`${e} not between ${iM(t,e)} and ${iM(n,e)}`}function CM(e,t){return J`${e} like ${t}`}function wM(e,t){return J`${e} not like ${t}`}function TM(e,t){return J`${e} ilike ${t}`}function EM(e,t){return J`${e} not ilike ${t}`}function DM(e,t){if(Array.isArray(t)){if(t.length===0)throw Error(`arrayContains requires at least one value`);let n=iM(t,e),r=J`${Array.isArray(n)?new Dj(n):n}`;return J`${e} @> ${r}`}return J`${e} @> ${iM(t,e)}`}function OM(e,t){if(Array.isArray(t)){if(t.length===0)throw Error(`arrayContained requires at least one value`);let n=iM(t,e),r=J`${Array.isArray(n)?new Dj(n):n}`;return J`${e} <@ ${r}`}return J`${e} <@ ${iM(t,e)}`}function kM(e,t){if(Array.isArray(t)){if(t.length===0)throw Error(`arrayOverlaps requires at least one value`);let n=iM(t,e),r=J`${Array.isArray(n)?new Dj(n):n}`;return J`${e} && ${r}`}return J`${e} && ${iM(t,e)}`}function AM(e){return J`${e} asc`}function jM(e){return J`${e} desc`}var MM={and:cM,between:xM,eq:Y,exists:yM,gt:dM,gte:fM,ilike:TM,inArray:hM,arrayContains:DM,arrayContained:OM,arrayOverlaps:kM,isNull:_M,isNotNull:vM,like:CM,lt:pM,lte:mM,ne:oM,not:uM,notBetween:SM,notExists:bM,notLike:wM,notIlike:EM,notInArray:gM,or:lM,sql:J},NM={sql:J,asc:AM,desc:jM};function PM(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){PM(o[t.key],!1,t.selection,!1,i);continue}PM(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 FM(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?PM(s,!1,t.selection,!1,i):PM(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 IM({selection:e,isFirst:t,parseJson:n,parseJsonIfString:r,rootJsonMappers:i,arrayModeRoot:a}){return(o=>t&&!o[0]?o[0]:a?FM(t?o[0]:o,t,e,n,r):PM(t?o[0]:o,t,e,n,r,i))}function LM(e,t,n,r,i,a,o,s,c){let l=[],u=[],d=!1,f=e.map(()=>`c${s.n++}`),p=e.map((e,t)=>c?f[t]:`${JSON.stringify(e.key)}: ${f[t]}`);l.push(c?`let [ ${p.join(`, `)} ] = ${t};`:`let { ${p.join(`, `)} } = ${t};`);for(let[t,{field:c,fieldType:p,key:m,codec:h,isArray:g,selection:_,arrayDimensions:v,subqueryDecoder:ee}]of e.entries()){let e=`${n}[${t}]`,te=JSON.stringify(m),ne=f[t];if(_){r?(l.push(`if (${ne} !== null) ${ne} = JSON.parse(${ne});`),d=!0):i&&(l.push(`if (typeof ${ne} === 'string') ${ne} = JSON.parse(${ne});`),d=!0);let t=`s${s.n++}`,n=o.length;if(o.push(`const { selection: ${t} } = ${e};`),g){let e=`j${s.n++}`,r=LM(_,`${ne}[${e}]`,t,!1,i,!0,o,s,!1);if(r.hasWork){d=!0,l.push(`if (${ne} !== null) {`),l.push(`\tfor (let ${e} = 0; ${e} < ${ne}.length; ++${e}) {`);for(let e of r.bodyStmts)l.push(`\t\t${e}`);l.push(`\t\t${ne}[${e}] = ${r.literal};`),l.push(` }`),l.push(`}`)}else o.splice(n,1)}else{let e=LM(_,ne,t,!1,i,!0,o,s,!1);if(e.hasWork){d=!0,l.push(`if (${ne} !== null) {`);for(let t of e.bodyStmts)l.push(`\t${t}`);l.push(`\t${ne} = ${e.literal};`),l.push(`}`)}else o.splice(n,1)}u.push(`${te}: ${ne}`);continue}let re=``,ie=``,ae=!1;switch(p){case`Column`:if(a&&c.mapFromJsonValue){ae=!0;let e=s.n++;ie=`field: dec${e}`,re=`dec${e}.mapFromJsonValue`}else if(!c.mapFromDriverValue.isNoop){let e=s.n++;ie=`field: dec${e}`,re=`dec${e}.mapFromDriverValue`}break;case`SQL`:if(a&&c.decoder.mapFromJsonValue){ae=!0;let e=s.n++;ie=`field: { decoder: dec${e} }`,re=`dec${e}.mapFromJsonValue`}else if(!c.decoder.mapFromDriverValue.isNoop){let e=s.n++;ie=`field: { decoder: dec${e} }`,re=`dec${e}.mapFromDriverValue`}break;case`SQL.Aliased`:if(a&&c.sql.decoder.mapFromJsonValue){ae=!0;let e=s.n++;ie=`field: { sql: { decoder: dec${e} } }`,re=`dec${e}.mapFromJsonValue`}else if(!c.sql.decoder.mapFromDriverValue.isNoop){let e=s.n++;ie=`field: { sql: { decoder: dec${e} } }`,re=`dec${e}.mapFromDriverValue`}break;case`Subquery`:if(a&&ee?.mapFromJsonValue){ae=!0;let e=s.n++;ie=`subqueryDecoder: dec${e}`,re=`dec${e}.mapFromJsonValue`}else if(ee&&!ee.mapFromDriverValue.isNoop){let e=s.n++;ie=`subqueryDecoder: dec${e}`,re=`dec${e}.mapFromDriverValue`}break;case`Nested`:break;default:{let t=c.getSQL();if(a&&t.decoder.mapFromJsonValue){ae=!0;let t=s.n++;o.push(`const dec${t} = ${e}.field.getSQL().decoder;`),re=`dec${t}.mapFromJsonValue`}else if(!t.decoder.mapFromDriverValue.isNoop){let t=s.n++;o.push(`const dec${t} = ${e}.field.getSQL().decoder;`),re=`dec${t}.mapFromDriverValue`}}}let oe=``;if(!ae&&h&&(oe=`codec${s.n++}`),ie||oe){let t=[];ie&&t.push(ie),oe&&t.push(`codec: ${oe}`),o.push(`const { ${t.join(`, `)} } = ${e};`)}if(re||oe){d=!0;let e=ne;oe&&(e=`${oe}(${e}, ${v})`),re&&(e=`${re}(${e})`),u.push(`${te}: ${ne} === null ? null : ${e}`)}else u.push(`${te}: ${ne}`)}return{bodyStmts:l,literal:`{ ${u.join(`, `)} }`,hasWork:d}}function RM({selection:e,isFirst:t,parseJson:n,parseJsonIfString:r,rootJsonMappers:i,arrayModeRoot:a}){let o=[],s=LM(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 Ij(`rows`,l).bind({selection:e}),{body:`function jitRqbMapper (rows) {\n${l}\n}`})}function zM(e,t){let n=e[ZA][t],r=xj(n);return Sj(n,r,q.column)?n:new _j([e,K[`.`],J.identifier(Sj(n,r,q.aliased)?n.fieldAlias:t)])}var BM=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 VM(e,t,n=[]){if(t===rN)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,Aj))return n.push(Y(e,t)),n;let r=Object.entries(t);if(!r.length)return;let i=new BM(n,K[`) and (`]);for(let[t,a]of r)if(a!==rN){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 (`]),VM(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 BM(n,t===`OR`?K[`) or (`]:K[`) and (`]);for(let t of r)o.open(),VM(e,t,n),o.close();o.finish(),i.close();continue}case`isNotNull`:case`isNull`:if(!a)continue;i.push(MM[t](e));continue;case`in`:i.push(MM.inArray(e,a));continue;case`notIn`:i.push(MM.notInArray(e,a));continue;default:i.push(MM[t](e,a));continue}}return i.finish()?n:void 0}function HM(e,t,n={},r={},i,a=0,o=[]){if(t===rN)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 BM(o,K[`) and (`]),l=!1,u=t=>{HM(e,t,n,r,i,a,o).hasRelationFilters&&(l=!0)};for(let[t,d]of s)if(d!==rN){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,MM):d.getSQL();if(t===rN)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 BM(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[ZA],t)&&e[ZA][t]){c.open(),VM(zM(e,t),d,o),c.close();continue}let s=Object.prototype.hasOwnProperty.call(n,t)?n[t]:void 0;if(!s)throw new JA({message:`Unknown relational filter field: "${t}"`});i&&(tN(i,s.targetTable),tN(i,s.throughTable));let u=$j(s.targetTable,`f${a}`),f=s.throughTable?$j(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 `]),nN(u,o),f&&(o.push(K[` inner join `]),nN(f,o),o.push(K[` on `]));let{filter:g}=XM(s,e,u,f,[],o);o.push(K[` where `]);let _=new BM(o,K[`) and (`]);if(_.pushChunks(g),!m){_.open();let e=HM(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 UM=new Set([`min`,`max`,`count`,`avg`,`first`]);function WM(e,t){if(typeof e!=`string`)throw new JA({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 JA({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 JA({message:`Invalid order "${t}": malformed value "${e}", expected "${r}" or "${r}(<aggregate>)"`});let i=n[1].slice(0,-1);if(!UM.has(i))throw new JA({message:`Invalid order "${t}": unknown aggregate "${i}" in "${e}", expected one of: ${[...UM].join(`, `)}`});return{direction:r,aggregate:i}}function GM(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[ZA],l)&&e[ZA][l]){let{direction:n,aggregate:r}=WM(u,t);if(!!r!=!!o?.isAggregated)throw new JA({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=zM(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 BM(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 JA({message:`Unknown relational order field: "${t}"`});let f=d.relationType===`many`&&typeof u==`string`?WM(u,t):void 0,p=f?.aggregate===`count`?f.direction:void 0;if(typeof u!=`object`&&!p)throw new JA({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&&(tN(i,d.targetTable),tN(i,d.throughTable));let m=o?.depth??0,h=$j(d.targetTable,`o${m}`),g=d.throughTable?$j(d.throughTable,`ot${m}`):void 0,_=o?[...o.from,K[` cross join `]]:[];nN(h,_),g&&(_.push(K[` inner join `]),nN(g,_),_.push(K[` on `]));let{filter:v}=XM(d,e,h,g,[],_),ee=o?[...o.filters,v]:[v];if(typeof u!=`object`){s.length>c&&s.push(K[`, `]),s.push(K[`(select count(*) from `]);for(let e=0;e<_.length;++e)s.push(_[e]);let e=s.length;s.push(K[` where `]);let t=new BM(s,K[`) and (`]);for(let e=0;e<ee.length;++e)t.pushChunks(ee[e]);t.finish()||(s.length=e),s.push(K[`)`],p===`asc`?K[` asc`]:K[` desc`])}else GM(h,u,r[d.targetTableName]?.relations??{},r,i,a,{from:_,filters:ee,isAggregated:!!o?.isAggregated||d.relationType===`many`,depth:m+1,path:t},s,c)}return s}function KM(e,t,n={},r={},i,a=`limit`,o=[]){let s=o.length;if(typeof t==`function`){let n=t(e,NM);if(!n)return;let r=xj(n);if(Sj(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),xj(t)!==q.sql&&o.push(K[` asc`])}else Sj(n,r,q.column)&&o.push(n,K[` asc`]);return o.length>s?o:void 0}return GM(e,t,n,r,i,a,void 0,o,s),o.length>s?o:void 0}function qM(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:MM.sql}):c;if(!t)continue;let l=t.getSQL(),u=n?Vj(l):void 0,d=u&&(!r||!u.jsonSelectIdentifier)?new _j([n.apply(u,r?`castInJson`:`cast`,new _j([K[`(`],l,K[`)`]])),K[` as `],J.identifier(s)]):new _j([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 JM({_:{column:e,key:t}}){let n=xj(e);return J.identifier(Sj(e,n,q.column)?e.name:Sj(e,n,q.aliased)?e.fieldAlias:t)}function YM(e,t,n,r,i,a){e.open(),t.push(n,K[`.`],JM(r),K[` = `],i,K[`.`],JM(a)),e.close()}function XM(e,t,n,r,i=[],a=[]){let o=e.isFilterReversed?t:n,s=t[rj],c=n[rj],l=r?.[rj],u=new BM(i,K[`) and (`]);if(e.through){let{sourceColumns:t,targetColumns:n,through:{source:r,target:d}}=e;u.open(),HM(o,e.where,{},{},void 0,0,i),u.close();for(let e=0;e<t.length;++e)YM(u,i,s,t[e],l,r[e]);u.finish();let f=new BM(a,K[`) and (`]);for(let e=0;e<n.length;++e)YM(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)YM(u,i,s,d[e],c,f[e]);return u.open(),HM(o,e.where,{},{},void 0,0,i),u.close(),u.finish(),{filter:i}}function ZM(e,t,n,r,i,a,o=[]){let s=new BM(o,K[`) and (`]),c=!1;return t&&`where`in t&&(s.open(),c=HM(e,t.where,n,r,i,0,o).hasRelationFilters,s.close()),s.pushChunks(a),{sql:s.finish()?o:void 0,hasRelationFilters:c}}function QM(e,t,n,r,i,a,o){a?e.push(i.apply(a,o?`castInJson`:`cast`,new _j([t,K[`.`],J.identifier(n)]))):e.push(t,K[`.`],J.identifier(n)),e.push(K[` as `],J.identifier(r))}function $M(e,t,n,r,i,a,o,s){let c,l,u,d=xj(t);if(Sj(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 _j([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(Sj(t,d,q.sql))c=Vj(t),u=`SQL`,QM(s,e,n,n,o,c,r);else if(Sj(t,d,q.aliased))c=Vj(t),u=`SQL.Aliased`,QM(s,e,t.fieldAlias,n,o,c,r);else if(Sj(t,d,q.subquery)){let i=Object.values(t._.selectedFields)[0],a=xj(i);Sj(i,a,q.column)?(c=i,l=i):Sj(i,a,q.aliased)?(c=Vj(i),l=i.sql.decoder):Sj(i,a,q.sql)&&(c=Vj(i),l=i.decoder),u=`Subquery`,QM(s,e,t._.alias,n,o,c,r)}else if(gj(t))c=Vj(t),u=`SQLWrapper`,QM(s,e,n,n,o,c,r);else throw new JA({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 eN(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[`, `]),$M(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[`, `]),$M(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[`, `]),$M(e,t[l],l,r,n,i,a,o));return o.length>c}function tN(e,t){let n=xj(t);if(e.usedTables!==void 0&&Sj(t,n,q.table)){e.usedTables.add(t[tj]);return}if(!Sj(t,n,q.subquery))return;let r=t._.alias,i=e.subqueries.get(r);if(i&&i._.sql!==t._.sql)throw new JA({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 nN(e,t=[]){if(!e[nj])return t.push(e),t;let n=e[XA];return n&&t.push(J.identifier(n),K[`.`]),t.push(J.identifier(e[$A]),K[` as `],e[rj]),t}var rN=Symbol.for(`drizzle:EmptyFilter`),iN=class e extends Rr()(`@usine/engine/internal/RunDatabase`){static layer=t=>Jf(e)(t)},aN=j.check(PT(/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u,{message:`Expected a GitHub login`})).pipe(L(`OperatorLogin`)),oN=z.pipe(L(`AttentionRevision`)),sN=class extends V(`@usine/engine/AttentionKey`)({id:z,revision:oN}){};V(`@usine/engine/AttentionAcknowledgement`)({...sN.fields,dismissedBy:yE(aN),dismissedAt:vE});var cN=j.check(PT(/\S/u,{message:`Expected a non-blank model ID`})).pipe(L(`ModelId`)),lN=F([`claude`,`codex`,`pi`]),uN=F([`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`]),dN=class extends V(`Agent/BrainSpec`)({harness:lN,model:cN,effort:uN}){},fN=j.check(PT(/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,{message:`Expected a kebab-case agent name`})).pipe(L(`AgentName`)),pN=j.check(PT(/\S/u,{message:`Expected a non-blank agent persona`})).pipe(L(`AgentPersona`)),mN=class extends V(`Agent`)({name:fN,brain:dN,parentModel:yE(cN),parentEffort:xE(uN),persona:pN}){},hN=(e,t)=>xr([e.parentModel,t]),gN=(e,t)=>yr(xr([e.parentEffort,t]),()=>e.brain.effort),_N=e=>{let t=M(e),n=new Set(Object.keys(e)),r=hT(j.check(NT(e=>!n.has(e))),iT.annotate({message:`Unexpected key`}));return t.rebuild(gT(t,[r]).ast)},vN=class extends H(`StepResult/Commit`)(`Commit`,{sha:Qk,summary:z}){},yN=class extends H(`StepResult/PullRequest`)(`PullRequest`,{number:R.check(HT(1)),url:rE}){},bN=F([`issue-comment`,`review`,`review-comment`]),xN=class extends H(`StepResult/Comment`)(`Comment`,{url:rE,kind:bN,at:xE(vE)}){},SN=P([vN,yN,xN]),CN=class extends V(`StepResult`)({message:z,facts:N(SN)}){},wN=z.pipe(L(`StepName`)),TN=class extends V(`Step`)({runId:HA,name:wN,result:B(CN)}){},EN=j.check(PT(/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,{message:`Expected a kebab-case worker name`})).pipe(L(`WorkerName`)),DN=F([`local`,`exe.dev`,`ssh`,`cloudflare`]),ON=j.check(PT(/^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\[bot\]$/u,{message:`Expected a GitHub bot login: <slug>[bot]`})).pipe(L(`BotLogin`)),kN=R.check(HT(1)).pipe(L(`BotUserId`)),AN=class extends V(`BotAccount`)({login:ON,id:kN}){get noreplyEmail(){return`${String(this.id)}+${this.login}@users.noreply.github.com`}},jN=j.check(PT(/^(?:[A-Za-z0-9._-]+@)?(?:[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?|[0-9A-Fa-f]{0,4}(?::[0-9A-Fa-f]{0,4}){2,7})$/u,{message:`Expected an SSH destination: a host name or address, optionally prefixed by a user`})).pipe(L(`SshDestination`)),MN=R.check(UT({minimum:1,maximum:65535})).pipe(L(`SshPort`)),NN=j.check(PT(/^(?:\/|~\/)[!-~]+$/u,{message:`Expected an absolute or ~/ key path without spaces or control characters`})).pipe(L(`SshIdentityFile`)),PN=j.check(PT(/^(?:\/[!-.0-~]+)+$/u,{message:`Expected an absolute directory without spaces, control characters, or a trailing /`})).pipe(L(`WorkerRoot`)),FN=j.check(PT(/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u,{message:`Expected a lowercase DNS domain`})).pipe(L(`GatewayDomain`)),IN=R.check(UT({minimum:1,maximum:65535})).pipe(L(`GatewayAdminPort`)),LN=F([`anthropic`,`openai`]),RN=F([`api-key`,`subscription`]),zN=j.check(PT(/^[a-z0-9][A-Za-z0-9._/:@-]{0,254}$/u,{message:`Expected a container image reference, such as ghcr.io/owner/image:tag, without spaces or a leading dash`})).pipe(L(`ContainerImage`)),BN=j.check(PT(/^[0-9a-f]{64}$/u,{message:`Expected a container ID of 64 lowercase hex digits`})).pipe(L(`ContainerId`)),VN=FT.check(VT(0)).pipe(L(`ContainerCpus`)),HN=R.check(HT(256)).pipe(L(`ContainerMemoryMib`)),UN=R.check(HT(64)).pipe(L(`ContainerPids`)),WN=class extends V(`ContainerLimits`)({cpus:VN,memoryMib:HN,pids:UN}){},GN=[`cpus`,`memoryMib`,`pids`],KN=F([`lite`,`basic`,`standard-1`,`standard-2`,`standard-3`,`standard-4`]),qN=j.check(PT(/^[A-Za-z_][A-Za-z0-9_]{0,62}$/u,{message:`Expected an image name of letters, digits, and underscores that doesn't start with a digit`})).pipe(L(`CloudflareImageName`)),JN=F([`anthropic`,`openai`]),YN=F([`hetzner`,`boat`]),XN=j.check(PT(/^[A-Za-z0-9_-]{1,64}$/u,{message:`Expected a provider machine ID`})).pipe(L(`MachineId`)),ZN=j.check(PT(/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/u,{message:`Expected a Hetzner server type, such as cx33`})).pipe(L(`HetznerServerType`)),QN=j.check(PT(/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/u,{message:`Expected a Hetzner location, such as nbg1`})).pipe(L(`HetznerLocation`)),$N=j.check(PT(/^[!-~](?:[ -~]{0,253}[!-~])?$/u,{message:`Expected a Hetzner image ID, snapshot description, or image name`})).pipe(L(`HetznerImage`)),eP=j.check(PT(/^[!-~](?:[ -~]{0,126}[!-~])?$/u,{message:`Expected a Hetzner resource name without control characters`})).pipe(L(`HetznerResourceName`)),tP=/^(?:[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,nP=hT(j,j.check(PT(/^(?:[a-z0-9A-Z](?:[-_.a-z0-9A-Z]{0,61}[a-z0-9A-Z])?)?$/u,{message:`Expected a Hetzner label value`}))).check(NT(e=>{let t=Object.keys(e),n=t.find(e=>!tP.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}"`})),rP=j.check(PT(/^[a-z_][a-z0-9_-]{0,31}$/u,{message:`Expected a Unix user name`})).pipe(L(`SshUser`)),iP=F([`small`,`default`,`large`,`xlarge`]),aP=j.check(PT(/^[a-z0-9][a-z0-9-]{0,62}$/u),NT(e=>![`latest`,`tree`,`pull`,`rm`,`save`,`current`,`self`,`new`].includes(e),{message:`Expected a non-reserved Boat snapshot name`})).pipe(L(`BoatSnapshotName`)),oP=j.check(PT(/^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(L(`TailnetAddress`)),sP=R.check(UT({minimum:1,maximum:2147483})).pipe(L(`ProvisionerSeconds`)),cP=e=>sP.pipe(DT(w(e)),TT(w(sP.make(e)))),lP=class extends V(`ProvisionerTimings`)(M({sshWait:cP(600),creationBackoffMin:cP(30),creationBackoffMax:cP(600),machineCheckInterval:cP(86400)}).check(NT(e=>e.creationBackoffMin<=e.creationBackoffMax||`Creation backoff minimum must not exceed its maximum`))){},uP=z.pipe(L(`AgentSessionId`)),dP=R.check(HT(0)).pipe(L(`TokenCount`)),fP=R.check(HT(1)),pP=fP.pipe(L(`ChildSessionBudget`)),mP=fP.pipe(L(`ChildSessionCount`)),hP=P([class extends H(`Agent/ParentSession`)(`ParentSession`,{id:uP,agent:fN,brain:dN}){},class extends H(`Agent/ChildSession`)(`ChildSession`,{id:uP,parentId:uP,agent:fN,brain:dN,gatewayCredential:xE(RN).pipe(TT(w(y())))}){}]),gP=z.pipe(L(`HarnessSessionId`)),_P=class extends V(`Agent/HarnessSession`)({id:gP,cwd:z,home:xE(z).pipe(TT(w(y())))}){},vP=class extends H(`Agent/SessionStarted`)(`SessionStarted`,{session:hP,harnessSession:xE(_P).pipe(TT(w(y())))}){},yP=class extends H(`Agent/TextOutput`)(`TextOutput`,{session:hP,text:z}){},bP=class extends H(`Agent/ToolStarted`)(`ToolStarted`,{session:hP,callId:z,tool:z,input:IE}){},xP=class extends H(`Agent/ToolFinished`)(`ToolFinished`,{session:hP,callId:z,tool:z,output:IE,isError:lT}){},SP=class extends H(`Agent/SessionFinished`)(`SessionFinished`,{session:hP}){},CP=class extends H(`Agent/SessionIdle`)(`SessionIdle`,{session:hP}){},wP=class extends H(`Agent/SessionResumed`)(`SessionResumed`,{session:hP}){},TP=FT.check(HT(0)).pipe(L(`UsdAmount`)),EP=R.check(HT(0)),DP=class extends V(`Agent/TokenBreakdown`)({input:EP,cachedInput:EP,cacheWrite:EP,output:EP}){},OP=class extends H(`Agent/SessionTokensUpdated`)(`SessionTokensUpdated`,{session:hP,totalTokens:dP,costUsd:xE(TP).pipe(TT(w(y()))),breakdown:xE(DP).pipe(TT(w(y())))}){},kP=F([`apiKeys`,`claudePlan`,`chatgptPlan`]),AP=(e,t)=>{switch(e.harness){case`claude`:return Fr(t,`api-key`)?`apiKeys`:`claudePlan`;case`codex`:return Fr(t,`api-key`)?`apiKeys`:`chatgptPlan`;case`pi`:return e.model.startsWith(`openai-codex/`)?`chatgptPlan`:`apiKeys`}},jP=e=>kk(e,{ParentSession:({brain:e})=>AP(e,y()),ChildSession:({brain:e,gatewayCredential:t})=>AP(e,t)}),MP=class extends V(`Agent/RateLimitWindow`)({usedPercent:cT,windowDurationMinutes:yE(cT),resetsAt:yE(vE)}){},NP=class extends V(`Agent/RateLimitsSnapshot`)({limitId:yE(j),limitName:yE(j),primary:yE(MP),secondary:yE(MP)}){},PP=class extends H(`Agent/PoolRateLimitsUpdated`)(`PoolRateLimitsUpdated`,{session:hP,pool:kP,rateLimits:NP}){},FP=fP.pipe(L(`ProviderRetries`)),IP=P([vP,yP,bP,xP,PP,SP,CP,wP,OP,class extends H(`Agent/ProviderRetrying`)(`ProviderRetrying`,{session:hP,message:z,retries:FP}){},class extends H(`Agent/ProviderRecovered`)(`ProviderRecovered`,{session:hP,retries:FP}){}]),LP=class extends NE(`AttemptFailure/GitHubPushFailure`)(`GitHubPushFailure`,{repository:Xk,ref:z,message:j}){},RP=class extends NE(`AttemptFailure/InfraFailure`)(`InfraFailure`,{message:j,cause:eE()}){},zP=class extends NE(`AttemptFailure/DefectFailure`)(`DefectFailure`,{message:j,cause:eE()}){},BP=class extends NE(`AttemptFailure/AgentFailure`)(`AgentFailure`,{message:j}){},VP=class extends NE(`AttemptFailure/BlockedFailure`)(`BlockedFailure`,{message:z}){},HP=class extends NE(`AttemptFailure/QuestionFailure`)(`QuestionFailure`,{question:z}){},UP=F([`wall-clock`,`tokens`]),WP=P([LP,RP,zP,BP,VP,HP,class extends NE(`AttemptFailure/RunawayFailure`)(`RunawayFailure`,{ceiling:UP}){},class extends NE(`AttemptFailure/ChildSessionBudgetFailure`)(`ChildSessionBudgetFailure`,{maxChildren:pP,attemptedChildren:mP}){}]),GP=Vw(RP),KP=class extends H(`AttemptOutcome/Succeeded`)(`Succeeded`,{}){},qP=class extends H(`AttemptOutcome/Failed`)(`Failed`,{failure:WP}){},JP=class extends H(`AttemptOutcome/Canceled`)(`Canceled`,{}){},YP=P([KP,qP,JP]),XP=z.pipe(L(`SalvageRef`)),ZP=(e,t)=>XP.make(`usine/salvage/${$k(e)}/${t}`),QP=class extends H(`AttemptSalvage/Pushed`)(`Pushed`,{ref:XP,commit:Qk}){},$P=P([QP,class extends H(`AttemptSalvage/PartlyPushed`)(`PartlyPushed`,{ref:XP,commit:Qk,path:z,message:j}){},class extends H(`AttemptSalvage/Retained`)(`Retained`,{path:z,commit:yE(Qk),message:j,pushFailure:yE(LP).pipe(DT(w(null)),TT(w(y())))}){},class extends H(`AttemptSalvage/Rejected`)(`Rejected`,{path:z,commit:Qk,message:j}){}]),eF=class extends H(`AttemptStart/Event`)(`Event`,{}){},tF=class extends H(`AttemptStart/Retry`)(`OperatorRetry`,{operator:yE(aN)}){},nF=class extends H(`AttemptStart/EditAndRetry`)(`EditAndRetry`,{operator:yE(aN)}){},rF=class extends H(`AttemptStart/InfraRetry`)(`InfraRetry`,{}){},iF=class extends H(`AttemptStart/AfterRestart`)(`AfterRestart`,{}){},aF=P([tF,nF]),oF=P([eF,tF,nF,rF,iF]),sF=z.pipe(L(`AttemptId`)),cF=R.check(HT(1)).pipe(L(`AttemptNumber`)),lF=j.check(PT(/\S/u,{message:`Expected non-blank task text`})).pipe(L(`AttemptTask`)),uF=F([`cancel`,`failed`,`startup`]),dF=class extends V(`AttemptContext`)({task:lF,agent:mN,parentModel:yE(cN)}){},fF=class extends V(`FailureResolution`)(_N({resolvedAt:vE,operator:yE(aN)})){},pF=R.check(HT(1)),mF=class extends V(`OutOfMemoryKills`)({kills:pF,memoryMib:HN}){},hF=class extends V(`ContainerOutOfMemoryKills`)({container:BN,kills:pF,memoryMib:HN}){},gF=e=>new mF({kills:e.reduce((e,{kills:t})=>e+t,0),memoryMib:na(e).memoryMib}),_F=class extends V(`Attempt`)({id:sF,runId:HA,stepName:wN,worker:EN,number:cF,brain:dN,task:lF,agent:fN,operatorIntervened:lT,parentModel:yE(cN),startedAt:_E,outcome:B(YP),endedAt:B(_E),salvage:B($P),failureResolution:B(fF).pipe(TT(w(y()))),start:B(oF).pipe(TT(w(y()))),reattachedAt:B(_E).pipe(TT(w(y()))),comments:N(xN).pipe(TT(w([]))),outOfMemory:B(mF).pipe(TT(w(y())))}){},vF=class extends V(`AttemptWindow`)({attemptId:sF,startedAt:_E,endedAt:B(_E)}){},yF=e=>S(e.outcome)&&x(e.endedAt)?y():b(new vF({attemptId:e.id,startedAt:e.startedAt,endedAt:e.endedAt})),bF=e=>{let t=K_(e.startedAt);return t-t%1e3},xF=(e,t)=>vr(e.endedAt,{onNone:()=>!0,onSome:e=>t<=K_(e)}),SF=(e,t)=>{let n=K_(t);return bF(e)<=n&&xF(e,n)},CF=(e,t)=>xF(e,bF(t))&&xF(t,bF(e)),wF=class extends V(`AttemptWindows`)({own:B(vF),overlapping:N(vF)}){},TF=e=>GP(e.failure)&&e.number<e.maxAutoAttempts,EF=R.check(HT(1)).pipe(L(`AttemptChannelSequence`)),DF=[`inbound`,`outbound`],OF=F(DF),kF=class extends V(`AttemptChannel/RunSpec`)({attemptId:sF,repository:Xk,revision:Zk,baseCommit:Qk,payload:IE,task:lF,agent:mN,parentModel:yE(cN),maxChildren:pP,parentEffort:uN,resume:yE(QP),conflictingSalvage:yE(QP).pipe(DT(w(null)),TT(w(y()))),preparedAt:yE(vE).pipe(DT(w(null))),botLogin:yE(ON).pipe(DT(w(null)))}){},AF=class extends H(`AttemptChannel/Started`)(`Started`,{parentModel:cN,conflictingSalvage:yE(QP).pipe(DT(w(null)),TT(w(y())))}){},jF=class extends H(`AttemptChannel/SessionEvent`)(`SessionEvent`,{event:IP}){},MF=class extends H(`AttemptChannel/Final`)(`Final`,{result:CN}){},NF=class extends H(`AttemptChannel/Failed`)(`Failed`,{failure:WP}){},PF=class extends H(`AttemptChannel/Interrupted`)(`Interrupted`,{}){},FF=class extends H(`AttemptChannel/Steer`)(`Steer`,{message:z}){},IF=class extends H(`AttemptChannel/Interrupt`)(`Interrupt`,{}){},LF=class extends H(`AttemptChannel/Cancel`)(`Cancel`,{}){},RF=class extends H(`AttemptChannel/OperatorMessage`)(`OperatorMessage`,{message:z}){},zF=class extends H(`AttemptChannel/Release`)(`Release`,{}){},BF=P([FF,IF,RF,zF]),VF=P([BF,LF]),HF=class extends H(`AttemptChannel/ParentTarget`)(`Parent`,{}){},UF=class extends H(`AttemptChannel/ChildTarget`)(`Child`,{sessionId:uP}){},WF=P([HF,UF]),GF=class extends V(`AttemptChannel/Intervention`)({operator:z,target:WF,action:BF}){},KF=class extends V(`AttemptChannel/InterventionState`)({held:lT,paused:lT,queued:lT.pipe(DT(w(!1)),TT(w(!1)))}){},qF=class extends H(`AttemptChannel/InterventionApplied`)(`InterventionApplied`,{inputSequence:EF,intervention:GF,state:KF}){},JF=class extends H(`AttemptChannel/InterventionRejected`)(`InterventionRejected`,{inputSequence:EF,intervention:GF,message:z}){},YF=class extends H(`AttemptChannel/WorkerUnresponsive`)(`WorkerUnresponsive`,{worker:EN,lastAnsweredAt:vE,reason:z,unansweredProbes:R.check(HT(1)).pipe(DT(w(1)),TT(w(1)))}){},XF=class extends H(`AttemptChannel/WorkerResponsive`)(`WorkerResponsive`,{worker:EN,lastAnsweredAt:vE,recovered:lT.pipe(DT(w(!0)),TT(w(!0)))}){};P([YF,XF]);var ZF=P([AF,jF,MF,NF,PF,qF,JF,YF,XF]),QF={version:rT(7),attemptId:sF,sequence:EF,sentAt:vE},$F=class extends H(`AttemptChannel/OutboundEnvelope`)(`OutboundEnvelope`,{...QF,payload:ZF}){},eI=class extends H(`AttemptChannel/InboundEnvelope`)(`InboundEnvelope`,{...QF,target:WF.pipe(DT(w({_tag:`Parent`}))),operator:z,payload:VF}){},tI=P([$F,eI]),nI=z.pipe(L(`ItemKey`)),rI=R.check(HT(1)).pipe(L(`ItemNumber`)),iI=R.check(HT(1)).pipe(L(`CycleLimit`)),aI=R.check(HT(0)).pipe(L(`CycleGeneration`)),oI=iI.make(3),sI=R.check(HT(0)).pipe(L(`CycleCount`)),cI=class extends V(`LoopCycleCount`)(_N({loop:aA,admitted:sI,completed:sI}).check(NT(({admitted:e,completed:t})=>t<=e,{message:`Completed runs can't exceed admitted runs`}))){},lI=nA.pipe(L(`CycleBudgetAskId`)),uI=class extends V(`CycleBudgetAsk`)(_N({id:lI,itemKey:nI,repository:Xk,loop:aA,limit:iI,counts:yT(cI)}).check(NT(({loop:e,limit:t,counts:n})=>new Set(n.map(e=>e.loop)).size===n.length&&n.some(n=>n.loop===e&&n.admitted>=t),{message:`Expected unique participating loops, including the exhausted loop at its limit`}))){get completedCycles(){return sI.make(Math.max(...this.counts.map(({completed:e})=>e)))}},dI=[`ui`,`github-ask`],fI=F(dI),pI=class extends V(`ApprovalSource`)(_N({channel:fI,approver:yE(aN)}).check(NT(({channel:e,approver:t})=>e!==`github-ask`||S(t),{message:`Expected an approver for a GitHub ask approval`}))){},mI=class extends V(`RunApproval`)({approvedAt:_E,source:B(pI)}){},hI=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 gI(e,this)}},gI=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[YA],...r,n[0].table[YA],...i];return e??`${a.join(`_`)}_fk`}isNameExplicit(){return!!this.reference().name}};function _I(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 hI(t)}var vI=class extends rM{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 hI(()=>{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))}},yI=class extends uj{static[U]=`SQLiteColumn`;table;constructor(e,t){super(e,t),this.table=e}},bI={},xI={cast:void 0,castInJson:void 0,castParam:void 0,normalize:void 0,normalizeInJson:void 0,normalizeParam:void 0},SI={cast:`cast`,castArray:`cast`,castInJson:`castInJson`,castArrayInJson:`castInJson`,castParam:`castParam`,castArrayParam:`castParam`,normalize:`normalize`,normalizeArray:`normalize`,normalizeInJson:`normalizeInJson`,normalizeArrayInJson:`normalizeInJson`,normalizeParam:`normalizeParam`,normalizeParamArray:`normalizeParam`},CI=class{resolveTypes;codecs;static[U]=`CodecsCollection`;static[Symbol.hasInstance](e){return W(e,this)}constructor(e,t=bI){this.resolveTypes=e,this.codecs=t}itemCodecsCache=new Map;arrayCodecsCache=new Map;codecsOf(e,t){let n=t??e.codec;if(!n)return xI;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}:xI,i.set(n,a)}return a}get(e,t,n){return this.codecsOf(e,n)[SI[t]]}apply(e,t,n,r){let i=SI[t],a=this.codecsOf(e,r)[i];return a?i===`castParam`?a(n,e,e.dimensions):a(n,e.dimensions):n}},wI={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 TI(e){return wI[e]??e}var EI=typeof Buffer>`u`?new TextEncoder:void 0,DI=EI?e=>EI.encode(e):e=>Buffer.from(e),OI={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 kI(e,t){return OI[e]?.[t]}var AI=class extends vI{static[U]=`SQLiteBigIntBuilder`;constructor(e){super(e,`bigint int64`,`SQLiteBigInt`)}build(e){return new jI(e,this.config)}},jI=class extends yI{static[U]=`SQLiteBigInt`;codec=`blob:bigint`;getSQLType(){return`blob`}mapToDriverValue=e=>DI(e.toString())},MI=class extends vI{static[U]=`SQLiteBlobJsonBuilder`;constructor(e){super(e,`object json`,`SQLiteBlobJson`)}build(e){return new NI(e,this.config)}},NI=class extends yI{static[U]=`SQLiteBlobJson`;codec=`blob:json`;getSQLType(){return`blob`}mapToDriverValue=e=>DI(JSON.stringify(e))},PI=class extends vI{static[U]=`SQLiteBlobBufferBuilder`;constructor(e){super(e,`object buffer`,`SQLiteBlobBuffer`)}build(e){return new FI(e,this.config)}},FI=class extends yI{static[U]=`SQLiteBlobBuffer`;codec=`blob`;getSQLType(){return`blob`}};function II(e,t){let{name:n,config:r}=Gj(e,t);return r?.mode===`bigint`?new AI(n):r?.mode===`buffer`?new PI(n):new MI(n)}var LI=class extends vI{static[U]=`SQLiteCustomColumnBuilder`;constructor(e,t,n){super(e,`custom`,`SQLiteCustomColumn`),this.config.fieldConfig=t,this.config.customTypeParams=n}build(e){return new RI(e,this.config)}},RI=class extends yI{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`?TI(n):void 0}getSQLType(){return this.sqlName}};function zI(e){return(t,n)=>{let{name:r,config:i}=Gj(t,n);return new LI(r,i,e)}}var BI=class extends vI{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()}},VI=class extends yI{static[U]=`SQLiteBaseInteger`;autoIncrement=this.config.autoIncrement;getSQLType(){return`integer`}},HI=class extends BI{static[U]=`SQLiteIntegerBuilder`;constructor(e){super(e,`number int53`,`SQLiteInteger`)}build(e){return new UI(e,this.config)}},UI=class extends VI{static[U]=`SQLiteInteger`;codec=`integer`},WI=class extends BI{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 GI(e,this.config)}},GI=class extends VI{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}},KI=class extends BI{static[U]=`SQLiteBooleanBuilder`;constructor(e,t){super(e,`boolean`,`SQLiteBoolean`),this.config.mode=t}build(e){return new qI(e,this.config)}},qI=class extends VI{static[U]=`SQLiteBoolean`;codec=`integer:boolean`;mode=this.config.mode;mapToDriverValue=e=>+!!e};function JI(e,t){let{name:n,config:r}=Gj(e,t);return r?.mode===`timestamp`||r?.mode===`timestamp_ms`?new WI(n,r.mode):r?.mode===`boolean`?new KI(n,r.mode):new HI(n)}var YI=class extends vI{static[U]=`SQLiteNumericBuilder`;constructor(e){super(e,`string numeric`,`SQLiteNumeric`)}build(e){return new XI(e,this.config)}},XI=class extends yI{static[U]=`SQLiteNumeric`;codec=`numeric`;getSQLType(){return`numeric`}},ZI=class extends vI{static[U]=`SQLiteNumericNumberBuilder`;constructor(e){super(e,`number`,`SQLiteNumericNumber`)}build(e){return new QI(e,this.config)}},QI=class extends yI{static[U]=`SQLiteNumericNumber`;codec=`numeric:number`;mapToDriverValue=String;getSQLType(){return`numeric`}},$I=class extends vI{static[U]=`SQLiteNumericBigIntBuilder`;constructor(e){super(e,`bigint int64`,`SQLiteNumericBigInt`)}build(e){return new eL(e,this.config)}},eL=class extends yI{static[U]=`SQLiteNumericBigInt`;codec=`numeric:bigint`;mapToDriverValue=String;getSQLType(){return`numeric`}};function tL(e,t){let{name:n,config:r}=Gj(e,t),i=r?.mode;return i===`number`?new ZI(n):i===`bigint`?new $I(n):new YI(n)}var nL=class extends vI{static[U]=`SQLiteRealBuilder`;constructor(e){super(e,`number double`,`SQLiteReal`)}build(e){return new rL(e,this.config)}},rL=class extends yI{static[U]=`SQLiteReal`;codec=`real`;getSQLType(){return`real`}};function iL(e){return new nL(e??``)}var aL=class extends vI{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 oL(e,this.config)}},oL=class extends yI{static[U]=`SQLiteText`;codec=`text`;enumValues=this.config.enumValues;constructor(e,t){super(e,t)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:``}`}},sL=class extends vI{static[U]=`SQLiteTextJsonBuilder`;constructor(e){super(e,`object json`,`SQLiteTextJson`)}build(e){return new cL(e,this.config)}},cL=class extends yI{static[U]=`SQLiteTextJson`;codec=`text:json`;getSQLType(){return`text`}mapToDriverValue=e=>JSON.stringify(e)};function X(e,t={}){let{name:n,config:r}=Gj(e,t);return r.mode===`json`?new sL(n):new aL(n,r)}function lL(){return{blob:II,customType:zI,integer:JI,numeric:tL,real:iL,text:X}}function uL(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 dL(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 fL(e){return e===`snake_case`?uL:e===`camelCase`?dL:e=>e}var pL=Symbol.for(`drizzle:SQLiteInlineForeignKeys`),mL=class extends oj{static[U]=`SQLiteTable`;static Symbol=Object.assign({},oj.Symbol,{InlineForeignKeys:pL});[oj.Symbol.Columns];[pL]=[];[oj.Symbol.ExtraConfigBuilder]=void 0};function hL(e,t,n,r,i,a=e){let o=fL(i),s=new mL(e,r,a),c=typeof t==`function`?t(lL()):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[pL].push(...n.buildForeignKeys(r,s)),[e,r]})),u=Object.assign(s,l);return u[oj.Symbol.Columns]=l,u[oj.Symbol.ExtraConfigColumns]=l,n&&(u[mL.Symbol.ExtraConfigBuilder]=n),u}function gL(e){return(t,n,r)=>hL(t,n,r,void 0,e)}var _L=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 vL(e,this)}},vL=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 yL(e,t){return new _L(e,t)}var bL=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 xL(this.name,e,this.unique)}},xL=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 SL(this.config,e)}},SL=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 CL(e){return new bL(e,!1)}function wL(e){return new bL(e,!0)}function TL(...e){return e[0].columns?new EL(e[0].columns,e[0].name):new EL(e)}var EL=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 DL(e,this.columns,this.name)}},DL=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[mL.Symbol.Name]}_${this.columns.map(e=>e.name).join(`_`)}_pk`}},OL=Kj(e=>`"${e.replace(/"/g,`""`)}"`),kL={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 `)},AL=class{static[U]=`SQLiteDialect`;static[Symbol.hasInstance](e){return W(e,this)}codecs;mapperGenerators;constructor(e){this.codecs=new CI(TI,e?.codecs),this.mapperGenerators=e?.useJitMappers?{rows:Rj,relationalRows:RM}:{rows:zj,relationalRows:IM}}escapeName(e){return OL(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 _j(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[oj.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,_j)?e:J.param(e,s)}a[e]=e<i-1?J`${J.identifier(s.name)} = ${c}, `:J`${J.identifier(s.name)} = ${c}`}return new _j(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 _j([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=xj(r),s=r?Sj(r,o,q.sql)||Sj(r,o,q.subquery)?void 0:r[oj.Symbol.IsAlias]||r[oj.Symbol.Schema]===void 0?r[oj.Symbol.Name]:`${r[oj.Symbol.Schema]}.${r[oj.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(nM(o).name):J.identifier(o.name):o.isAlias?nM(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,uj)){let{table:e}=i;if((e[oj.Symbol.IsAlias]||e[oj.Symbol.Schema]===void 0?e[oj.Symbol.Name]:`${e[oj.Symbol.Schema]}.${e[oj.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 _j(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,uj)){let{table:e}=i;if((e[oj.Symbol.IsAlias]||e[oj.Symbol.Schema]===void 0?e[oj.Symbol.Name]:`${e[oj.Symbol.Schema]}.${e[oj.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 _j(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 _j(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,mL)?t.push(J`${new G(r.joinType)} join ${i[oj.Symbol.IsAlias]?eM(i):i}${a}`):t.push(J`${new G(r.joinType)} join ${i}${a}`),n<e.length-1&&t.push(K[` `])}return new _j(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,oj)&&e[oj.Symbol.IsAlias])return eM(e);if(W(e,pj)&&e[dj].isAlias){let t=J`${J.identifier(e[dj].originalName)}`;return e[dj].schema&&(t=J`${J.identifier(e[dj].schema)}.${t}`),J`${t} ${J.identifier(e[dj].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??Bj(t,void 0,this.codecs),h=xj(a),g=Sj(a,h,q.subquery)?a._.alias:Sj(a,h,q.view)?a[dj].name:Sj(a,h,q.sql)?void 0:sj(a);for(let e of m)if(W(e.field,uj)&&sj(e.field.table)!==g&&!(e=>o?.some(({alias:t})=>t===(e[oj.Symbol.IsAlias]?sj(e):e[oj.Symbol.BaseName])))(e.field.table)){let t=sj(e.field.table);throw Error(`Your "${e.path.join(`->`)}" field references a column "${t}"."${e.field.name}", but the table "${t}" is not part of the query! Did you forget to join it?`)}let _=!o||o.length===0,v=this.buildWithCTE(e),ee=d?J` distinct`:void 0,te=this.buildSelection(m,{isSingleTable:_,table:a,ignoreCastCodecs:!p||f.length>0}),ne=this.buildFromTable(a),re=this.buildJoins(o),ie=r?J` where ${r}`:void 0,ae=i?J` having ${i}`:void 0,oe=[];if(c)for(let[e,t]of c.entries())oe.push(t),e<c.length-1&&oe.push(K[`, `]);let se=oe.length>0?J` group by ${J.join(oe)}`:void 0,ce=this.buildOrderBy(s),le=this.buildLimit(l),ue=u?J` offset ${u}`:void 0,de=J`${v}select${ee} ${te} from ${ne}${re}${ie}${se}${ae}${ce}${le}${ue}`;return f.length>0?this.buildSetOperations(de,m,p,f):de}buildSetOperations(e,t,n,r){for(let n=0;n<r.length;++n){let i=r[n];e=this.buildSetOperationQuery({leftSelect:e,setOperator:i});let a=Bj(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?kI(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 _j.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 _j.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,yI)?e.push(J.identifier(t.name)):W(t,_j)?e.push(J`${jj(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[oj.Symbol.Columns],l=o?o.map(e=>[e,c[e]]):Object.entries(c),u=a&&!W(t,_j)?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 _j(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 Oj(n,u.map(([,e])=>e))]}let h=this.buildWithCTE(i),g=new _j(m),_=r?J` returning ${this.buildSelection(r,{isSingleTable:!0,ignoreCastCodecs:!s,table:e})}`:void 0,v=n?.length?J.join(n):void 0;return J`${h}insert into ${e} ${p} ${g}${v}${_}`}sqlToQuery(e,t){return e.toQuery({escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,codecs:this.codecs,invokeSource:t})}buildRelationalQuery(e){let t=[],n=this.collectRelationalQuery(e,t);return{sql:new _j(t),selection:n}}collectRelationalQuery({schema:e,table:t,tableConfig:n,queryConfig:r,relationWhere:i,mode:a,nested:o,errorPath:s,depth:c,through:l,jsonb:u,withSubqueries:d,usedTables:f},p){let m=[],h=a===`first`,g=r===!0?void 0:r,_=s??``,v=c??0,ee=d??{subqueries:new Map,usedTables:f};v||(tN(ee,t),t=$j(t,`d${v}`));let te=t[rj],ne=h?1:g?.limit,re=g?.offset,{sql:ie}=ZM(t,g,n.relations,e,ee,i),ae=g?.orderBy?KM(t,g.orderBy,n.relations,e,ee):void 0,oe=g?g.with:void 0,se=[];if(oe)for(let e of Object.keys(oe))oe[e]&&se.push(e);let ce=v?-1:p.length;v||p.push(void 0),p.push(K[`select `]);let le=+!!eN(te,n.table[ZA],m,!!o,n.name,this.codecs,p,g?.columns);if(g?.extras){let e=p.length;le&&p.push(K[`, `]);let n=qM(t,g.extras,this.codecs,!!o,p);m.push(...n.selection),n.sql?++le:p.length=e}if(!le&&!se.length)throw new JA({message:`No fields selected for table "${n.name}"${_?` ("${_}")`:``}`});for(let r of se){let i=oe[r],a=n.relations[r];if(!a)throw new JA({message:`Unknown relation "${n.name}" -> "${r}"`});let s=a.relationType===`one`;tN(ee,a.targetTable),tN(ee,a.throughTable);let c=$j(a.targetTable,`d${v+1}`),l=a.throughTable?$j(a.throughTable,`tr${v}`):void 0,{filter:d,joinCondition:f}=XM(a,t,c,l);le++&&p.push(K[`, `]);let h=p.length;p.push(void 0,kL.relationFrom);let g=this.collectRelationalQuery({table:c,mode:s?`first`:`many`,schema:e,queryConfig:i,tableConfig:e[a.targetTableName],relationWhere:d,nested:!0,errorPath:`${_.length?`${_}.`:``}${r}`,depth:v+1,withSubqueries:ee,through:l?{table:l,condition:f}:void 0,jsonb:u},p);p.push(kL.relationClose,J.identifier(r));let te=[K[`(select `],o?u:kL.json,s?kL.object:kL.groupArray];for(let e=0;e<g.length;++e){let t=g[e];e&&te.push(K[`, `]),te.push(new G(this.escapeString(t.key)),K[`, `]),t.selection?te.push(u,K[`(`],J.identifier(t.key),K[`)`]):te.push(J.identifier(t.key))}te.push(s?K[`)`]:kL.groupArrayClose),p[h]=new _j(te),m.push({field:c,fieldType:`Nested`,key:r,selection:g,isArray:!s,isOptional:(a.optional??!1)||i!==!0&&!!i.where})}return p.push(K[` from `]),nN(t,p),l&&(p.push(K[` inner join `]),nN(l.table,p),p.push(K[` on `],...l.condition)),ie&&p.push(K[` where `],...ie),ae&&p.push(K[` order by `],...ae),ne!==void 0&&p.push(K[` limit `],ne),re!==void 0&&p.push(K[` offset `],re),ce!==-1&&(p[ce]=this.buildWithCTE([...ee.subqueries.values()])),m}},jL=class extends pj{static[U]=`SQLiteViewBase`},ML=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===dj)return{...t[dj],selectedFields:new Proxy(t[dj].selectedFields,this)};if(typeof n==`symbol`)return t[n];let i=xj(t),a=(Sj(t,i,q.subquery)?t._.selectedFields:Sj(t,i,q.view)?t[dj].selectedFields:t)[n];if(a===void 0&&n===`getSQL`){let e=t[n];return typeof e==`function`?e.bind(r??t):e}let o=xj(a);if(Sj(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(Sj(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 Sj(a,o,q.column)?this.config.alias?new Proxy(a,new qj(new Proxy(a.table,new Yj(this.config.alias,this.config.replaceOriginalName??!1,!0)),!0)):a:typeof a!=`object`||!a?a:new Proxy(a,new e(this.config))}};function NL(e){if(W(e,oj))return[e[tj]];let t=new Set;return Mj(e.queryChunks,t),[...t]}var PL=class{static[U]=`TypedQueryBuilder`;static[Symbol.hasInstance](e){return W(e,this)}getSelectedFields(){return this._.selectedFields}},FL=class{builder;static[U]=`SQLiteSelectBuilder`;static[Symbol.hasInstance](e){return W(e,this)}fields;session;dialect;withList;distinct;constructor(e,t=IL){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,mj)?Object.fromEntries(Object.keys(e._.selectedFields).map(t=>[t,e[t]])):W(e,jL)?e[dj].selectedFields:W(e,_j)?{}:Uj(e),new this.builder({table:e,fields:n,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList??[],distinct:this.distinct})}},IL=class extends PL{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=Wj(e),this.joinsNotNullableMap=typeof this.tableName==`string`?{[this.tableName]:!0}:{}}getUsedTables(e=this.getSQL()){return NL(e)}createJoin(e){return(t,n)=>{let r=this.tableName,i=Wj(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,_j))){let e=W(t,mj)?t._.selectedFields:W(t,pj)?t[dj].selectedFields:t[oj.Symbol.Columns];this.config.fields[i]=e}if(typeof n==`function`&&(n=n(new Proxy(this.config.fields,new ML({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(RL()):n;if(!Hj(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 ML({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})))),this.config.where=e,this}having(e){return typeof e==`function`&&(e=e(new Proxy(this.config.fields,new ML({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 ML({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 ML({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??=Bj(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 mj(this.getSQL(),this.config.fields,e),new ML({alias:e,sqlAliasedBehavior:`alias`,sqlBehavior:`error`}))}getSelectedFields(){return new Proxy(this.config.fields,new ML({alias:this.tableName,sqlAliasedBehavior:`alias`,sqlBehavior:`error`}))}$dynamic(){return this}};function LL(e,t){return(n,r,...i)=>{let a=[r,...i].map(n=>({type:e,isAll:t,rightSelect:n}));for(let e of a)if(!Hj(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 RL=()=>({union:zL,unionAll:BL,intersect:VL,except:HL}),zL=LL(`union`,!1),BL=LL(`union`,!0),VL=LL(`intersect`,!1),HL=LL(`except`,!1),UL=class{static[U]=`SQLiteQueryBuilder`;static[Symbol.hasInstance](e){return W(e,this)}dialect;dialectConfig;constructor(e){this.dialect=W(e,AL)?e:void 0,this.dialectConfig=W(e,AL)?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 hj(i,t??(`getSelectedFields`in r?r.getSelectedFields()??{}:{}),e,!0),new ML({alias:e,sqlAliasedBehavior:`alias`,sqlBehavior:`error`}))}}};with(...e){let t=this;function n(n){return new FL({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function r(n){return new FL({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e,distinct:!0})}return{select:n,selectDistinct:r}}select(e){return new FL({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new FL({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){return this.dialect||=new AL(this.dialectConfig),this.dialect}},WL=class{name;static[U]=`SQLiteViewBuilderCore`;static[Symbol.hasInstance](e){return W(e,this)}constructor(e){this.name=e}config={}},GL=class extends WL{static[U]=`SQLiteViewBuilder`;as(e){typeof e==`function`&&(e=e(new UL));let t=new ML({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}),n=e.getSelectedFields();return new Proxy(new qL({config:{name:this.name,schema:void 0,selectedFields:n,query:e.getSQL().inlineParams()}}),t)}},KL=class extends WL{static[U]=`SQLiteManualViewBuilder`;columns;constructor(e,t,n){super(e),this.columns=Uj(hL(e,t,void 0,void 0,n))}existing(){return new Proxy(new qL({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:void 0}}),new ML({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}))}as(e){return new Proxy(new qL({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:e.inlineParams()}}),new ML({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}))}},qL=class extends jL{static[U]=`SQLiteView`;constructor({config:e}){super(e)}};function JL(e){return((t,n)=>n?new KL(t,n,e):new GL(t))}function YL(e,t){return new Proxy(e,new Yj(t,!1))}var XL={table:gL(`snake_case`),view:JL(`snake_case`)},ZL=class extends V(`CycleBudgetReset`)({itemKey:nI,repository:Xk,generation:aI}){},QL=class extends NE(`CycleBudgetResetRejectedError`)(`CycleBudgetResetRejectedError`,{askId:lI}){},$L=[`ItemClosed`];F($L);var eR=M({...ZL.fields,ask:yE(uI),resetPending:lT}),tR=`~effect/encoding/Ndjson/NdjsonError`,nR=new TextEncoder,rR=new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0}),iR=class extends wo(`NdjsonError`){[tR]=tR;get message(){return this.kind}},aR=e=>pe(e,tR),oR=()=>BD((e,t)=>w(E(e,e=>{try{return w(ma(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 Uh(new iR({kind:`Pack`,cause:e}))}}))),sR=()=>ZD(oR(),ha(e=>nR.encode(e))),cR=(e,t,n)=>{let r,i,a=(e,t)=>(r=t,Yi(e)?w(e):t===void 0?void 0:Uh(t)),o=Rh(()=>r===void 0?i===void 0?th(e,{onSuccess:e=>{let n=[];return a(n,t(e,n))??o},onFailure:Wh,onDone:e=>{i={leftover:e};let t=[];return a(t,n(t))??sf(e)}}):sf(i.leftover):Uh(r));return o},lR=(e,t,n,r)=>{if(!(n&&e.length===0))try{t.push(JSON.parse(e))}catch(e){return new iR({kind:`Unpack`,reason:`InvalidJson`,unterminated:r,cause:e})}},uR=10,dR=13,fR=new Uint8Array,pR=e=>BD((t,n)=>zh(()=>{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 iR({kind:`Unpack`,reason:`InvalidUtf8`,unterminated:r,cause:e})}let o=i!==rR;if(i=rR,!(o&&r&&a.length===0))return lR(a,t,n,r)};return cR(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===uR||a===dR){if(a===uR&&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===dR}else if(s=!1,o+i+1-e>r)return new iR({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(fR,0,0),e,!0))})),mR=`~effect/encoding/Sse/SseError`,hR=class extends wo(`EventTooLarge`){get message(){return`Pending SSE event exceeded the maximum size of ${this.maxEventSize}`}},gR=class extends wo(`SseError`){[mR]=mR;get message(){return this.reason.message}},_R=10485760,vR=e=>BD((t,n)=>zh(()=>{let n=[],r,i=bR(e=>{e._tag===`Retry`?r=e:n.push(e)},e),a=E(t,e=>{for(let t=0;t<e.length;t++){let n=i.feed(e[t]);if(n!==void 0)return Uh(n)}return Bh});return Rh(function e(){if(Yi(n)){let e=n;return n=[],w(e)}return r?Uh(r):E(a,e)})})),yR=(e,t,n)=>dO(vR(t),bO(TR.pipe(ST(e,ER)),n)());function bR(e,t){let n=t?.maxEventSize??_R,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(xR)&&(e=e.slice(xR.length)),i=!1;let t=e.length,r=c,l=0;for(;l<t;){if(s&&(s=!1,e.charCodeAt(l)===SR)){++l;continue}let n=l;for(;n<t;){let t=e.charCodeAt(n);if(t===CR||t===SR)break;++n}if(n===t){a.push(e.slice(l)),o+=t-l;break}s=e.charCodeAt(n)===CR;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 gR({reason:new hR({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)===wR?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 OR({duration:eo(parseInt(a,10)),lastEventId:l}))}}var xR=``,SR=10,CR=13,wR=32,TR=M({_tag:kT(`Event`),id:xT(j),event:j,data:j}),ER=Eb({decode:e=>e.id===void 0?{event:e.event,data:e.data}:{id:e.id,event:e.event,data:e.data},encode:e=>({_tag:`Event`,id:e.id,event:e.event??`message`,data:e.data})}),DR=`~effect/encoding/Sse/Retry`,OR=class e extends Co(`Retry`){[DR]=DR;static is(e){return pe(e,DR)}static filter(t){return e.is(t)?Si(t):Ci(t)}},kR=class extends V(`@usine/engine/Submission`)({event:iA,itemKey:nI,loop:aA,step:wN,approval:sA,permissions:lA.pipe(DT(w(`write`)),TT(w(`write`))),cycleLimit:B(iI).pipe(OT(w(b(oI))),TT(w(b(oI)))),cycleGeneration:aI.pipe(DT(w(aI.make(0))),TT(w(aI.make(0)))),repository:Xk,revision:Zk,task:lF,agent:mN,parentModel:B(cN)}){},AR=`@usine/engine/DurableRun`,jR=O(`Submission.runIdFor`)(function*(e){let t=yield*(yield*YO).digest(`SHA-256`,new TextEncoder().encode(`${AR}-${e.event.dedupKey}`)).pipe(fg);return HA.make(Do(t.subarray(0,16)))}),MR=(e,t,n)=>{let r=rA.make(JSON.stringify([`reopened`,n,t]));return new kR({...e,event:new iA({...e.event,id:nA.make(r),dedupKey:r})})},NR=class extends H(`@usine/engine/Claimed`)(`Claimed`,{eventId:nA,runId:HA}){},PR=class extends H(`@usine/engine/Queued`)(`Queued`,{eventId:nA}){},FR=[`superseded`,`revoked`],IR=F(FR),LR=class extends H(`@usine/engine/Ignored`)(`Ignored`,{eventId:nA,reason:IR}){},RR=class extends H(`@usine/engine/Suppressed`)(`Suppressed`,{eventId:nA,runId:HA}){},zR=class extends H(`@usine/engine/CycleBlocked`)(`CycleBlocked`,{eventId:nA,ask:uI}){},BR=P([NR,PR,RR,LR,zR]),VR=XL.table(`usine_events`,{eventId:X().$type().primaryKey(),dedupKey:X().$type().notNull().unique(),payloadJson:X({mode:`json`}).$type().notNull(),receivedAt:X().notNull()},e=>[yL(`usine_events_payload_json_valid`,J`json_valid(${e.payloadJson})`)]),Z=XL.table(`usine_trigger_events`,{eventId:X().$type().primaryKey().references(()=>VR.eventId),itemKey:X().$type().notNull(),loopName:X().$type().notNull(),stepName:X().$type().notNull(),approval:X({enum:oA}).$type().notNull(),permissions:X({enum:cA}).$type().notNull().default(`write`),cycleLimit:JI().$type(),cycleGeneration:JI().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(()=>VR.eventId),reopening:JI().notNull().default(0)},e=>[yL(`usine_trigger_events_approval`,J`${e.approval} in ('none', 'required')`),yL(`usine_trigger_events_cycle_limit`,J`${e.cycleLimit} is null or ${e.cycleLimit} >= 1`),yL(`usine_trigger_events_agent_json_valid`,J`json_valid(${e.agentJson})`),CL(`usine_trigger_events_item`).on(e.loopName,e.itemKey),CL(`usine_trigger_events_item_history`).on(e.itemKey),wL(`usine_trigger_event_reopening`).on(e.reopensEventId,e.reopening)]),HR=XL.table(`usine_loop_items`,{loopName:X().$type().notNull(),itemKey:X().$type().notNull(),observedEventId:X().$type().references(()=>VR.eventId),suppressedByRunId:X().$type().references(()=>Q.runId),suppressedEventId:X().$type().references(()=>VR.eventId)},e=>[TL({columns:[e.loopName,e.itemKey]})]),UR=XL.table(`usine_item_cycle_budgets`,{itemKey:X().$type().primaryKey(),repository:X().$type().notNull(),generation:JI().notNull().default(0),askJson:X({mode:`json`}).$type(),resetPending:JI({mode:`boolean`}).notNull().default(!1)},e=>[yL(`usine_item_cycle_generation`,J`${e.generation} >= 0`),yL(`usine_item_cycle_ask_json`,J`${e.askJson} is null or json_valid(${e.askJson})`)]),WR=XL.table(`usine_cycle_reservations`,{runId:X().$type().primaryKey().references(()=>Q.runId),itemKey:X().$type().notNull().references(()=>UR.itemKey),generation:JI().notNull(),loop:X().$type().notNull()},e=>[CL(`usine_cycle_reservations_item`).on(e.itemKey,e.generation,e.loop),yL(`usine_cycle_reservations_generation`,J`${e.generation} >= 0`)]),GR=XL.table(`usine_cycle_resets`,{askId:X().$type().primaryKey(),eventId:X().$type().notNull().unique().references(()=>VR.eventId),itemKey:X().$type().notNull().references(()=>UR.itemKey)}),KR=XL.table(`usine_cycle_ask_closures`,{askId:X().$type().primaryKey(),itemKey:X().$type().notNull().references(()=>UR.itemKey),reason:X({enum:$L}).$type().notNull(),askJson:X({mode:`json`}).$type().notNull(),closedAt:X().notNull()},e=>[yL(`usine_cycle_ask_closures_reason`,J`${e.reason} in ('ItemClosed')`),yL(`usine_cycle_ask_closures_ask_json`,J`json_valid(${e.askJson})`)]),Q=XL.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=>[yL(`usine_runs_state_json_valid`,J`json_valid(${e.stateJson})`),yL(`usine_runs_agent_json_valid`,J`json_valid(${e.agentJson})`)]),qR=XL.table(`usine_steps`,{runId:X().$type().notNull().references(()=>Q.runId),stepName:X().$type().notNull(),result:X({mode:`json`}).$type()},e=>[TL({columns:[e.runId,e.stepName]}),yL(`usine_steps_result_json_valid`,J`${e.result} is null or json_valid(${e.result})`)]),$=XL.table(`usine_attempts`,{attemptId:X().$type().primaryKey(),runId:X().$type().notNull(),stepName:X().$type().notNull(),workerName:X().$type().notNull(),attemptNumber:JI({mode:`number`}).$type().notNull(),brainJson:X({mode:`json`}).$type().notNull(),task:X().$type().notNull(),agent:X().$type().notNull(),operatorIntervened:JI({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=>[yL(`usine_attempts_number`,J`${e.attemptNumber} >= 1`),yL(`usine_attempts_brain_json_valid`,J`json_valid(${e.brainJson})`),yL(`usine_attempts_outcome_json_valid`,J`${e.outcomeJson} is null or json_valid(${e.outcomeJson})`),yL(`usine_attempts_salvage_json_valid`,J`${e.salvageJson} is null or json_valid(${e.salvageJson})`),wL(`usine_attempt_number`).on(e.runId,e.stepName,e.attemptNumber),wL(`usine_one_in_flight_attempt`).on(e.runId).where(J`${e.outcomeJson} is null`),_I({columns:[e.runId,e.stepName],foreignColumns:[qR.runId,qR.stepName]})]),JR=XL.table(`usine_attempt_transcripts`,{sequence:JI({mode:`number`}).primaryKey({autoIncrement:!0}),attemptId:X().$type().notNull().references(()=>$.attemptId),direction:X({enum:DF}).notNull(),channelSequence:JI({mode:`number`}).$type().notNull(),envelope:X({mode:`json`}).$type().notNull(),receivedAt:X().notNull()},e=>[yL(`usine_attempt_transcripts_direction`,J`${e.direction} in ('inbound', 'outbound')`),yL(`usine_attempt_transcripts_sequence`,J`${e.channelSequence} >= 1`),yL(`usine_attempt_transcripts_envelope_json_valid`,J`json_valid(${e.envelope})`),wL(`usine_attempt_transcript_envelope`).on(e.attemptId,e.direction,e.channelSequence),CL(`usine_attempt_transcript_tail`).on(e.attemptId,e.sequence)]),YR=XL.table(`usine_approvals`,{runId:X().$type().primaryKey().references(()=>Q.runId),eventId:X().$type().notNull().unique().references(()=>VR.eventId),channel:X({enum:dI}).$type(),approver:X().$type()},e=>[yL(`usine_approvals_source`,J`(${e.channel} is null and ${e.approver} is null) or ${e.channel} = 'ui' or (${e.channel} = 'github-ask' and ${e.approver} is not null)`)]),XR=XL.table(`usine_run_again_events`,{eventId:X().$type().primaryKey().references(()=>Z.eventId),fromRunId:X().$type().notNull().references(()=>Q.runId),requestedBy:X().$type()}),ZR=XL.table(`usine_ignored_events`,{eventId:X().$type().primaryKey().references(()=>Z.eventId),reason:X({enum:FR}).$type().notNull()},e=>[yL(`usine_ignored_events_reason`,J`${e.reason} in ('superseded', 'revoked')`)]),QR=XL.table(`usine_cursors`,{cursorKey:X().primaryKey(),valueJson:X({mode:`json`}).$type().notNull()},e=>[yL(`usine_cursors_value_json_valid`,J`json_valid(${e.valueJson})`)]),$R=XL.table(`usine_item_projections`,{itemKey:X().$type().primaryKey(),repository:X().$type().notNull(),source:X().notNull(),itemNumber:JI({mode:`number`}).notNull(),contentHash:X().notNull(),payloadJson:X({mode:`json`}).$type().notNull(),goneAt:X()},e=>[yL(`usine_item_projections_number`,J`${e.itemNumber} >= 1`),yL(`usine_item_projections_payload_json_valid`,J`json_valid(${e.payloadJson})`),wL(`usine_item_projection_number`).on(e.repository,e.itemNumber)]),ez=XL.table(`usine_repository_label_projections`,{repository:X().$type().primaryKey(),labelsJson:X({mode:`json`}).$type().notNull()},e=>[yL(`usine_repository_label_projections_labels_json_valid`,J`json_valid(${e.labelsJson})`)]),tz=XL.table(`usine_board_moves`,{moveId:JI({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=>[yL(`usine_board_moves_added_json_valid`,J`json_valid(${e.addedJson})`),yL(`usine_board_moves_removed_json_valid`,J`json_valid(${e.removedJson})`),CL(`usine_board_moves_item`).on(e.itemKey,e.movedAt)]),nz=XL.table(`usine_loop_runtime`,{loopName:X().$type().primaryKey(),paused:JI({mode:`boolean`}).notNull()}),rz=XL.table(`usine_projection_revision`,{singleton:JI({mode:`number`}).primaryKey().default(1),revision:JI({mode:`number`}).notNull().default(0)},e=>[yL(`usine_projection_revision_singleton`,J`${e.singleton} = 1`)]);XL.table(`usine_attention_acknowledgements`,{id:X().notNull(),revision:X().$type().notNull(),dismissedBy:X().$type(),dismissedAt:X().notNull()},e=>[TL({columns:[e.id,e.revision]})]);var iz=class extends NE(`@usine/engine/RunNotFoundError`)(`RunNotFoundError`,{runId:HA}){},az=class extends NE(`@usine/engine/RunOperationRejectedError`)(`RunOperationRejectedError`,{runId:HA,operation:F([`approve`,`retry`,`resolveFailure`,`runAgain`,`cancel`]),state:j}){},oz=class extends NE(`@usine/engine/RunRetryBlockedError`)(`RunRetryBlockedError`,{runId:HA,openRunId:HA,message:z}){},sz=class extends NE(`@usine/engine/EnginePersistenceError`)(`EnginePersistenceError`,{operation:j,cause:eE()}){},cz=class extends NE(`@usine/engine/AttemptCancellationError`)(`AttemptCancellationError`,{attemptId:sF,cause:eE()}){},lz=P([iz,az,oz,sz]),uz=class extends NE(`@usine/engine/RunInterventionRejectedError`)(`RunInterventionRejectedError`,{runId:HA,attemptId:sF,message:z}){},dz=class extends NE(`@usine/engine/LeftoversDiscardRejectedError`)(`LeftoversDiscardRejectedError`,{worker:EN,running:R.check(HT(0))}){};P([iz,az,oz,sz,cz,uz]);var fz=j.check(PT(/^\S(?:.*\S)?$/u,{message:`Expected a GitHub label name without surrounding whitespace`}),JT(50,{message:`Expected a GitHub label name of at most 50 characters`})).pipe(L(`GitHubLabelName`)),pz=e=>e.toLowerCase(),mz=j.check(PT(/^[0-9a-fA-F]{6}$/u,{message:`Expected a six-digit hex GitHub label color without #`})).pipe(L(`GitHubLabelColor`)),hz=j.check(JT(100,{message:`Expected a GitHub label description of at most 100 characters`})),gz=class extends V(`@usine/config/DeclaredLabel`)({name:fz,color:xE(mz),description:xE(hz)}){},_z=e=>j.check(PT(/\S/u,{message:e})),vz=e=>NT(t=>new Set(t.map(t=>tA(e(t)))).size===t.length,{message:`Expected unique repository names, ignoring case`}),yz=_z(`Expected a non-blank lane name`).pipe(L(`LaneName`)),bz=F([`issue-open`,`issue-closed`,`pr-open`,`pr-closed`,`pr-merged`]),xz=F([`issue-closed`,`pr-closed`,`pr-merged`]),Sz=Vw(xz),Cz=e=>Sz(e),wz=class extends V(`@usine/config/LabelLaneSource`)({label:fz}){},Tz=P([wz,class extends V(`@usine/config/StateLaneSource`)({state:bz}){}]),Ez=class extends V(`@usine/config/Lane`)({name:yz,sources:N(Tz).check(qT())}){},Dz=class extends V(`RunAgain`)(_N({from:HA,requestedBy:yE(aN)})){},Oz=class extends H(`@usine/orchestrator/GitHubPushFailureView`)(`GitHubPushFailure`,{message:j}){},kz=class extends H(`@usine/orchestrator/InfraFailureView`)(`InfraFailure`,{message:j}){},Az=class extends H(`@usine/orchestrator/DefectFailureView`)(`DefectFailure`,{message:j}){},jz=class extends H(`@usine/orchestrator/AgentFailureView`)(`AgentFailure`,{message:j}){},Mz=class extends H(`@usine/orchestrator/BlockedFailureView`)(`BlockedFailure`,{message:j}){},Nz=class extends H(`@usine/orchestrator/QuestionFailureView`)(`QuestionFailure`,{question:j}){},Pz=class extends H(`@usine/orchestrator/RunawayFailureView`)(`RunawayFailure`,{ceiling:UP}){},Fz=class extends H(`@usine/orchestrator/ChildSessionBudgetFailureView`)(`ChildSessionBudgetFailure`,{maxChildren:pP,attemptedChildren:mP}){},Iz=P([Oz,kz,Az,jz,Mz,Nz,Pz,Fz]),Lz=class extends H(`@usine/orchestrator/SucceededAttemptView`)(`Succeeded`,{}){},Rz=class extends H(`@usine/orchestrator/FailedAttemptView`)(`Failed`,{failure:Iz}){},zz=class extends H(`@usine/orchestrator/CanceledAttemptView`)(`Canceled`,{}){},Bz=P([Lz,Rz,zz]),Vz=class extends H(`@usine/orchestrator/LocalWorkerAccess`)(`Local`,{}){},Hz=class extends H(`@usine/orchestrator/SshWorkerAccess`)(`Ssh`,{destination:jN,port:I(MN)}){},Uz=class extends H(`@usine/orchestrator/ProvisionedWorkerAccess`)(`Provisioned`,{provider:YN}){},Wz=class extends H(`@usine/orchestrator/SandboxWorkerAccess`)(`Sandbox`,{}){},Gz=P([Vz,Hz,Uz,Wz]),Kz=class extends V(`@usine/orchestrator/AttemptView`)({id:sF,number:cF,worker:EN,workerAccess:I(Gz),brain:dN,task:lF,agent:fN,operatorIntervened:lT,startedAt:j,outcome:I(Bz),endedAt:I(j),salvage:I($P),start:I(oF).pipe(TT(w(null))),reattachedAt:I(j).pipe(TT(w(null))),outOfMemory:I(mF).pipe(TT(w(null)))}){},qz=F([`preflight`,`prepare`,`launch`,`cancel`,`cleanup`]),Jz=F([`machine`,`toolchain`,`memory`,`harness-login`,`credentials`,`gateway`,`container`,`provider`]),Yz=class extends NE(`@usine/executor/ExecutorOperationError`)(`ExecutorOperationError`,{operation:qz,message:z,cause:eE()}){},Xz=F([`refused`,`unreachable`]),Zz=class extends NE(`@usine/executor/CredentialUnavailableError`)(`CredentialUnavailableError`,{repository:Xk,reason:Xz,message:z,cause:eE()}){},Qz=class extends NE(`@usine/executor/WorkerCapabilityError`)(`WorkerCapabilityError`,{worker:EN,capability:Jz,message:z,cause:eE()}){},$z=F([`capacity`,`quota`,`refused`,`provider`,`unreachable`,`timeout`]);NE(`@usine/executor/MachineUnavailableError`)(`MachineUnavailableError`,{worker:EN,provider:YN,reason:$z,message:z}),P([Yz,Zz,Qz]),V(`@usine/executor/CheckoutRequest`)({attemptId:sF,worker:EN,repository:Xk,loop:aA,permissions:lA,revision:Zk,payload:IE,task:lF,agent:mN,parentModel:B(cN),maxChildren:pP,maxAttemptMinutes:B(R.check(VT(0))),maxAttemptTokens:B(R.check(VT(0))),parentEffort:uN,salvageRef:XP,resume:B(QP),reattach:lT.pipe(TT(w(!1))),botLogin:B(ON).pipe(TT(w(y()))),commitAuthor:AN});var eB=z.pipe(L(`WorktreePath`));V(`@usine/executor/AttemptWorkspace`)({worker:EN,spec:kF,worktree:eB});var tB=Nw(e=>_v(e)&&ee(bv(e)),{expected:`Redacted<string>`});V(`@usine/executor/WorkerCredential`)({value:tB,expiresAt:_E}),Rr()(`@usine/executor/CredentialProvider`),Rr()(`@usine/executor/Executor`);var nB=z.pipe(L(`MachineHold`)),rB=class extends V(`@usine/executor/MachineCheck`)({brains:N(dN),containerLimits:B(WN)}){};V(`@usine/executor/MachineGrant`)({hold:nB,id:XN,worker:EN,provider:YN,checked:B(rB)});var iB=F([`creating`,`ready`,`deleting`]);V(`@usine/executor/MachineStatus`)({worker:EN,provider:YN,state:iB,id:B(XN),runId:B(HA),attemptId:B(sF),since:_E}),Rr()(`@usine/executor/WorkerMachines`);var aB=class extends V(`@usine/orchestrator/MachineView`)({worker:EN,provider:YN,state:iB,id:I(XN),runId:I(HA),attemptId:I(sF),since:j}){},oB=class extends V(`@usine/orchestrator/ProvisioningPauseView`)({reason:P([$z,rT(`check`)]),message:j,failures:R,failedAt:j,retryAt:j,blocked:lT}){},sB=class extends H(`@usine/orchestrator/HetznerProvisionerView`)(`hetzner`,{tokenEnv:j,serverType:ZN,location:QN,image:$N,network:I(eP),firewall:I(eP).pipe(TT(w(null))),sshKey:eP,sshUser:rP,labels:hT(j,j),anthropicKeyEnv:I(j),openaiKeyEnv:I(j)}){},cB=class extends H(`@usine/orchestrator/BoatProvisionerView`)(`boat`,{tokenEnv:j,size:iP,anthropicKeyEnv:I(j),openaiKeyEnv:I(j)}){},lB=P([sB,cB]),uB=e=>new aB({worker:e.worker,provider:e.provider,state:e.state,id:C(e.id),runId:C(e.runId),attemptId:C(e.attemptId),since:J_(e.since)}),dB=e=>new oB({reason:e.reason,message:e.message,failures:e.failures,failedAt:J_(e.failedAt),retryAt:J_(e.retryAt),blocked:e.blocked}),fB=e=>vr(e.provisioner,{onNone:()=>null,onSome:e=>e.provider===`hetzner`?new sB({tokenEnv:e.tokenEnv,serverType:e.serverType,location:e.location,image:e.image,network:C(e.network),firewall:C(e.firewall),sshKey:e.sshKey,sshUser:e.sshUser,labels:e.labels,anthropicKeyEnv:C(e.apiKeys.anthropic),openaiKeyEnv:C(e.apiKeys.openai)}):new cB({tokenEnv:e.tokenEnv,size:e.size,anthropicKeyEnv:C(e.apiKeys.anthropic),openaiKeyEnv:C(e.apiKeys.openai)})}),pB=R.check(HT(1)).pipe(L(`TranscriptSequence`)),mB=F([3,4]),hB=M({...$F.fields,version:mB}),gB=M({_tag:rT(`InboundEnvelope`),version:mB,attemptId:sF,sequence:EF,sentAt:vE,payload:P([FF,IF])}),_B=F([5,6]),vB=P([tI,M({...$F.fields,version:_B}),M({...eI.fields,version:_B}),hB,gB]),yB=class extends V(`@usine/engine/TranscriptEntry`)({sequence:pB,attemptId:sF,direction:OF,envelope:vB,receivedAt:_E}){},bB=class extends H(`@usine/engine/TranscriptAllQuery`)(`TranscriptAllQuery`,{attemptId:sF}){},xB=class extends H(`@usine/engine/TranscriptSessionsQuery`)(`TranscriptSessionsQuery`,{attemptId:sF}){},SB=class extends H(`@usine/engine/TranscriptWorkerQuery`)(`TranscriptWorkerQuery`,{attemptId:sF}){},CB=class extends H(`@usine/engine/TranscriptUsageQuery`)(`TranscriptUsageQuery`,{attemptId:sF}){},wB=class extends H(`@usine/engine/TranscriptTailQuery`)(`TranscriptTailQuery`,{attemptId:sF,after:pB,limit:R.check(HT(1))}){},TB=class extends H(`@usine/engine/TranscriptPageQuery`)(`TranscriptPageQuery`,{attemptId:sF,before:B(pB),limit:R.check(HT(1))}){};P([bB,xB,SB,CB,wB,TB]);var EB=class extends H(`@usine/orchestrator/FailedTranscriptView`)(`Failed`,{failure:Iz}){},DB=P([AF,jF,MF,EB,PF,FF,IF,RF,zF,LF,qF,JF,YF,XF]),OB=class extends V(`@usine/orchestrator/TranscriptEventView`)({sequence:pB,attemptId:sF,receivedAt:j,direction:OF,target:$w(WF),operator:$w(z),payload:DB}){},kB=class extends V(`@usine/orchestrator/TranscriptPageCursor`)({attemptId:sF,before:pB}){},AB=class extends H(`@usine/orchestrator/ColdTranscriptRequest`)(`ColdTranscriptRequest`,{}){},jB=class extends H(`@usine/orchestrator/TailTranscriptRequest`)(`TailTranscriptRequest`,{after:pB}){},MB=class extends H(`@usine/orchestrator/EarlierTranscriptRequest`)(`EarlierTranscriptRequest`,{attemptId:sF,before:pB}){};P([AB,jB,MB]);var NB=class extends NE(`@usine/orchestrator/TranscriptAttemptNotFoundError`)(`TranscriptAttemptNotFoundError`,{runId:HA,attemptId:sF}){},PB=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}]]),FB=(e,t)=>Or(Sr(PB.get(e)),e=>TP.make((t.input*e.input+t.cachedInput*e.cachedInput+t.cacheWrite*(e.cacheWrite??e.input)+t.output*e.output)/1e6)),IB=class extends V(`@usine/engine/RunSnapshot`)({event:iA,itemKey:nI,run:UA,step:TN,attempts:N(_F),resolvedFailureAttemptId:B(sF),closedAt:B(_E),approval:B(mI),runAgain:B(Dz),repository:Xk,revision:Zk,task:lF,agent:mN,parentModel:B(cN),permissions:lA}){},LB=class extends V(`@usine/engine/RunEvent`)({runId:HA,event:iA}){},RB=class extends V(`@usine/engine/RunEvidence`)({snapshot:IB,transcript:N(yB)}){},zB=class extends V(`@usine/engine/RunSummary`)({itemKey:nI,run:UA,step:TN,attempts:N(_F),resolvedFailureAttemptId:B(sF),closedAt:B(_E),approval:B(mI),runAgain:B(Dz),repository:Xk,task:lF,agent:mN}){},BB=class extends V(`@usine/engine/WorkerAttempts`)(M({worker:EN,attempts:R.check(HT(1)),running:R.check(HT(0))}).check(NT(({attempts:e,running:t})=>t<=e,{message:`Expected no more open attempts than attempts`}))){},VB=class extends V(`@usine/engine/LoopSighting`)({loop:aA,itemKey:nI,event:B(nA),run:B(HA),suppressedBy:B(HA)}){},HB=R.check(HT(0)).pipe(L(`ProjectionRevision`)),UB=M({eventId:nA,dedupKey:rA,payload:IE,receivedAt:vE,itemKey:nI,loop:aA,step:wN,approval:sA,permissions:lA,cycleLimit:I(iI),cycleGeneration:aI,repository:Xk,revision:Zk,task:lF,agent:mN,parentModel:I(cN)}),WB=M({itemKey:nI,repository:Xk,revision:Zk,task:lF,agent:mN,parentModel:I(cN),runId:HA,eventId:nA,loop:aA,state:SA,resolvedFailureAttemptId:I(sF),openedAt:vE,closedAt:I(vE),stepName:wN,result:I(CN),approvedAt:I(vE),approvalChannel:I(fI),approver:I(aN),againFrom:I(HA),againRequestedBy:I(aN)}),GB=M({attemptId:sF,runId:HA,stepName:wN,worker:EN,number:cF,brain:dN,task:lF,agent:fN,operatorIntervened:lT,parentModel:I(cN),startedAt:vE,outcome:I(YP),endedAt:I(vE),salvage:I($P),start:I(oF),failureResolution:I(fF),reattachedAt:I(vE),comments:I(N(xN)),outOfMemory:I(N(hF))}),KB=M({sequence:pB,attemptId:sF,direction:OF,envelope:yB.fields.envelope,receivedAt:vE}),qB=M({runId:HA}),JB=M({reason:IR}),YB=M({revision:HB}),XB=M({runId:HA,eventId:nA,dedupKey:rA,payload:IE,receivedAt:vE}),ZB=M({...UB.fields,reopening:R}),QB=M({eventId:nA,dedupKey:rA}),$B=Hw(N(UB)),eV=Hw(N(ZB)),tV=Hw(N(QB)),nV=Hw(N(WB)),rV=Hw(N(XB)),iV=Hw(N(GB)),aV=Hw(N(qB)),oV=Hw(N(JB)),sV=Hw(N(YB)),cV=Hw(N(KB)),lV=Xw(IE),uV=Xw(vE),dV=Xw(SA),fV=Xw(YP),pV=Xw($P),mV=Xw(N(xN)),hV=Xw(N(hF)),gV=Hw(N(M({outOfMemory:I(N(hF))}))),_V=Xw(fF),vV=Xw(oF),yV=Hw(N(M({nextStart:I(aF)}))),bV=Xw(CN),xV=Xw(tI),SV=Xw(mN),CV=Xw(dN),wV=Vw(lz),TV=e=>t=>dg(t,t=>wV(t)?t:new sz({operation:e,cause:t})),EV=e=>new iA({id:e.eventId,dedupKey:e.dedupKey,payload:e.payload,receivedAt:e.receivedAt}),DV=e=>new LB({runId:e.runId,event:EV(e)}),OV=e=>new kR({event:EV(e),itemKey:e.itemKey,loop:e.loop,step:e.step,approval:e.approval,permissions:e.permissions,cycleLimit:Sr(e.cycleLimit),cycleGeneration:e.cycleGeneration,repository:e.repository,revision:e.revision,task:e.task,agent:e.agent,parentModel:Sr(e.parentModel)}),kV=e=>new UA({id:e.runId,eventId:e.eventId,loop:e.loop,state:e.state,openedAt:e.openedAt}),AV=e=>Or(Sr(e.approvedAt),t=>new mI({approvedAt:t,source:Or(Sr(e.approvalChannel),t=>new pI({channel:t,approver:Sr(e.approver)}))})),jV=e=>Or(Sr(e.againFrom),t=>new Dz({from:t,requestedBy:Sr(e.againRequestedBy)})),MV=e=>new TN({runId:e.runId,name:e.stepName,result:Sr(e.result)}),NV=e=>new _F({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:Sr(e.parentModel),startedAt:e.startedAt,outcome:Sr(e.outcome),endedAt:Sr(e.endedAt),salvage:Sr(e.salvage),start:Sr(e.start),failureResolution:Sr(e.failureResolution),reattachedAt:Sr(e.reattachedAt),comments:e.comments??[],outOfMemory:Pr(e.outOfMemory??[],Xi).pipe(Or(gF))}),PV=(e,t)=>new zB({itemKey:e.itemKey,run:kV(e),step:MV(e),attempts:t.map(NV),resolvedFailureAttemptId:Sr(e.resolvedFailureAttemptId),closedAt:Sr(e.closedAt),approval:AV(e),runAgain:jV(e),repository:e.repository,task:e.task,agent:e.agent}),FV=e=>new yB({sequence:e.sequence,attemptId:e.attemptId,direction:e.direction,envelope:e.envelope,receivedAt:e.receivedAt}),IV=_M($.leftoversDiscardedAt),LV=_M($.outcomeJson),RV=e=>{let t=O(`RunStoreQueries.attemptCountsByWorker`)(function*(){let t=yield*e.select({worker:$.workerName,attempts:J`count(*)`,running:J`sum(case when ${LV} then 1 else 0 end)`}).from($).where(IV).groupBy($.workerName).orderBy(AM($.workerName)).execute();return yield*Hw(N(BB))(t)});return{attemptCountsByWorker:t,openAttempts:O(`RunStoreQueries.openAttempts`)(function*(e){return(yield*t()).find(t=>t.worker===e)?.running??0}),discardLeftovers:O(`RunStoreQueries.discardLeftovers`)(function*(t,n){return(yield*e.update($).set({leftoversDiscardedAt:uV(n)}).where(cM(Y($.workerName,t),IV)).returning({attemptId:$.attemptId}).execute()).map(({attemptId:e})=>e)})}},zV={itemKey:UR.itemKey,repository:UR.repository,generation:UR.generation,ask:UR.askJson,resetPending:UR.resetPending},BV=Hw(N(eR),{onExcessProperty:`error`}),VV=e=>{let t=Y(Z.cycleGeneration,J`coalesce((
|
|
30
|
-
select ${UR.generation} from ${UR}
|
|
31
|
-
where ${UR.itemKey} = ${Z.itemKey}
|
|
32
|
-
), 0)`),n=O(`CycleBudget.get`)(function*(t){return yield*D({itemKey:t}),Sr((yield*e.select(zV).from(UR).where(Y(UR.itemKey,t)).execute().pipe(E(BV)))[0])}),r=O(`CycleBudget.counts`)(function*(t){yield*D({itemKey:t.itemKey,generation:t.generation});let n=yM(e.select({id:$.attemptId}).from($).where(Y($.runId,Q.runId))),r=J`json_extract(${Q.stateJson}, '$._tag')`,i=yield*e.select({loop:WR.loop,admitted:J`count(*)`,completed:J`sum(case when ${gM(r,[...AA])} and ${n} then 1 else 0 end)`}).from(WR).innerJoin(Q,Y(Q.runId,WR.runId)).where(cM(Y(WR.itemKey,t.itemKey),Y(WR.generation,t.generation),lM(oM(r,`Canceled`),n))).groupBy(WR.loop).orderBy(AM(WR.loop)).execute();return yield*Hw(N(cI))(i,{onExcessProperty:`error`})});return{admit:O(`CycleBudget.admit`)(function*(t){yield*D({itemKey:t.itemKey,loop:t.loop});let i=yield*n(t.itemKey);if(S(i)&&S(i.value.ask))return yield*k(`Item cycle budget remains exhausted`,{itemKey:t.itemKey,askId:i.value.ask.value.id,loop:t.loop}),i.value.ask;if(x(t.cycleLimit))return y();yield*e.insert(UR).values({itemKey:t.itemKey,repository:t.repository}).onConflictDoNothing().execute();let a=yield*n(t.itemKey);if(x(a))return yield*Kh(Error(`Cycle budget missing after insertion`));let o=yield*r(a.value),s=o.find(({loop:e})=>e===t.loop);if(s===void 0||s.admitted<t.cycleLimit.value)return y();let c=new uI({id:lI.make(nA.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(UR).set({askJson:Xw(uI)(c)}).where(Y(UR.itemKey,t.itemKey)).execute(),yield*e_(`Item cycle budget exhausted; operator reset required`,{itemKey:t.itemKey,repository:t.repository,askId:c.id,loop:c.loop,limit:c.limit,completedCycles:c.completedCycles,counts:c.counts}),b(c)}),reserve:O(`CycleBudget.reserve`)(function*(t,i){if(x(t.cycleLimit))return;yield*D({runId:i,itemKey:t.itemKey,loop:t.loop});let a=yield*n(t.itemKey);if(x(a))return yield*Kh(Error(`Run admitted without its cycle budget`));yield*e.insert(WR).values({runId:i,itemKey:t.itemKey,loop:t.loop,generation:a.value.generation}).onConflictDoNothing().execute(),yield*k(`Item cycle reserved`,{runId:i,itemKey:t.itemKey,loop:t.loop,generation:a.value.generation,counts:yield*r(a.value)})}),get:n,asks:O(`CycleBudget.asks`)(function*(){return(yield*e.select(zV).from(UR).where(vM(UR.askJson)).execute().pipe(E(BV))).flatMap(({ask:e})=>Mr(e))}),pendingResets:O(`CycleBudget.pendingResets`)(function*(){return yield*e.select(zV).from(UR).where(Y(UR.resetPending,!0)).execute().pipe(E(BV))}),isCurrentEvent:O(`CycleBudget.isCurrentEvent`)(function*(e){yield*D({eventId:e.event.id,itemKey:e.itemKey});let t=vr(yield*n(e.itemKey),{onNone:()=>0,onSome:e=>e.generation}),r=e.cycleGeneration===t;return r||(yield*k(`Event observation was superseded by a cycle reset`,{eventId:e.event.id,itemKey:e.itemKey,observedGeneration:e.cycleGeneration,generation:t})),r}),currentEvent:t}},HV=Hw(N(M({observedEventId:I(nA),suppressedByRunId:I(HA),suppressedEventId:I(nA)}))),UV=Hw(N(M({loop:aA,itemKey:nI,observedEventId:I(nA),suppressedByRunId:I(HA)}))),WV=Hw(N(M({eventId:nA,reopensEventId:nA}))),GV=Hw(N(M({eventId:nA,runId:HA}))),KV=e=>{let t=(e,t)=>cM(Y(HR.loopName,e),Y(HR.itemKey,t)),n=O(`LoopItems.row`)(function*(n,r){return Sr((yield*HV(yield*e.select({observedEventId:HR.observedEventId,suppressedByRunId:HR.suppressedByRunId,suppressedEventId:HR.suppressedEventId}).from(HR).where(t(n,r)).execute()))[0])});return{sighted:O(`LoopItems.sighted`)(function*(t,r,i){let a=Or(yield*n(t,r),({observedEventId:e})=>Sr(e));return yield*e.insert(HR).values({loopName:t,itemKey:r,observedEventId:i}).onConflictDoUpdate({target:[HR.loopName,HR.itemKey],set:{observedEventId:i}}).execute(),a}),unmatched:O(`LoopItems.unmatched`)(function*(n,r){yield*e.update(HR).set({observedEventId:null,suppressedByRunId:null,suppressedEventId:null}).where(t(n,r)).execute()}),suppression:O(`LoopItems.suppression`)(function*(e,t){return kr(yield*n(e,t),({suppressedByRunId:e,suppressedEventId:t})=>e===null?y():b({runId:e,suppressedEventId:Sr(t)}))}),startSuppression:O(`LoopItems.startSuppression`)(function*(t,r,i,a,o){if(Ir(yield*n(t,r),({observedEventId:e})=>e===null))return!1;let s=C(o);return yield*e.insert(HR).values({loopName:t,itemKey:r,observedEventId:a,suppressedByRunId:i,suppressedEventId:s}).onConflictDoUpdate({target:[HR.loopName,HR.itemKey],set:{suppressedByRunId:i,suppressedEventId:s}}).execute(),!0}),suppressFrom:O(`LoopItems.suppressFrom`)(function*(n,r,i){yield*e.update(HR).set({suppressedEventId:i}).where(cM(t(n,r),vM(HR.suppressedByRunId))).execute()}),lift:O(`LoopItems.lift`)(function*(n,r){yield*e.update(HR).set({suppressedByRunId:null,suppressedEventId:null}).where(t(n,r)).execute()}),liftRun:O(`LoopItems.liftRun`)(function*(t){return(yield*e.update(HR).set({suppressedByRunId:null,suppressedEventId:null}).where(Y(HR.suppressedByRunId,t)).returning({loopName:HR.loopName}).execute()).length>0}),sightings:O(`LoopItems.sightings`)(function*(t){let n=[...new Set(t)];if(n.length===0)return[];let r=(yield*Ph(ua(n,100),t=>e.select({loop:HR.loopName,itemKey:HR.itemKey,observedEventId:HR.observedEventId,suppressedByRunId:HR.suppressedByRunId}).from(HR).where(hM(HR.itemKey,t)).execute().pipe(E(UV)))).flat(),i=[...new Set(r.flatMap(({observedEventId:e})=>e===null?[]:[e]))],a=(yield*Ph(ua(i,100),t=>e.select({eventId:Z.eventId,reopensEventId:Z.reopensEventId}).from(Z).where(hM(Z.reopensEventId,t)).orderBy(jM(Z.reopening)).execute().pipe(E(WV)))).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*Ph(ua(i.map(s),100),t=>e.select({eventId:Q.eventId,runId:Q.runId}).from(Q).where(hM(Q.eventId,t)).execute().pipe(E(GV)))).flat().map(({eventId:e,runId:t})=>[e,t]));return r.map(({loop:e,itemKey:t,observedEventId:n,suppressedByRunId:r})=>{let i=Or(Sr(n),s);return new VB({loop:e,itemKey:t,event:i,run:kr(i,e=>Sr(c.get(e))),suppressedBy:Sr(r)})})})}},qV=e=>({appendTranscript:O(`RunStoreQueries.appendTranscript`)(function*(t,n,r){return(yield*e.insert(JR).values({attemptId:n.attemptId,direction:t,channelSequence:n.sequence,envelope:xV(n),receivedAt:uV(r)}).onConflictDoNothing().returning({sequence:JR.sequence}).execute()).length>0}),transcript:O(`RunStoreQueries.transcript`)(function*(t){yield*D({attemptId:t.attemptId,query:t._tag});let n=kk(t,{TranscriptWorkerQuery:({attemptId:e})=>cM(Y(JR.attemptId,e),Y(JR.direction,`outbound`),J`json_extract(${JR.envelope}, '$.payload._tag') IN ('WorkerUnresponsive', 'WorkerResponsive')`),TranscriptSessionsQuery:({attemptId:t})=>hM(JR.sequence,e.select({sequence:J`max(${JR.sequence})`}).from(JR).where(cM(Y(JR.attemptId,t),J`(
|
|
33
|
-
json_extract(${JR.envelope}, '$.payload._tag') = 'InterventionApplied'
|
|
34
|
-
OR (json_extract(${JR.envelope}, '$.payload._tag') = 'SessionEvent'
|
|
35
|
-
AND json_extract(${JR.envelope}, '$.payload.event._tag') IN ('SessionStarted', 'SessionIdle', 'SessionResumed', 'SessionFinished'))
|
|
36
|
-
)`)).groupBy(J`coalesce(json_extract(${JR.envelope}, '$.payload.event.session.id'), json_extract(${JR.envelope}, '$.payload.intervention.target.sessionId'), '@parent')`,J`json_extract(${JR.envelope}, '$.payload._tag')`,J`json_extract(${JR.envelope}, '$.payload.event._tag') = 'SessionStarted'`)),TranscriptUsageQuery:({attemptId:t})=>{let n=e.select({sequence:JR.sequence,tokens:J`max(json_extract(${JR.envelope}, '$.payload.event.totalTokens'))`.as(`tokens`)}).from(JR).where(cM(Y(JR.attemptId,t),J`json_extract(${JR.envelope}, '$.payload._tag') = 'SessionEvent'`,J`json_extract(${JR.envelope}, '$.payload.event._tag') = 'SessionTokensUpdated'`)).groupBy(J`json_extract(${JR.envelope}, '$.payload.event.session.id')`).as(`highest`);return hM(JR.sequence,e.select({sequence:n.sequence}).from(n))},TranscriptAllQuery:({attemptId:e})=>Y(JR.attemptId,e),TranscriptTailQuery:({attemptId:e,after:t})=>cM(Y(JR.attemptId,e),dM(JR.sequence,t)),TranscriptPageQuery:({attemptId:e,before:t})=>vr(t,{onNone:()=>Y(JR.attemptId,e),onSome:t=>cM(Y(JR.attemptId,e),pM(JR.sequence,t))})}),r=e.select({sequence:JR.sequence,attemptId:JR.attemptId,direction:JR.direction,envelope:JR.envelope,receivedAt:JR.receivedAt}).from(JR).where(n);return(yield*cV(yield*kk(t,{TranscriptWorkerQuery:()=>r.orderBy(jM(JR.sequence)).limit(1).execute(),TranscriptSessionsQuery:()=>r.orderBy(AM(JR.sequence)).execute(),TranscriptUsageQuery:()=>r.orderBy(AM(JR.sequence)).execute(),TranscriptAllQuery:()=>r.orderBy(AM(JR.sequence)).execute(),TranscriptTailQuery:({limit:e})=>r.orderBy(AM(JR.sequence)).limit(e).execute(),TranscriptPageQuery:({limit:e})=>r.orderBy(jM(JR.sequence)).limit(e).execute()}),{onExcessProperty:`error`})).map(FV).sort((e,t)=>e.sequence-t.sequence)})}),JV=(e,t)=>K_(t.openedAt)-K_(e.openedAt)||t.runId.localeCompare(e.runId),YV={eventId:VR.eventId,dedupKey:VR.dedupKey,payload:VR.payloadJson,receivedAt:VR.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},XV=YL(VR,`approval_event`),ZV={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:qR.stepName,result:qR.result,approvedAt:XV.receivedAt,approvalChannel:YR.channel,approver:YR.approver,againFrom:XR.fromRunId,againRequestedBy:XR.requestedBy},QV={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},$V=J`json_extract(${Q.stateJson}, '$._tag')`,eH=hM($V,[...AA]),tH=hM($V,[...MA]),nH=e=>Kw(IE)(SV(e)),rH=e=>{let t=O(`RunStoreQueries.eventRouteByDedup`)(function*(t){return yield*$B(yield*e.select(YV).from(VR).innerJoin(Z,Y(Z.eventId,VR.eventId)).where(Y(VR.dedupKey,t)).execute())}),n=O(`RunStoreQueries.eventRouteByRun`)(function*(t){return yield*$B(yield*e.select(YV).from(Q).innerJoin(VR,Y(VR.eventId,Q.eventId)).innerJoin(Z,Y(Z.eventId,VR.eventId)).where(Y(Q.runId,t)).execute())}),r=()=>e.select(ZV).from(Q).innerJoin(Z,Y(Z.eventId,Q.eventId)).innerJoin(qR,Y(qR.runId,Q.runId)).leftJoin(YR,Y(YR.runId,Q.runId)).leftJoin(XV,Y(XV.eventId,YR.eventId)).leftJoin(XR,Y(XR.eventId,Q.eventId)),i=O(`RunStoreQueries.runRows`)(function*(e){return yield*nV(yield*r().where(Y(Q.runId,e)).execute())}),a=(...t)=>T(function*(){let n=yield*e.select({attemptId:$.attemptId,worker:$.workerName,repository:Q.repository,runId:$.runId,loop:Z.loopName,itemKey:Z.itemKey,number:$.attemptNumber,permissions:Z.permissions,outcome:J`coalesce(json_extract(${$.outcomeJson}, '$._tag'), '')`,salvage:$.salvageJson}).from($).innerJoin(Q,Y(Q.runId,$.runId)).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(cM(_M($.leftoversDiscardedAt),...t)).execute();return(yield*Hw(N(M({attemptId:sF,worker:EN,repository:Xk,runId:HA,loop:aA,itemKey:nI,number:cF,permissions:lA,outcome:j,salvage:I($P)})))(n)).map(({number:e,outcome:t,salvage:n,...r})=>({...r,ref:ZP(r.runId,e),succeeded:t===`Succeeded`,open:t===``,rejected:n?._tag===`Rejected`?b(n):y()}))}),o=O(`RunStoreQueries.salvageCandidates`)(function*(){return yield*a()}),s=O(`RunStoreQueries.salvageCandidate`)(function*(e){return yield*D({attemptId:e}),ea(yield*a(Y($.attemptId,e)))}),c=O(`RunStoreQueries.attemptRows`)(function*(t){return yield*iV(yield*e.select(QV).from($).where(Y($.runId,t)).orderBy($.attemptNumber).execute())}),l=O(`RunStoreQueries.snapshot`)(function*(e){let[t,r,a]=yield*Nh([i(e),c(e),n(e)]),o=t[0],s=a[0];return o===void 0||s===void 0?yield*new iz({runId:e}):new IB({event:EV(s),itemKey:s.itemKey,run:kV(o),step:MV(o),attempts:r.map(NV),resolvedFailureAttemptId:Sr(o.resolvedFailureAttemptId),closedAt:Sr(o.closedAt),approval:AV(o),runAgain:jV(o),repository:o.repository,revision:o.revision,task:o.task,agent:o.agent,parentModel:Sr(o.parentModel),permissions:s.permissions})}),u=O(`RunStoreQueries.summariesWithAttempts`)(function*(t){let n=da((yield*Ph(ua(t.map(({runId:e})=>e),100),t=>e.select(QV).from($).where(hM($.runId,t)).orderBy(AM($.runId),AM($.attemptNumber)).execute().pipe(E(iV)))).flat(),({runId:e})=>e);return t.map(e=>PV(e,n[e.runId]??[]))}),d=O(`RunStoreQueries.itemRunSummaries`)(function*(e){if(e.length===0)return[];let t=(yield*Ph(ua([...new Set(e)],100),e=>r().where(hM(Z.itemKey,e)).execute().pipe(E(nV)))).flat().sort(JV);return yield*u(t)}),f=O(`RunStoreQueries.runSummaries`)(function*(e){let[t,n]=yield*Nh([r().where(eH).orderBy(jM(Q.openedAt),jM(Q.runId)).execute().pipe(E(nV)),r().where(gM($V,[...AA])).orderBy(jM(Q.openedAt),jM(Q.runId)).limit(e).execute().pipe(E(nV))]),i=[...t,...n].sort(JV);return yield*u(i)}),p=O(`RunStoreQueries.runEvents`)(function*(t){return(yield*Ph(ua([...new Set(t)],100),t=>e.select({runId:Q.runId,eventId:VR.eventId,dedupKey:VR.dedupKey,payload:VR.payloadJson,receivedAt:VR.receivedAt}).from(Q).innerJoin(VR,Y(VR.eventId,Q.eventId)).where(hM(Q.runId,t)).execute().pipe(E(rV)))).flat().map(DV)}),m=O(`RunStoreQueries.closedRunSummaries`)(function*(e){let t=yield*r().where(gM($V,[...AA])).orderBy(jM(Q.closedAt),jM(Q.runId)).limit(e).execute().pipe(E(nV));return yield*u(t)}),h=O(`RunStoreQueries.closedRunSummariesSince`)(function*(e){let t=gM($V,[...AA]),n=yield*r().where(vr(e,{onNone:()=>t,onSome:e=>cM(t,fM(Q.closedAt,uV(e)))})).orderBy(jM(Q.closedAt),jM(Q.runId)).execute().pipe(E(nV));return yield*u(n)}),g=O(`RunStoreQueries.projectionRevision`)(function*(){return Sr((yield*sV(yield*e.select({revision:rz.revision}).from(rz).where(Y(rz.singleton,1)).limit(1).execute()))[0]?.revision)}),_=O(`RunStoreQueries.updateState`)(function*(t,n,r){let i=TA(n)?null:uV(r??(yield*B_));if((yield*e.update(Q).set({stateJson:dV(n),closedAt:i}).where(Y(Q.runId,t)).returning({runId:Q.runId}).execute()).length===0)return yield*new iz({runId:t})}),v=O(`RunStoreQueries.resolveFailure`)(function*(t,n,r){yield*D({runId:t,attemptId:n}),yield*e.update($).set({failureResolutionJson:_V(r)}).where(Y($.attemptId,n)).execute(),yield*e.update(Q).set({resolvedFailureAttemptId:n}).where(Y(Q.runId,t)).execute()}),ee=O(`RunStoreQueries.addAttempt`)(function*(t){yield*e.insert($).values({attemptId:t.id,runId:t.runId,stepName:t.stepName,workerName:t.worker,attemptNumber:t.number,brainJson:CV(t.brain),task:t.task,agent:t.agent,operatorIntervened:t.operatorIntervened,parentModel:C(t.parentModel),startedAt:uV(t.startedAt),outcomeJson:null,endedAt:null,salvageJson:null,startJson:vr(t.start,{onNone:()=>null,onSome:vV})}).execute()}),te=O(`RunStoreQueries.recordReattach`)(function*(t,n){yield*D({attemptId:t}),yield*e.update($).set({reattachedAt:uV(n)}).where(Y($.attemptId,t)).execute()}),ne=O(`RunStoreQueries.nextStart`)(function*(t){return Sr((yield*yV(yield*e.select({nextStart:Q.nextStartJson}).from(Q).where(Y(Q.runId,t)).execute()))[0]?.nextStart)}),re=O(`RunStoreQueries.setNextStart`)(function*(t,n){yield*e.update(Q).set({nextStartJson:vr(n,{onNone:()=>null,onSome:vV})}).where(Y(Q.runId,t)).execute()}),ie=O(`RunStoreQueries.recordSalvage`)(function*(t,n){yield*D({attemptId:t,salvage:n._tag}),yield*e.update($).set({salvageJson:pV(n)}).where(Y($.attemptId,t)).execute(),n._tag===`Retained`&&S(n.pushFailure)&&(yield*e.update($).set({outcomeJson:fV(new qP({failure:n.pushFailure.value}))}).where(cM(Y($.attemptId,t),J`json_extract(${$.outcomeJson}, '$._tag') = 'Failed'`,J`json_extract(${$.outcomeJson}, '$.failure._tag') != 'GitHubPushFailure'`)).execute())}),ae=O(`RunStoreQueries.recordComments`)(function*(t,n){yield*D({attemptId:t,comments:n.length}),yield*e.update($).set({commentsJson:mV(n)}).where(Y($.attemptId,t)).execute()}),oe=O(`RunStoreQueries.recordOutOfMemory`)(function*(t,n){yield*D({attemptId:t,container:n.container,kills:n.kills});let r=qi(((yield*gV(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:hV(r)}).where(Y($.attemptId,t)).execute(),gF(r)}),se=O(`RunStoreQueries.closeAttempt`)(function*(t,n,r){yield*e.update($).set({outcomeJson:fV(n),endedAt:uV(r)}).where(cM(Y($.attemptId,t),_M($.outcomeJson))).execute()}),ce=O(`RunStoreQueries.amend`)(function*(t,n){yield*D({runId:t,agent:n.agent.name}),yield*e.update(Q).set({task:n.task,agentJson:nH(n.agent),parentModel:C(n.parentModel)}).where(Y(Q.runId,t)).execute()}),le=O(`RunStoreQueries.markIntervened`)(function*(t){yield*D({attemptId:t}),yield*e.update($).set({operatorIntervened:!0}).where(Y($.attemptId,t)).execute()}),ue=O(`RunStoreQueries.updateAttemptParentModel`)(function*(t,n){yield*e.update($).set({parentModel:n}).where(Y($.attemptId,t)).execute()}),de=O(`RunStoreQueries.updateStepResult`)(function*(t,n,r){yield*e.update(qR).set({result:bV(r)}).where(cM(Y(qR.runId,t),Y(qR.stepName,n))).execute()}),fe=O(`RunStoreQueries.approvalExists`)(function*(t){return(yield*e.$count(YR,Y(YR.runId,t)).execute())>0}),pe=O(`RunStoreQueries.recordApproval`)(function*(t,n,r){yield*e.insert(VR).values({eventId:n.id,dedupKey:n.dedupKey,payloadJson:lV(n.payload),receivedAt:uV(n.receivedAt)}).onConflictDoNothing().execute(),yield*e.insert(YR).values({runId:t,eventId:n.id,channel:r.channel,approver:C(r.approver)}).execute()}),me=O(`RunStoreQueries.createRun`)(function*(t,n,r){let i=YL(Z,`candidate`),a=YL(Q,`candidate_run`),o=YL(ZR,`ignored`);yield*e.insert(ZR).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(cM(Y(i.loopName,t.loop),Y(i.itemKey,t.itemKey),oM(i.eventId,n),_M(a.runId),_M(o.eventId)))).onConflictDoNothing().execute(),yield*e.insert(Q).values({runId:r,eventId:n,loopName:t.loop,stateJson:dV(new mA),openedAt:uV(t.event.receivedAt),repository:t.repository,revision:t.revision,task:t.task,agentJson:nH(t.agent),parentModel:C(t.parentModel)}).onConflictDoNothing().execute(),yield*e.insert(qR).values({runId:r,stepName:t.step,result:null}).onConflictDoNothing().execute()}),he=O(`RunStoreQueries.runForEvent`)(function*(t){return yield*aV(yield*e.select({runId:Q.runId}).from(Q).where(Y(Q.eventId,t)).execute())}),ge=O(`RunStoreQueries.ignoredEvent`)(function*(t){return yield*oV(yield*e.select({reason:ZR.reason}).from(ZR).where(Y(ZR.eventId,t)).execute())}),_e=O(`RunStoreQueries.blockingRun`)(function*(t,n){return yield*aV(yield*e.select({runId:Q.runId}).from(Q).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(cM(Y(Z.loopName,t),Y(Z.itemKey,n),eH)).orderBy(jM(Q.openedAt)).limit(1).execute())}),ve=O(`RunStoreQueries.newestReopening`)(function*(t){return Or(Sr((yield*eV(yield*e.select({...YV,reopening:Z.reopening}).from(VR).innerJoin(Z,Y(Z.eventId,VR.eventId)).where(Y(Z.reopensEventId,t)).orderBy(jM(Z.reopening)).limit(1).execute()))[0]),e=>({submission:OV(e),reopening:e.reopening}))}),ye=O(`RunStoreQueries.reopenedEvent`)(function*(t){let n=YL(VR,`reopened_event`);return Sr((yield*tV(yield*e.select({eventId:n.eventId,dedupKey:n.dedupKey}).from(Z).innerJoin(n,Y(n.eventId,Z.reopensEventId)).where(Y(Z.eventId,t)).execute()))[0])}),be=O(`RunStoreQueries.recordRunAgain`)(function*(t,n){yield*e.insert(XR).values({eventId:t,fromRunId:n.from,requestedBy:C(n.requestedBy)}).execute()}),xe=O(`RunStoreQueries.recordTriggerEvent`)(function*(n,r=y()){yield*e.insert(VR).values({eventId:n.event.id,dedupKey:n.event.dedupKey,payloadJson:lV(n.event.payload),receivedAt:uV(n.event.receivedAt)}).onConflictDoNothing().execute();let i=(yield*t(n.event.dedupKey))[0];return i===void 0?(yield*e.insert(Z).values({eventId:n.event.id,itemKey:n.itemKey,loopName:n.loop,stepName:n.step,approval:n.approval,permissions:n.permissions,cycleLimit:C(n.cycleLimit),cycleGeneration:n.cycleGeneration,repository:n.repository,revision:n.revision,task:n.task,agentJson:nH(n.agent),parentModel:C(n.parentModel),reopensEventId:C(Or(r,({eventId:e})=>e)),reopening:vr(r,{onNone:()=>0,onSome:({reopening:e})=>e})}).execute(),n):OV(i)}),Se=O(`RunStoreQueries.nextQueued`)(function*(t){let r=(yield*n(t))[0];if(r===void 0)return y();let i=yield*KV(e).suppression(r.loop,r.itemKey);if(S(i))return yield*k(`Queued Events wait while a suppression keeps the Item`,{runId:t,suppressedBy:i.value.runId,loop:r.loop,itemKey:r.itemKey}),y();let a=yield*$B(yield*e.select(YV).from(VR).innerJoin(Z,Y(Z.eventId,VR.eventId)).leftJoin(Q,Y(Q.eventId,VR.eventId)).leftJoin(ZR,Y(ZR.eventId,VR.eventId)).where(cM(Y(Z.loopName,r.loop),Y(Z.itemKey,r.itemKey),VV(e).currentEvent,_M(Q.runId),_M(ZR.eventId))).orderBy(jM(VR.receivedAt)).execute());return Sr(a[0]).pipe(Or(e=>({submission:OV(e),eventIds:a.map(e=>e.eventId)})))}),Ce=O(`RunStoreQueries.runIdsToDrive`)(function*(){return(yield*aV(yield*e.select({runId:Q.runId}).from(Q).where(cM(eH,oM($V,`Waiting`))).execute())).map(({runId:e})=>e)}),we=O(`RunStoreQueries.pendingContinuations`)(function*(){let t=yield*e.selectDistinct({loop:Z.loopName,itemKey:Z.itemKey}).from(Z).leftJoin(Q,Y(Q.eventId,Z.eventId)).leftJoin(ZR,Y(ZR.eventId,Z.eventId)).leftJoin(UR,Y(UR.itemKey,Z.itemKey)).leftJoin(HR,cM(Y(HR.loopName,Z.loopName),Y(HR.itemKey,Z.itemKey))).where(cM(_M(Q.runId),_M(ZR.eventId),_M(UR.askJson),_M(HR.suppressedByRunId),VV(e).currentEvent)).execute();return(yield*Ph(yield*Hw(N(M({loop:aA,itemKey:nI})))(t),({loop:t,itemKey:n})=>T(function*(){return(yield*_e(t,n)).length>0?[]:yield*aV(yield*e.select({runId:Q.runId}).from(Q).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(cM(Y(Z.loopName,t),Y(Z.itemKey,n))).orderBy(jM(Q.openedAt),jM(Q.runId)).limit(1).execute())}))).flat().map(({runId:e})=>e)}),Te=O(`RunStoreQueries.revokeQueued`)(function*(t,n,r){let i=YL(Z,`candidate`),a=YL(Q,`candidate_run`);return(yield*e.insert(ZR).select(e.select({eventId:i.eventId,reason:J`'revoked'`.as(`reason`)}).from(i).leftJoin(a,Y(a.eventId,i.eventId)).where(cM(Y(i.loopName,t),Y(i.itemKey,n),hM(i.eventId,r),_M(a.runId)))).onConflictDoNothing().returning({eventId:ZR.eventId}).execute()).length}),Ee=O(`RunStoreQueries.revokeUnstarted`)(function*(t,n){let r=yield*aV(yield*e.select({runId:Q.runId}).from(Q).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(cM(Y(Z.loopName,t),Y(Z.itemKey,n),tH)).execute()),i=e.select({eventId:Z.eventId}).from(Z).where(cM(Y(Z.loopName,t),Y(Z.itemKey,n)));return yield*Te(t,n,i),r});return{salvageCandidates:o,salvageCandidate:s,cycles:VV(e),loopItems:KV(e),...qV(e),addAttempt:ee,recordReattach:te,nextStart:ne,setNextStart:re,recordSalvage:ie,recordComments:ae,recordOutOfMemory:oe,amend:ce,markIntervened:le,approvalExists:fe,blockingRun:_e,closeAttempt:se,createRun:me,eventRouteByRun:n,ignoredEvent:ge,newestReopening:ve,nextQueued:Se,reopenedEvent:ye,recordRunAgain:be,pendingContinuations:we,recordTriggerEvent:xe,runIdsToDrive:Ce,recordApproval:pe,revision:g,revokeQueued:Te,revokeUnstarted:Ee,runSummaries:f,closedRunSummaries:m,closedRunSummariesSince:h,itemRunSummaries:d,runEvents:p,runForEvent:he,snapshot:l,updateStepResult:de,updateAttemptParentModel:ue,updateState:_,resolveFailure:v}},iH=T(function*(){let e=yield*iN,t=rH(e),n=O(`RunReader.inspect`)(e=>t.snapshot(e).pipe(TV(`read run`))),r=O(`RunReader.evidence`)(function*(t){yield*D({runId:t});let n=yield*e.transaction(e=>T(function*(){let n=rH(e),r=yield*n.snapshot(t);return new RB({snapshot:r,transcript:(yield*Ph(r.attempts,({id:e})=>n.transcript(new bB({attemptId:e})))).flat().sort((e,t)=>e.sequence-t.sequence)})})).pipe(TV(`read run evidence`));return yield*A(`Run evidence read`,{runId:t,attempts:n.snapshot.attempts.length,transcriptRows:n.transcript.length}),n}),i=O(`RunReader.list`)(e=>t.runSummaries(e.closedLimit).pipe(TV(`list runs`))),a=O(`RunReader.closed`)(e=>t.closedRunSummaries(e.limit).pipe(TV(`list closed runs`))),o=O(`RunReader.closedSince`)(e=>t.closedRunSummariesSince(e).pipe(TV(`list runs closed since a time`))),s=O(`RunReader.revision`)(()=>t.revision().pipe(TV(`read projection revision`)));return{inspect:n,evidence:r,list:i,closed:a,closedSince:o,forItems:O(`RunReader.forItems`)(e=>t.itemRunSummaries(e).pipe(TV(`read item run histories`))),events:O(`RunReader.events`)(e=>t.runEvents(e).pipe(TV(`read the events of runs`))),revision:s,transcript:O(`RunReader.transcript`)(e=>t.transcript(e).pipe(TV(`read attempt transcript`))),attemptsByWorker:O(`RunReader.attemptsByWorker`)(()=>RV(e).attemptCountsByWorker().pipe(TV(`count attempts by worker`))),sightings:O(`RunReader.sightings`)(e=>t.loopItems.sightings(e).pipe(TV(`read loop sightings`)))}}),aH=class e extends Rr()(`@usine/engine/RunReader`){static layer=Xf(e,iH)},oH=class extends V(`@usine/orchestrator/UsageCostView`)({usd:TP,estimate:lT}){},sH=class extends V(`@usine/orchestrator/SessionUsageView`)({attemptId:sF,session:hP,pool:kP,tokens:dP,cost:I(oH)}){},cH=class extends V(`@usine/orchestrator/PoolUsageView`)({pool:kP,tokens:dP,cost:I(oH)}){},lH=class extends V(`@usine/orchestrator/RunUsageView`)({tokens:dP,pools:N(cH),sessions:N(sH)}){},uH=class extends V(`@usine/orchestrator/TaskPoolUsageView`)({pool:kP,tokens:dP,cost:I(oH),unpriced:lT}){},dH=class extends V(`@usine/orchestrator/TaskUsageView`)({durationMillis:R.check(HT(0)),runningSince:N(j),unmeasured:R.check(HT(0)),tokens:dP,pools:N(uH),cost:I(oH)}){},fH=[`apiKeys`,`claudePlan`,`chatgptPlan`],pH=(e,t)=>vr(t,{onNone:()=>null,onSome:t=>new oH({usd:t,estimate:e!==`apiKeys`})}),mH=({session:e,costUsd:t,breakdown:n})=>S(t)||e.brain.harness!==`codex`?t:kr(n,t=>FB(e.brain.model,t)),hH=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:mH(e.report)})),r=n.map(({attemptId:e,report:t,price:n})=>{let r=jP(t.session);return new sH({attemptId:e,session:t.session,pool:r,tokens:t.totalTokens,cost:pH(r,n)})}),i=new Set(n.flatMap(({report:e,price:t})=>x(t)&&e.session.brain.harness===`codex`&&S(e.breakdown)?[e.session.brain.model]:[])),a=fH.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 cH({pool:e,tokens:dP.make(t.reduce((e,{tokens:t})=>e+t,0)),cost:pH(e,n.length===t.length?b(TP.make(n.reduce((e,t)=>e+t,0))):y())})]});return{view:new lH({tokens:dP.make(r.reduce((e,{tokens:t})=>e+t,0)),pools:a,sessions:r}),unknownModels:i}},gH=(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=fH.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 uH({pool:e,tokens:dP.make(t.reduce((e,{tokens:t})=>e+t,0)),cost:pH(e,n.length===0?y():b(TP.make(n.reduce((e,t)=>e+t,0)))),unpriced:n.length<t.length})]}),s=o.flatMap(({cost:e})=>e===null?[]:[e]);return new dH({durationMillis:Math.round(n),runningSince:i,unmeasured:r,tokens:dP.make(a.reduce((e,{tokens:t})=>e+t,0)),pools:o,cost:s.length===0?null:new oH({usd:TP.make(s.reduce((e,{usd:t})=>e+t,0)),estimate:s.some(({estimate:e})=>e)})})},_H=T(function*(){let e=yield*aH,t=yield*zh(()=>new Map),n=yield*zh(()=>new Set),r=O(`RunUsageReader.attemptReports`)(function*(n){let r=t.get(n.id);if(r!==void 0)return{reports:r,read:!1};let i=yield*e.transcript(new CB({attemptId:n.id}));return S(n.outcome)&&t.set(n.id,i),{reports:i,read:!0}});return{read:O(`RunUsageReader.read`)(function*(e){yield*D({runId:e.run.id});let t=yield*Ph(e.attempts,r,{concurrency:4}),{view:i,unknownModels:a}=hH(t.flatMap(({reports:e})=>e));for(let t of a)n.has(t)||(n.add(t),yield*e_(`The OpenAI price table has no rates for a Codex model, so its sessions have no cost`,{model:t,runId:e.run.id}));return yield*A(`Read Run usage`,{runId:e.run.id,sessions:i.sessions.length,tokens:i.tokens,attemptsRead:t.filter(({read:e})=>e).length,attemptsCached:t.filter(({read:e})=>!e).length}),i})}});(class e extends Rr()(`@usine/orchestrator/RunUsageReader`){static layer=Xf(e,_H)});var vH=F(jA),yH=I(j),bH=class extends V(`@usine/orchestrator/EditAndRetry`)({task:lF,agent:fN}){},xH=class extends V(`@usine/orchestrator/SessionIntervention`)({attemptId:sF,target:WF.pipe(DT(w({_tag:`Parent`}))),action:BF}){};NE(`@usine/orchestrator/RosterAgentNotFoundError`)(`RosterAgentNotFoundError`,{agent:fN,message:j}),NE(`@usine/orchestrator/LoopNotFoundError`)(`LoopNotFoundError`,{loop:aA,message:j});var SH=class extends V(`@usine/orchestrator/ApprovalView`)({approvedAt:j,source:I(pI)}){},CH=class extends V(`@usine/orchestrator/RunView`)({id:HA,itemKey:nI,loop:aA,repository:Xk,agent:fN,agentBrain:dN,state:vH,loopPaused:lT,openedAt:j,closedAt:I(j),task:j,attempts:N(Kz),approval:I(SH),runAgain:I(Dz),resultMessage:yH,pullRequestUrl:yH,canApprove:lT,canRetry:lT,canResolveFailure:lT,canCancel:lT,canRunAgain:lT}){},wH=R.check(HT(0)),TH=R.check(HT(0)),EH=class extends V(`@usine/orchestrator/RunDurationView`)({endedMillis:wH,runningSince:I(j),unmeasured:TH}){},DH=class extends V(`@usine/orchestrator/UnconfirmedStopView`)({runId:HA,attemptNumber:cF,worker:EN}){},OH=class extends V(`@usine/orchestrator/RunDetailView`)({run:CH,agentDefinitionChanged:lT,eventDedupKey:j,eventPayload:IE,transcript:N(OB),sessionState:N(OB),earlierTranscript:N(kB),worker:I(EN).pipe(TT(w(null))),settledItemState:I(xz).pipe(TT(w(null))),duration:EH.pipe(TT(w(new EH({endedMillis:0,runningSince:null,unmeasured:0})))),usage:lH.pipe(TT(w(new lH({tokens:dP.make(0),pools:[],sessions:[]})))),unconfirmedStop:I(DH).pipe(TT(w(null))),machine:I(aB).pipe(TT(w(null)))}){},kH=z.pipe(L(`BoardLaneId`)),AH=F([`authored`,`proposed`,`fallback`]),jH=class extends V(`@usine/orchestrator/BoardItemLink`)({itemKey:nI,kind:F([`issue`,`pr`]),number:rI,title:j,url:z,state:bz}){},MH=class extends V(`@usine/orchestrator/BoardPullRequestView`)({number:rI,url:z,state:F([`pr-open`,`pr-merged`])}){},NH=class extends V(`@usine/orchestrator/BoardTaskView`)({...jH.fields,labels:N(fz),items:N(jH).check(qT()),pullRequest:I(MH),runs:N(CH),run:I(CH),needsYou:lT,conflicting:lT,loops:N(aA),usage:dH}){},PH={id:kH,name:yz,sources:N(Tz),origin:AH,items:N(NH)},FH=class extends H(`@usine/orchestrator/WritableBoardLaneView`)(`WritableBoardLane`,{...PH,origin:rT(`authored`),labels:N(fz).check(qT())}){},IH=class extends H(`@usine/orchestrator/ReadOnlyBoardLaneView`)(`ReadOnlyBoardLane`,PH){},LH=P([FH,IH]),RH=class extends NE(`@usine/orchestrator/BoardProjectionError`)(`BoardProjectionError`,{repository:Xk,itemKey:nI,message:z}){},zH=class extends V(`@usine/orchestrator/BoardView`)({lanes:N(LH),failures:N(RH)}){},BH=class extends V(`@usine/orchestrator/LabelView`)({name:fz,color:I(j),description:I(j)}){};V(`@usine/orchestrator/BoardMove`)({repository:Xk,item:rI,toLane:kH});var VH=class extends NE(`@usine/orchestrator/BoardProjectNotFoundError`)(`BoardProjectNotFoundError`,{repository:Xk}){},HH=class extends NE(`@usine/orchestrator/BoardItemNotFoundError`)(`BoardItemNotFoundError`,{repository:Xk,item:rI}){};NE(`@usine/orchestrator/BoardLaneNotFoundError`)(`BoardLaneNotFoundError`,{repository:Xk,lane:kH}),NE(`@usine/orchestrator/BoardLaneReadOnlyError`)(`BoardLaneReadOnlyError`,{repository:Xk,lane:kH});var UH=j.check(PT(/^(?:[A-Za-z_][A-Za-z0-9_.]*|list<[A-Za-z_][A-Za-z0-9_.]*>|map<[A-Za-z_][A-Za-z0-9_.]*,[A-Za-z_][A-Za-z0-9_.]*>)$/u,{message:`Expected a CEL type reference`})).pipe(L(`CelTypeReference`)),WH=j.check(PT(/^[A-Za-z_][A-Za-z0-9_]*$/u,{message:`Expected a CEL identifier`})),GH=j.check(PT(/^[A-Za-z_][A-Za-z0-9_.]*$/u,{message:`Expected a CEL object-type name`})),KH=e=>NT(e=>new Set(e.map(({name:e})=>e)).size===e.length,{message:e}),qH=class extends V(`@usine/expression/ObjectField`)({name:WH,type:UH,nullable:lT.pipe(TT(w(!1)))}){},JH=class extends V(`@usine/expression/ObjectType`)({name:GH,fields:N(qH).check(KH(`Expected unique CEL object-field names`))}){},YH=class extends V(`@usine/expression/Variable`)({name:WH,type:UH}){},XH=class extends V(`@usine/expression/Environment`)({types:N(JH).check(KH(`Expected unique CEL object-type names`)),variables:N(YH).check(KH(`Expected unique CEL variable names`))}){},ZH=j.check(PT(/\S/u,{message:`Expected a non-blank CEL expression`})).pipe(L(`ExpressionSource`)),QH=R.check(HT(0)),$H=F([`check_failed`,`parse_error`,`type_error`,`unexpected_result_type`]);P([class extends NE(`@usine/expression/ExpressionCheckError`)(`ExpressionCheckError`,{source:ZH,code:$H,message:z,position:B(QH)}){},class extends NE(`@usine/expression/ExpressionEvaluationError`)(`ExpressionEvaluationError`,{source:ZH,message:z}){}]),P([j,cT,uT,lT,oT]);var eU=class extends Rr()(`@usine/expression/ExpressionEngine`){},tU=z.pipe(L(`InstancePath`)),nU=F([`expression`,`frontmatter`,`read`,`reference`,`schema`,`yaml`]),rU=class e extends NE(`@usine/config/ConfigFileError`)(`ConfigFileError`,{file:tU,stage:nU,expression:xE(ZH),message:z,details:$w(N(M({path:N(P([j,cT])),message:j})))}){static fromSchema(t,n){let r=Hy()(n.issue).issues.map(({path:e,message:t})=>({path:(e??[]).map(e=>Ok(e).pipe(Ak(jk,e=>e),Ak(Mk,e=>e),Ak(Nk,String),Pk(({key:e})=>String(e)))),message:t}));return new e({file:t,stage:`schema`,expression:y(),message:Yy()(n.issue),details:r})}};P([rU,class extends NE(`@usine/config/FactoryConfigError`)(`FactoryConfigError`,{file:tU,stage:nU,message:z}){}]);var iU=j.check(PT(/\S/u,{message:`Expected a non-blank repository label`})),aU=j.check(PT(/^[0-9a-fA-F]{6}$/u,{message:`Expected a six-digit hex label color`})),oU=class extends V(`@usine/engine/RepositoryLabel`)({name:iU,color:yE(aU),description:yE(j)}){},sU=NT(e=>new Set(e.map(({name:e})=>e)).size===e.length,{message:`Expected unique label names`}),cU=N(oU).check(sU),lU=class extends V(`@usine/engine/RepositoryLabelProjection`)({repository:Xk,labels:cU}){},uU=N(j),dU=Vw(uU),fU=M({repository:Xk,labels:P([lU.fields.labels,uU])}),pU=e=>dU(e)?e.map(e=>new oU({name:e,color:y(),description:y()})):e,mU=Hw(N(fU)),hU=Xw(lU.fields.labels),gU=e=>t=>dg(t,t=>new sz({operation:e,cause:t})),_U=T(function*(){let e=yield*iN;return{get:O(`RepositoryLabelProjectionReader.get`)(function*(t){let n=(yield*mU(yield*e.select({repository:ez.repository,labels:ez.labelsJson}).from(ez).where(Y(ez.repository,t)).limit(1).execute(),{onExcessProperty:`error`}))[0];return n===void 0?y():b(new lU({repository:n.repository,labels:pU(n.labels)}))},gU(`read repository label projection`))}}),vU=T(function*(){let e=yield*iN;return{replace:O(`RepositoryLabelProjectionWriter.replace`)(function*(t){yield*D({repository:t.repository});let n=hU(t.labels);return(yield*e.insert(ez).values({repository:t.repository,labelsJson:n}).onConflictDoUpdate({target:ez.repository,set:{labelsJson:n},setWhere:oM(ez.labelsJson,n)}).returning({repository:ez.repository}).execute()).length===0?(yield*A(`Repository label projection already matched GitHub`,{repository:t.repository,labels:t.labels.length}),!1):(yield*A(`Repository label projection updated from trigger polling`,{repository:t.repository,labels:t.labels.length}),!0)},gU(`write repository label projection`))}}),yU=class e extends Rr()(`@usine/engine/RepositoryLabelProjectionReader`){static layer=Xf(e,_U)},bU=class e extends Rr()(`@usine/engine/RepositoryLabelProjectionWriter`){static layer=Xf(e,vU)},xU=`~effect/http/HttpBody`,SU=e=>pe(e,xU),CU=class{[xU];constructor(){this[xU]=xU}[gt](){return this.toJSON()}toString(){return ot(this,{ignoreToString:!0})}},wU=new class extends CU{_tag=`Empty`;toJSON(){return{_id:`effect/HttpBody`,_tag:`Empty`}}},TU=class extends CU{_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??=kU(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}}},EU=(e,t)=>new TU(e,t??`application/octet-stream`,e.length),DU=new TextEncoder,OU=globalThis.Buffer,kU=OU===void 0?e=>DU.encode(e):e=>OU.from(e,`utf8`),AU=(e,t)=>{if(typeof e!=`string`&&(e=e===void 0?``:String(e)),OU!==void 0)return new TU(void 0,t??`text/plain`,OU.byteLength(e,`utf8`),e);let n=DU.encode(e);return new TU(n,t??`text/plain`,n.length,e)},jU=(e,t)=>AU(JSON.stringify(e),t??`application/json`),MU=(e,t)=>AU(Xv(Vv(e)),t??`application/x-www-form-urlencoded`),NU=class extends CU{_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}}},PU=e=>new NU(e),FU=class extends CU{_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}}},IU=(e,t,n)=>new FU(e,t??`application/octet-stream`,n),LU=`~effect/http/HttpClientError`,RU=class extends wo(`HttpClientError`){constructor(e){`cause`in e.reason?super({...e,cause:e.reason.cause}):super(e)}[LU]=LU;get request(){return this.reason.request}get response(){return`response`in this.reason?this.reason.response:void 0}get message(){return this.reason.message}},zU=e=>e.endsWith(`Error`)?e.slice(0,-5):e,BU=(e,t,n)=>t?`${e}: ${t} (${n})`:`${e} error (${n})`,VU=e=>`${e.method} ${ey(e.url)}`,HU=class extends wo(`TransportError`){get methodAndUrl(){return VU(this.request)}get message(){return BU(zU(this._tag),this.description,this.methodAndUrl)}},UU=class extends wo(`InvalidUrlError`){get methodAndUrl(){return VU(this.request)}get message(){return BU(zU(this._tag),this.description,this.methodAndUrl)}},WU=class extends wo(`StatusCodeError`){get methodAndUrl(){return VU(this.request)}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return BU(zU(this._tag),this.description,e)}},GU=class extends wo(`DecodeError`){get methodAndUrl(){return VU(this.request)}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return BU(zU(this._tag),this.description,e)}},KU=class extends wo(`EmptyBodyError`){get methodAndUrl(){return VU(this.request)}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return BU(zU(this._tag),this.description,e)}},qU=e=>e!==`GET`&&e!==`HEAD`&&e!==`OPTIONS`&&e!==`TRACE`,JU=[[`GET`,`get`],[`POST`,`post`],[`PUT`,`put`],[`DELETE`,`del`],[`PATCH`,`patch`],[`HEAD`,`head`],[`OPTIONS`,`options`],[`TRACE`,`trace`],[`QUERY`,`query`]],YU=(e,t)=>t._tag===`Empty`||t._tag===`FormData`?Mv(Mv(e,`content-type`),`content-length`):(e=t.contentType===void 0?Mv(e,`content-type`):kv(e,`content-type`,t.contentType),t.contentLength===void 0?Mv(e,`content-length`):kv(e,`content-length`,t.contentLength.toString())),XU=class extends wo(`UrlError`){},ZU=(e,t,n)=>Ti({try:()=>{let r=new URL(e,QU());for(let e=0;e<t.params.length;e++){let[n,i]=t.params[e];i!==void 0&&r.searchParams.append(n,Iv(i))}return n!==void 0&&(r.hash=n),r},catch:e=>new XU({cause:e})}),QU=()=>{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}}},$U=`~effect/http/HttpClientRequest`,eW={[$U]:$U,...yt,toJSON(){return{_id:`HttpClientRequest`,method:this.method,url:ey(this.url),urlParams:this.urlParams,hash:this.hash,headers:tt(this.headers),body:this.body.toJSON()}},pipe(){return e(this,arguments)}};function tW(e,t,n,r,i,a){let o=Object.create(eW);return o.method=e,o.url=t,o.urlParams=n,o.hash=r,o.headers=i,o.body=a,o}var nW=tW(`GET`,``,Kv,y(),Ev,wU),rW=e=>(t,n)=>oW(nW,{method:e,url:t,...n??void 0}),iW=rW(`GET`),aW=rW(`POST`),oW=r(2,(e,t)=>{let n=e;return t.method&&(n=sW(n,t.method)),t.url&&(n=pW(n,t.url)),t.headers&&(n=lW(n,t.headers)),t.urlParams&&(n=gW(n,t.urlParams)),t.hash&&(n=vW(n,t.hash)),t.body&&(n=yW(n,t.body)),t.accept&&(n=uW(n,t.accept)),t.acceptJson&&(n=dW(n)),n}),sW=r(2,(e,t)=>tW(t,e.url,e.urlParams,e.hash,e.headers,e.body)),cW=r(3,(e,t,n)=>tW(e.method,e.url,e.urlParams,e.hash,kv(e.headers,t,n),e.body)),lW=r(2,(e,t)=>tW(e.method,e.url,e.urlParams,e.hash,Av(e.headers,t),e.body)),uW=r(2,(e,t)=>cW(e,`Accept`,t)),dW=uW(`application/json`),fW=r(2,(e,t)=>tW(e.method,e.url,e.urlParams,e.hash,kv(kv(e.headers,`connection`,`Upgrade`),`upgrade`,t),e.body)),pW=r(2,(e,t)=>{if(typeof t==`string`)return tW(e.method,t,e.urlParams,e.hash,e.headers,e.body);let n=new URL(t.toString()),r=Vv(n.searchParams),i=Sr(n.hash===``?void 0:n.hash.slice(1));return n.search=``,n.hash=``,tW(e.method,n.toString(),r,i,e.headers,e.body)}),mW=r(2,(e,t)=>t===``?e:tW(e.method,hW(t,e.url),e.urlParams,e.hash,e.headers,e.body)),hW=(e,t)=>{let n=e.endsWith(`/`),r=t.startsWith(`/`);return n&&r?e+t.slice(1):!n&&!r?e+`/`+t:e+t},gW=r(2,(e,t)=>tW(e.method,e.url,Jv(e.urlParams,t),e.hash,e.headers,e.body)),_W=r(2,(e,t)=>tW(e.method,e.url,Yv(e.urlParams,t),e.hash,e.headers,e.body)),vW=r(2,(e,t)=>tW(e.method,e.url,e.urlParams,b(t),e.headers,e.body)),yW=r(2,(e,t)=>tW(e.method,e.url,e.urlParams,e.hash,YU(e.headers,t),t)),bW=r(2,(e,t)=>yW(e,jU(t))),xW=r(2,(e,t)=>yW(e,PU(t)));function SW(e){let t=ZU(e.url,e.urlParams,Tr(e.hash));return Oi(t)?b(t.success):y()}var CW=`~effect/http/HttpIncomingMessage`,wW=(e,t)=>{let n=Uw(PE(e)),r=t?.reviver===void 0?void 0:Uw(aE(PE(e),t));return e=>r===void 0?E(e.json,e=>n(e,t)):E(e.text,i=>i===``?E(e.json,e=>n(e,t)):r(i,t))},TW=(e,t)=>({...t,headers:tt(e.headers),remoteAddress:e.remoteAddress}),EW=`~effect/http/HttpClientResponse/WebSource`,DW=e=>e[EW]?.(),OW=`~effect/http/HttpClientResponse`,kW=(e,t)=>new AW(e,t),AW=class extends bt{[CW];[OW];request;source;constructor(e,t){super(),this.request=e,this.source=t,this[CW]=CW,this[OW]=OW}toJSON(){return TW(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=SW(this.request);return x(e)?``:(e.value.hash=``,e.value.href)}get headers(){return Dv(this.source.headers)}cachedCookies;get cookies(){return this.cachedCookies?this.cachedCookies:this.cachedCookies=lv(this.source.headers.getSetCookie?.()??[])}get remoteAddress(){return y()}[EW](){return this.source}get stream(){return this.source.body?PO({evaluate:()=>this.source.body,onError:e=>new RU({reason:new GU({request:this.request,response:this,cause:e})})}):MO(new RU({reason:new KU({request:this.request,response:this,description:`can not create stream from empty body`})}))}get json(){return E(this.text,e=>qh({try:()=>e===``?null:JSON.parse(e),catch:e=>new RU({reason:new GU({request:this.request,response:this,cause:e})})}))}textBody;get text(){return this.textBody??=ng(this.arrayBuffer,e=>new TextDecoder().decode(e))}get urlParamsBody(){return E(this.text,e=>qh({try:()=>Vv(new URLSearchParams(e)),catch:e=>new RU({reason:new GU({request:this.request,response:this,cause:e})})}))}formDataBody;get formData(){return this.formDataBody??=Ih({try:()=>this.source.formData(),catch:e=>new RU({reason:new GU({request:this.request,response:this,cause:e})})}).pipe(Ig,Zg)}arrayBufferBody;get arrayBuffer(){return this.arrayBufferBody||=Ih({try:()=>this.source.arrayBuffer(),catch:e=>new RU({reason:new GU({request:this.request,response:this,cause:e})})}).pipe(Ig,Zg),this.arrayBufferBody}get upgrade(){return Uh(new RU({reason:new WU({request:this.request,response:this,description:`fetch cannot hand over the connection of an HTTP upgrade`})}))}pipe(){return e(this,arguments)}},jW=e=>Ov({b3:`${e.traceId}-${e.spanId}-${e.sampled?`1`:`0`}${vr(e.parent,{onNone:()=>``,onSome:e=>`-${e.spanId}`})}`,traceparent:`00-${e.traceId.padStart(32,`0`)}-${e.spanId}-${e.sampled?`01`:`00`}`}),MW={"http:":80,"https:":443,"ws:":80,"wss:":443},NW=(e,t,n)=>{let r=ey(t.search,n).slice(1);if(e.attribute(`url.full`,ey(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===``?MW[t.protocol]:Number(t.port);n!==void 0&&e.attribute(`server.port`,n)}},PW=(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()]},FW=(e,t,n,r,i)=>{for(let a in n)r(a,t)&&e.attribute(`http.${t}.header.${a}`,Pv(a,i)?`<redacted>`:n[a])},IW=`~effect/http/HttpClient`,LW=Rr(`effect/HttpClient`),RW=r(2,(e,t)=>zW(n=>t(e.postprocess(n)),e.preprocess)),zW=(e,t)=>{let n=Object.create(BW);return n.preprocess=t,n.postprocess=e,n.execute=function(n){return e(t(n))},n},BW={[IW]:IW,pipe(){return e(this,arguments)},...yt,toJSON(){return{_id:`effect/HttpClient`}},...Object.fromEntries(JU.map(([e,t])=>[t,function(t,n){return this.execute(rW(e)(t,n))}]))},VW=e=>zW(t=>E(t,t=>Jh(n=>{let r=XW.get(t),i=r??new AbortController,a=ZU(t.url,t.urlParams,Tr(t.hash));if(Di(a))return Uh(new RU({reason:new UU({request:t,cause:a.failure})}));let o=a.success;if(n.getRef(Bo)||n.getRef(WW)(t)){let a=e(t,o,i.signal,n);return r?a:Bg(e=>Sg(e(a),{onSuccess(e){return YW.register(e,i),w(new ZW(e,i))},onFailure(e){return nf(e)&&i.abort(),Wh(e)}}))}return Ug(n.getRef(qW)(t),{kind:`client`},a=>{a.attribute(`http.request.method`,t.method);let s=n.getRef(Fv);NW(a,o,PW(t.urlParams,n.getRef(cy)));let c=n.getRef(GW);return FW(a,`request`,t.headers,c,s),t=n.getRef(KW)?lW(t,jW(a)):t,Bg(l=>l(e(t,o,i.signal,n)).pipe(Gg(a,{captureStackTrace:!1}),Sg({onSuccess:e=>(a.attribute(`http.response.status_code`,e.status),FW(a,`response`,e.headers,c,s),e.status>=400&&e.status<600&&(a.attribute(`error.type`,String(e.status)),HW(n,a,t,e)),r?w(e):(YW.register(e,i),w(new ZW(e,i)))),onFailure(e){return!r&&nf(e)&&i.abort(),Wh(e)}})))})})),w),HW=(e,t,n,r)=>{let i=St();Ct(0);let a;try{a=df(new RU({reason:new WU({request:n,response:r})}))}finally{Ct(i)}t.end(e.getRef(Ef)?e.getRef(ap).currentTimeNanosUnsafe():BigInt(0),a)},UW=r(2,(e,t)=>zW(e.postprocess,n=>ng(e.preprocess(n),t))),WW=vi(`effect/http/HttpClient/TracerDisabledWhen`,{defaultValue:()=>s}),GW=vi(`effect/http/HttpClient/TracerHeaderFilter`,{defaultValue:()=>s}),KW=vi(`effect/http/HttpClient/TracerPropagationEnabled`,{defaultValue:o}),qW=vi(`effect/http/HttpClient/SpanNameGenerator`,{defaultValue:()=>e=>e.method}),JW=e=>Xf(LW)(wg(t=>ng(e,e=>RW(e,Og(e=>hi(t,e)))))),YW=(()=>{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))}}})(),XW=new WeakMap,ZW=class{original;controller;constructor(e,t){this.original=e,this.controller=t}[OW]=OW;[CW]=CW;applyInterrupt(e){return Rh(()=>(YW.unregister(this.original),Rg(e,()=>zh(()=>{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)}[EW](){let e=DW(this.original);return e!==void 0&&YW.unregister(this.original),e}get stream(){return AO(()=>(YW.unregister(this.original),WO(this.original.stream,zh(()=>{this.controller.abort()}))))}toJSON(){return this.original.toJSON()}[gt](){return this.original[gt]()}pipe(){return e(this,arguments)}},QW=vi(`effect/http/FetchHttpClient/Fetch`,{defaultValue:()=>globalThis.fetch}),$W=class extends Rr()(`effect/http/FetchHttpClient/RequestInit`){},eG=JW(w(VW((e,t,n,r)=>{if(e.headers.upgrade!==void 0)return Uh(new RU({reason:new HU({request:e,description:`fetch cannot send an HTTP upgrade request`})}));let i=r.getRef(QW),a=si(r.context,$W)??{},o=a.headers?jv(Dv(a.headers),e.headers):e.headers;o[`content-length`]&&(o=Mv(o,`content-length`));let s,c=zh(()=>s?.abort()),l=r=>ng(Ih({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 RU({reason:new HU({request:e,cause:t})})}),t=>{let n=kW(e,t);return s?(t.body===null&&s.abort(),Object.create(n,{...Object.fromEntries([`arrayBuffer`,`text`,`json`,`formData`,`urlParamsBody`].map(e=>[e,{get:()=>Mg(n[e],c)}])),stream:{get:()=>WO(n.stream,c)}})):n}).pipe(Ng(()=>c));switch(e.body._tag){case`Raw`:case`Uint8Array`:return l(e.body.body);case`FormData`:return l(e.body.formData);case`Stream`:{s=new AbortController;let t=AbortSignal.any([n,s.signal]),r=Vh(e=>{let n=()=>e(Lg);if(t.aborted)n();else return t.addEventListener(`abort`,n,{once:!0}),zh(()=>t.removeEventListener(`abort`,n))});return E(JO(UO(e.body.stream,r)),l)}}return l(void 0)})));function tG(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 nG=Rr(`effect/http/HttpEffect/CurrentRequestState`),rG=e=>Jh(t=>{let n=si(t.context,nG);return n!==void 0&&(n.loggerDisabled=!0),e}),iG=Rr(`effect/http/HttpRouter`),aG=e=>e.endsWith(`/`)?e.slice(0,-1):e,oG=r(2,(e,t)=>(t=aG(t),e===`*`?`${t}/*`:e===`/`?t:t+e)),sG=`~effect/http/HttpRouter/Middleware`,cG=function(){return arguments.length===0?lG:lG(arguments[0],arguments[1])},lG=(e,t)=>t?.global?$f(T(function*(){let t=yield*iG,n=Mh(e)?yield*e:e;yield*t.addGlobalMiddleware(n)})):new fG(Mh(e)?Qf(ng(e,e=>Zr(new Map([[dG,e]])))):Yf(Zr(new Map([[dG,e]])))),uG=0,dG=`effect/http/HttpRouter/MiddlewareFn`,fG=class e{[sG]={};layerFn;dependencies;constructor(e,t){this.layerFn=e,this.dependencies=t;let n=`effect/http/HttpRouter/Middleware-${++uG}`;this.layer=Qf(T({self:this},function*(){let e=yield*Cg(),t=[ci(e,dG)];if(this.dependencies){let n=yield*Gf,r=ui(e,Df),i=yield*Kf(this.dependencies,n,r);t.push(...mG(i))}return Zr(new Map([[n,t]]))})).pipe(rp(this.layerFn))}layer;combine(t){return new e(this.layerFn,this.dependencies?ip(this.dependencies,t.layer):t.layer)}},pG=new WeakMap,mG=e=>{let t=pG.get(e);if(t)return t;let n=pa(),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 pG.set(e,t),t};cG(rG).layer;var hG={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},gG=e=>hG[e],_G=R.check(HT(1)).pipe(L(`GitHubAppId`)),vG=CE(z.check(PT(/^-----BEGIN (?:RSA )?PRIVATE KEY-----[\s\S]+-----END (?:RSA )?PRIVATE KEY-----\s*$/u,{message:`Expected a PEM-encoded RSA private key`})).pipe(L(`GitHubAppPrivateKey`)),{disallowEncode:!0});V(`@usine/github/AppCredentials`)({appId:_G,privateKey:vG});var yG=class extends Rr()(`@usine/github/GitHubCredentials`){},bG=class extends NE(`@usine/github/AppAuthenticationError`)(`AppAuthenticationError`,{message:z}){},xG=new TextEncoder,SG=new Uint8Array([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]),CG=(...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},wG=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])},TG=(e,t)=>CG(new Uint8Array([e]),wG(t.length),t),EG=e=>TG(48,CG(new Uint8Array([2,1,0]),SG,TG(4,e))),DG=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?EG(i):i},OG=e=>{let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/=/gu,``).replace(/\+/gu,`-`).replace(/\//gu,`_`)},kG=e=>OG(xG.encode(JSON.stringify(e))),AG=e=>{let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t},jG=O(`AppJwt.import`)(function*(e){let t=yield*Ih({try:async()=>crypto.subtle.importKey(`pkcs8`,AG(DG(bv(e.privateKey))),{name:`RSASSA-PKCS1-v1_5`,hash:`SHA-256`},!1,[`sign`]),catch:()=>new bG({message:`Could not import the GitHub App private key as an RSA private key`})});return O(`AppJwt.sign`)(function*(){let n=Math.floor((yield*op)/1e3),r=`${kG({alg:`RS256`,typ:`JWT`})}.${kG({iat:n-60,exp:n+540,iss:e.appId})}`,i=yield*Fh(()=>crypto.subtle.sign(`RSASSA-PKCS1-v1_5`,t,AG(xG.encode(r))));return vv(`${r}.${OG(new Uint8Array(i))}`)})}),MG=R.check(HT(1)),NG=MG.pipe(L(`GitHubInstallationId`)),PG=MG.pipe(L(`GitHubRepositoryId`)),FG=z.pipe(L(`GitHubAppSlug`)),IG=class extends V(`@usine/github/Installation`)({id:NG,accountLogin:z,appSlug:FG}){},LG=class extends H(`@usine/github/TokenScope/InstallationWide`)(`InstallationWide`,{}){},RG=class extends H(`@usine/github/TokenScope/SingleRepository`)(`SingleRepository`,{repository:Xk,repositoryId:PG,permissions:lA}){},zG=P([LG,RG]),BG=class extends V(`@usine/github/InstallationToken`)({value:SE(z,{disallowJsonEncode:!0}),expiresAt:_E,scope:zG}){},VG=F([`missing`,`multiple`,`suspended`]),HG=class extends NE(`@usine/github/InstallationDiscoveryError`)(`InstallationDiscoveryError`,{reason:VG,message:z}){},UG={checks:`read`,contents:`write`,issues:`write`,metadata:`read`,pull_requests:`write`},WG={write:{checks:`read`,contents:`write`,issues:`write`,metadata:`read`,pull_requests:`write`},read:{checks:`read`,contents:`read`,issues:`write`,metadata:`read`,pull_requests:`write`}},GG=(e,t)=>e===t||t===`read`&&e===`write`,KG=e=>Object.entries(UG).flatMap(([t,n])=>GG(e[t],n)?[]:[`${t}:${n}`]),qG=class extends H(`@usine/github/ProjectAccess/CoveredProject`)(`CoveredProject`,{installationId:NG,repository:Xk,repositoryId:PG}){},JG=class extends NE(`@usine/github/ProjectNotInstalledError`)(`ProjectNotInstalledError`,{repository:Xk,message:z}){};P([qG,JG]);var YG=(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 JG({repository:t,message:`The GitHub App installation has no access to "${t}"`}):new qG({installationId:e.id,repository:t,repositoryId:n.id})})},XG=class extends NE(`@usine/github/AppPermissionError`)(`AppPermissionError`,{missing:N(z).check(qT()),message:z}){},ZG=F([`create-repository-label`,`discover-installation`,`fetch-base-ref-head`,`fetch-item-labels`,`fetch-issue-snapshot`,`fetch-item-timeline`,`fetch-pull-request-snapshot`,`find-missing-issues`,`list-installation-repositories`,`list-repository-labels`,`mint-installation-token`,`mint-worker-token`,`poll-repository-changes`,`read-bot-account`,`update-item-labels`]),QG=class extends NE(`@usine/github/GitHubApiError`)(`GitHubApiError`,{operation:ZG,status:B(R),message:z}){},$G=class extends NE(`@usine/github/GitHubRateLimitError`)(`GitHubRateLimitError`,{operation:ZG,retryAt:_E,message:z}){},eK=class extends NE(`@usine/github/InvalidGitHubResponseError`)(`InvalidGitHubResponseError`,{operation:ZG,message:z,detail:z}){},tK=class extends NE(`@usine/github/GitHubItemNotFoundError`)(`GitHubItemNotFoundError`,{operation:ZG,item:R.check(HT(1)),message:z}){};P([HG,XG,QG,$G,eK]);var nK=`https://api.github.com`,rK=`2026-03-10`,iK=e=>lW({accept:`application/vnd.github+json`,authorization:`Bearer ${bv(e)}`,"user-agent":`usine`,"x-github-api-version":rK}),aK=(e,t)=>new QG({operation:e,status:t.response===void 0?y():b(t.response.status),message:t.response===void 0?`Could not send the request to GitHub`:`GitHub returned HTTP status ${t.response.status}`}),oK=Ww(M({message:z})),sK=(e,t)=>t.json.pipe(ng(t=>vr(oK(t),{onNone:()=>e,onSome:({message:t})=>new QG({operation:e.operation,status:e.status,message:`${e.message}: ${t}`})})),og(t=>A(`GitHub's error response has no JSON body to read a reason from`,{operation:e.operation,message:t.message}).pipe(rg(e)))),cK=(e,t)=>new eK({operation:e,message:`GitHub returned a response in an unexpected format`,detail:t}),lK=e=>{if(e===void 0||!/^\d+$/u.test(e))return y();let t=Number(e);return Number.isSafeInteger(t)?b(t):y()},uK=(e,t)=>{let n=lK(e);if(S(n))return b(t+n.value*1e3);if(e===void 0)return y();let r=Date.parse(e);return Number.isFinite(r)?b(r):y()},dK=(e,t)=>{let n=lK(e[`x-ratelimit-remaining`]),r=lK(e[`x-ratelimit-reset`]);return S(n)&&n.value<=t&&S(r)?b(r.value*1e3):y()},fK=(e,t)=>Or(lK(e[`x-poll-interval`]),e=>t+e*1e3),pK=e=>{let t=e.flatMap(e=>vr(e,{onNone:()=>[],onSome:e=>[e]}));return t.length===0?y():b(Math.max(...t))},mK=(e,t)=>pK([uK(e[`retry-after`],t),dK(e,0)]),hK=(e,t,n)=>{let r=kr(mK(t.headers,n),z_);return(t.status===403||t.status===429)&&S(r)?new $G({operation:e,retryAt:r.value,message:`GitHub API rate limit exceeded`}):new QG({operation:e,status:b(t.status),message:`GitHub returned HTTP status ${t.status}`})},gK=36e5,_K=3e5,vK=N(M({id:NG,appSlug:FG,account:M({login:z}),permissions:hT(j,j),suspendedAt:I(j)}).pipe(mT({appSlug:`app_slug`,suspendedAt:`suspended_at`}))),yK=M({login:ON,id:kN}),bK=M({id:PG,name:Xk}).pipe(mT({name:`full_name`})),xK=M({totalCount:R.check(HT(0)),repositories:N(bK)}).pipe(mT({totalCount:`total_count`})),SK=M({token:z,expiresAt:vE,repositories:xE(N(bK))}).pipe(mT({expiresAt:`expires_at`})),CK=e=>e._tag===`InstallationWide`?{operation:`mint-installation-token`,body:{permissions:UG}}:{operation:`mint-worker-token`,body:{permissions:WG[e.permissions],repository_ids:[e.repositoryId]}},wK=class e extends Rr()(`@usine/github/GitHubApp`){static layer=Xf(e,T(function*(){let e=yield*jG(yield*yG),t=yield*LW,n=(e,n,r)=>T(function*(){let i=yield*t.execute(n).pipe(dg(t=>aK(e,t)));if(i.status<200||i.status>=300){let t=hK(e,i,yield*op);return t._tag===`GitHubRateLimitError`?yield*t:yield*yield*sK(t,i)}return yield*wW(r)(i).pipe(dg(t=>cK(e,t.message)))}),r=O(`GitHubApp.discoverInstallation`)(function*(){let t=yield*e(),[r,...i]=yield*n(`discover-installation`,iW(`${nK}/app/installations?per_page=2`).pipe(iK(t)),vK);if(r===void 0)return yield*new HG({reason:`missing`,message:`The GitHub App is not installed on any account. Install it on the account that owns the repositories.`});if(i.length>0)return yield*new HG({reason:`multiple`,message:`The GitHub App has more than one installation. Uninstall it from every account except one.`});if(r.suspendedAt!==null)return yield*new HG({reason:`suspended`,message:`The GitHub App installation is suspended. Unsuspend it in the installation settings on GitHub.`});let a=KG(r.permissions);return a.length>0?yield*new XG({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 IG({id:r.id,accountLogin:r.account.login,appSlug:r.appSlug})}),i=O(`GitHubApp.mintToken`)(function*(t,r){let{operation:i,body:a}=CK(r);yield*D({installationId:t,operation:i,scope:r._tag,permissions:r._tag===`SingleRepository`?r.permissions:`installation`});let o=yield*e(),s=yield*n(i,aW(`${nK}/app/installations/${t}/access_tokens`).pipe(bW(a),iK(o)),SK),c=yield*op,l=K_(s.expiresAt)-c;if(l<=0||l>378e4)return yield*new eK({operation:i,message:`GitHub returned an installation token that is expired or exceeds the one-hour lifetime limit`,detail:`expires_at ${J_(s.expiresAt)} is ${l}ms from now`});l>gK&&(yield*k(`Accepted GitHub token clock skew; capped the local lease`,{installationId:t,operation:i,skewMillis:l-gK}));let u=yr(s.repositories,()=>[]);return r._tag===`SingleRepository`&&!(u.length===1&&u.every(e=>e.id===r.repositoryId))?yield*new eK({operation:i,message:`GitHub did not confirm that the worker token is scoped to exactly one repository`,detail:`expected repository ID ${r.repositoryId}, got [${u.map(e=>e.id).join(`, `)}]`}):new BG({value:vv(s.token),expiresAt:R_(c+Math.min(l,gK)),scope:r})}),a=O(`GitHubApp.installedRepositories`)(function*(e){let t=[];for(let r=1;;r+=1){let i=yield*n(`list-installation-repositories`,iW(`${nK}/installation/repositories?per_page=100&page=${r}`).pipe(iK(e.value)),xK);if(t.push(...i.repositories),t.length>=i.totalCount)return t;if(i.repositories.length===0)return yield*new eK({operation:`list-installation-repositories`,message:`GitHub returned an empty page before it listed total_count repositories`,detail:`page ${r} was empty after ${t.length} of ${i.totalCount} repositories`})}}),o=yield*qk(y()),s=O(`GitHubApp.lease`)(()=>Yk(o,e=>T(function*(){let t=yield*op;if(S(e)&&K_(e.value.token.expiresAt)-t>_K)return[e.value,e];let n=yield*r(),a={installation:n,token:yield*i(n.id,new LG)};return[a,b(a)]}))),c=yield*qk(y()),l=O(`GitHubApp.botAccount`)(()=>Yk(c,e=>T(function*(){let{installation:t,token:r}=yield*s(),{appSlug:i}=t;if(yield*D({appSlug:i}),S(e)&&e.value.appSlug===i)return[e.value.account,e];let a=new AN(yield*n(`read-bot-account`,iW(`${nK}/users/${encodeURIComponent(`${i}[bot]`)}`).pipe(iK(r.value)),yK));return yield*k(`Read the App's bot account`,{appSlug:i,login:a.login,id:a.id}),[a,b({appSlug:i,account:a})]})));return{repositories:O(`GitHubApp.repositories`)(function*(){let{token:e,installation:t}=yield*s();yield*D({installationId:t.id});let n=yield*a(e);return yield*A(`Listed installation repositories`,{count:n.length}),n.map(({name:e})=>e)}),installation:O(`GitHubApp.installation`)(()=>ng(s(),e=>e.installation)),botAccount:l,installationToken:O(`GitHubApp.installationToken`)(()=>ng(s(),e=>e.token)),projectAccess:O(`GitHubApp.projectAccess`)(function*(e){let{installation:t,token:n}=yield*s();return YG(t,e,yield*a(n))}),workerToken:O(`GitHubApp.workerToken`)((e,t)=>i(e.installationId,new RG({repository:e.repository,repositoryId:e.repositoryId,permissions:t})))}}))},TK=z.pipe(L(`GitHubEntityTag`)),EK=z.pipe(L(`GitHubBaseRefName`)),DK=class extends V(`@usine/github/BaseRefHead`)({baseRefName:EK,sha:Qk,entityTag:yE(TK)}){},OK=class e extends V(`@usine/github/PollCursor`)({entityTag:yE(TK),watermark:yE(vE)}){static empty=new e({entityTag:y(),watermark:y()})},kK=class extends H(`@usine/github/ChangedIssue`)(`ChangedIssue`,{number:R.check(HT(1)),updatedAt:_E}){},AK=class extends H(`@usine/github/ChangedPullRequest`)(`ChangedPullRequest`,{number:R.check(HT(1)),updatedAt:_E}){},jK=P([kK,AK]),MK=class extends H(`@usine/github/RepositoryNotModified`)(`RepositoryNotModified`,{cursor:OK,nextPollAt:B(_E),backoffUntil:B(_E).pipe(TT(w(y())))}){},NK=class extends H(`@usine/github/RepositoryChanges`)(`RepositoryChanges`,{cursor:OK,items:N(jK),backlog:lT,nextPollAt:B(_E),backoffUntil:B(_E).pipe(TT(w(y())))}){};P([MK,NK]);var PK=z.pipe(L(`GitHubRepositoryLabelName`)),FK=j.check(PT(/^[0-9a-fA-F]{6}$/u,{message:`Expected a six-digit hex label color`})).pipe(L(`GitHubRepositoryLabelColor`)),IK=class extends V(`@usine/github/RepositoryLabel`)({name:PK,color:FK,description:yE(j)}){},LK=NT(e=>new Set(e.map(({name:e})=>e)).size===e.length,{message:`Expected unique label names`}),RK=class extends V(`@usine/github/RepositoryLabelCatalog`)({entityTag:yE(TK),labels:N(IK).check(LK)}){},zK=class extends H(`@usine/github/RepositoryLabelsNotModified`)(`RepositoryLabelsNotModified`,{}){};P([RK,zK]);var BK=class extends V(`@usine/github/NewRepositoryLabel`)({name:PK,color:B(FK),description:B(j)}){},VK=M({name:PK,color:FK,description:I(j)}),HK=e=>{let{name:t,owner:n}=eA(e);return`${nK}/repos/${encodeURIComponent(n)}/${encodeURIComponent(t)}/labels`},UK=class e extends Rr()(`@usine/github/GitHubLabelWriter`){static layer=Xf(e,T(function*(){let e=yield*wK,t=yield*LW;return{create:O(`GitHubLabelWriter.create`)(function*(n,r){yield*D({repository:n,label:r.name});let i=yield*e.installationToken(),a={name:r.name};S(r.color)&&(a.color=r.color.value),S(r.description)&&(a.description=r.description.value);let o=aW(HK(n)).pipe(bW(a),iK(i.value)),s=yield*t.execute(o).pipe(dg(e=>aK(`create-repository-label`,e)));if(s.status<200||s.status>=300)return yield*hK(`create-repository-label`,s,yield*op);let c=yield*wW(VK)(s).pipe(dg(e=>cK(`create-repository-label`,e.message)));return new IK({name:c.name,color:c.color,description:Sr(c.description)})})}}))},WK=new Set([`closedAt`,`createdAt`,`mergedAt`,`submittedAt`,`updatedAt`]),GK=e=>Array.isArray(e)?e.map(GK):Vw(LE)(e)?Object.fromEntries(Object.entries(e).filter(([e])=>!WK.has(e)).sort(([e],[t])=>e<t?-1:+(e>t)).map(([e,t])=>[e,GK(t)])):e,KK=6e4,qK=M({data:$w(aT),errors:$w(N(M({message:j,type:$w(j)})))}),JK=O(`GitHub.queryGraphql`)(function*(e,t,n,r,i,a){let o=aW(`${nK}/graphql`).pipe(bW({query:r,variables:i}),iK(t.value)),s=yield*e.execute(o).pipe(dg(e=>aK(n,e))),c=yield*op;if(s.status!==200)return yield*hK(n,s,c);let l=yield*wW(qK)(s).pipe(dg(e=>cK(n,e.message)));if(l.errors!==void 0&&l.errors.length>0){if(l.errors.some(e=>e.type===`RATE_LIMITED`))return yield*new $G({operation:n,retryAt:R_(yr(mK(s.headers,c),()=>c+KK)),message:`GitHub GraphQL API rate limit exceeded`});if(!l.errors.every(e=>e.type===`NOT_FOUND`))return yield*cK(n,`GraphQL errors: ${l.errors.map(e=>e.message).join(`; `)}`)}return yield*Hw(a)(l.data).pipe(dg(e=>cK(n,e.message)))}),YK=R.check(HT(1)),XK=R.check(HT(0)),ZK=j.check(PT(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/u,{message:`Expected a GitHub UTC timestamp`})),QK=(e,t)=>I(e).pipe(ST(e,{decode:sb(e=>e??t),encode:sb(e=>e)})),$K={totalCount:0,nodes:[]},eq=M({login:z}),tq=I(eq),nq=M({totalCount:XK,nodes:N(M({name:z}))}),rq=M({totalCount:XK,nodes:N(M({author:tq,body:j,createdAt:ZK}))}),iq=M({number:YK,title:j,body:j,url:z,state:j,stateReason:I(j),createdAt:ZK,updatedAt:ZK,closedAt:I(ZK),author:tq,issueType:I(M({name:j})),milestone:I(M({title:j})),labels:QK(nq,$K),assignees:M({totalCount:XK,nodes:N(eq)}),comments:rq,closedByPullRequestsReferences:QK(M({totalCount:XK,nodes:N(M({number:YK,state:j,isDraft:lT,url:z}))}),$K)}),aq=I(M({login:$w(z)})),oq=M({author:tq,state:j,body:j,submittedAt:I(ZK),commit:I(M({oid:z}))}),sq=M({author:tq,body:j}),cq=M({number:YK,title:j,body:j,url:z,state:j,isDraft:lT,merged:lT,createdAt:ZK,updatedAt:ZK,mergedAt:I(ZK),author:tq,baseRefName:EK,headRefName:j,headRefOid:z,additions:XK,deletions:XK,changedFiles:XK,reviewDecision:I(j),mergeable:j.pipe(DT(w(`UNKNOWN`))),mergeStateStatus:j.pipe(DT(w(`UNKNOWN`))),statusCheckRollup:I(M({state:j})),labels:QK(nq,$K),reviewRequests:QK(M({totalCount:XK,nodes:N(M({requestedReviewer:aq}))}),$K),reviews:QK(M({totalCount:XK,nodes:N(oq)}),$K),reviewThreads:M({totalCount:XK,nodes:N(M({isResolved:lT,isOutdated:lT,path:j,comments:M({totalCount:XK,nodes:N(sq)})}))}),comments:rq,closingIssuesReferences:QK(M({totalCount:XK,nodes:N(M({number:YK,state:j}))}),$K)}),lq=j.check(PT(/^[a-f0-9]{64}$/u,{message:`Expected a SHA-256 content hash`})).pipe(L(`GitHubContentHash`)),uq=class extends H(`@usine/github/IssueSnapshot`)(`IssueSnapshot`,{payload:iq,contentHash:lq}){},dq=class extends H(`@usine/github/PullRequestSnapshot`)(`PullRequestSnapshot`,{payload:cq,contentHash:lq}){};P([uq,dq]);var fq=`
|
|
37
|
-
query UsineIssuePayload($owner: String!, $name: String!, $number: Int!) {
|
|
38
|
-
repository(owner: $owner, name: $name) {
|
|
39
|
-
issue(number: $number) {
|
|
40
|
-
number
|
|
41
|
-
title
|
|
42
|
-
body
|
|
43
|
-
url
|
|
44
|
-
state
|
|
45
|
-
stateReason
|
|
46
|
-
createdAt
|
|
47
|
-
updatedAt
|
|
48
|
-
closedAt
|
|
49
|
-
author { login }
|
|
50
|
-
issueType { name }
|
|
51
|
-
milestone { title }
|
|
52
|
-
labels(first: 50) {
|
|
53
|
-
totalCount
|
|
54
|
-
nodes { name }
|
|
55
|
-
}
|
|
56
|
-
assignees(first: 10) {
|
|
57
|
-
totalCount
|
|
58
|
-
nodes { login }
|
|
59
|
-
}
|
|
60
|
-
comments(last: 20) {
|
|
61
|
-
totalCount
|
|
62
|
-
nodes {
|
|
63
|
-
author { login }
|
|
64
|
-
body
|
|
65
|
-
createdAt
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
closedByPullRequestsReferences(first: 10, includeClosedPrs: true) {
|
|
69
|
-
totalCount
|
|
70
|
-
nodes {
|
|
71
|
-
number
|
|
72
|
-
state
|
|
73
|
-
isDraft
|
|
74
|
-
url
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
`,pq=`
|
|
81
|
-
query UsinePullRequestPayload($owner: String!, $name: String!, $number: Int!) {
|
|
82
|
-
repository(owner: $owner, name: $name) {
|
|
83
|
-
pullRequest(number: $number) {
|
|
84
|
-
number
|
|
85
|
-
title
|
|
86
|
-
body
|
|
87
|
-
url
|
|
88
|
-
state
|
|
89
|
-
isDraft
|
|
90
|
-
merged
|
|
91
|
-
createdAt
|
|
92
|
-
updatedAt
|
|
93
|
-
mergedAt
|
|
94
|
-
author { login }
|
|
95
|
-
baseRefName
|
|
96
|
-
headRefName
|
|
97
|
-
headRefOid
|
|
98
|
-
additions
|
|
99
|
-
deletions
|
|
100
|
-
changedFiles
|
|
101
|
-
reviewDecision
|
|
102
|
-
mergeable
|
|
103
|
-
mergeStateStatus
|
|
104
|
-
statusCheckRollup { state }
|
|
105
|
-
labels(first: 50) {
|
|
106
|
-
totalCount
|
|
107
|
-
nodes { name }
|
|
108
|
-
}
|
|
109
|
-
reviewRequests(first: 10) {
|
|
110
|
-
totalCount
|
|
111
|
-
nodes {
|
|
112
|
-
requestedReviewer {
|
|
113
|
-
... on User { login }
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
reviews(last: 20) {
|
|
118
|
-
totalCount
|
|
119
|
-
nodes {
|
|
120
|
-
author { login }
|
|
121
|
-
state
|
|
122
|
-
body
|
|
123
|
-
submittedAt
|
|
124
|
-
commit { oid }
|
|
125
|
-
}
|
|
126
|
-
}
|
|
127
|
-
reviewThreads(first: 50) {
|
|
128
|
-
totalCount
|
|
129
|
-
nodes {
|
|
130
|
-
isResolved
|
|
131
|
-
isOutdated
|
|
132
|
-
path
|
|
133
|
-
comments(first: 10) {
|
|
134
|
-
totalCount
|
|
135
|
-
nodes {
|
|
136
|
-
author { login }
|
|
137
|
-
body
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
comments(last: 20) {
|
|
143
|
-
totalCount
|
|
144
|
-
nodes {
|
|
145
|
-
author { login }
|
|
146
|
-
body
|
|
147
|
-
createdAt
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
closingIssuesReferences(first: 10) {
|
|
151
|
-
totalCount
|
|
152
|
-
nodes {
|
|
153
|
-
number
|
|
154
|
-
state
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
`,mq=e=>{let t=Array.from({length:e},(e,t)=>t);return`
|
|
161
|
-
query UsineIssuesPresent($owner: String!, $name: String!, ${t.map(e=>`$n${e}: Int!`).join(`, `)}) {
|
|
162
|
-
repository(owner: $owner, name: $name) {
|
|
163
|
-
${t.map(e=>`i${e}: issue(number: $n${e}) { number }`).join(`
|
|
164
|
-
`)}
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
`},hq=5e3,gq=100,_q=10,vq=100,yq=50,bq=N(M({number:R.check(HT(1)),updatedAt:vE,pullRequest:$w(aT)}).pipe(mT({updatedAt:`updated_at`,pullRequest:`pull_request`}))),xq=M({object:M({sha:Qk})}),Sq=N(M({name:PK,color:FK,description:I(j)})),Cq=({name:e,color:t,description:n})=>new IK({name:e,color:t,description:Sr(n)}),wq=M({repository:yE(M({issue:yE(iq)}))}),Tq=M({repository:yE(M({pullRequest:yE(cq)}))}),Eq=I(M({number:R})),Dq=e=>M({repository:yE(M(Object.fromEntries(Array.from({length:e},(e,t)=>[`i${t}`,Eq]))))}),Oq=e=>z_(e),kq=e=>e.map(e=>e.pullRequest===void 0?new kK({number:e.number,updatedAt:e.updatedAt}):new AK({number:e.number,updatedAt:e.updatedAt})),Aq=e=>{let t=e.flatMap(e=>vr(e,{onNone:()=>[],onSome:e=>[e]}));return t.length===0?y():Oq(Math.max(...t))},jq=(e,t)=>Aq([uK(e[`retry-after`],t),dK(e,gq)]),Mq=(e,t)=>Aq([fK(e,t),uK(e[`retry-after`],t),dK(e,gq)]),Nq=e=>e===void 0?y():Sr(/<(?<url>[^>]+)>;\s*rel="next"/u.exec(e)?.groups?.url),Pq=e=>{let t=K_(e)-hq;return`${new Date(t-t%1e3).toISOString().slice(0,19)}Z`},Fq=(e,t)=>{let{name:n,owner:r}=eA(e),i=new URL(`${nK}/repos/${encodeURIComponent(r)}/${encodeURIComponent(n)}/issues`);return i.searchParams.set(`state`,`all`),i.searchParams.set(`sort`,`updated`),i.searchParams.set(`direction`,`asc`),i.searchParams.set(`per_page`,`100`),S(t.watermark)&&i.searchParams.set(`since`,Pq(t.watermark.value)),i.toString()},Iq=e=>{let{name:t,owner:n}=eA(e),r=new URL(`${nK}/repos/${encodeURIComponent(n)}/${encodeURIComponent(t)}/labels`);return r.searchParams.set(`per_page`,`100`),r.toString()},Lq=(e,t)=>{let{name:n,owner:r}=eA(e),i=t.split(`/`).map(encodeURIComponent).join(`/`);return`${nK}/repos/${encodeURIComponent(r)}/${encodeURIComponent(n)}/git/ref/heads/${i}`},Rq=(e,t)=>{let{name:n,owner:r}=eA(e),i=new URL(`${nK}/repos/${encodeURIComponent(r)}/${encodeURIComponent(n)}/issues/${t}/labels`);return i.searchParams.set(`per_page`,`100`),i.toString()},zq=(e,t)=>{let n=t.map(({updatedAt:e})=>K_(e));return S(e.watermark)&&n.push(K_(e.watermark.value)),n.length===0?y():Oq(Math.max(...n))},Bq=class e extends Rr()(`@usine/github/GitHubPolling`){static layer=Xf(e,T(function*(){let e=yield*wK,t=yield*YO,n=yield*LW,r=Vq(t),i=O(`GitHubPolling.execute`)(function*(e,t){return yield*n.execute(t).pipe(dg(t=>aK(e,t)))}),a=O(`GitHubPolling.changesPage`)(function*(t){let n=yield*e.installationToken(),r=iW(t).pipe(iK(n.value)),a=yield*i(`poll-repository-changes`,r),o=yield*op;return a.status===200?{items:kq(yield*wW(bq)(a).pipe(dg(e=>cK(`poll-repository-changes`,e.message)))),next:Nq(a.headers.link)}:yield*hK(`poll-repository-changes`,a,o)}),o=O(`GitHubPolling.labelsPage`)(function*(t,n){let r=yield*e.installationToken(),a=iW(n).pipe(iK(r.value)),o=yield*i(t,a),s=yield*op;return o.status===200?{labels:(yield*wW(Sq)(o).pipe(dg(e=>cK(t,e.message)))).map(Cq),next:Nq(o.headers.link)}:yield*hK(t,o,s)}),s=O(`GitHubPolling.remainingLabelPages`)(function*(e,t){let n=[...t.labels],r=t.next,i=1;for(;S(r)&&i<vq;){let t=yield*o(e,r.value);n.push(...t.labels),r=t.next,i+=1}return S(r)?yield*cK(e,`the GitHub label list has more than ${vq} pages`):n.sort((e,t)=>e.name.localeCompare(t.name))}),c=O(`GitHubPolling.allLabels`)(function*(e,t){return yield*s(e,yield*o(e,t))}),l=O(`GitHubPolling.labels`)(function*(t,n){yield*D({repository:t});let r=yield*e.installationToken(),a=iW(Iq(t)).pipe(iK(r.value));S(n)&&(a=cW(a,`if-none-match`,n.value));let o=yield*i(`list-repository-labels`,a),c=yield*op;if(o.status===304)return new zK;if(o.status!==200)return yield*hK(`list-repository-labels`,o,c);let l=yield*wW(Sq)(o).pipe(dg(e=>cK(`list-repository-labels`,e.message))),u=yield*s(`list-repository-labels`,{labels:l.map(Cq),next:Nq(o.headers.link)}),d=Ww(TK)(o.headers.etag);return x(d)&&(yield*e_(`GitHub omitted the label catalog ETag; next poll is unconditional`,{repository:t})),new RK({entityTag:d,labels:u})}),u=O(`GitHubPolling.changes`)(function*(t,n){let r=yield*e.installationToken(),o=iW(Fq(t,n)).pipe(iK(r.value));S(n.entityTag)&&(o=cW(o,`if-none-match`,n.entityTag.value));let s=yield*i(`poll-repository-changes`,o),c=yield*op,l=Mq(s.headers,c);if(s.status===304)return new MK({cursor:n,nextPollAt:l,backoffUntil:jq(s.headers,c)});if(s.status!==200)return yield*hK(`poll-repository-changes`,s,c);let u=kq(yield*wW(bq)(s).pipe(dg(e=>cK(`poll-repository-changes`,e.message)))),d=Ww(TK)(s.headers.etag);x(d)&&(yield*e_(`GitHub omitted the changes ETag; next poll is unconditional`,{repository:t}));let f=[...u],p=Nq(s.headers.link),m=1;for(;S(p)&&m<_q;){let e=yield*a(p.value);f.push(...e.items),p=e.next,m+=1}let h=S(p);return h&&(yield*k(`GitHub changes walk hit the page cap; backlog remains`,{repository:t,pages:m,items:f.length})),new NK({cursor:new OK({entityTag:d,watermark:zq(n,f)}),items:f,backlog:h,nextPollAt:l,backoffUntil:jq(s.headers,c)})}),d=O(`GitHubPolling.baseRefHead`)(function*(t,n,r){yield*D({repository:t,baseRefName:n});let a=yield*e.installationToken(),o=iW(Lq(t,n)).pipe(iK(a.value)),s=kr(r,({entityTag:e})=>e);S(s)&&(o=cW(o,`if-none-match`,s.value));let c=yield*i(`fetch-base-ref-head`,o),l=yield*op;if(c.status===304&&S(r))return r.value;if(c.status!==200)return yield*hK(`fetch-base-ref-head`,c,l);let u=yield*wW(xq)(c).pipe(dg(e=>cK(`fetch-base-ref-head`,e.message))),d=Ww(TK)(c.headers.etag);return x(d)&&(yield*e_(`GitHub omitted the base branch ETag; next read is unconditional`,{repository:t,baseRefName:n})),new DK({baseRefName:n,sha:u.object.sha,entityTag:d})}),f=O(`GitHubPolling.graphql`)(function*(t,r,i,a,o){let s=yield*e.installationToken(),{name:c,owner:l}=eA(r);return yield*JK(n,s,t,a,{owner:l,name:c,number:i},o)});return{changes:u,labels:l,baseRefHead:d,snapshot:O(`GitHubPolling.snapshot`)((e,t)=>T(function*(){let n=t=>cK(t,`repository "${e}" is null: deleted, renamed, or no longer accessible`),i=(n,r)=>new tK({operation:n,item:t.number,message:`GitHub ${r} ${e}#${t.number} was not found. It was deleted or transferred, or the GitHub App can no longer read it.`}),a=O(`GitHubPolling.completeItemLabels`)(function*(n){if(n.labels.nodes.length>=n.labels.totalCount)return n.labels;yield*A(`Completing truncated Item label connection for Board matching`,{repository:e,item:t.number,listedLabels:n.labels.nodes.length,totalLabels:n.labels.totalCount});let r=yield*c(`fetch-item-labels`,Rq(e,t.number));return{totalCount:r.length,nodes:r.map(({name:e})=>({name:e}))}});if(t._tag===`ChangedIssue`){let o=yield*f(`fetch-issue-snapshot`,e,t.number,fq,wq);if(x(o.repository))return yield*n(`fetch-issue-snapshot`);let s=o.repository.value.issue;if(x(s))return yield*i(`fetch-issue-snapshot`,`issue`);let c={...s.value,labels:yield*a(s.value)};return new uq({payload:c,contentHash:yield*r(c)})}let o=yield*f(`fetch-pull-request-snapshot`,e,t.number,pq,Tq);if(x(o.repository))return yield*n(`fetch-pull-request-snapshot`);let s=o.repository.value.pullRequest;if(x(s))return yield*i(`fetch-pull-request-snapshot`,`pull request`);let l={...s.value,labels:yield*a(s.value)};return new dq({payload:l,contentHash:yield*r(l)})})),missingIssues:O(`GitHubPolling.missingIssues`)(function*(t,r){yield*D({repository:t,issues:r.length});let{name:i,owner:a}=eA(t);return(yield*Ph(ua(r,yq),r=>T(function*(){let o=yield*e.installationToken(),s=yield*JK(n,o,`find-missing-issues`,mq(r.length),{owner:a,name:i,...Object.fromEntries(r.map((e,t)=>[`n${t}`,e]))},Dq(r.length));if(x(s.repository))return yield*cK(`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()})}}))},Vq=e=>O(`GitHubPolling.contentHash`)(function*(t){let n=new TextEncoder().encode(JSON.stringify(GK(t))),r=yield*e.digest(`SHA-256`,n).pipe(fg);return lq.make(Array.from(r,e=>e.toString(16).padStart(2,`0`)).join(``))}),Hq=class extends V(`@usine/orchestrator/LabelPreflightFinding`)({repository:Xk,label:fz,errorTag:z,message:z}){},Uq=(e,t)=>{let n=[];if(S(e.color)){let r=e.color.value.toLowerCase();vr(t.color,{onNone:()=>!0,onSome:e=>e.toLowerCase()!==r})&&n.push(`color`)}if(S(e.description)){let r=e.description.value;vr(t.description,{onNone:()=>!0,onSome:e=>e!==r})&&n.push(`description`)}return n},Wq=e=>new BK({name:PK.make(e.name),color:Or(e.color,FK.make),description:e.description}),Gq=class e extends Rr()(`@usine/orchestrator/LabelReconciler`){static layer=Xf(e,T(function*(){let e=yield*UK;return{reconcile:O(`LabelReconciler.reconcile`)(function*(t,n,r){yield*D({repository:t});let i=[...r],a=new Map(r.map(e=>[pz(e.name),e])),o=[],s=!1,c=y();for(let r of n){let n=a.get(pz(r.name));if(n!==void 0){let e=Uq(r,n);e.length>0?yield*e_(`Declared GitHub label differs from the existing repository label; left unchanged`,{repository:t,label:r.name,drift:e.join(`, `)}):yield*A(`Declared GitHub label already exists`,{repository:t,label:r.name});continue}let l=yield*$h(e.create(t,Wq(r)));if(Di(l)){let e=l.failure;if(o.push(new Hq({repository:t,label:r.name,errorTag:e._tag,message:e.message})),e._tag===`GitHubRateLimitError`){c=b(e.retryAt),yield*e_(`Label creation rate-limited; remaining declarations deferred and trigger evaluation continues`,{repository:t,label:r.name,errorTag:e._tag,message:e.message,retryAt:J_(e.retryAt)});break}yield*t_(`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 oU({name:l.success.name,color:b(l.success.color),description:l.success.description});i.push(u),a.set(pz(u.name),u),s=!0,yield*k(`Created declared GitHub label`,{repository:t,label:u.name})}return i.sort((e,t)=>e.name.localeCompare(t.name)),{labels:i,findings:o,catalogChanged:s,nextPollAt:c}})}}))},Kq=(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},qq=(e,t)=>{let n=t.startsWith(`---\r
|
|
168
|
-
`)?`\r
|
|
169
|
-
`:t.startsWith(`---
|
|
170
|
-
`)?`
|
|
171
|
-
`:void 0;if(n===void 0)return new rU({file:e,stage:`frontmatter`,expression:y(),message:`Expected the file to start with a YAML frontmatter delimiter (---)`});let r=3+n.length,i=`${n}---`,a=Kq(t,n,r);if(a<0)return new rU({file:e,stage:`frontmatter`,expression:y(),message:`Expected a closing YAML frontmatter delimiter (---)`});let o=a+i.length,s=t.startsWith(n,o)?o+n.length:o;return w({yaml:t.slice(r,a),body:t.slice(s),newline:n})},Jq=class extends V(`@usine/config/AgentFile`)({name:fN,harness:lN,model:cN,effort:uN,parentModel:B(cN),parentEffort:B(uN),persona:pN}){get agent(){return new mN({name:this.name,persona:this.persona,brain:new dN({harness:this.harness,model:this.model,effort:this.effort}),parentModel:this.parentModel,parentEffort:this.parentEffort})}},Yq=class extends V(`@usine/config/InvalidAgent`)({file:tU,error:rU}){},Xq=F([`latest`,`next`]),Zq=F([`off`,`propose`,`automatic`]),Qq=j.check(PT(/^(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(L(`ReleaseVersion`)),$q=F([`idle`,`now`]),eJ={previous:Qq,target:Qq},tJ=P([class extends V(`@usine/core/UpgradeInstalling`)({...eJ,status:rT(`installing`)}){},class extends V(`@usine/core/UpgradeGood`)({...eJ,status:rT(`good`)}){},class extends V(`@usine/core/UpgradeRolledBack`)({...eJ,status:rT(`rolled-back`),reason:z,failureStage:F([`install`,`health-check`,`unknown`]).pipe(DT(w(`unknown`)))}){},class extends V(`@usine/core/UpgradeFailed`)({...eJ,status:rT(`failed`),reason:z}){}]),nJ=_z(`Expected a non-blank registry tag`).pipe(L(`RegistryTag`)),rJ=R.check(HT(1)),iJ=NT(e=>new Set(e.map(({name:e})=>e)).size===e.length,{message:`Expected unique names`}),aJ=e=>`label`in e?`label:${pz(e.label)}`:`state:${e.state}`,oJ=NT(e=>{let t=e.flatMap(({sources:e})=>e.map(aJ));return new Set(t).size===t.length},{message:`Expected each lane source in only one lane`}),sJ=N(Ez).check(iJ,oJ),cJ=NT(e=>new Set(e.map(({name:e})=>pz(e))).size===e.length,{message:`Expected unique GitHub label names`}),lJ=N(gz).check(cJ),uJ=class extends V(`@usine/config/ManagedRepo`)({name:Xk,tags:N(nJ).check(XT()).pipe(DT(w([]))),lanes:sJ.pipe(DT(w([])))}){},dJ=rJ.pipe(DT(w(1))),fJ=class extends V(`@usine/config/LocalWorker`)({name:EN,kind:rT(`local`),maxConcurrentAttempts:dJ}){},pJ=class extends V(`@usine/config/ExeDevWorker`)({name:EN,kind:rT(`exe.dev`),maxConcurrentAttempts:dJ}){},mJ=j.check(PT(/^[A-Za-z_][A-Za-z0-9_]*$/u,{message:`Expected an environment variable name`})).pipe(L(`EnvironmentVariableName`)),hJ=class extends V(`@usine/config/WorkerGateway`)({domain:FN,destination:jN,adminPort:IN.pipe(DT(w(7070))),adminTokenEnv:mJ,llmProviders:N(LN).check(XT()).pipe(DT(w([])))}){},gJ=class extends V(`@usine/config/WorkerContainer`)({image:xE(zN),cpus:xE(VN),memoryMib:xE(HN),pids:xE(UN)}){},_J=class extends V(`@usine/config/ProviderApiKeys`)({anthropic:xE(mJ),openai:xE(mJ)}){}.pipe(DT(w({}))),vJ=lP.pipe(mT({sshWait:`ssh_wait`,creationBackoffMin:`creation_backoff_min`,creationBackoffMax:`creation_backoff_max`,machineCheckInterval:`machine_check_interval`}),DT(w({}))),yJ=class extends V(`@usine/config/HetznerProvisioner`)({provider:rT(`hetzner`),tokenEnv:mJ,serverType:ZN,location:QN,image:$N,network:xE(eP),firewall:xE(eP),sshKey:eP,sshUser:rP.pipe(DT(w(`usine`))),labels:nP.pipe(DT(w({}))),apiKeys:_J,timings:vJ}){},bJ=class extends V(`@usine/config/BoatTailnet`)({gatewayAddress:oP,clientIdEnv:mJ,clientSecretEnv:mJ}){},xJ=class extends V(`@usine/config/BoatProvisioner`)({provider:rT(`boat`),tokenEnv:mJ,size:iP.pipe(DT(w(`default`))),snapshot:xE(aP),tailnet:xE(bJ.pipe(mT({gatewayAddress:`gateway_address`,clientIdEnv:`client_id_env`,clientSecretEnv:`client_secret_env`}))),apiKeys:_J,timings:vJ}){};P([yJ,xJ]);var SJ=P([yJ.pipe(mT({tokenEnv:`token_env`,serverType:`server_type`,sshKey:`ssh_key`,sshUser:`ssh_user`,apiKeys:`api_keys`})),xJ.pipe(mT({tokenEnv:`token_env`,apiKeys:`api_keys`}))]),CJ=class extends V(`@usine/config/SshWorker`)({name:EN,kind:rT(`ssh`),maxConcurrentAttempts:dJ,destination:xE(jN),provisioner:xE(SJ),identityFile:xE(NN),port:xE(MN),root:PN,gateway:xE(hJ.pipe(mT({adminPort:`admin_port`,adminTokenEnv:`admin_token_env`,llmProviders:`llm_providers`}))),container:gJ.pipe(mT({memoryMib:`memory_mib`}),DT(w({})))}){},wJ=e=>{let t=Tr(e.provisioner);if(t===void 0)return x(e.destination)?`SSH worker "${e.name}" needs a destination or a provisioner`:void 0;if(S(e.destination))return`SSH worker "${e.name}" sets both destination and provisioner; a provisioned worker creates its machines, so remove destination`;if(S(e.port))return`SSH worker "${e.name}" sets port, which a provisioned worker takes from its provider`;switch(t.provider){case`hetzner`:return S(e.gateway)&&x(t.network)?`SSH worker "${e.name}" has a gateway, so its provisioner needs the gateway's private network in network`:void 0;case`boat`:return S(e.gateway)&&(x(t.tailnet)||x(t.snapshot))?`SSH worker "${e.name}" needs provisioner.tailnet and provisioner.snapshot to use a Boat gateway`:S(t.tailnet)&&x(e.gateway)?`SSH worker "${e.name}" sets provisioner.tailnet without a gateway`:x(e.identityFile)?`SSH worker "${e.name}" has a Boat provisioner and needs identity_file, whose .pub file usine adds to each sandbox`:void 0}},TJ=rE.check(NT(e=>e.protocol===`https:`,{message:`Expected an https URL`}),NT(e=>e.username===``&&e.password===``&&e.search===``&&e.hash===``&&e.pathname===`/`,{message:`Expected the Worker's origin, without a path, credentials, or query string`})),EJ=class extends V(`@usine/config/CloudflareLlmProviderKey`)({provider:JN,apiKeyEnv:mJ}){},DJ=NT(e=>new Set(e.map(({provider:e})=>e)).size===e.length,{message:`Expected each provider once`}),OJ=class extends V(`@usine/config/CloudflareWorker`)({name:EN,kind:rT(`cloudflare`),maxConcurrentAttempts:dJ,workerUrl:TJ,accessClientIdEnv:mJ,accessClientSecretEnv:mJ,image:qN,instanceType:KN.pipe(DT(w(`standard-4`))),llmProviders:N(EJ.pipe(mT({apiKeyEnv:`api_key_env`}))).check(DJ).pipe(DT(w([])))}){},kJ=P([fJ,pJ,CJ,OJ]),AJ=class extends V(`@usine/config/Settings`)({upgradeChannel:Xq.pipe(DT(w(`latest`))),upgradeMode:Zq.pipe(DT(w(`propose`))),pollInterval:rJ.pipe(DT(w(60))),maxChildren:pP.pipe(DT(w(4))),maxAttemptMinutes:xE(rJ),maxAttemptTokens:xE(rJ),parentModel:xE(cN),parentEffort:xE(uN)}){},jJ=P([M({mode:rT(`off`)}),M({mode:rT(`deliveries`)}),M({mode:rT(`endpoint`),publicUrl:rE}).pipe(mT({publicUrl:`public_url`}))]),MJ=rE.check(NT(e=>e.protocol===`http:`||e.protocol===`https:`,{message:`Expected an http or https URL`}),NT(e=>e.username===``&&e.password===``&&e.search===``,{message:`Expected a URL without a username, password, or query string; authenticate in a collector next to usine up`})),NJ=class extends V(`@usine/config/Tracing`)({otlpUrl:MJ,serviceName:_z(`Expected a non-blank service name`).pipe(DT(w(`usine`)))}){},PJ=AJ.pipe(mT({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`})),FJ=P([fJ.pipe(mT({maxConcurrentAttempts:`max_concurrent_attempts`})),pJ.pipe(mT({maxConcurrentAttempts:`max_concurrent_attempts`})),CJ.pipe(mT({maxConcurrentAttempts:`max_concurrent_attempts`,identityFile:`identity_file`})).check(NT(e=>wJ(e)??!0)),OJ.pipe(mT({maxConcurrentAttempts:`max_concurrent_attempts`,workerUrl:`worker_url`,accessClientIdEnv:`access_client_id_env`,accessClientSecretEnv:`access_client_secret_env`,instanceType:`instance_type`,llmProviders:`llm_providers`}))]),IJ=N(uJ).check(vz(e=>e.name)),LJ=N(FJ).check(qT(),iJ),RJ=class extends V(`@usine/config/UsineConfig`)({version:rT(1),labels:lJ.pipe(DT(w([]))),repos:IJ,settings:PJ.pipe(DT(w({}))),workers:LJ.pipe(DT(w([{name:`local`,kind:`local`}]))),webhooks:jJ.pipe(DT(w({mode:`off`}))),operator:xE(aN),tracing:xE(NJ.pipe(mT({otlpUrl:`otlp_url`,serviceName:`service_name`})))}){},zJ=class extends V(`@usine/config/Selector`)({repos:xE(N(Xk).check(qT(),vz(e=>e))),tags:xE(N(nJ).check(qT(),XT()))}){}.check(NT(e=>S(e.repos)||S(e.tags),{message:`Expected selector.repos, selector.tags, or both`})),BJ=(e,t)=>vr(e,{onNone:()=>!0,onSome:e=>{let n=vr(e.repos,{onNone:()=>!0,onSome:e=>e.some(e=>tA(e)===tA(t.name))}),r=vr(e.tags,{onNone:()=>!0,onSome:e=>e.some(e=>t.tags.includes(e))});return n&&r}}),VJ=j.check(NT(e=>e.trim().split(/\s+/u).length===5&&Oi(Dm(e)),{message:`Expected a valid five-field cron expression`})).pipe(L(`Cron`)),HJ=j.check(NT(e=>S(H_(e)),{message:`Expected an IANA time-zone name`})).pipe(L(`TimeZone`)),UJ=class extends V(`@usine/config/IssueTrigger`)({on:rT(`issue`),if:ZH}){},WJ=class extends V(`@usine/config/PullRequestTrigger`)({on:rT(`pr`),if:ZH}){},GJ=class extends V(`@usine/config/ScheduleTrigger`)({on:rT(`schedule`),if:ZH,cron:VJ,tz:HJ.pipe(DT(w(`UTC`)))}){},KJ=P([UJ,WJ,GJ]),qJ=PT(/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,{message:`Expected a kebab-case file name`}),JJ=aA.check(qJ),YJ=_z(`Expected a non-blank Markdown prompt`).pipe(L(`PromptTemplate`)),XJ=R.check(HT(1,{message:`Expected a priority of at least 1`})).pipe(L(`LoopPriority`)),ZJ=class extends V(`@usine/config/LoopFile`)({name:JJ,trigger:KJ,selector:B(zJ),approval:sA,maxCycles:iI.pipe(DT(w(oI)),TT(w(oI))),permissions:lA.pipe(DT(w(`write`)),TT(w(`write`))),priority:B(XJ).pipe(TT(w(y()))),step:wN,agent:fN,body:YJ}){},QJ=class extends V(`@usine/config/QuarantinedLoop`)({file:tU,error:rU}){},$J=e=>tU.make(`loops/${e}.md`),eY=class extends H(`@usine/config/UndeclaredLaneLabelWarning`)(`UndeclaredLaneLabelWarning`,{repository:Xk,lane:yz,label:fz}){},tY=class extends H(`@usine/config/UndeclaredTriggerLabelWarning`)(`UndeclaredTriggerLabelWarning`,{loop:ZJ.fields.name,label:fz}){},nY=P([eY,tY]),rY=Kw(UH),iY=(e,t)=>new JH({name:e,fields:t.map(([e,t,n])=>new qH({name:e,type:rY(t),nullable:n===`nullable`}))}),aY=iY(`Actor`,[[`login`,`string`]]),oY=iY(`Label`,[[`name`,`string`]]),sY=iY(`Milestone`,[[`title`,`string`]]),cY=iY(`IssueType`,[[`name`,`string`]]),lY=iY(`Commit`,[[`oid`,`string`]]),uY=iY(`RepoContext`,[[`name`,`string`],[`owner`,`string`],[`url`,`string`]]),dY=iY(`Labels`,[[`totalCount`,`int`],[`nodes`,`list<Label>`]]),fY=iY(`Assignees`,[[`totalCount`,`int`],[`nodes`,`list<Actor>`]]),pY=iY(`IssueComment`,[[`author`,`Actor`,`nullable`],[`body`,`string`],[`createdAt`,`string`]]),mY=iY(`IssueComments`,[[`totalCount`,`int`],[`nodes`,`list<IssueComment>`]]),hY=iY(`PullRequestReference`,[[`number`,`int`],[`state`,`string`],[`isDraft`,`bool`],[`url`,`string`]]),gY=iY(`PullRequestReferences`,[[`totalCount`,`int`],[`nodes`,`list<PullRequestReference>`]]),_Y=iY(`IssuePayload`,[[`number`,`int`],[`title`,`string`],[`body`,`string`],[`url`,`string`],[`state`,`string`],[`stateReason`,`string`,`nullable`],[`createdAt`,`string`],[`updatedAt`,`string`],[`closedAt`,`string`,`nullable`],[`author`,`Actor`,`nullable`],[`issueType`,`IssueType`,`nullable`],[`milestone`,`Milestone`,`nullable`],[`labels`,`Labels`],[`assignees`,`Assignees`],[`comments`,`IssueComments`],[`closedByPullRequestsReferences`,`PullRequestReferences`]]),vY=iY(`RequestedReviewer`,[[`login`,`string`,`nullable`]]),yY=iY(`ReviewRequest`,[[`requestedReviewer`,`RequestedReviewer`,`nullable`]]),bY=iY(`ReviewRequests`,[[`totalCount`,`int`],[`nodes`,`list<ReviewRequest>`]]),xY=iY(`Review`,[[`author`,`Actor`,`nullable`],[`state`,`string`],[`body`,`string`],[`submittedAt`,`string`,`nullable`],[`commit`,`Commit`,`nullable`]]),SY=iY(`Reviews`,[[`totalCount`,`int`],[`nodes`,`list<Review>`]]),CY=iY(`ReviewThreadComment`,[[`author`,`Actor`,`nullable`],[`body`,`string`]]),wY=iY(`ReviewThreadComments`,[[`totalCount`,`int`],[`nodes`,`list<ReviewThreadComment>`]]),TY=iY(`ReviewThread`,[[`isResolved`,`bool`],[`isOutdated`,`bool`],[`path`,`string`],[`comments`,`ReviewThreadComments`]]),EY=iY(`ReviewThreads`,[[`totalCount`,`int`],[`nodes`,`list<ReviewThread>`]]),DY=iY(`PullRequestComment`,[[`author`,`Actor`,`nullable`],[`body`,`string`],[`createdAt`,`string`]]),OY=iY(`PullRequestComments`,[[`totalCount`,`int`],[`nodes`,`list<PullRequestComment>`]]),kY=iY(`ClosingIssueReference`,[[`number`,`int`],[`state`,`string`]]),AY=iY(`ClosingIssueReferences`,[[`totalCount`,`int`],[`nodes`,`list<ClosingIssueReference>`]]),jY=iY(`StatusCheckRollup`,[[`state`,`string`]]),MY=iY(`PullRequestPayload`,[[`number`,`int`],[`title`,`string`],[`body`,`string`],[`url`,`string`],[`state`,`string`],[`isDraft`,`bool`],[`merged`,`bool`],[`createdAt`,`string`],[`updatedAt`,`string`],[`mergedAt`,`string`,`nullable`],[`author`,`Actor`,`nullable`],[`baseRefName`,`string`],[`headRefName`,`string`],[`headRefOid`,`string`],[`additions`,`int`],[`deletions`,`int`],[`changedFiles`,`int`],[`reviewDecision`,`string`,`nullable`],[`mergeable`,`string`],[`mergeStateStatus`,`string`],[`statusCheckRollup`,`StatusCheckRollup`,`nullable`],[`labels`,`Labels`],[`reviewRequests`,`ReviewRequests`],[`reviews`,`Reviews`],[`reviewThreads`,`ReviewThreads`],[`comments`,`PullRequestComments`],[`closingIssuesReferences`,`ClosingIssueReferences`]]),NY=iY(`Tick`,[[`scheduledAt`,`string`],[`scheduledAtLocal`,`string`],[`cron`,`string`],[`tz`,`string`]]),PY=iY(`SchedulePayload`,[[`tick`,`Tick`]]),FY=(e,t)=>new XH({types:[uY,...e],variables:[new YH({name:`repo`,type:rY(`RepoContext`)}),new YH({name:`item`,type:rY(t)})]}),IY=FY([aY,oY,sY,cY,dY,fY,pY,mY,hY,gY,_Y],`IssuePayload`),LY=FY([aY,oY,lY,dY,vY,yY,bY,xY,SY,CY,wY,TY,EY,DY,OY,kY,AY,jY,MY],`PullRequestPayload`),RY=FY([NY,PY],`SchedulePayload`),zY=e=>{switch(e){case`issue`:return IY;case`pr`:return LY;case`schedule`:return RY}},BY=e=>{let{owner:t}=eA(e.name);return{name:e.name,owner:t,url:`https://github.com/${e.name}`}},VY=Symbol.for(`yaml.alias`),HY=Symbol.for(`yaml.document`),UY=Symbol.for(`yaml.map`),WY=Symbol.for(`yaml.pair`),GY=Symbol.for(`yaml.scalar`),KY=Symbol.for(`yaml.seq`),qY=Symbol.for(`yaml.node.type`),JY=e=>!!e&&typeof e==`object`&&e[qY]===VY,YY=e=>!!e&&typeof e==`object`&&e[qY]===HY,XY=e=>!!e&&typeof e==`object`&&e[qY]===UY,ZY=e=>!!e&&typeof e==`object`&&e[qY]===WY,QY=e=>!!e&&typeof e==`object`&&e[qY]===GY,$Y=e=>!!e&&typeof e==`object`&&e[qY]===KY;function eX(e){if(e&&typeof e==`object`)switch(e[qY]){case UY:case KY:return!0}return!1}function tX(e){if(e&&typeof e==`object`)switch(e[qY]){case VY:case UY:case GY:case KY:return!0}return!1}var nX=e=>(QY(e)||eX(e))&&!!e.anchor,rX=Symbol(`break visit`),iX=Symbol(`skip children`),aX=Symbol(`remove node`);function oX(e,t){let n=cX(t);YY(e)?sX(null,e.contents,n,Object.freeze([e]))===aX&&(e.contents=null):sX(null,e,n,Object.freeze([]))}oX.BREAK=rX,oX.SKIP=iX,oX.REMOVE=aX;function sX(e,t,n,r){let i=lX(e,t,n,r);if(tX(i)||ZY(i))return uX(e,r,i),sX(e,i,n,r);if(typeof i!=`symbol`){if(eX(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){let i=sX(e,t.items[e],n,r);if(typeof i==`number`)e=i-1;else if(i===rX)return rX;else i===aX&&(t.items.splice(e,1),--e)}}else if(ZY(t)){r=Object.freeze(r.concat(t));let e=sX(`key`,t.key,n,r);if(e===rX)return rX;e===aX&&(t.key=null);let i=sX(`value`,t.value,n,r);if(i===rX)return rX;i===aX&&(t.value=null)}}return i}function cX(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 lX(e,t,n,r){if(typeof n==`function`)return n(e,t,r);if(XY(t))return n.Map?.(e,t,r);if($Y(t))return n.Seq?.(e,t,r);if(ZY(t))return n.Pair?.(e,t,r);if(QY(t))return n.Scalar?.(e,t,r);if(JY(t))return n.Alias?.(e,t,r)}function uX(e,t,n){let r=t[t.length-1];if(eX(r))r.items[e]=n;else if(ZY(r))e===`key`?r.key=n:r.value=n;else if(YY(r))r.contents=n;else{let e=JY(r)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}var dX={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},fX=e=>e.replace(/[!,[\]{}]/g,e=>dX[e]),pX=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+fX(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&&tX(e.contents)){let t={};oX(e.contents,(e,n)=>{tX(n)&&n.tag&&(t[n.tag]=!0)}),r=Object.keys(t)}else r=[];for(let[i,a]of n)(i!==`!!`||a!==`tag:yaml.org,2002:`)&&(!e||r.some(e=>e.startsWith(a)))&&t.push(`%TAG ${i} ${a}`);return t.join(`
|
|
172
|
-
`)}};pX.defaultYaml={explicit:!1,version:`1.2`},pX.defaultTags={"!!":`tag:yaml.org,2002:`};function mX(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 hX(e){let t=new Set;return oX(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function gX(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function _X(e,t){let n=[],r=new Map,i=null;return{onAnchor:r=>{n.push(r),i??=hX(e);let a=gX(t,i);return i.add(a),a},setAnchors:()=>{for(let e of n){let t=r.get(e);if(typeof t==`object`&&t.anchor&&(QY(t.node)||eX(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 vX(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=vX(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=vX(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=vX(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=vX(e,r,t,n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}}return e.call(t,n,r)}function yX(e,t,n){if(Array.isArray(e))return e.map((e,t)=>yX(e,String(t),n));if(e&&typeof e.toJSON==`function`){if(!n||!nX(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 bX=class{constructor(e){Object.defineProperty(this,qY,{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(!YY(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=yX(this,``,a);if(typeof r==`function`)for(let{count:e,res:t}of a.anchors.values())r(t,e);return typeof i==`function`?vX(i,{"":o},``,o):o}},xX=class extends bX{constructor(e){super(VY),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=[],oX(e,{Node:(e,t)=>{(JY(t)||nX(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||=(yX(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=SX(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(mX(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 SX(e,t,n){if(JY(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(eX(t)){let r=0;for(let i of t.items){let t=SX(e,i,n);t>r&&(r=t)}return r}if(ZY(t)){let r=SX(e,t.key,n),i=SX(e,t.value,n);return Math.max(r,i)}return 1}var CX=e=>!e||typeof e!=`function`&&typeof e!=`object`,wX=class extends bX{constructor(e){super(GY),this.value=e}toJSON(e,t){return t?.keep?this.value:yX(this.value,e,t)}toString(){return String(this.value)}};wX.BLOCK_FOLDED=`BLOCK_FOLDED`,wX.BLOCK_LITERAL=`BLOCK_LITERAL`,wX.PLAIN=`PLAIN`,wX.QUOTE_DOUBLE=`QUOTE_DOUBLE`,wX.QUOTE_SINGLE=`QUOTE_SINGLE`;var TX=`tag:yaml.org,2002:`;function EX(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 DX(e,t,n){if(YY(e)&&(e=e.contents),tX(e))return e;if(ZY(e)){let t=n.schema[UY].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 xX(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith(`!!`)&&(t=TX+t.slice(2));let l=EX(e,t,o.tags);if(!l){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new wX(e);return c&&(c.node=t),t}l=e instanceof Map?o[UY]:Symbol.iterator in Object(e)?o[KY]:o[UY]}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 wX(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}function OX(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 DX(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema:e,sourceObjects:new Map})}var kX=e=>e==null||typeof e==`object`&&!!e[Symbol.iterator]().next().done,AX=class extends bX{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=>tX(t)||ZY(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(kX(e))this.add(t);else{let[n,...r]=e,i=this.get(n,!0);if(eX(i))i.addIn(r,t);else if(i===void 0&&this.schema)this.set(n,OX(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(eX(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&&QY(i)?i.value:i:eX(i)?i.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!ZY(t))return!1;let n=t.value;return n==null||e&&QY(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 eX(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(eX(e))e.setIn(r,t);else if(e===void 0&&this.schema)this.set(n,OX(this.schema,r,t));else throw Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}},jX=e=>e.replace(/^(?!$)(?: $)?/gm,`#`);function MX(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var NX=(e,t,n)=>e.endsWith(`
|
|
173
|
-
`)?MX(n,t):n.includes(`
|
|
174
|
-
`)?`
|
|
175
|
-
`+MX(n,t):(e.endsWith(` `)?``:` `)+n,PX=`flow`,FX=`block`,IX=`quoted`;function LX(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=RX(e,h,t.length),h!==-1&&(d=h+c));for(let r;r=e[h+=1];){if(n===`quoted`&&r===`\\`){switch(g=h,e[h+1]){case`x`:h+=3;break;case`u`:h+=5;break;case`U`:h+=9;break;default:h+=1}_=h}if(r===`
|
|
176
|
-
`)n===`block`&&(h=RX(e,h,t.length)),d=h+t.length+c,f=void 0;else{if(r===` `&&p&&p!==` `&&p!==`
|
|
177
|
-
`&&p!==` `){let t=e[h+1];t&&t!==` `&&t!==`
|
|
178
|
-
`&&t!==` `&&(f=h)}if(h>=d){if(f)l.push(f),d=f+c,f=void 0;else if(n===`quoted`){for(;p===` `||p===` `;)p=r,r=e[h+=1],m=!0;let t=h>_+1?h-2:g-1;if(u[t])return e;l.push(t),u[t]=!0,d=t+c,f=void 0}else m=!0}}p=r}if(m&&s&&s(),l.length===0)return e;o&&o();let v=e.slice(0,l[0]);for(let r=0;r<l.length;++r){let i=l[r],a=l[r+1]||e.length;i===0?v=`\n${t}${e.slice(0,a)}`:(n===`quoted`&&u[i]&&(v+=`${e[i]}\\`),v+=`\n${t}${e.slice(i+1,a)}`)}return v}function RX(e,t,n){let r=t,i=t+1,a=e[i];for(;a===` `||a===` `;)if(t<i+n)a=e[++t];else{do a=e[++t];while(a&&a!==`
|
|
179
|
-
`);r=t,i=t+1,a=e[i]}return r}var zX=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),BX=e=>/^(%|---|\.\.\.)/m.test(e);function VX(e,t,n){if(!t||t<0)return!1;let r=t-n,i=e.length;if(i<=r)return!1;for(let t=0,n=0;t<i;++t)if(e[t]===`
|
|
180
|
-
`){if(t-n>r)return!0;if(n=t+1,i-n<=r)return!1}return!0}function HX(e,t){let n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=t,i=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(BX(e)?` `:``),o=``,s=0;for(let e=0,t=n[e];t;t=n[++e])if(t===` `&&n[e+1]===`\\`&&n[e+2]===`n`&&(o+=n.slice(s,e)+`\\ `,e+=1,s=e,t=`\\`),t===`\\`)switch(n[e+1]){case`u`:{o+=n.slice(s,e);let t=n.substr(e+2,4);switch(t){case`0000`:o+=`\\0`;break;case`0007`:o+=`\\a`;break;case`000b`:o+=`\\v`;break;case`001b`:o+=`\\e`;break;case`0085`:o+=`\\N`;break;case`00a0`:o+=`\\_`;break;case`2028`:o+=`\\L`;break;case`2029`:o+=`\\P`;break;default:t.substr(0,2)===`00`?o+=`\\x`+t.substr(2):o+=n.substr(e,6)}e+=5,s=e+1}break;case`n`:if(r||n[e+2]===`"`||n.length<i)e+=1;else{for(o+=n.slice(s,e)+`
|
|
181
|
-
|
|
182
|
-
`;n[e+2]===`\\`&&n[e+3]===`n`&&n[e+4]!==`"`;)o+=`
|
|
183
|
-
`,e+=2;o+=a,n[e+2]===` `&&(o+=`\\`),e+=1,s=e+1}break;default:e+=1}return o=s?o+n.slice(s):n,r?o:LX(o,a,IX,zX(t,!1))}function UX(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
|
|
184
|
-
`)||/[ \t]\n|\n[ \t]/.test(e))return HX(e,t);let n=t.indent||(BX(e)?` `:``),r=`'`+e.replace(/'/g,`''`).replace(/\n+/g,`$&\n${n}`)+`'`;return t.implicitKey?r:LX(r,n,PX,zX(t,!1))}function WX(e,t){let{singleQuote:n}=t.options,r;if(n===!1)r=HX;else{let t=e.includes(`"`),i=e.includes(`'`);r=t&&!i?UX:i&&!t?HX:n?UX:HX}return r(e,t)}var GX;try{GX=RegExp(`(^|(?<!
|
|
185
|
-
))
|
|
186
|
-
+(?!
|
|
187
|
-
|$)`,`g`)}catch{GX=/\n+(?!\n|$)/g}function KX({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 WX(n,r);let l=r.indent||(r.forceBlockIndent||BX(n)?` `:``),u=o===`literal`?!0:o===`folded`||t===wX.BLOCK_FOLDED?!1:t===wX.BLOCK_LITERAL||!VX(n,c,l.length);if(!n)return u?`|
|
|
188
|
-
`:`>
|
|
189
|
-
`;let d,f;for(f=n.length;f>0;--f){let e=n[f-1];if(e!==`
|
|
190
|
-
`&&e!==` `&&e!==` `)break}let p=n.substring(f),m=p.indexOf(`
|
|
191
|
-
`);m===-1?d=`-`:n===p||m!==p.length-1?(d=`+`,a&&a()):d=``,p&&=(n=n.slice(0,-p.length),p[p.length-1]===`
|
|
192
|
-
`&&(p=p.slice(0,-1)),p.replace(GX,`$&${l}`));let h=!1,g,_=-1;for(g=0;g<n.length;++g){let e=n[g];if(e===` `)h=!0;else if(e===`
|
|
193
|
-
`)_=g;else break}let v=n.substring(0,_<g?_+1:g);v&&=(n=n.substring(v.length),v.replace(/\n+/g,`$&${l}`));let ee=(h?l?`2`:`1`:``)+d;if(e&&(ee+=` `+s(e.replace(/ ?[\r\n]+/g,` `)),i&&i()),!u){let e=n.replace(/\n+/g,`
|
|
194
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\n+/g,`$&${l}`),i=!1,a=zX(r,!0);o!==`folded`&&t!==wX.BLOCK_FOLDED&&(a.onOverflow=()=>{i=!0});let s=LX(`${v}${e}${p}`,l,FX,a);if(!i)return`>${ee}\n${l}${s}`}return n=n.replace(/\n+/g,`$&${l}`),`|${ee}\n${l}${v}${n}${p}`}function qX(e,t,n,r){let{type:i,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
|
|
195
|
-
`)||u&&/[[\]{},]/.test(a))return WX(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
|
|
196
|
-
`)?WX(a,t):KX(e,t,n,r);if(!s&&!u&&i!==wX.PLAIN&&a.includes(`
|
|
197
|
-
`))return KX(e,t,n,r);if(BX(a)){if(c===``)return t.forceBlockIndent=!0,KX(e,t,n,r);if(s&&c===l)return WX(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 WX(a,t)}return s?d:LX(d,c,PX,zX(t,!1))}function JX(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!==wX.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=wX.QUOTE_DOUBLE);let c=e=>{switch(e){case wX.BLOCK_FOLDED:case wX.BLOCK_LITERAL:return i||a?WX(o.value,t):KX(o,t,n,r);case wX.QUOTE_DOUBLE:return HX(o.value,t);case wX.QUOTE_SINGLE:return UX(o.value,t);case wX.PLAIN:return qX(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 YX(e,t){let n=Object.assign({blockQuote:!0,commentString:jX,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 XX(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(QY(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 ZX(e,t,{anchors:n,doc:r}){if(!r.directives)return``;let i=[],a=(QY(e)||eX(e))&&e.anchor;a&&mX(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 QX(e,t,n,r){if(ZY(e))return e.toString(t,n,r);if(JY(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=tX(e)?e:t.doc.createNode(e,{onTagObj:e=>i=e});i??=XX(t.doc.schema.tags,a);let o=ZX(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):QY(a)?JX(a,t,n,r):a.toString(t,n,r);return o?QY(a)||s[0]===`{`||s[0]===`[`?`${o} ${s}`:`${o}\n${t.indent}${s}`:s}function $X({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=tX(e)&&e.comment||null;if(d){if(f)throw Error(`With simple keys, key nodes cannot have comments`);if(eX(e)||!tX(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||eX(e)||(QY(e)?e.type===wX.BLOCK_FOLDED||e.type===wX.BLOCK_LITERAL:typeof e==`object`));n=Object.assign({},n,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let m=!1,h=!1,g=QX(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+=NX(g,n.indent,l(f)):h&&i&&i(),g;m&&(f=null),p?(f&&(g+=NX(g,n.indent,l(f))),g=`? ${g}\n${s}:`):(g=`${g}:`,f&&(g+=NX(g,n.indent,l(f))));let _,v,ee;tX(t)?(_=!!t.spaceBefore,v=t.commentBefore,ee=t.comment):(_=!1,v=null,ee=null,t&&typeof t==`object`&&(t=o.createNode(t))),n.implicitKey=!1,!p&&!f&&QY(t)&&(n.indentAtStart=g.length+1),h=!1,!u&&c.length>=2&&!n.inFlow&&!p&&$Y(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let te=!1,ne=QX(t,n,()=>te=!0,()=>h=!0),re=` `;if(f||_||v){if(re=_?`
|
|
198
|
-
`:``,v){let e=l(v);re+=`\n${MX(e,n.indent)}`}ne===``&&!n.inFlow?re===`
|
|
199
|
-
`&&ee&&(re=`
|
|
200
|
-
|
|
201
|
-
`):re+=`\n${n.indent}`}else if(!p&&eX(t)){let e=ne[0],r=ne.indexOf(`
|
|
202
|
-
`),i=r!==-1,a=n.inFlow??t.flow??t.items.length===0;if(i||!a){let t=!1;if(i&&(e===`&`||e===`!`)){let n=ne.indexOf(` `);e===`&`&&n!==-1&&n<r&&ne[n+1]===`!`&&(n=ne.indexOf(` `,n+1)),(n===-1||r<n)&&(t=!0)}t||(re=`\n${n.indent}`)}}else(ne===``||ne[0]===`
|
|
203
|
-
`)&&(re=``);return g+=re+ne,n.inFlow?te&&r&&r():ee&&!te?g+=NX(g,n.indent,l(ee)):h&&i&&i(),g}function eZ(e,t){(e===`debug`||e===`warn`)&&console.warn(t)}var tZ=`<<`,nZ={identify:e=>e===tZ||typeof e==`symbol`&&e.description===tZ,default:`key`,tag:`tag:yaml.org,2002:merge`,test:/^<<$/,resolve:()=>Object.assign(new wX(Symbol(tZ)),{addToJSMap:iZ}),stringify:()=>tZ},rZ=(e,t)=>(nZ.identify(t)||QY(t)&&(!t.type||t.type===wX.PLAIN)&&nZ.identify(t.value))&&e?.doc.schema.tags.some(e=>e.tag===nZ.tag&&e.default);function iZ(e,t,n){let r=oZ(e,n);if($Y(r))for(let n of r.items)aZ(e,t,n);else if(Array.isArray(r))for(let n of r)aZ(e,t,n);else aZ(e,t,r)}function aZ(e,t,n){let r=oZ(e,n);if(!XY(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 oZ(e,t){return e&&JY(t)?t.resolve(e.doc,e):t}function sZ(e,t,{key:n,value:r}){if(tX(n)&&n.addToJSMap)n.addToJSMap(e,t,r);else if(rZ(e,n))iZ(e,t,r);else{let i=yX(n,``,e);if(t instanceof Map)t.set(i,yX(r,i,e));else if(t instanceof Set)t.add(i);else{let a=cZ(n,i,e),o=yX(r,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function cZ(e,t,n){if(t===null)return``;if(typeof t!=`object`)return String(t);if(tX(e)&&n?.doc){let t=YX(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)+`..."`),eZ(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 lZ(e,t,n){return new uZ(DX(e,void 0,n),DX(t,void 0,n))}var uZ=class e{constructor(e,t=null){Object.defineProperty(this,qY,{value:WY}),this.key=e,this.value=t}clone(t){let{key:n,value:r}=this;return tX(n)&&(n=n.clone(t)),tX(r)&&(r=r.clone(t)),new e(n,r)}toJSON(e,t){return sZ(t,t?.mapAsMap?new Map:{},this)}toString(e,t,n){return e?.doc?$X(this,e,t,n):JSON.stringify(this)}};function dZ(e,t,n){return(t.inFlow??e.flow?pZ:fZ)(e,t,n)}function fZ({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(tX(i))!d&&i.spaceBefore&&f.push(``),mZ(n,f,i.commentBefore,d),i.comment&&(o=i.comment);else if(ZY(i)){let e=tX(i.key)?i.key:null;e&&(!d&&e.spaceBefore&&f.push(``),mZ(n,f,e.commentBefore,d))}d=!1;let s=QX(i,u,()=>o=null,()=>d=!0);o&&(s+=NX(s,a,l(o))),d&&o&&(d=!1),f.push(r+s)}let p;if(f.length===0)p=i.start+i.end;else{p=f[0];for(let e=1;e<f.length;++e){let t=f[e];p+=t?`\n${c}${t}`:`
|
|
204
|
-
`}}return e?(p+=`
|
|
205
|
-
`+MX(l(e),c),s&&s()):d&&o&&o(),p}function pZ({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(tX(i))i.spaceBefore&&d.push(``),mZ(t,d,i.commentBefore,!1),i.comment&&(a=i.comment);else if(ZY(i)){let e=tX(i.key)?i.key:null;e&&(e.spaceBefore&&d.push(``),mZ(t,d,e.commentBefore,!1),e.comment&&(l=!0));let n=tX(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=QX(i,c,()=>a=null);l||=d.length>u||o.includes(`
|
|
206
|
-
`),n<e.length-1?o+=`,`:t.options.trailingComma&&(t.options.lineWidth>0&&(l||=d.reduce((e,t)=>e+t.length+2,2)+(o.length+2)>t.options.lineWidth),l&&(o+=`,`)),a&&(o+=NX(o,r,s(a))),d.push(o),u=d.length}let{start:f,end:p}=n;if(d.length===0)return f+p;if(!l){let e=d.reduce((e,t)=>e+t.length+2,2);l=t.options.lineWidth>0&&e>t.options.lineWidth}if(l){let e=f;for(let t of d)e+=t?`\n${a}${i}${t}`:`
|
|
207
|
-
`;return`${e}\n${i}${p}`}return`${f}${o}${d.join(` `)}${o}${p}`}function mZ({indent:e,options:{commentString:t}},n,r,i){if(r&&i&&(r=r.replace(/^\n+/,``)),r){let i=MX(t(r),e);n.push(i.trimStart())}}function hZ(e,t){let n=QY(t)?t.value:t;for(let r of e)if(ZY(r)&&(r.key===t||r.key===n||QY(r.key)&&r.key.value===n))return r}var gZ=class extends AX{static get tagName(){return`tag:yaml.org,2002:map`}constructor(e){super(UY,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(lZ(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=ZY(e)?e:!e||typeof e!=`object`||!(`key`in e)?new uZ(e,e?.value):new uZ(e.key,e.value);let r=hZ(this.items,n.key),i=this.schema?.sortMapEntries;if(r){if(!t)throw Error(`Key ${n.key} already set`);QY(r.value)&&CX(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=hZ(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let n=hZ(this.items,e)?.value;return(!t&&QY(n)?n.value:n)??void 0}has(e){return!!hZ(this.items,e)}set(e,t){this.add(new uZ(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)sZ(t,r,e);return r}toString(e,t,n){if(!e)return JSON.stringify(this);for(let e of this.items)if(!ZY(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})),dZ(this,e,{blockItemPrefix:``,flowChars:{start:`{`,end:`}`},itemIndent:e.indent||``,onChompKeep:n,onComment:t})}},_Z={collection:`map`,default:!0,nodeClass:gZ,tag:`tag:yaml.org,2002:map`,resolve(e,t){return XY(e)||t(`Expected a mapping for this tag`),e},createNode:(e,t,n)=>gZ.from(e,t,n)},vZ=class extends AX{static get tagName(){return`tag:yaml.org,2002:seq`}constructor(e){super(KY,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=yZ(e);return typeof t==`number`&&this.items.splice(t,1).length>0}get(e,t){let n=yZ(e);if(typeof n!=`number`)return;let r=this.items[n];return!t&&QY(r)?r.value:r}has(e){let t=yZ(e);return typeof t==`number`&&t<this.items.length}set(e,t){let n=yZ(e);if(typeof n!=`number`)throw Error(`Expected a valid index, not ${e}.`);let r=this.items[n];QY(r)&&CX(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(yX(e,String(r++),t));return n}toString(e,t,n){return e?dZ(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(DX(a,void 0,n))}}return i}};function yZ(e){let t=QY(e)?e.value:e;return t&&typeof t==`string`&&(t=Number(t)),typeof t==`number`&&Number.isInteger(t)&&t>=0?t:null}var bZ={collection:`seq`,default:!0,nodeClass:vZ,tag:`tag:yaml.org,2002:seq`,resolve(e,t){return $Y(e)||t(`Expected a sequence for this tag`),e},createNode:(e,t,n)=>vZ.from(e,t,n)},xZ={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),JX(e,t,n,r)}},SZ={identify:e=>e==null,createNode:()=>new wX(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new wX(null),stringify:({source:e},t)=>typeof e==`string`&&SZ.test.test(e)?e:t.options.nullStr},CZ={identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new wX(e[0]===`t`||e[0]===`T`),stringify({source:e,value:t},n){return e&&CZ.test.test(e)&&t===(e[0]===`t`||e[0]===`T`)?e:t?n.options.trueStr:n.options.falseStr}};function wZ({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 TZ={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:wZ},EZ={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():wZ(e)}},DZ={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 wX(parseFloat(e)),n=e.indexOf(`.`);return n!==-1&&e[e.length-1]===`0`&&(t.minFractionDigits=e.length-n-1),t},stringify:wZ},OZ=e=>typeof e==`bigint`||Number.isInteger(e),kZ=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n);function AZ(e,t,n){let{value:r}=e;return OZ(r)&&r>=0?n+r.toString(t):wZ(e)}var jZ={identify:e=>OZ(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^0o[0-7]+$/,resolve:(e,t,n)=>kZ(e,2,8,n),stringify:e=>AZ(e,8,`0o`)},MZ={identify:OZ,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>kZ(e,0,10,n),stringify:wZ},NZ={identify:e=>OZ(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>kZ(e,2,16,n),stringify:e=>AZ(e,16,`0x`)},PZ=[_Z,bZ,xZ,SZ,CZ,jZ,MZ,NZ,TZ,EZ,DZ];function FZ(e){return typeof e==`bigint`||Number.isInteger(e)}var IZ=({value:e})=>JSON.stringify(e),LZ=[{identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify:IZ},{identify:e=>e==null,createNode:()=>new wX(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^null$/,resolve:()=>null,stringify:IZ},{identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^true$|^false$/,resolve:e=>e===`true`,stringify:IZ},{identify:FZ,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})=>FZ(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:IZ}],RZ=[_Z,bZ].concat(LZ,{default:!0,tag:``,test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}}),zZ={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??=wX.BLOCK_LITERAL,t!==wX.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===wX.BLOCK_LITERAL?`
|
|
208
|
-
`:` `)}return JX({comment:e,type:t,value:s},r,i,a)}};function BZ(e,t){if($Y(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!ZY(r)){if(XY(r)){r.items.length>1&&t(`Each pair must have its own sequence indicator`);let e=r.items[0]||new uZ(new wX(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]=ZY(r)?r:new uZ(r)}}else t(`Expected a sequence for this tag`);return e}function VZ(e,t,n){let{replacer:r}=n,i=new vZ(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(lZ(o,s,n))}return i}var HZ={collection:`seq`,default:!1,tag:`tag:yaml.org,2002:pairs`,resolve:BZ,createNode:VZ},UZ=class e extends vZ{constructor(){super(),this.add=gZ.prototype.add.bind(this),this.delete=gZ.prototype.delete.bind(this),this.get=gZ.prototype.get.bind(this),this.has=gZ.prototype.has.bind(this),this.set=gZ.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(ZY(e)?(r=yX(e.key,``,t),i=yX(e.value,r,t)):r=yX(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=VZ(e,t,n),i=new this;return i.items=r.items,i}};UZ.tag=`tag:yaml.org,2002:omap`;var WZ={collection:`seq`,identify:e=>e instanceof Map,nodeClass:UZ,default:!1,tag:`tag:yaml.org,2002:omap`,resolve(e,t){let n=BZ(e,t),r=[];for(let{key:e}of n.items)QY(e)&&(r.includes(e.value)?t(`Ordered maps must not include duplicate keys: ${e.value}`):r.push(e.value));return Object.assign(new UZ,n)},createNode:(e,t,n)=>UZ.from(e,t,n)};function GZ({value:e,source:t},n){return t&&(e?KZ:qZ).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var KZ={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 wX(!0),stringify:GZ},qZ={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 wX(!1),stringify:GZ},JZ={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:wZ},YZ={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():wZ(e)}},XZ={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 wX(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:wZ},ZZ=e=>typeof e==`bigint`||Number.isInteger(e);function QZ(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 $Z(e,t,n){let{value:r}=e;if(ZZ(r)){let e=r.toString(t);return r<0?`-`+n+e.substr(1):n+e}return wZ(e)}var eQ={identify:ZZ,default:!0,tag:`tag:yaml.org,2002:int`,format:`BIN`,test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>QZ(e,2,2,n),stringify:e=>$Z(e,2,`0b`)},tQ={identify:ZZ,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>QZ(e,1,8,n),stringify:e=>$Z(e,8,`0`)},nQ={identify:ZZ,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>QZ(e,0,10,n),stringify:wZ},rQ={identify:ZZ,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>QZ(e,2,16,n),stringify:e=>$Z(e,16,`0x`)},iQ=class e extends gZ{constructor(t){super(t),this.tag=e.tag}add(e){let t;t=ZY(e)?e:e&&typeof e==`object`&&`key`in e&&`value`in e&&e.value===null?new uZ(e.key,null):new uZ(e,null),hZ(this.items,t.key)||this.items.push(t)}get(e,t){let n=hZ(this.items,e);return!t&&ZY(n)?QY(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=hZ(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new uZ(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(lZ(e,null,n));return i}};iQ.tag=`tag:yaml.org,2002:set`;var aQ={collection:`map`,identify:e=>e instanceof Set,nodeClass:iQ,default:!1,tag:`tag:yaml.org,2002:set`,createNode:(e,t,n)=>iQ.from(e,t,n),resolve(e,t){if(XY(e)){if(e.hasAllNullValues(!0))return Object.assign(new iQ,e);t(`Set items must all have null values`)}else t(`Expected a mapping for this tag`);return e}};function oQ(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 sQ(e){let{value:t}=e,n=e=>e;if(typeof t==`bigint`)n=e=>BigInt(e);else if(isNaN(t)||!isFinite(t))return wZ(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 cQ={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})=>oQ(e,n),stringify:sQ},lQ={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=>oQ(e,!1),stringify:sQ},uQ={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(uQ.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=oQ(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$/,``)??``},dQ=[_Z,bZ,xZ,SZ,KZ,qZ,eQ,tQ,nQ,rQ,JZ,YZ,XZ,zZ,nZ,WZ,HZ,aQ,cQ,lQ,uQ],fQ=new Map([[`core`,PZ],[`failsafe`,[_Z,bZ,xZ]],[`json`,RZ],[`yaml11`,dQ],[`yaml-1.1`,dQ]]),pQ={binary:zZ,bool:CZ,float:DZ,floatExp:EZ,floatNaN:TZ,floatTime:lQ,int:MZ,intHex:NZ,intOct:jZ,intTime:cQ,map:_Z,merge:nZ,null:SZ,omap:WZ,pairs:HZ,seq:bZ,set:aQ,timestamp:uQ},mQ={"tag:yaml.org,2002:binary":zZ,"tag:yaml.org,2002:merge":nZ,"tag:yaml.org,2002:omap":WZ,"tag:yaml.org,2002:pairs":HZ,"tag:yaml.org,2002:set":aQ,"tag:yaml.org,2002:timestamp":uQ};function hQ(e,t,n){let r=fQ.get(t);if(r&&!e)return n&&!r.includes(nZ)?r.concat(nZ):r.slice();let i=r;if(!i){if(Array.isArray(e))i=[];else{let e=Array.from(fQ.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(nZ)),i.reduce((e,t)=>{let n=typeof t==`string`?pQ[t]:t;if(!n){let e=JSON.stringify(t),n=Object.keys(pQ).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 gQ=(e,t)=>e.key<t.key?-1:+(e.key>t.key),_Q=class e{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:r,schema:i,sortMapEntries:a,toStringDefaults:o}){this.compat=Array.isArray(e)?hQ(e,`compat`):e?hQ(null,e):null,this.name=typeof i==`string`&&i||`core`,this.knownTags=r?mQ:{},this.tags=hQ(t,this.name,n),this.toStringOptions=o??null,Object.defineProperty(this,UY,{value:_Z}),Object.defineProperty(this,GY,{value:xZ}),Object.defineProperty(this,KY,{value:bZ}),this.sortMapEntries=typeof a==`function`?a:a===!0?gQ:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};function vQ(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=YX(e,t),{commentString:a}=i.options;if(e.commentBefore){n.length!==1&&n.unshift(``);let t=a(e.commentBefore);n.unshift(MX(t,``))}let o=!1,s=null;if(e.contents){if(tX(e.contents)){if(e.contents.spaceBefore&&r&&n.push(``),e.contents.commentBefore){let t=a(e.contents.commentBefore);n.push(MX(t,``))}i.forceBlockIndent=!!e.comment,s=e.contents.comment}let t=s?void 0:()=>o=!0,c=QX(e.contents,i,()=>s=null,t);s&&(c+=NX(c,``,a(s))),(c[0]===`|`||c[0]===`>`)&&n[n.length-1]===`---`?n[n.length-1]=`--- ${c}`:n.push(c)}else n.push(QX(e.contents,i));if(e.directives?.docEnd){if(e.comment){let t=a(e.comment);t.includes(`
|
|
209
|
-
`)?(n.push(`...`),n.push(MX(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(MX(a(t),``)))}return n.join(`
|
|
210
|
-
`)+`
|
|
211
|
-
`}var yQ=class e{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,qY,{value:HY});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 pX({version:a}),this.setSchema(a,n),this.contents=e===void 0?null:this.createNode(e,r,n)}clone(){let t=Object.create(e.prototype,{[qY]:{value:HY}});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=tX(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(e){bQ(this.contents)&&this.contents.add(e)}addIn(e,t){bQ(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=hX(this);e.anchor=!t||n.has(t)?gX(t||`a`,n):t}return new xX(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}=_X(this,a||`a`),p={aliasDuplicateObjects:i??!0,keepUndefined:s??!1,onAnchor:u,onTagObj:c,replacer:r,schema:this.schema,sourceObjects:f},m=DX(e,l,p);return o&&eX(m)&&(m.flow=!0),d(),m}createPair(e,t,n={}){return new uZ(this.createNode(e,null,n),this.createNode(t,null,n))}delete(e){return bQ(this.contents)?this.contents.delete(e):!1}deleteIn(e){return kX(e)?this.contents!=null&&(this.contents=null,!0):bQ(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return eX(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return kX(e)?!t&&QY(this.contents)?this.contents.value:this.contents:eX(this.contents)?this.contents.getIn(e,t):void 0}has(e){return eX(this.contents)?this.contents.has(e):!1}hasIn(e){return kX(e)?this.contents!==void 0:eX(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=OX(this.schema,[e],t):bQ(this.contents)&&this.contents.set(e,t)}setIn(e,t){kX(e)?this.contents=t:this.contents==null?this.contents=OX(this.schema,Array.from(e),t):bQ(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 pX({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 pX({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 _Q(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=yX(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`?vX(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 vQ(this,e)}};function bQ(e){if(eX(e))return!0;throw Error(`Expected a YAML collection as document contents`)}var xQ=class extends Error{constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}},SQ=class extends xQ{constructor(e,t,n){super(`YAMLParseError`,e,t,n)}},CQ=class extends xQ{constructor(e,t,n){super(`YAMLWarning`,e,t,n)}},wQ=(e,t)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(e=>t.linePos(e));let{line:r,col:i}=n.linePos[0];n.message+=` at line ${r}, column ${i}`;let a=i-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,``);if(a>=60&&o.length>80){let e=Math.min(a-39,o.length-79);o=`…`+o.substring(e),a-=e-1}if(o.length>80&&(o=o.substring(0,79)+`…`),r>1&&/^ *$/.test(o.substring(0,a))){let n=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);n.length>80&&(n=n.substring(0,79)+`…
|
|
212
|
-
`),o=n+o}if(/[^ ]/.test(o)){let e=1,t=n.linePos[1];t?.line===r&&t.col>i&&(e=Math.max(1,Math.min(t.col-i,80-a)));let s=` `.repeat(a)+`^`.repeat(e);n.message+=`:\n\n${o}\n${s}\n`}};function TQ(e,{flow:t,indicator:n,next:r,offset:i,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d=``,f=``,p=!1,m=!1,h=null,g=null,_=null,v=null,ee=null,te=null,ne=null;for(let i of e)switch(m&&=(i.type!==`space`&&i.type!==`newline`&&i.type!==`comma`&&a(i.offset,`MISSING_CHAR`,`Tags and anchors must be separated from the next token by white space`),!1),h&&=(l&&i.type!==`comment`&&i.type!==`newline`&&a(h,`TAB_AS_INDENT`,`Tabs are not allowed as indentation`),null),i.type){case`space`:!t&&(n!==`doc-start`||r?.type!==`flow-collection`)&&i.source.includes(` `)&&(h=i),u=!0;break;case`comment`:{u||a(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`);let e=i.source.substring(1)||` `;d?d+=f+e:d=e,f=``,l=!1;break}case`newline`:l?d?d+=i.source:(!te||n!==`seq-item-ind`)&&(c=!0):f+=i.source,l=!0,p=!0,(g||_)&&(v=i),u=!0;break;case`anchor`:g&&a(i,`MULTIPLE_ANCHORS`,`A node can have at most one anchor`),i.source.endsWith(`:`)&&a(i.offset+i.source.length-1,`BAD_ALIAS`,`Anchor ending in : is ambiguous`,!0),g=i,ne??=i.offset,l=!1,u=!1,m=!0;break;case`tag`:_&&a(i,`MULTIPLE_TAGS`,`A node can have at most one tag`),_=i,ne??=i.offset,l=!1,u=!1,m=!0;break;case n:(g||_)&&a(i,`BAD_PROP_ORDER`,`Anchors and tags must be after the ${i.source} indicator`),te&&a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.source} in ${t??`collection`}`),te=i,l=n===`seq-item-ind`||n===`explicit-key-ind`,u=!1;break;case`comma`:if(t){ee&&a(i,`UNEXPECTED_TOKEN`,`Unexpected , in ${t}`),ee=i,l=!1,u=!1;break}default:a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.type} token`),l=!1,u=!1}let re=e[e.length-1],ie=re?re.offset+re.source.length:i;return m&&r&&r.type!==`space`&&r.type!==`newline`&&r.type!==`comma`&&(r.type!==`scalar`||r.source!==``)&&a(r.offset,`MISSING_CHAR`,`Tags and anchors must be separated from the next token by white space`),h&&(l&&h.indent<=o||r?.type===`block-map`||r?.type===`block-seq`)&&a(h,`TAB_AS_INDENT`,`Tabs are not allowed as indentation`),{comma:ee,found:te,spaceBefore:c,comment:d,hasNewline:p,anchor:g,tag:_,newlineAfterProp:v,end:ie,start:ne??ie}}function EQ(e){if(!e)return null;switch(e.type){case`alias`:case`scalar`:case`double-quoted-scalar`:case`single-quoted-scalar`:if(e.source.includes(`
|
|
213
|
-
`))return!0;if(e.end){for(let t of e.end)if(t.type===`newline`)return!0}return!1;case`flow-collection`:for(let t of e.items){for(let e of t.start)if(e.type===`newline`)return!0;if(t.sep){for(let e of t.sep)if(e.type===`newline`)return!0}if(EQ(t.key)||EQ(t.value))return!0}return!1;default:return!0}}function DQ(e,t,n){if(t?.type===`flow-collection`){let r=t.end[0];r.indent===e&&(r.source===`]`||r.source===`}`)&&EQ(t)&&n(r,`BAD_INDENT`,`Flow end indicator should be more indented than parent`,!0)}}function OQ(e,t,n){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let i=typeof r==`function`?r:(e,t)=>e===t||QY(e)&&QY(t)&&e.value===t.value;return t.some(e=>i(e.key,n))}var kQ=`All mapping items must start at the same column`;function AQ({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??gZ)(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=TQ(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`,kQ)),!p.anchor&&!p.tag&&!d){c=p.end,p.comment&&(o.comment?o.comment+=`
|
|
214
|
-
`+p.comment:o.comment=p.comment);continue}(p.newlineAfterProp||EQ(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`,kQ);n.atKey=!0;let h=p.end,g=u?e(n,u,p,i):t(n,h,l,null,p,i);n.schema.compat&&DQ(r.indent,u,i),n.atKey=!1,OQ(n,o.items,g)&&i(h,`DUPLICATE_KEY`,`Map keys must be unique`);let _=TQ(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&&DQ(r.indent,f,i),s=c.range[2];let l=new uZ(g,c);n.options.keepSourceTokens&&(l.srcToken=a),o.items.push(l)}else{m&&i(g.range,`MISSING_CHAR`,`Implicit map keys need to be followed by map values`),_.comment&&(g.comment?g.comment+=`
|
|
215
|
-
`+_.comment:g.comment=_.comment);let e=new uZ(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 jQ({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??vZ)(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=TQ(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&&DQ(r.indent,l,i),s=d.range[2],o.items.push(d)}return o.range=[r.offset,s,c??s],o}function MQ(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 NQ=`Block collections are not allowed within flow collections`,PQ=e=>e&&(e.type===`block-map`||e.type===`block-seq`);function FQ({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=r.start.source===`{`,s=o?`flow map`:`flow sequence`,c=new((a?.nodeClass)??(o?gZ:vZ))(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=TQ(d,{flow:s,indicator:`explicit-key-ind`,next:f??p?.[0],offset:u,onError:i,parentIndent:r.indent,startOnNewline:!1});if(!h.found){if(!h.anchor&&!h.tag&&!p&&!m){a===0&&h.comma?i(h.comma,`UNEXPECTED_TOKEN`,`Unexpected , in ${s}`):a<r.items.length-1&&i(h.start,`UNEXPECTED_TOKEN`,`Unexpected empty item in ${s}`),h.comment&&(c.comment?c.comment+=`
|
|
216
|
-
`+h.comment:c.comment=h.comment),u=h.end;continue}!o&&n.options.strict&&EQ(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];ZY(t)&&(t=t.value??t.key),t.comment?t.comment+=`
|
|
217
|
-
`+e:t.comment=e,h.comment=h.comment.substring(e.length+1)}}if(!o&&!p&&!h.found){let r=m?e(n,m,h,i):t(n,h.end,p,null,h,i);c.items.push(r),u=r.range[2],PQ(m)&&i(r.range,`BLOCK_IN_FLOW`,NQ)}else{n.atKey=!0;let a=h.end,g=f?e(n,f,h,i):t(n,a,d,null,h,i);PQ(f)&&i(g.range,`BLOCK_IN_FLOW`,NQ),n.atKey=!1;let _=TQ(p??[],{flow:s,indicator:`map-value-ind`,next:m,offset:g.range[2],onError:i,parentIndent:r.indent,startOnNewline:!1});if(_.found){if(!o&&!h.found&&n.options.strict){if(p)for(let e of p){if(e===_.found)break;if(e.type===`newline`){i(e,`MULTILINE_IMPLICIT_KEY`,`Implicit keys of flow sequence pairs need to be on a single line`);break}}h.start<_.found.offset-1024&&i(_.found,`KEY_OVER_1024_CHARS`,`The : indicator must be at most 1024 chars after the start of an implicit flow sequence key`)}}else m&&(`source`in m&&m.source?.[0]===`:`?i(m,`MISSING_CHAR`,`Missing space after : in ${s}`):i(_.start,`MISSING_CHAR`,`Missing , or : between ${s} items`));let v=m?e(n,m,_,i):_.found?t(n,_.end,p,null,_,i):null;v?PQ(m)&&i(v.range,`BLOCK_IN_FLOW`,NQ):_.comment&&(g.comment?g.comment+=`
|
|
218
|
-
`+_.comment:g.comment=_.comment);let ee=new uZ(g,v);if(n.options.keepSourceTokens&&(ee.srcToken=l),o){let e=c;OQ(n,e.items,g)&&i(a,`DUPLICATE_KEY`,`Map keys must be unique`),e.items.push(ee)}else{let e=new gZ(n.schema);e.flow=!0,e.items.push(ee);let t=(v??g).range;e.range=[g.range[0],t[1],t[2]],c.items.push(e)}u=v?v.range[2]:_.end}}let d=o?`}`:`]`,[f,...p]=r.end,m=u;if(f?.source===d)m=f.offset+f.source.length;else{let e=s[0].toUpperCase()+s.substring(1),t=l?`${e} must end with a ${d}`:`${e} in block collection must be sufficiently indented and end with a ${d}`;i(u,l?`MISSING_CHAR`:`BAD_INDENT`,t),f&&f.source.length!==1&&p.unshift(f)}if(p.length>0){let e=MQ(p,m,n.options.strict,i);e.comment&&(c.comment?c.comment+=`
|
|
219
|
-
`+e.comment:c.comment=e.comment),c.range=[r.offset,m,e.offset]}else c.range=[r.offset,m,m];return c}function IQ(e,t,n,r,i,a){let o=n.type===`block-map`?AQ(e,t,n,r,a):n.type===`block-seq`?jQ(e,t,n,r,a):FQ(e,t,n,r,a),s=o.constructor;return i===`!`||i===s.tagName?(o.tag=s.tagName,o):(i&&(o.tag=i),o)}function LQ(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===gZ.tagName&&s===`map`||o===vZ.tagName&&s===`seq`)return IQ(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),IQ(e,t,n,i,o)}let l=IQ(e,t,n,i,o,c),u=c.resolve?.(l,e=>i(a,`TAG_RESOLVE_FAILED`,e),t.options)??l,d=tX(u)?u:new wX(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}function RQ(e,t,n){let r=t.offset,i=zQ(t,e.options.strict,n);if(!i)return{value:``,type:null,comment:``,range:[r,r,r]};let a=i.mode===`>`?wX.BLOCK_FOLDED:wX.BLOCK_LITERAL,o=t.source?BQ(t.source):[],s=o.length;for(let e=o.length-1;e>=0;--e){let t=o[e][1];if(t===``||t===`\r`)s=e;else break}if(s===0){let e=i.chomp===`+`&&o.length>0?`
|
|
220
|
-
`.repeat(Math.max(1,o.length-1)):``,n=r+i.length;return t.source&&(n+=t.source.length),{value:e,type:a,comment:i.comment,range:[r,n,n]}}let c=t.indent+i.indent,l=t.offset+i.length,u=0;for(let t=0;t<s;++t){let[r,a]=o[t];if(a===``||a===`\r`)i.indent===0&&r.length>c&&(c=r.length);else{r.length<c&&n(l+r.length,`MISSING_CHAR`,`Block scalars with more-indented leading empty lines must use an explicit indentation indicator`),i.indent===0&&(c=r.length),u=t,c===0&&!e.atRoot&&n(l,`BAD_INDENT`,`Block scalar values in collections must be indented`);break}l+=r.length+a.length+1}for(let e=o.length-1;e>=s;--e)o[e][0].length>c&&(s=e+1);let d=``,f=``,p=!1;for(let e=0;e<u;++e)d+=o[e][0].slice(c)+`
|
|
221
|
-
`;for(let e=u;e<s;++e){let[t,r]=o[e];l+=t.length+r.length+1;let s=r[r.length-1]===`\r`;if(s&&(r=r.slice(0,-1)),r&&t.length<c){let e=`Block scalar lines must not be less indented than their ${i.indent?`explicit indentation indicator`:`first line`}`;n(l-r.length-(s?2:1),`BAD_INDENT`,e),t=``}a===wX.BLOCK_LITERAL?(d+=f+t.slice(c)+r,f=`
|
|
222
|
-
`):t.length>c||r[0]===` `?(f===` `?f=`
|
|
223
|
-
`:!p&&f===`
|
|
224
|
-
`&&(f=`
|
|
225
|
-
|
|
226
|
-
`),d+=f+t.slice(c)+r,f=`
|
|
227
|
-
`,p=!0):r===``?f===`
|
|
228
|
-
`?d+=`
|
|
229
|
-
`:f=`
|
|
230
|
-
`:(d+=f+r,f=` `,p=!1)}switch(i.chomp){case`-`:break;case`+`:for(let e=s;e<o.length;++e)d+=`
|
|
231
|
-
`+o[e][0].slice(c);d[d.length-1]!==`
|
|
232
|
-
`&&(d+=`
|
|
233
|
-
`);break;default:d+=`
|
|
234
|
-
`}let m=r+i.length+t.source.length;return{value:d,type:a,comment:i.comment,range:[r,m,m]}}function zQ({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 BQ(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 VQ(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=wX.PLAIN,c=HQ(a,l);break;case`single-quoted-scalar`:s=wX.QUOTE_SINGLE,c=UQ(a,l);break;case`double-quoted-scalar`:s=wX.QUOTE_DOUBLE,c=GQ(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=MQ(o,u,t,n);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function HQ(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}`),WQ(e)}function UQ(e,t){return(e[e.length-1]!==`'`||e.length===1)&&t(e.length,`MISSING_CHAR`,`Missing closing 'quote`),WQ(e.slice(1,-1)).replace(/''/g,`'`)}function WQ(e){let t=/(.*?)\r?\n/sy,n=t.exec(e);if(!n)return e;let r,i;try{r=RegExp(`(?<![ ])[ ]+$`),i=RegExp(`^[ ]+|(?<![ ])[ ]+$`,`g`)}catch{r=/[ \t]+$/,i=/^[ \t]+|[ \t]+$/g}let a=n[1].replace(r,``),o=` `,s=t.lastIndex;for(;n=t.exec(e);){let e=n[1].replace(i,``);e===``?o===`
|
|
235
|
-
`?a+=o:o=`
|
|
236
|
-
`:(a+=o+e,o=` `),s=t.lastIndex}let c=/[ \t]*(.*)/sy;return c.lastIndex=s,n=c.exec(e),a+o+(n?.[1]??``)}function GQ(e,t){let n=``;for(let r=1;r<e.length-1;++r){let i=e[r];if(i!==`\r`||e[r+1]!==`
|
|
237
|
-
`){if(i===`
|
|
238
|
-
`){let{fold:t,offset:i}=KQ(e,r);n+=t,r=i}else if(i===`\\`){let i=e[++r],a=qQ[i];if(a)n+=a;else if(i===`
|
|
239
|
-
`)for(i=e[r+1];i===` `||i===` `;)i=e[++r+1];else if(i===`\r`&&e[r+1]===`
|
|
240
|
-
`)for(i=e[++r+1];i===` `||i===` `;)i=e[++r+1];else if(i===`x`||i===`u`||i===`U`){let a=i===`x`?2:i===`u`?4:8;n+=JQ(e,r+1,a,t),r+=a}else{let i=e.substr(r-1,2);t(r-1,`BAD_DQ_ESCAPE`,`Invalid escape sequence ${i}`),n+=i}}else if(i===` `||i===` `){let t=r,a=e[r+1];for(;a===` `||a===` `;)a=e[++r+1];a!==`
|
|
241
|
-
`&&(a!==`\r`||e[r+2]!==`
|
|
242
|
-
`)&&(n+=r>t?e.slice(t,r+1):i)}else n+=i}}return(e[e.length-1]!==`"`||e.length===1)&&t(e.length,`MISSING_CHAR`,`Missing closing "quote`),n}function KQ(e,t){let n=``,r=e[t+1];for(;(r===` `||r===` `||r===`
|
|
243
|
-
`||r===`\r`)&&(r!==`\r`||e[t+2]===`
|
|
244
|
-
`);)r===`
|
|
245
|
-
`&&(n+=`
|
|
246
|
-
`),t+=1,r=e[t+1];return n||=` `,{fold:n,offset:t}}var qQ={0:`\0`,a:`\x07`,b:`\b`,e:`\x1B`,f:`\f`,n:`
|
|
247
|
-
`,r:`\r`,t:` `,v:`\v`,N:`
`,_:`\xA0`,L:`\u2028`,P:`\u2029`," ":` `,'"':`"`,"/":`/`,"\\":`\\`," ":` `};function JQ(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 YQ(e,t,n,r){let{value:i,type:a,comment:o,range:s}=t.type===`block-scalar`?RQ(e,t,r):VQ(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[GY]:c?XQ(e.schema,i,c,n,r):t.type===`scalar`?ZQ(e,i,t,r):e.schema[GY];let u;try{let a=l.resolve(i,e=>r(n??t,`TAG_RESOLVE_FAILED`,e),e.options);u=QY(a)?a:new wX(a)}catch(e){let a=e instanceof Error?e.message:String(e);r(n??t,`TAG_RESOLVE_FAILED`,a),u=new wX(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 XQ(e,t,n,r,i){if(n===`!`)return e[GY];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[GY])}function ZQ({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[GY];if(n.compat){let e=n.compat.find(e=>e.default&&e.test?.test(r))??n[GY];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 QQ(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 $Q={composeNode:e$,composeEmptyNode:t$};function e$(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=n$(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=YQ(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case`block-map`:case`block-seq`:case`flow-collection`:try{l=LQ($Q,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??=t$(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&&(!QY(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 t$(e,t,n,r,{spaceBefore:i,comment:a,anchor:o,tag:s,end:c},l){let u=YQ(e,{type:`scalar`,offset:QQ(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 n$({options:e},{offset:t,source:n,end:r},i){let a=new xX(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=MQ(r,o,e.strict,i);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}function r$(e,t,{offset:n,start:r,value:i,end:a},o){let s=new yQ(void 0,Object.assign({_directives:t},e)),c={atKey:!1,atRoot:!0,directives:s.directives,options:s.options,schema:s.schema},l=TQ(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?e$(c,i,l,o):t$(c,l.end,r,null,l,o);let u=s.contents.range[2],d=MQ(a,u,!1,o);return d.comment&&(s.comment=d.comment),s.range=[n,u,d.offset],s}function i$(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 a$(e){let t=``,n=!1,r=!1;for(let i=0;i<e.length;++i){let a=e[i];switch(a[0]){case`#`:t+=(t===``?``:r?`
|
|
248
|
-
|
|
249
|
-
`:`
|
|
250
|
-
`)+(a.substring(1)||` `),n=!0,r=!1;break;case`%`:e[i+1]?.[0]!==`#`&&(i+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:t,afterEmptyLine:r}}var o$=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{let i=i$(e);r?this.warnings.push(new CQ(i,t,n)):this.errors.push(new SQ(i,t,n))},this.directives=new pX({version:e.version||`1.2`}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:r}=a$(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(eX(i)&&!i.flow&&i.items.length>0){let e=i.items[0];ZY(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:a$(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=i$(e);i[0]+=t,this.onError(i,`BAD_DIRECTIVE`,n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case`document`:{let t=r$(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 SQ(i$(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 SQ(i$(e),`UNEXPECTED_TOKEN`,`Unexpected doc-end without preceding document`));break}this.doc.directives.docEnd=!0;let t=MQ(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 SQ(i$(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 yQ(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}}},s$=Symbol(`break visit`),c$=Symbol(`skip children`),l$=Symbol(`remove item`);function u$(e,t){`type`in e&&e.type===`document`&&(e={start:e.start,value:e.value}),d$(Object.freeze([]),e,t)}u$.BREAK=s$,u$.SKIP=c$,u$.REMOVE=l$,u$.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},u$.parentCollection=(e,t)=>{let n=u$.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 d$(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=d$(Object.freeze(e.concat([[i,t]])),a.items[t],n);if(typeof r==`number`)t=r-1;else if(r===s$)return s$;else r===l$&&(a.items.splice(t,1),--t)}typeof r==`function`&&i===`key`&&(r=r(t,e))}}return typeof r==`function`?r(t,e):r}function f$(e){switch(e){case``:return`byte-order-mark`;case``:return`doc-mode`;case``:return`flow-error-end`;case``:return`scalar`;case`---`:return`doc-start`;case`...`:return`doc-end`;case``:case`
|
|
251
|
-
`:case`\r
|
|
252
|
-
`:return`newline`;case`-`:return`seq-item-ind`;case`?`:return`explicit-key-ind`;case`:`:return`map-value-ind`;case`{`:return`flow-map-start`;case`}`:return`flow-map-end`;case`[`:return`flow-seq-start`;case`]`:return`flow-seq-end`;case`,`:return`comma`}switch(e[0]){case` `:case` `:return`space`;case`#`:return`comment`;case`%`:return`directive-line`;case`*`:return`alias`;case`&`:return`anchor`;case`!`:return`tag`;case`'`:return`single-quoted-scalar`;case`"`:return`double-quoted-scalar`;case`|`:case`>`:return`block-scalar-header`}return null}function p$(e){switch(e){case void 0:case` `:case`
|
|
253
|
-
`:case`\r`:case` `:return!0;default:return!1}}var m$=new Set(`0123456789ABCDEFabcdef`),h$=new Set(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()`),g$=new Set(`,[]{}`),_$=new Set(` ,[]{}
|
|
254
|
-
\r `),v$=e=>!e||_$.has(e),y$=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer=``,this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!=`string`)throw TypeError(`source is not a string`);this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=this.next??`stream`;for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===` `||t===` `;)t=this.buffer[++e];return!t||t===`#`||t===`
|
|
255
|
-
`||t===`\r`&&this.buffer[e+1]===`
|
|
256
|
-
`}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let n=0;for(;t===` `;)t=this.buffer[++n+e];if(t===`\r`){let t=this.buffer[n+e+1];if(t===`
|
|
257
|
-
`||!t&&!this.atEnd)return e+n+1}return t===`
|
|
258
|
-
`||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t===`-`||t===`.`){let t=this.buffer.substr(e,3);if((t===`---`||t===`...`)&&p$(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!=`number`||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
|
|
259
|
-
`,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]===`\r`&&--e,this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case`stream`:return yield*this.parseStream();case`line-start`:return yield*this.parseLineStart();case`block-start`:return yield*this.parseBlockStart();case`doc`:return yield*this.parseDocument();case`flow`:return yield*this.parseFlowCollection();case`quoted-scalar`:return yield*this.parseQuotedScalar();case`block-scalar`:return yield*this.parseBlockScalar();case`plain-scalar`:return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext(`stream`);if(e[0]===``&&(yield*this.pushCount(1),e=e.substring(1)),e[0]===`%`){let t=e.length,n=e.indexOf(`#`);for(;n!==-1;){let r=e[n-1];if(r===` `||r===` `){t=n-1;break}n=e.indexOf(`#`,n+1)}for(;;){let n=e[t-1];if(n===` `||n===` `)--t;else break}let r=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-r),this.pushNewline(),`stream`}if(this.atLineEnd()){let t=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-t),yield*this.pushNewline(),`stream`}return yield``,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext(`line-start`);if(e===`-`||e===`.`){if(!this.atEnd&&!this.hasChars(4))return this.setNext(`line-start`);let e=this.peek(3);if((e===`---`||e===`...`)&&p$(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&&!p$(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===`:`)&&p$(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(v$),`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(`...`))&&p$(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(v$),`flow`;case`"`:case`'`:return this.flowKey=!0,yield*this.parseQuotedScalar();case`:`:{let e=this.charAt(1);if(this.flowKey||p$(e)||e===`,`)return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),`flow`}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),t=this.buffer.indexOf(e,this.pos+1);if(e===`'`)for(;t!==-1&&this.buffer[t+1]===`'`;)t=this.buffer.indexOf(`'`,t+2);else for(;t!==-1;){let e=0;for(;this.buffer[t-1-e]===`\\`;)e+=1;if(e%2==0)break;t=this.buffer.indexOf(`"`,t+1)}let n=this.buffer.substring(0,t),r=n.indexOf(`
|
|
260
|
-
`,this.pos);if(r!==-1){for(;r!==-1;){let e=this.continueScalar(r+1);if(e===-1)break;r=n.indexOf(`
|
|
261
|
-
`,e)}r!==-1&&(t=r-(n[r-1]===`\r`?2:1))}if(t===-1){if(!this.atEnd)return this.setNext(`quoted-scalar`);t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?`flow`:`doc`}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let t=this.buffer[++e];if(t===`+`)this.blockScalarKeep=!0;else if(t>`0`&&t<=`9`)this.blockScalarIndent=Number(t)-1;else if(t!==`-`)break}return yield*this.pushUntil(e=>p$(e)||e===`#`)}*parseBlockScalar(){let e=this.pos-1,t=0,n;loop:for(let r=this.pos;n=this.buffer[r];++r)switch(n){case` `:t+=1;break;case`
|
|
262
|
-
`:e=r,t=0;break;case`\r`:{let e=this.buffer[r+1];if(!e&&!this.atEnd)return this.setNext(`block-scalar`);if(e===`
|
|
263
|
-
`)break}default:break loop}if(!n&&!this.atEnd)return this.setNext(`block-scalar`);if(t>=this.indentNext){this.indentNext=this.blockScalarIndent===-1?t:this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let t=this.continueScalar(e+1);if(t===-1)break;e=this.buffer.indexOf(`
|
|
264
|
-
`,t)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext(`block-scalar`);e=this.buffer.length}}let r=e+1;for(n=this.buffer[r];n===` `;)n=this.buffer[++r];if(n===` `){for(;n===` `||n===` `||n===`\r`||n===`
|
|
265
|
-
`;)n=this.buffer[++r];e=r-1}else if(!this.blockScalarKeep)do{let n=e-1,r=this.buffer[n];r===`\r`&&(r=this.buffer[--n]);let i=n;for(;r===` `;)r=this.buffer[--n];if(r===`
|
|
266
|
-
`&&n>=this.pos&&n+1+t>i)e=n;else break}while(1);return yield``,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,t=this.pos-1,n=this.pos-1,r;for(;r=this.buffer[++n];)if(r===`:`){let r=this.buffer[n+1];if(p$(r)||e&&g$.has(r))break;t=n}else if(p$(r)){let i=this.buffer[n+1];if(r===`\r`&&(i===`
|
|
267
|
-
`?(n+=1,r=`
|
|
268
|
-
`,i=this.buffer[n+1]):t=n),i===`#`||e&&g$.has(i))break;if(r===`
|
|
269
|
-
`){let e=this.continueScalar(n+1);if(e===-1)break;n=Math.max(n,e-2)}}else{if(e&&g$.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(v$),e+=yield*this.pushSpaces(!0);continue loop;case`-`:case`?`:case`:`:{let t=this.flowLevel>0,n=this.charAt(1);if(p$(n)||t&&g$.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(;!p$(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(h$.has(t))t=this.buffer[++e];else if(t===`%`&&m$.has(this.buffer[e+1])&&m$.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
|
|
270
|
-
`?yield*this.pushCount(1):e===`\r`&&this.charAt(1)===`
|
|
271
|
-
`?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===` `||e&&n===` `);let r=t-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=t),r}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}},b$=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 x$(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function S$(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 C$(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 w$(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 T$(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 E$(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 D$(e){if(e.start.type===`flow-seq-start`)for(let t of e.items)t.sep&&!t.value&&!x$(t.start,`explicit-key-ind`)&&!x$(t.sep,`map-value-ind`)&&(t.key&&(t.value=t.key),delete t.key,C$(t.value)?t.value.end?E$(t.value.end,t.sep):t.value.end=t.sep:E$(t.start,t.sep),delete t.sep)}var O$=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 y$,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=f$(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`&&D$(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&&S$(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`:S$(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=T$(w$(this.peek(2))),n;e.end?(n=e.end,n.push(this.sourceToken),delete e.end):n=[this.sourceToken];let r={type:`block-map`,offset:e.offset,indent:e.indent,items:[{start:t,key:e,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=r}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case`space`:case`comment`:case`newline`:e.props.push(this.sourceToken);return;case`scalar`:if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let e=this.source.indexOf(`
|
|
272
|
-
`)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
|
|
273
|
-
`,e)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(this.onKeyLine=!1,t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){E$(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(x$(t.start,`newline`))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let e=T$(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(x$(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(C$(t.key)&&!x$(t.sep,`newline`)){let e=T$(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]}):x$(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&&!x$(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)){E$(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||x$(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=T$(w$(t));D$(e);let r=e.end.splice(1,e.end.length);r.push(this.sourceToken);let i={type:`block-map`,offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let e=this.source.indexOf(`
|
|
274
|
-
`)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
|
|
275
|
-
`,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=T$(w$(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=T$(w$(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 k$(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new b$||null,prettyErrors:t}}function A$(e,t={}){let{lineCounter:n,prettyErrors:r}=k$(t),i=new O$(n?.addNewLine),a=new o$(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 SQ(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return r&&n&&(o.errors.forEach(wQ(e,n)),o.warnings.forEach(wQ(e,n))),o}function j$(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 YY(e)&&!r?e.toString(n):new yQ(e,r,n).toString(n)}var M$=e=>vr(Ww(M({message:z}))(e),{onNone:()=>`The YAML parser failed without an error message`,onSome:({message:e})=>e}),N$=(e,t)=>T(function*(){let n=yield*qh({try:()=>A$(t,{keepSourceTokens:!0,prettyErrors:!0,strict:!0,uniqueKeys:!0}),catch:t=>new rU({file:e,stage:`yaml`,expression:y(),message:M$(t)})}),r=n.errors[0]??n.warnings[0];return r===void 0?n:yield*new rU({file:e,stage:`yaml`,expression:y(),message:r.message})}),P$=e=>j$(e);V(`@usine/config/YamlEdit`)({path:N(z).check(qT()),value:IE});var F$=(e,t)=>{let n=e.replaceAll(`\r
|
|
276
|
-
`,`
|
|
277
|
-
`);return t===`\r
|
|
278
|
-
`?n.replaceAll(`
|
|
279
|
-
`,`\r
|
|
280
|
-
`):n},I$=O(`YamlWriter.updateYaml`)((e,t,n)=>T(function*(){let r=yield*N$(e,t);return r.setIn(n.path,n.value),F$(r.toString(),t.includes(`\r
|
|
281
|
-
`)?`\r
|
|
282
|
-
`:`
|
|
283
|
-
`)}));O(`YamlWriter.updateFrontmatter`)((e,t,n)=>T(function*(){let r=yield*qq(e,t),i=F$(yield*I$(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 L$=Yy(),R$=P([j,lT]).annotate({message:`Expected a CEL expression. Quote the value so that YAML reads it as a string.`}).pipe(ST(ZH,{decode:sb(e=>String(e)),encode:sb(e=>e)})),z$=P([UJ.mapFields(Tw({if:R$})).pipe(ST(UJ)),WJ.mapFields(Tw({if:R$})).pipe(ST(WJ)),GJ.mapFields(Tw({if:R$})).pipe(ST(GJ))]),B$=class extends V(`@usine/config/LoopFrontmatter`)({trigger:z$,selector:xE(zJ),approval:sA.pipe(DT(w(`none`))),step:wN.pipe(DT(w(`run`))),agent:fN,maxCycles:ZJ.fields.maxCycles,permissions:ZJ.fields.permissions,priority:xE(XJ)}){},V$=B$.pipe(mT({maxCycles:`max_cycles`})),H$=class extends V(`@usine/config/AgentFrontmatter`)({harness:lN,model:cN,effort:uN,parentModel:xE(cN),parentEffort:xE(uN)}){},U$=H$.pipe(mT({parentModel:`parent_model`,parentEffort:`parent_effort`})),W$=e=>`---\n${P$(Xw(U$)(new H$(e)))}---\n${e.persona}`,G$=e=>`---\n${P$(Xw(V$)(new B$(e)))}---\n${e.body}`,K$=(e,t)=>rU.fromSchema(e,t),q$=Hw(IE),J$=(e,t)=>T(function*(){return yield*q$((yield*N$(e,t)).toJS()).pipe(dg(t=>new rU({file:e,stage:`yaml`,expression:y(),message:L$(t.issue)})))}),Y$=(e,t,n)=>new rU({file:e,stage:`expression`,expression:b(t.source),message:t.message,details:[{path:n,message:t.message}]}),X$=e=>{let t=e.slice(e.lastIndexOf(`/`)+1);return t.endsWith(`.md`)?w(t.slice(0,-3)):new rU({file:e,stage:`schema`,expression:y(),message:`Expected a .md filename`})},Z$=e=>X$(e).pipe(E(t=>Hw(ZJ.fields.name)(t).pipe(dg(t=>K$(e,t))))),Q$=e=>X$(e).pipe(E(t=>Hw(fN)(t).pipe(dg(t=>K$(e,t))))),$$=(e,t)=>T(function*(){let n=[],r=0;for(;r<t.length;){let i=t.indexOf(`{{`,r);if(i<0)break;let a=t.indexOf(`}}`,i+2);if(a<0)return yield*new rU({file:e,stage:`expression`,expression:y(),message:`The prompt has an unclosed {{ at character ${i}. Close it with }}.`});let o=t.slice(i+2,a).trim(),s=yield*Hw(ZH)(o).pipe(dg(t=>K$(e,t)));n.push({source:s,start:i,end:a+2}),r=a+2}return n}),e1=(e,t,n)=>{let r=$J(t.name),i=zY(t.trigger.on);return T(function*(){let a=yield*Ph(yield*$$(r,t.body),t=>e.evaluateScalar(t.source,i,n).pipe(dg(e=>Y$(r,e,[`body`])),ng(e=>({expression:t,value:e})))),o=``,s=0;for(let{expression:e,value:n}of a)o+=t.body.slice(s,e.start),o+=String(n),s=e.end;return o+t.body.slice(s)})},t1=O(`ConfigParser.parseUsineYaml`)((e,t)=>T(function*(){let n=yield*J$(e,t);return yield*Hw(RJ)(n,{onExcessProperty:`error`,errors:`all`}).pipe(dg(t=>K$(e,t)))})),n1=O(`ConfigParser.parseAgentFile`)((e,t)=>T(function*(){let n=yield*Q$(e),r=yield*qq(e,t),i=yield*J$(e,r.yaml),a=yield*Hw(U$)(i,{onExcessProperty:`error`,errors:`all`}).pipe(dg(t=>K$(e,t))),o=yield*Hw(pN)(r.body).pipe(dg(t=>K$(e,t)));return new Jq({name:n,harness:a.harness,model:a.model,effort:a.effort,parentModel:a.parentModel,parentEffort:a.parentEffort,persona:o})})),r1=e=>O(`ConfigParser.parseLoopFile`)((t,n)=>T(function*(){let r=yield*Z$(t),i=yield*qq(t,n),a=yield*J$(t,i.yaml),o=yield*Hw(V$)(a,{onExcessProperty:`error`,errors:`all`}).pipe(dg(e=>K$(t,e))),s=yield*Hw(YJ)(i.body).pipe(dg(e=>K$(t,e))),c=zY(o.trigger.on),l=[],u=yield*e.checkBoolean(o.trigger.if,c).pipe(dg(e=>Y$(t,e,[`trigger`,`if`])),$h);Di(u)&&l.push(u.failure);let d=yield*$$(t,s).pipe($h);if(Di(d))l.push(d.failure);else{let n=yield*Ph(d.success,({source:n})=>e.checkScalar(n,c).pipe(dg(e=>Y$(t,e,[`body`])),$h));for(let e of n)Di(e)&&l.push(e.failure)}return Yi(l)?yield*new rU({file:t,stage:`expression`,expression:l[0].expression,message:l.map(({message:e})=>e).join(`
|
|
284
|
-
`),details:l.flatMap(e=>e.details??[{path:[`body`],message:e.message}])}):new ZJ({name:r,trigger:o.trigger,selector:o.selector,approval:o.approval,maxCycles:o.maxCycles,permissions:o.permissions,priority:o.priority,step:o.step,agent:o.agent,body:s})})),i1=Ww(fz),a1=e=>O(`ConfigParser.configWarnings`)(function*(t,n){let r=new Set(t.labels.map(({name:e})=>pz(e))),i=[];for(let e of t.repos)for(let t of e.lanes)for(let n of t.sources)`label`in n&&!r.has(pz(n.label))&&i.push(new eY({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=i1(e);S(n)&&!r.has(pz(n.value))&&i.push(new tY({loop:t.name,label:n.value}))}}return i}),o1=class e extends Rr()(`@usine/config/ConfigParser`){static layer=Xf(e,T(function*(){return s1(yield*eU)}))},s1=e=>({configWarnings:a1(e),parseUsineYaml:t1,parseAgentFile:n1,parseLoopFile:r1(e),renderPrompt:O(`ConfigParser.renderPrompt`)((t,n)=>e1(e,t,n))}),c1=z.pipe(L(`CursorKey`)),l1=Hw(N(M({value:IE}))),u1=e=>t=>dg(t,t=>new sz({operation:e,cause:t})),d1=class e extends Rr()(`@usine/engine/CursorStore`){static layer=Xf(e,T(function*(){let e=yield*iN;return{read:O(`CursorStore.read`)(function*(t,n){let r=Sr((yield*T(function*(){return yield*l1(yield*e.select({value:QR.valueJson}).from(QR).where(Y(QR.cursorKey,t)).limit(1).execute())}).pipe(u1(`read runtime cursor`)))[0]);return x(r)?y():yield*Hw(n)(r.value.value,{onExcessProperty:`error`}).pipe(ng(b),og(e=>e_(`Stored cursor no longer decodes; treating it as absent`,{key:t,detail:e.message}).pipe(rg(y()))))}),write:O(`CursorStore.write`)(function*(t,n,r){let i=yield*Jw(n)(r).pipe(u1(`encode runtime cursor`));yield*e.insert(QR).values({cursorKey:t,valueJson:i}).onConflictDoUpdate({target:QR.cursorKey,set:{valueJson:i}}).execute().pipe(ag,u1(`write runtime cursor`))})}}))},f1=e=>e.pipe(dg(e=>e instanceof QL?e:new sz({operation:`update cycle budget`,cause:e}))),p1=class e extends Rr()(`@usine/engine/CycleBudgets`){static layer=Xf(e,T(function*(){let e=yield*iN,t=VV(e);return{generation:O(`CycleBudgets.generation`)(function*(e){return yield*D({itemKey:e}),vr(yield*t.get(e).pipe(dg(e=>new sz({operation:`read cycle generation`,cause:e}))),{onNone:()=>aI.make(0),onSome:e=>e.generation})}),asks:O(`CycleBudgets.asks`)(()=>t.asks().pipe(dg(e=>new sz({operation:`read cycle asks`,cause:e})))),reset:O(`CycleBudgets.reset`)(function*(t,n){yield*D({askId:t,eventId:n.id}),yield*e.transaction(e=>T(function*(){if((yield*e.select().from(GR).where(Y(GR.askId,t)).execute())[0]?.eventId===n.id){yield*k(`Cycle budget reset answer already recorded`,{askId:t,eventId:n.id});return}let r=(yield*VV(e).asks()).find(({id:e})=>e===t);if(r===void 0)return yield*new QL({askId:t});let i=yield*VV(e).get(r.itemKey);if(x(i))return yield*Kh(Error(`Open cycle ask has no budget`));let a=i.value.generation+1;yield*e.insert(VR).values({eventId:n.id,dedupKey:n.dedupKey,payloadJson:lV(n.payload),receivedAt:uV(n.receivedAt)}).execute(),yield*e.insert(GR).values({askId:t,eventId:n.id,itemKey:r.itemKey}).execute(),yield*e.update(UR).set({generation:a,askJson:null,resetPending:!0}).where(Y(UR.itemKey,r.itemKey)).execute(),yield*e.update(WR).set({generation:a}).where(cM(Y(WR.itemKey,r.itemKey),hM(WR.runId,e.select({runId:Q.runId}).from(Q).where(hM(J`json_extract(${Q.stateJson}, '$._tag')`,[...MA]))))).execute(),yield*k(`Operator reset Item cycle budget`,{askId:t,eventId:n.id,itemKey:r.itemKey,repository:r.repository,generation:a,completedCycles:r.completedCycles,counts:r.counts})})).pipe(f1)}),close:O(`CycleBudgets.close`)(function*(t,n){yield*D({askId:t,reason:n});let r=uV(yield*B_);return yield*e.transaction(e=>T(function*(){let i=(yield*VV(e).asks()).find(({id:e})=>e===t);if(i===void 0)return yield*k(`Cycle-budget Ask is no longer open; nothing to close`,{askId:t,reason:n}),!1;let a=Xw(uI)(i);return yield*e.insert(KR).values({askId:t,itemKey:i.itemKey,reason:n,askJson:a,closedAt:r}).onConflictDoUpdate({target:KR.askId,set:{reason:n,askJson:a,closedAt:r}}).execute(),yield*e.update(UR).set({askJson:null}).where(Y(UR.itemKey,i.itemKey)).execute(),yield*k(`Closed cycle-budget Ask without a reset`,{askId:t,reason:n,itemKey:i.itemKey,repository:i.repository,loop:i.loop,completedCycles:i.completedCycles,counts:i.counts}),!0})).pipe(dg(e=>new sz({operation:`close cycle ask`,cause:e})))}),pendingResets:O(`CycleBudgets.pendingResets`)(()=>t.pendingResets().pipe(ng(e=>e.map(e=>new ZL(e))),dg(e=>new sz({operation:`read pending cycle resets`,cause:e})))),acknowledgeReset:O(`CycleBudgets.acknowledgeReset`)(function*(t){yield*D({itemKey:t.itemKey,generation:t.generation}),yield*e.update(UR).set({resetPending:!1}).where(cM(Y(UR.itemKey,t.itemKey),Y(UR.generation,t.generation))).execute().pipe(dg(e=>new sz({operation:`acknowledge cycle reset`,cause:e}))),yield*k(`Cycle reset trigger refresh recorded`,{itemKey:t.itemKey,generation:t.generation})})}}))},m1=new class extends V(`@usine/engine/RetryRequest`)({requestedBy:B(aN),amendment:B(dF)}){}({requestedBy:y(),amendment:y()});V(`@usine/engine/RunAgainRequest`)({step:wN,approval:sA,cycleLimit:B(iI),permissions:lA,context:dF,requestedBy:B(aN)});var h1=P([NR,zR]),g1=(e,t,n)=>{let r=rA.make(JSON.stringify([`operator-run-again`,n.reopening,n.trigger]));return new kR({event:new iA({id:nA.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})},_1=class extends V(`@usine/engine/StepExecution`)({attempt:_F,event:iA,run:UA,step:TN,repository:Xk,revision:Zk,task:lF,agent:mN,parentModel:B(cN),permissions:lA,resume:B(QP),reattach:lT.pipe(TT(w(!1)))}){},v1=class extends Rr()(`@usine/engine/StepExecutor`){},y1=e=>({attemptWindows:O(`RunStoreQueries.attemptWindows`)(function*(t){yield*D({attemptId:t});let[n]=yield*e.select(QV).from($).where(Y($.attemptId,t)).execute().pipe(E(iV));if(n===void 0)return yield*Kh(Error(`No attempt ${t} recorded`));let r=yF(NV(n));if(x(r))return yield*A(`The Attempt ended before end times were recorded, so it has no window and none overlaps it`,{attemptId:t}),new wF({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 wF({own:r,overlapping:(yield*e.select(QV).from($).innerJoin(Q,Y(Q.runId,$.runId)).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(cM(hM(Z.itemKey,i),Y($.agent,n.agent),oM($.attemptId,t))).orderBy($.startedAt).execute().pipe(E(iV))).flatMap(e=>Mr(yF(NV(e)))).filter(e=>CF(r.value,e))})})}),b1=cF.make(3),x1=e=>Sr(e.attempts.at(-1)).pipe(Nr(e=>x(e.outcome))),S1=e=>kr(e.salvage,e=>e._tag===`Retained`?e.pushFailure:y()),C1=(e,t,n)=>{let r=new qP({failure:n});return TF({failure:n,number:t.number,maxAutoAttempts:b1})?{_tag:`RetryAttempt`,attempt:t,outcome:r}:{_tag:`RunFailed`,attempt:t,outcome:r,state:LA(e)}},w1=(e,t,n)=>{if(e.run.state._tag!==`Running`)return{_tag:`Unchanged`,reason:`RunNotRunning`};let r=x1(e);if(x(r))return{_tag:`Unchanged`,reason:`NoOpenAttempt`};if(r.value.id!==t)return{_tag:`Unchanged`,reason:`AttemptReplaced`};let i=vr(S1(r.value),{onNone:()=>n,onSome:e=>Ci(e)});return Di(i)?C1(e.run.state,r.value,i.failure):{_tag:`RunSucceeded`,attempt:r.value,outcome:new KP,state:IA(e.run.state),result:i.success}},T1=e=>kk(e,{Pushed:e=>b(e),PartlyPushed:({ref:e,commit:t})=>b(new QP({ref:e,commit:t})),Retained:()=>y(),Rejected:()=>y()}),E1=e=>ra(e,e=>kr(e.salvage,T1)),D1=(e,t,n,r)=>{let i=e.run.state;if(!DA(i)&&i._tag!==`Running`)return{_tag:`RunClosed`,state:i};let a=y(),o=x1(e);if(i._tag===`Running`&&S(o)){if(Fr(n,o.value.id))return{_tag:`ReattachAttempt`,state:i,attempt:o.value,resume:E1(e.attempts)};let r=C1(i,o.value,yr(S1(o.value),()=>t));if(r._tag===`RunFailed`)return r;a=b(r)}let s=S(a)?new iF:yr(r,()=>e.attempts.length===0?new eF:new rF);return{_tag:`StartAttempt`,state:i._tag===`Running`?i:FA(i),number:cF.make((e.attempts.at(-1)?.number??0)+1),start:s,interrupted:a,resume:E1(e.attempts)}},O1=e=>e.run.state._tag===`Canceled`?{_tag:`AlreadyClosed`}:TA(e.run.state)?{_tag:`Canceled`,state:zA(e.run.state),attempt:e.run.state._tag===`Running`?Or(x1(e),e=>({id:e.id,worker:e.worker,outcome:new JP})):y()}:{_tag:`CancelRejected`},k1=e=>{let t=e.run.state;return t._tag===`Failed`?{_tag:`Resume`,state:RA(t)}:t._tag===`Running`&&x(x1(e))?{_tag:`ResumePending`}:{_tag:`RetryRejected`}},A1=(e,t)=>vr(e,{onNone:()=>!1,onSome:e=>!Fr(e,t)}),j1=(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},M1=(e,t)=>{if(e._tag!==`RunFailed`||Oi(t))return y();switch(t.failure._tag){case`QuestionFailure`:return b(`question`);case`BlockedFailure`:return b(`blocker`);default:return y()}},N1=(e,t)=>vr(e.suppressedEventId,{onNone:()=>({_tag:`SuppressFrom`}),onSome:e=>e===t?{_tag:`Suppress`}:{_tag:`Lift`}}),P1=(e,t)=>{if(x(e))return{_tag:`OpenRun`};let n=e.value;return n.state._tag===`Running`?{_tag:`QueueEvent`}:EA(n.state)?{_tag:`SupersedeRun`,runId:n.id,state:BA(n.state,t)}:{_tag:`OpenRun`}},F1=B(HA).pipe(TT(w(y()))),I1=class extends V(`@usine/engine/internal/Claim`)({result:BR,openedRun:F1,supersededRun:F1}){},L1=class extends H(`@usine/engine/internal/AttemptStarted`)(`AttemptStarted`,{execution:_1}){},R1=class extends H(`@usine/engine/internal/AttemptRecoveryFailed`)(`AttemptRecoveryFailed`,{}){},z1=class extends H(`@usine/engine/internal/RunClosed`)(`RunClosed`,{}){},B1=T(function*(){let e=yield*iN,t=yield*YO,n=rH(e),r=O(`RunStore.admitRun`)(function*(e,t,n){let r=yield*e.cycles.admit(t);return S(r)?new zR({eventId:t.event.id,ask:r.value}):(yield*e.createRun(t,t.event.id,n),yield*e.cycles.reserve(t,n),new NR({eventId:t.event.id,runId:n}))}),i=O(`RunStore.openRun`)(function*(e,t,n,i=y()){let a=yield*r(e,t,n);return new I1({result:a,openedRun:a._tag===`Claimed`?b(n):y(),supersededRun:i})}),a=e=>jR(e).pipe(kg(YO,t)),o=O(`RunStore.settlementOf`)(function*(e,t){let n=(yield*e.runForEvent(t))[0];if(n!==void 0){let t=(yield*e.snapshot(n.runId)).run;return b({_tag:`Owned`,run:t})}let r=(yield*e.ignoredEvent(t))[0];return r===void 0?y():b({_tag:`Ignored`,reason:r.reason})}),s=O(`RunStore.claimEvent`)(function*(e,t,n){if(!(yield*e.cycles.isCurrentEvent(t)))return new I1({result:new LR({eventId:t.event.id,reason:`superseded`})});let r=yield*e.loopItems.suppression(t.loop,t.itemKey);if(S(r)){let n=N1(r.value,t.event.id),i={eventId:t.event.id,suppressedBy:r.value.runId,loop:t.loop,itemKey:t.itemKey};switch(n._tag){case`SuppressFrom`:return yield*e.loopItems.suppressFrom(t.loop,t.itemKey,t.event.id),yield*k(`First Item state after the Agent stopped for the operator; it waits for the operator`,i),new I1({result:new RR({eventId:t.event.id,runId:r.value.runId})});case`Suppress`:return yield*k(`Item unchanged since the Agent stopped for the operator; no Run opens`,i),new I1({result:new RR({eventId:t.event.id,runId:r.value.runId})});case`Lift`:yield*e.loopItems.lift(t.loop,t.itemKey),yield*k(`Item changed after the Agent stopped for the operator; the Loop acts on its new state`,i)}}let a=(yield*e.blockingRun(t.loop,t.itemKey))[0],o=P1(a===void 0?y():b((yield*e.snapshot(a.runId)).run),t.event.id);switch(yield*k(`Event claim decided`,{eventId:t.event.id,decision:o._tag}),o._tag){case`QueueEvent`:return new I1({result:new PR({eventId:t.event.id})});case`SupersedeRun`:return yield*e.updateState(o.runId,o.state),yield*i(e,t,n,b(o.runId));case`OpenRun`:return yield*i(e,t,n)}}),c=O(`RunStore.recordAndClaim`)(function*(t,n){return yield*D({eventId:t.event.id,runId:n,loop:t.loop,itemKey:t.itemKey}),yield*e.transaction(e=>T(function*(){let r=rH(e),i=yield*r.recordTriggerEvent(t),c=yield*r.loopItems.sighted(i.loop,i.itemKey,i.event.id),l=yr(yield*r.newestReopening(i.event.id),()=>({submission:i,reopening:0})),u=l.submission.event.id,d=yield*o(r,u);if(x(d))return yield*s(r,l.submission,l.reopening===0?n:yield*a(l.submission));let f=j1(d.value,A1(c,i.event.id));switch(f._tag){case`JoinRun`:return yield*k(`Event joined its existing Run`,{eventId:u,runId:f.run.id,state:f.run.state._tag}),new I1({result:new NR({eventId:u,runId:f.run.id})});case`StayIgnored`:return yield*k(`Event remains ignored`,{eventId:u,reason:f.reason}),new I1({result:new LR({eventId:u,reason:f.reason})});case`ReopenEvent`:{let e=l.reopening+1,n=yield*r.recordTriggerEvent(MR(t,i.event.dedupKey,e),b({eventId:i.event.id,reopening:e}));return yield*k(`The Item came back to the state of an Event no Attempt worked on; it opens again`,{eventId:u,settled:d.value._tag,reopenedEventId:n.event.id,reopening:e}),yield*s(r,n,yield*a(n))}}}))},TV(`submit event`)),l=O(`RunStore.parkForApproval`)(function*(t){return yield*D({runId:t}),yield*e.transaction(e=>T(function*(){let n=rH(e),r=yield*n.snapshot(t);if(r.run.state._tag!==`Pending`)return r.run.state;let i=NA(r.run.state);return yield*n.updateState(t,i),i}))},TV(`park run for approval`)),u=O(`RunStore.applyFinish`)(function*(e,t,n){if(yield*D({runId:t}),n._tag===`Unchanged`){yield*k(`Attempt completion ignored`,{runId:t,reason:n.reason});return}let{attempt:r,outcome:i}=n;yield*D({attemptId:r.id});let a={runId:t,attemptId:r.id,number:r.number,decision:n._tag};yield*k(`Attempt completion decided`,kk(i,{Failed:({failure:e})=>({...a,failure:e._tag}),Succeeded:()=>a}));let o=yield*B_;yield*e.closeAttempt(r.id,i,o),n._tag!==`RetryAttempt`&&(n._tag===`RunSucceeded`&&(yield*e.updateStepResult(t,r.stepName,n.result)),yield*e.updateState(t,n.state,o))}),d=O(`RunStore.suppressForOperator`)(function*(e,t,n){let r=t.run.id,i=Or(yield*e.nextQueued(r),({submission:e})=>e.event.id),a={runId:r,loop:t.run.loop,itemKey:t.itemKey,stop:n};(yield*e.loopItems.startSuppression(t.run.loop,t.itemKey,r,t.event.id,i))?yield*k(`Agent stopped for the operator; its Loop suppresses the Item`,{...a,suppressedEventId:yr(i,()=>`none yet`)}):yield*k(`Agent stopped for the operator, but nothing is suppressed; the Loop last saw the Item not matching`,a)}),f=(e,{attempt:t,state:n,resume:r,reattach:i})=>new _1({attempt:t,event:e.event,run:new UA({id:e.run.id,eventId:e.run.eventId,loop:e.run.loop,state:n,openedAt:e.run.openedAt}),step:e.step,repository:e.repository,revision:e.revision,task:e.task,agent:e.agent,parentModel:e.parentModel,permissions:e.permissions,resume:r,reattach:i}),p=O(`RunStore.beginAttempt`)(function*(t,n,r){return yield*D({runId:t,worker:n}),yield*e.transaction(e=>T(function*(){let i=rH(e),a=yield*i.snapshot(t),o=new RP({message:`The orchestrator stopped during the attempt`,cause:Error(`attempt interrupted by orchestrator restart`)}),s=yield*i.nextStart(t),c=D1(a,o,r,s);if(c._tag===`RunClosed`)return yield*k(`Attempt start skipped`,{runId:t,state:c.state._tag}),new z1;if(c._tag===`RunFailed`)return yield*u(i,t,c),new R1;if(c._tag===`ReattachAttempt`){let e=yield*B_,r=new _F({...c.attempt,reattachedAt:b(e)});return yield*i.recordReattach(r.id,e),yield*D({attemptId:r.id}),yield*k(`Attempt reattached after an orchestrator restart`,{runId:t,attemptId:r.id,number:r.number,worker:r.worker}),r.worker!==n&&(yield*t_(`Reattached Attempt keeps its own Worker, not the reserved one`,{runId:t,attemptId:r.id,worker:r.worker,reservedWorker:n})),new L1({execution:f(a,{attempt:r,state:c.state,resume:c.resume,reattach:!0})})}S(c.interrupted)&&(yield*u(i,t,c.interrupted.value)),a.run.state._tag!==c.state._tag&&(yield*i.updateState(t,c.state));let l=sF.make(`${t}/${a.step.name}/${c.number}`),d=yield*B_,p=new _F({id:l,runId:t,stepName:a.step.name,worker:n,number:c.number,brain:a.agent.brain,task:a.task,agent:a.agent.name,operatorIntervened:!1,parentModel:a.parentModel,startedAt:d,outcome:y(),endedAt:y(),salvage:y(),start:b(c.start),reattachedAt:y()});return yield*i.addAttempt(p),S(s)&&(yield*i.setNextStart(t,y())),yield*k(`Attempt started`,{runId:t,attemptId:l,number:c.number,worker:n,start:c.start._tag,resumesFrom:Or(c.resume,({ref:e})=>e)}),new L1({execution:f(a,{attempt:p,state:c.state,resume:c.resume,reattach:!1})})}))},TV(`begin attempt`)),m=O(`RunStore.recordSalvage`)(function*(t,n){yield*D({attemptId:t,salvage:n._tag}),yield*e.transaction(e=>rH(e).recordSalvage(t,n)),yield*k(`Attempt salvage recorded`,kk(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:Or(r,({message:e})=>e)}),Rejected:({path:e,commit:n})=>({attemptId:t,path:e,commit:n})}))},TV(`record attempt salvage`)),h=O(`RunStore.recordComments`)(function*(t,n){yield*D({attemptId:t,comments:n.length}),yield*e.transaction(e=>rH(e).recordComments(t,n)),yield*k(`Recorded the comments an Attempt posted before it ended without success`,{attemptId:t,comments:n.map(({kind:e,url:t})=>`${e} ${t.href}`)})},TV(`record attempt comments`)),g=O(`RunStore.recordOutOfMemory`)(function*(t,n){yield*D({attemptId:t,container:n.container,kills:n.kills});let r=yield*e.transaction(e=>rH(e).recordOutOfMemory(t,n));yield*k(`Recorded the processes the kernel killed in the Attempt's container`,{attemptId:t,container:n.container,kills:n.kills,memoryMib:n.memoryMib,attemptKills:r.kills})},TV(`record attempt out-of-memory kills`)),_=O(`RunStore.attemptWindows`)(function*(t){yield*D({attemptId:t});let n=yield*y1(e).attemptWindows(t);return yield*A(`Read the Attempt's window and the Attempts of the same Agent that overlap it on its Item`,{attemptId:t,recorded:S(n.own),ended:Ir(n.own,({endedAt:e})=>S(e)),overlapping:n.overlapping.map(e=>e.attemptId)}),n},TV(`read attempt windows`)),v=O(`RunStore.discardLeftovers`)(function*(t){yield*D({worker:t});let n=yield*B_;return yield*e.transaction(e=>RV(e).discardLeftovers(t,n))},TV(`discard attempt leftovers`)),ee=O(`RunStore.openAttempts`)(function*(t){return yield*D({worker:t}),yield*RV(e).openAttempts(t)},TV(`count open attempts`)),te=O(`RunStore.finishAttempt`)(function*(t,n){return yield*D({runId:t.runId,attemptId:t.id}),yield*e.transaction(e=>T(function*(){let r=rH(e),i=yield*r.snapshot(t.runId),a=w1(i,t.id,n);yield*u(r,t.runId,a);let o=M1(a,n);return S(o)&&(yield*d(r,i,o.value)),a}))},TV(`finish attempt`)),ne=O(`RunStore.resolveFailure`)(function*(t,n,r){return yield*D({runId:t,attemptId:n}),yield*e.transaction(e=>T(function*(){let i=rH(e),a=yield*i.snapshot(t),o=a.attempts.at(-1);if(!OA(a.run.state).canResolveFailure||o?.id!==n)return yield*k(`Failure resolution rejected; Run or Attempt changed`,{runId:t,attemptId:n,state:a.run.state._tag,latestAttemptId:o?.id}),yield*new az({runId:t,operation:`resolveFailure`,state:a.run.state._tag});if(Fr(a.resolvedFailureAttemptId,n))return yield*k(`Run failure already resolved`,{runId:t,attemptId:n}),!1;let s=new fF({resolvedAt:yield*B_,operator:r});yield*i.resolveFailure(t,n,s);let c=yield*i.loopItems.liftRun(t);return yield*k(`Run failure resolved`,{runId:t,attemptId:n,liftedSuppression:c,resolvedAt:J_(s.resolvedAt),operator:C(r)}),c}))},TV(`resolve run failure`)),re=O(`RunStore.approve`)(function*(t,n,r){return yield*D({runId:t,eventId:n.id,channel:r.channel}),yield*e.transaction(e=>T(function*(){let i=rH(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,PA(a.run.state)),!0):yield*new az({runId:t,operation:`approve`,state:a.run.state._tag})}))},TV(`approve run`)),ie=O(`RunStore.retry`)(function*(t,n=m1){let{amendment:r,requestedBy:i}=n;return yield*D({runId:t}),yield*e.transaction(e=>T(function*(){let n=rH(e),a=yield*n.snapshot(t),o=k1(a);if(yield*k(`Operator retry decided`,{runId:t,state:a.run.state._tag,decision:o._tag}),o._tag===`Resume`){let e=(yield*n.blockingRun(a.run.loop,a.itemKey))[0];return e===void 0?(S(r)&&(yield*n.amend(t,r.value),yield*k(`Run effective task and Agent amended`,{runId:t,agent:r.value.agent.name})),(yield*n.loopItems.liftRun(t))&&(yield*k(`Operator retry lifts the suppression of the Item`,{runId:t})),yield*n.setNextStart(t,b(S(r)?new nF({operator:i}):new tF({operator:i}))),yield*n.updateState(t,o.state),!0):(yield*k(`Operator retry rejected; another Run is open on the Item`,{runId:t,openRunId:e.runId,loop:a.run.loop,itemKey:a.itemKey}),yield*new oz({runId:t,openRunId:e.runId,message:`Cannot retry run ${t}: run ${e.runId} of loop "${a.run.loop}" is open on the same item. Cancel run ${e.runId}, or try again after it closes.`}))}return o._tag===`ResumePending`&&x(r)?!1:yield*new az({runId:t,operation:`retry`,state:a.run.state._tag})}))},TV(`retry run`)),ae=O(`RunStore.runAgain`)(function*(t,n){yield*D({runId:t,agent:n.context.agent.name});let i=yield*B_;return yield*e.transaction(e=>T(function*(){let o=rH(e),s=yield*o.snapshot(t),{loop:c}=s.run,{itemKey:l}=s;if(!OA(s.run.state).canRunAgain)return yield*k(`Run again rejected; only a succeeded or canceled Run runs again`,{runId:t,state:s.run.state._tag}),yield*new az({runId:t,operation:`runAgain`,state:s.run.state._tag});let u=(yield*o.blockingRun(c,l))[0];if(u!==void 0)return yield*k(`Run again rejected; another Run is open on the Item`,{runId:t,openRunId:u.runId,loop:c,itemKey:l}),yield*new oz({runId:t,openRunId:u.runId,message:`Run ${t} cannot run again: run ${u.runId} of loop "${c}" is open on the same item. Cancel run ${u.runId}, or try again after it closes.`});let d=yr(yield*o.reopenedEvent(s.event.id),()=>({eventId:s.event.id,dedupKey:s.event.dedupKey})),f=vr(yield*o.newestReopening(d.eventId),{onNone:()=>1,onSome:e=>e.reopening+1}),p=vr(yield*o.cycles.get(l),{onNone:()=>aI.make(0),onSome:e=>e.generation}),m=g1(s,n,{trigger:d.dedupKey,reopening:f,generation:p,receivedAt:i}),h=yield*o.recordTriggerEvent(m,b({eventId:d.eventId,reopening:f}));yield*o.recordRunAgain(h.event.id,new Dz({from:t,requestedBy:n.requestedBy}));let g=yield*r(o,h,yield*a(h));return yield*k(`Run again decided`,kk(g,{Claimed:({runId:e})=>({runId:t,eventId:h.event.id,reopening:f,decision:`OpenRun`,openedRunId:e,requestedBy:yr(n.requestedBy,()=>`none`)}),CycleBlocked:({ask:e})=>({runId:t,eventId:h.event.id,reopening:f,decision:`CycleBlocked`,askId:e.id,requestedBy:yr(n.requestedBy,()=>`none`)})})),g}))},TV(`run again`)),oe=O(`RunStore.cancel`)(function*(t){return yield*D({runId:t}),yield*e.transaction(e=>T(function*(){let n=rH(e),r=yield*n.snapshot(t),i=O1(r);if(yield*k(`Operator cancellation decided`,{runId:t,state:r.run.state._tag,decision:i._tag}),i._tag===`AlreadyClosed`)return i;if(i._tag===`CancelRejected`)return yield*new az({runId:t,operation:`cancel`,state:r.run.state._tag});let a=yield*B_;if(S(i.attempt)){let{id:e,outcome:t}=i.attempt.value;yield*n.closeAttempt(e,t,a)}return yield*n.updateState(t,i.state,a),{_tag:`Canceled`,openAttempt:Or(i.attempt,({id:e,worker:t})=>({id:e,worker:t})),loop:r.run.loop,itemKey:r.itemKey}}))},TV(`cancel run`)),se=O(`RunStore.revoke`)(function*(t,n){return yield*e.transaction(e=>T(function*(){let r=rH(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);EA(t.run.state)&&(yield*r.updateState(e.runId,VA(t.run.state)))}return i.map(e=>e.runId)}))},TV(`revoke run`)),ce=O(`RunStore.revokeQueued`)(function*(e){let{loop:t,itemKey:r,event:i}=e.submission;return yield*D({loop:t,itemKey:r,eventId:i.id}),yield*n.revokeQueued(t,r,e.eventIds)},TV(`revoke queued events`)),le=O(`RunStore.claimQueued`)(function*(t,n){return yield*e.transaction(e=>T(function*(){let r=rH(e),a=yield*r.runForEvent(t.event.id);return a[0]===void 0?(yield*r.ignoredEvent(t.event.id)).length>0||(yield*r.blockingRun(t.loop,t.itemKey)).length>0||S(yield*r.loopItems.suppression(t.loop,t.itemKey))||!(yield*r.cycles.isCurrentEvent(t))?y():(yield*i(r,t,n)).openedRun:(yield*k(`Queued Event already opened its Run`,{eventId:t.event.id,runId:a[0].runId}),y())}))},TV(`claim queued event`)),ue=O(`RunStore.appendTranscript`)(function*(t,n){let r=yield*B_;yield*e.transaction(e=>T(function*(){let i=rH(e);t===`outbound`&&n.payload._tag===`Started`&&(yield*i.updateAttemptParentModel(n.attemptId,n.payload.parentModel)),t===`outbound`&&n.payload._tag===`InterventionApplied`&&(yield*i.markIntervened(n.attemptId)),(yield*i.appendTranscript(t,n,r))||(yield*A(`Transcript envelope already recorded; keeping the first copy`,{attemptId:n.attemptId,direction:t,sequence:n.sequence}))}))},TV(`append attempt transcript`)),de=O(`RunStore.transcript`)(function*(e){return yield*n.transcript(e)},TV(`read attempt transcript`));return{approve:re,appendTranscript:ue,beginAttempt:p,cancel:oe,claimQueued:le,finishAttempt:te,nextQueued:e=>n.nextQueued(e).pipe(TV(`find queued event`)),parkForApproval:l,pendingContinuations:n.pendingContinuations().pipe(TV(`list pending continuations`)),runIdsToDrive:n.runIdsToDrive().pipe(TV(`list the runs to drive`)),recordAndClaim:c,salvageCandidates:n.salvageCandidates().pipe(TV(`list salvage candidates`)),salvageCandidate:e=>n.salvageCandidate(e).pipe(TV(`read a salvage candidate`)),recordSalvage:m,recordComments:h,recordOutOfMemory:g,attemptWindows:_,discardLeftovers:v,openAttempts:ee,submission:e=>n.eventRouteByRun(e).pipe(E(t=>t[0]===void 0?Uh(new iz({runId:e})):w(OV(t[0]))),TV(`read run submission`)),resolveFailure:ne,retry:ie,revoke:se,revokeQueued:ce,runAgain:ae,snapshot:e=>n.snapshot(e).pipe(TV(`read run`)),transcript:de}}),V1=class e extends Rr()(`@usine/engine/internal/RunStore`){static layer=Xf(e,B1)},H1=z.pipe(L(`ItemProjectionSource`)),U1=z.pipe(L(`ItemContentHash`)),W1=class extends V(`@usine/engine/ItemProjection`)({itemKey:nI,repository:Xk,source:H1,number:rI,contentHash:U1,payload:LE,goneAt:yE(vE).pipe(DT(w(null)),TT(w(y())))}){},G1=M({itemKey:W1.fields.itemKey,repository:Xk,source:H1,number:rI,contentHash:U1,payload:LE,goneAt:W1.fields.goneAt}),K1=Hw(N(G1)),q1=Hw(N(rI)),J1=Xw(LE),Y1=Xw(G1.fields.goneAt),X1=e=>t=>dg(t,t=>new sz({operation:e,cause:t})),Z1={itemKey:$R.itemKey,repository:$R.repository,source:$R.source,number:$R.itemNumber,contentHash:$R.contentHash,payload:$R.payloadJson,goneAt:$R.goneAt},Q1=T(function*(){let e=yield*iN;return{get:O(`ItemProjectionReader.get`)(function*(t){yield*D({itemKey:t});let[n]=yield*K1(yield*e.select(Z1).from($R).where(Y($R.itemKey,t)).execute(),{onExcessProperty:`error`});return Or(Sr(n),e=>new W1(e))},X1(`read item projection`)),list:O(`ItemProjectionReader.list`)(function*(t,n){return yield*D({repository:t,limit:n.limit}),(yield*K1(yield*e.select(Z1).from($R).where(Y($R.repository,t)).orderBy(jM($R.itemNumber)).limit(n.limit).execute(),{onExcessProperty:`error`})).map(e=>new W1(e))},X1(`list item projections`)),openIssues:O(`ItemProjectionReader.openIssues`)(function*(t){return yield*D({repository:t}),yield*q1((yield*e.select({number:$R.itemNumber}).from($R).where(cM(Y($R.repository,t),Y($R.source,`issue`),_M($R.goneAt),J`json_extract(${$R.payloadJson}, '$.state') = 'OPEN'`)).orderBy(AM($R.itemNumber)).execute()).map(({number:e})=>e))},X1(`list open issue projections`))}}),$1=T(function*(){let e=yield*iN;return{upsert:O(`ItemProjectionWriter.upsert`)(function*(t){yield*D({repository:t.repository,item:t.number,itemKey:t.itemKey});let n=Y1(t.goneAt);return(yield*e.insert($R).values({itemKey:t.itemKey,repository:t.repository,source:t.source,itemNumber:t.number,contentHash:t.contentHash,payloadJson:J1(t.payload),goneAt:n}).onConflictDoUpdate({target:$R.itemKey,set:{repository:t.repository,source:t.source,itemNumber:t.number,contentHash:t.contentHash,payloadJson:J1(t.payload),goneAt:n},setWhere:J`${$R.contentHash} != ${t.contentHash} OR ${$R.goneAt} IS NOT ${n}`}).returning({itemKey:$R.itemKey}).execute()).length===0?(yield*A(`Item projection already matched the observed snapshot`,{repository:t.repository,item:t.number,contentHash:t.contentHash}),!1):(yield*A(`Item projection updated from trigger polling`,{repository:t.repository,item:t.number,source:t.source,contentHash:t.contentHash}),!0)},X1(`write item projection`)),markGone:O(`ItemProjectionWriter.markGone`)(function*(t,n){return yield*D({itemKey:t}),(yield*e.update($R).set({goneAt:Y1(b(n))}).where(cM(Y($R.itemKey,t),_M($R.goneAt))).returning({itemKey:$R.itemKey}).execute()).length===0?(yield*A(`Item projection already gone or never stored`,{itemKey:t}),!1):(yield*k(`Item projection marked gone from GitHub`,{itemKey:t,goneAt:J_(n)}),!0)},X1(`mark item projection gone`))}}),e0=class e extends Rr()(`@usine/engine/ItemProjectionReader`){static layer=Xf(e,Q1)},t0=class e extends Rr()(`@usine/engine/ItemProjectionWriter`){static layer=Xf(e,$1)},n0=class extends Rr()(`@usine/engine/TriggerCondition`){},r0=class extends V(`@usine/engine/LoopRuntimeState`)({loop:aA,paused:lT}){},i0=e=>t=>t.pipe(dg(t=>new sz({operation:e,cause:t}))),a0=T(function*(){let e=yield*iN,t=O(`LoopControl.stateFor`)(function*(t){yield*D({loop:t});let n=(yield*e.select({loop:nz.loopName,paused:nz.paused}).from(nz).where(Y(nz.loopName,t)).limit(1).execute())[0];return n===void 0?new r0({loop:t,paused:!1}):new r0(n)},i0(`read loop runtime state`)),n=O(`LoopControl.states`)(function*(){return(yield*e.select({loop:nz.loopName,paused:nz.paused}).from(nz).orderBy(AM(nz.loopName)).execute()).map(e=>new r0(e))},i0(`list loop runtime states`)),r=O(`LoopControl.write`)(function*(n){yield*D({loop:n.loop});let r=yield*t(n.loop);return r.paused===n.paused?(yield*A(`Loop runtime state was already set`,{loop:n.loop,paused:n.paused}),r):(yield*e.insert(nz).values({loopName:n.loop,paused:n.paused}).onConflictDoUpdate({target:nz.loopName,set:{paused:n.paused}}).execute().pipe(i0(`write loop runtime state`)),yield*k(n.paused?`Loop paused`:`Loop unpaused`,{loop:n.loop,paused:n.paused}),n)});return{isPaused:O(`LoopControl.isPaused`)(function*(e){return(yield*t(e)).paused}),pause:O(`LoopControl.pause`)(e=>r(new r0({loop:e,paused:!0}))),states:n(),unpause:O(`LoopControl.unpause`)(e=>r(new r0({loop:e,paused:!1})))}}),o0=class e extends Rr()(`@usine/engine/LoopControl`){static layer=Xf(e,a0)},s0=N(z),c0=class extends V(`@usine/engine/BoardMoveRecord`)({repository:Xk,itemKey:nI,at:_E,fromLane:z,toLane:z,added:s0.check(qT()),removed:s0}){},l0=Hw(N(M({repository:c0.fields.repository,itemKey:c0.fields.itemKey,at:vE,fromLane:c0.fields.fromLane,toLane:c0.fields.toLane,added:c0.fields.added,removed:c0.fields.removed}))),u0=Xw(c0.fields.added),d0=Xw(c0.fields.removed),f0=e=>t=>dg(t,t=>new sz({operation:e,cause:t})),p0=T(function*(){let e=yield*iN;return{record:O(`BoardMoves.record`)(function*(t){yield*D({repository:t.repository,itemKey:t.itemKey}),yield*e.insert(tz).values({repository:t.repository,itemKey:t.itemKey,movedAt:uV(t.at),fromLane:t.fromLane,toLane:t.toLane,addedJson:u0(t.added),removedJson:d0(t.removed)}).execute(),yield*A(`Recorded a Board move before writing its labels`,{repository:t.repository,itemKey:t.itemKey,at:uV(t.at),fromLane:t.fromLane,toLane:t.toLane})},f0(`record board move`)),onItem:O(`BoardMoves.onItem`)(function*(t,n){return yield*D({itemKey:t}),(yield*l0(yield*e.select({repository:tz.repository,itemKey:tz.itemKey,at:tz.movedAt,fromLane:tz.fromLane,toLane:tz.toLane,added:tz.addedJson,removed:tz.removedJson}).from(tz).where(cM(Y(tz.itemKey,t),fM(tz.movedAt,uV(n)))).orderBy(AM(tz.movedAt),AM(tz.moveId)).execute(),{onExcessProperty:`error`})).map(e=>new c0(e))},f0(`read board moves`))}}),m0=class e extends Rr()(`@usine/engine/BoardMoves`){static layer=Xf(e,p0)},h0=class extends Rr()(`@usine/engine/RunEngineShutdown`){},g0=class e extends Rr()(`@usine/engine/AttemptAdmission`){static layer=Xf(e,T(function*(){let e=yield*Dg(h0),t=S(e)?e.value:yield*vf(),n=yield*Lk(new Set),r=yield*vf(),i=O(`AttemptAdmission.enter`)(function*(e){yield*D({runId:e});let r=yield*Bk(n,n=>Sf(t)?[!1,n]:[!0,new Set([...n,e])]);return r||(yield*k(`Attempt deferred until restart; the engine is draining`,{runId:e})),r}),a=O(`AttemptAdmission.leave`)(function*(e){yield*D({runId:e});let i=yield*Hk(n,t=>new Set([...t].filter(t=>t!==e)));(yield*xf(t))&&(yield*k(`Attempt settled during drain`,{runId:e,remainingRunIds:[...i]}),i.size===0&&(yield*Cf(r,void 0)))});return{withAttempt:O(`AttemptAdmission.withAttempt`)(function*(e,t){return yield*D({runId:e}),yield*jg(i(e),e=>e?t:Hh,t=>t?a(e):Bh)}),drain:O(`AttemptAdmission.drain`)(function*(){yield*Cf(t,void 0);let e=yield*Rk(n);yield*k(`Engine drain started; no further Attempts will be admitted`,{activeRunIds:[...e]}),e.size===0&&(yield*Cf(r,void 0)),yield*yf(r),yield*k(`Engine drain completed; all admitted Attempts settled`)})}}))},_0=class extends NE(`@usine/engine/internal/ParentStopUnconfirmedError`)(`ParentStopUnconfirmedError`,{attemptId:sF,worker:EN,cause:eE()}){},v0=(e,t)=>{let n=new Map(e);return n.delete(t),n},y0=O(`CheckoutRecovery.for`)(function*(e,t){let n=yield*Lk(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(pg(e=>t_(`Attempt salvage reconciliation failed; work retained`,{attemptId:n.attemptId,worker:n.worker,message:String(e)})),gg),i=O(`CheckoutRecovery.keep`)(function*(e){yield*t.occupy(e.worker,e.attemptId).pipe(E(e=>Ig(e.release).pipe(ng(t=>({worker:e.worker,release:t,checkoutKept:!0})))),E(t=>Vk(n,n=>new Map(n).set(e.attemptId,t))),zg)}),a=O(`CheckoutRecovery.recoverOpen`)(function*(e){let n={attemptId:e.attemptId,worker:e.worker};yield*D(n);let a=yield*t.isLive(e.attemptId).pipe($h);if(Oi(a)&&!a.success)return yield*r(e);Di(a)?yield*e_(`Could not read whether an open Attempt's parent task is live; its checkout stays for its Run to decide`,{...n,errorTag:a.failure._tag,message:a.failure.message}):yield*k(`Leaving the checkout of an open Attempt whose parent task is live for its Run to reattach`,n),yield*i(e),yield*k(`Occupied a slot on the Worker of an open Attempt kept for its Run to reattach`,n)}),o=O(`CheckoutRecovery.recoverClosed`)(function*(e){let n={attemptId:e.attemptId,runId:e.runId,worker:e.worker};yield*D(n);let a=yield*t.interrupt(e.attemptId,`startup`).pipe($h);return Oi(a)?(yield*r(e),y()):(yield*e_(`Could not confirm that the parent task of a closed Attempt stopped; its checkout and a slot of its Worker stay kept, and no Attempt starts on its Item, until a reconcile confirms the stop`,{...n,errorTag:a.failure._tag,message:a.failure.message}),yield*i(e),b(e))}),s=O(`CheckoutRecovery.atStartup`)(function*(){let n=new Set(yield*t.workers),r=yield*e.salvageCandidates,i=r.filter(({worker:e})=>n.has(e)),s=r.filter(({worker:e})=>!n.has(e));return s.length>0&&(yield*e_(`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(`,`)})),ga(yield*Ph(i,e=>e.open?a(e).pipe(rg(y())):o(e)))}),c=O(`CheckoutRecovery.reattachSlot`)(function*(e){return Or(Nr(Cr((yield*Rk(n)).get(e)),({checkoutKept:e})=>e),t=>({worker:t.worker,release:Rk(n).pipe(E(n=>n.get(e)===t?k(`The slot startup occupied stays kept with the checkout no execution acquired, until the Attempt's parent task is confirmed stopped`,{attemptId:e,worker:t.worker}):t.release))}))}),l=O(`CheckoutRecovery.acquired`)(function*(e){(yield*Bk(n,t=>t.get(e)?.checkoutKept===!0?[!0,v0(t,e)]:[!1,t]))&&(yield*k(`The reattached Attempt's execution acquired the checkout startup kept; its executor releases the checkout from here, and its Run the slot once the Attempt ends`,{attemptId:e}))}),u=O(`CheckoutRecovery.hold`)(function*(e,t){let r={attemptId:e,worker:t.worker};yield*D(r);let i=yield*Ig(t.release);(yield*Bk(n,n=>n.has(e)?[!1,n]:[!0,new Map(n).set(e,{worker:t.worker,release:i,checkoutKept:!1})]))?yield*k(`The Attempt keeps its Run's slot until its parent task is confirmed stopped`,r):(yield*A(`The Attempt already has a slot kept until its parent task is confirmed stopped; releasing its Run's lease`,r),yield*i)},zg),d=O(`CheckoutRecovery.confirmStop`)(function*(e,n,r){let i={attemptId:e,worker:n.worker,checkoutKept:n.checkoutKept,reason:r};yield*D(i);let a=yield*t.interrupt(e,r).pipe($h);if(Oi(a))return;let o={...i,errorTag:a.failure._tag,message:a.failure.message};return yield*n.checkoutKept?e_(`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):e_(`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 _0({attemptId:e,worker:n.worker,cause:a.failure})}),f=O(`CheckoutRecovery.recoverKept`)(function*(n){let i=yield*e.salvageCandidate(n).pipe($h);if(Di(i)){yield*t_(`Could not read the Attempt whose checkout startup kept; the checkout stays until the next startup`,{attemptId:n,errorTag:i.failure._tag});return}if(x(i.success)){yield*e_(`The leftovers of the Attempt whose checkout startup kept were discarded; the checkout stays`,{attemptId:n});return}let a=i.success.value,o={attemptId:n,worker:a.worker,open:a.open};yield*D(o),(yield*t.workers).includes(a.worker)?(yield*k(`Reconciling the checkout startup kept for an Attempt that was not reattached`,o),yield*r(a)):yield*e_(`The Worker of the Attempt whose checkout startup kept is no longer configured; the checkout stays until it is configured again or its leftovers are discarded`,o)});return{atStartup:s,reattachSlot:c,acquired:l,hold:u,reconcile:O(`CheckoutRecovery.reconcile`)(function*(e,t){yield*D({attemptId:e,reason:t});let r=(yield*Rk(n)).get(e);r===void 0?yield*A(`No slot kept for the Attempt awaits its parent task's stop`,{attemptId:e}):(yield*d(e,r,t),r.checkoutKept&&(yield*f(e)),yield*Vk(n,t=>v0(t,e)).pipe(Zh(r.release),zg),yield*k(`Released the slot kept for an Attempt whose parent task is confirmed stopped`,{attemptId:e,worker:r.worker,checkoutKept:r.checkoutKept}))})}}),b0=class extends V(`@usine/engine/UnconfirmedStop`)({attemptId:sF,runId:HA,loop:aA,itemKey:nI,worker:EN,reason:uF}){},x0=class e extends Rr()(`@usine/engine/UnconfirmedStops`){static empty=Jf(e)({list:w([])})},S0=e=>cg(e,{EnginePersistenceError:e=>new RP({message:`Runtime store error: could not ${e.operation}`,cause:e}),RunNotFoundError:e=>Kh(e),RunOperationRejectedError:e=>Kh(e),RunRetryBlockedError:e=>Kh(e)}),C0=4,w0=`100 millis`,T0=(e,t)=>n=>n.pipe(pg(n=>n._tag===`EnginePersistenceError`?e_(`A Run store operation failed to persist`,{runId:e,operation:t,cause:n.cause}):Bh),hg({schedule:dh(w0),times:C0,while:e=>e._tag===`EnginePersistenceError`})),E0=e=>kr(e,e=>e._tag===`Live`?b(e.attempt):y()),D0=class e extends Rr()(`@usine/engine/internal/RunDriver`){static layer=Xf(e,T(function*(){let e=yield*V1,t=yield*v1,n=yield*g0,r=yield*n0,i=yield*t0,a=yield*YO,o=yield*ek(),s=yield*y0(e,t),c=yield*Lk(new Map),l=yield*Lk(new Map),u=(e,t)=>Bk(l,n=>n.get(e)===t?[!0,v0(n,e)]:[!1,n]).pipe(E(n=>n?t.release:A(`The Run's slot stays with its Attempt until the parent task is confirmed stopped`,{runId:e,worker:t.worker}))),d=O(`RunDriver.launch`)(function*(e){if(yield*D({runId:e}),yield*sk(o,e)){yield*A(`The Run's fiber already runs in this process`,{runId:e});return}yield*A(`Starting the Run's fiber`,{runId:e});let t=yield*eg(Hg);yield*uk(o,e,ee(e).pipe(mg(t=>Qd(t)?Bh:t_(`The Run's fiber stopped on an engine failure; the next reconcile or a restart resumes it`,{runId:e,cause:t})),Wg(`RunDriver.drive`,{root:!0,links:Mr(Or(t,e=>({span:e,attributes:{}})))}),lg(e=>Qd(e)?Wh(e):Bh)),{onlyIfMissing:!0})}),f=O(`RunDriver.resume`)(function*(e){yield*D({runId:e});let t=yield*ak(o,e);S(t)&&(yield*A(`Waiting for the Run's previous fiber to end`,{runId:e}),yield*RE(t.value)),yield*d(e)}),p=O(`RunDriver.stop`)(function*(e){yield*D({runId:e}),(yield*sk(o,e))?(yield*ck(o,e),yield*k(`The closed Run's fiber stopped`,{runId:e})):yield*A(`The closed Run has no fiber in this process`,{runId:e})}),m=O(`RunDriver.markItemGone`)(function*(e,t){return yield*D({runId:e,itemKey:t.itemKey}),yield*i.markGone(t.itemKey,yield*B_).pipe(T0(e,`mark the item's projection gone`),og(n=>e_(`Could not mark the gone Item's projection; its Board card stays in place`,{completedRunId:e,itemKey:t.itemKey,errorTag:n._tag}).pipe(rg(!1))))}),h=O(`RunDriver.continueWithNewest`)(function*(t){yield*D({runId:t});let n=yield*e.nextQueued(t).pipe(T0(t,`read the queued events`));if(x(n))return;let i=n.value.submission,o={completedRunId:t,eventId:i.event.id,loop:i.loop,itemKey:i.itemKey},s=yield*r.recheck(i);if(s!==`matches`){let r=yield*e.revokeQueued(n.value).pipe(T0(t,`revoke the queued events`));if(s===`no-longer-matches`){yield*k(`Queued Event no longer matches its trigger; revoked`,{...o,revokedEvents:r});return}let a=yield*m(t,i);yield*k(`Queued Event's Item is gone from its source; revoked its queued Events`,{...o,revokedEvents:r,projectionMarkedGone:a});return}let c=yield*jR(i).pipe(kg(YO,a)),l=yield*e.claimQueued(i,c).pipe(T0(t,`claim the queued event`));x(l)?yield*k(`Queued Event still matches its trigger but could no longer be claimed; no Run opened`,o):(yield*k(`Queued Event still matches its trigger; opening its Run`,{...o,runId:l.value}),yield*d(l.value))}),g=O(`RunDriver.openAttempt`)(function*(n){yield*D({runId:n});let r=yield*e.snapshot(n).pipe(T0(n,`read the run`)),i=r.attempts.at(-1);if(r.run.state._tag!==`Running`||i===void 0||S(i.outcome))return y();let a={runId:n,attemptId:i.id,worker:i.worker};yield*D({attemptId:i.id,worker:i.worker});let o=yield*t.isLive(i.id).pipe($h);if(Di(o))return yield*e_(`Could not read whether the open Attempt is live; the Run does not reattach it`,{...a,errorTag:o.failure._tag,message:o.failure.message}),b({_tag:`Interrupted`,attempt:i});if(o.success)return yield*k(`The open Attempt's parent task is live; reattaching it`,a),b({_tag:`Live`,attempt:i});let s=yield*t.outcome(i.id).pipe($h);if(Di(s))return yield*e_(`Could not read the open Attempt's stored outcome; the Run does not reattach it`,{...a,errorTag:s.failure._tag,message:s.failure.message}),b({_tag:`Interrupted`,attempt:i});if(x(s.success))return yield*k(`The open Attempt's parent task is gone; the Run does not reattach it`,a),b({_tag:`Interrupted`,attempt:i});let c=s.success.value;return yield*k(`The open Attempt's parent task finished before this process recorded it; finishing the Attempt with its stored result`,{...a,outcome:Ai(c,{onSuccess:()=>`Succeeded`,onFailure:({_tag:e})=>e})}),b({_tag:`Finished`,attempt:i,result:c})}),_=O(`RunDriver.slot`)(function*(e,n,r,i){yield*D({runId:e});let a=w(r),o=E0(r);if(S(o)){let t=yield*s.reattachSlot(o.value.id);if(S(t))return yield*k(`The Run reattaches its open Attempt in the slot startup occupied on its Worker`,{runId:e,attemptId:o.value.id,worker:t.value.worker}),{lease:t.value,open:a}}return{lease:yield*i(t.reserve(e,n,Or(o,({worker:e})=>e))),open:S(o)?g(e):a}}),v=O(`RunDriver.attempt`)(function*(n,r,i,a){yield*D({runId:n,worker:i});let o=yield*a;if(x(E0(o))&&S(yield*ie(r)))return yield*k(`Run waits for an unconfirmed stop after reserving a worker slot`,{runId:n,worker:i,itemKey:r.itemKey}),`WaitingForStop`;if(S(o)&&o.value._tag===`Finished`){let t=yield*e.finishAttempt(o.value.attempt,o.value.result).pipe(T0(n,`finish the attempt`));if(t._tag!==`RetryAttempt`)return t._tag}let c=yield*e.beginAttempt(n,i,Or(E0(o),({id:e})=>e)).pipe(T0(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(S0),salvage:t=>e.recordSalvage(c.execution.attempt.id,t).pipe(S0),comments:t=>e.recordComments(c.execution.attempt.id,t).pipe(S0),outOfMemory:t=>e.recordOutOfMemory(c.execution.attempt.id,t).pipe(S0),windows:e.attemptWindows(c.execution.attempt.id).pipe(T0(n,`read the attempt windows`),S0),transcript:e.transcript(new bB({attemptId:c.execution.attempt.id})).pipe(T0(n,`read the attempt transcript`),S0,ng(e=>e.flatMap(({envelope:e})=>e.version===7?[e]:[]))),checkoutAcquired:s.acquired(c.execution.attempt.id)}).pipe(ug(e=>t_(`Step executor defect; operator intervention required`,{runId:n,attemptId:c.execution.attempt.id,defect:e instanceof Error?e.message:String(e)}).pipe(Zh(new zP({message:`The step executor crashed with an unexpected error`,cause:e})))),$h);return c.execution.reattach&&Di(l)&&(yield*ae(new b0({attemptId:c.execution.attempt.id,runId:n,loop:r.loop,itemKey:r.itemKey,worker:i,reason:`failed`}))),Di(l)&&(yield*re({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(T0(n,`finish the attempt`)))._tag}),ee=$g(function*(t){let r=yield*e.submission(t).pipe(T0(t,`read the run's submission`));if(yield*D({runId:t,loop:r.loop,itemKey:r.itemKey}),r.approval===`required`&&(yield*e.parkForApproval(t).pipe(T0(t,`park the run for approval`)))._tag===`Waiting`){yield*k(`Run waits for its approval`,{runId:t});return}let i;do{let e=yield*g(t);if(S(e)&&e.value._tag!==`Live`&&(yield*ae(new b0({attemptId:e.value.attempt.id,runId:t,loop:r.loop,itemKey:r.itemKey,worker:e.value.attempt.worker,reason:`startup`}))),x(E0(e))){let e=yield*ie(r);if(S(e)){yield*k(`The Run starts no Attempt while the parent task of an earlier Attempt on its Item is not confirmed stopped; each reconcile tries that stop again, then drives the Run`,{runId:t,loop:r.loop,itemKey:r.itemKey,unstoppedAttemptId:e.value.attemptId,unstoppedRunId:e.value.runId,worker:e.value.worker,reason:e.value.reason});return}}i=yield*Bg(i=>_(t,r,e,i).pipe(Qh(({lease:e})=>Vk(l,n=>new Map(n).set(t,e))),E(({lease:e,open:a})=>i(n.withAttempt(t,v(t,r,e.worker,a))).pipe(Mg(u(t,e))))))}while(i===`RetryAttempt`);i!==`WaitingForStop`&&(i===`Unchanged`?yield*k(`Run closed by another operation; its fiber ends`,{runId:t}):yield*h(t))}),te=O(`RunDriver.holdSlot`)(function*(e){let{runId:t,attemptId:n}=e;yield*D({runId:t,attemptId:n}),yield*ne(new b0(e));let r=yield*Bk(l,e=>[Cr(e.get(t)),v0(e,t)]);x(r)?yield*A(`The Run's fiber holds no slot in this process; no slot moves to its Attempt`,{runId:t,attemptId:n}):yield*s.hold(n,r.value)},zg),ne=e=>Vk(c,t=>t.has(e.attemptId)?t:new Map(t).set(e.attemptId,e)),re=O(`RunDriver.confirmStopAfterFailure`)(function*(e){let{attemptId:n,runId:r,worker:i}=e,a={runId:r,attemptId:n,worker:i,reason:e.reason};yield*D(a),yield*ne(new b0(e));let o=yield*t.interrupt(n,e.reason).pipe($h);Oi(o)?(yield*Vk(c,e=>v0(e,n)),yield*A(`The parent task of the failed Attempt is confirmed stopped; the Run's slot is freed`,a)):(yield*e_(`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*te(e))}),ie=e=>Rk(c).pipe(ng(t=>Cr([...t.values()].find(({itemKey:t})=>t===e.itemKey)))),ae=O(`RunDriver.reconcileKept`)(function*(e){yield*D({...e}),yield*ne(e),yield*s.reconcile(e.attemptId,e.reason),yield*Vk(c,t=>v0(t,e.attemptId)),yield*k(`Parent stop confirmed; runs on the item can start attempts again`,{...e})}),oe=O(`RunDriver.releaseKept`)(function*(e){yield*D({...e}),yield*ae(e).pipe(sg(`ParentStopUnconfirmedError`,t=>e_(`Parent stop unconfirmed; the worker slot and checkout stay reserved until reconciliation succeeds`,{...e,errorTag:t._tag})))}),se=O(`RunDriver.recoverWorkspaces`)(function*(){yield*Ph(yield*s.atStartup(),({attemptId:e,runId:t,loop:n,itemKey:r,worker:i})=>ne(new b0({attemptId:e,runId:t,loop:n,itemKey:r,worker:i,reason:`startup`})),{discard:!0})});return{launch:d,resume:f,stop:p,continueWithNewest:h,reconcile:O(`RunDriver.reconcile`)(function*(){let n=[...(yield*Rk(c)).values()];yield*Ph(n,e=>sk(o,e.runId).pipe(E(t=>t?Bh:oe(e))),{discard:!0});let r=yield*e.pendingContinuations;yield*Ph(r,e=>h(e).pipe(pg(t=>t_(`Could not continue the queued Events behind a closed Run`,{runId:e,errorTag:t._tag})),gg),{discard:!0});let i=yield*e.runIdsToDrive,a=yield*bg(i,e=>ng(sk(o,e),e=>!e));yield*Ph(a,d,{discard:!0}),yield*t.sweep;let s={continuedAfterRunIds:r,startedRunIds:a,drivenRunIds:i.length,retriedStopAttemptIds:n.map(({attemptId:e})=>e)};r.length===0&&a.length===0&&n.length===0?yield*A(`Every Run to drive already has its fiber`,s):yield*k(`Runs recovered from the run tables`,s)}),recoverWorkspaces:se,holdSlot:te,releaseKept:oe,unconfirmedStops:Rk(c).pipe(ng(e=>[...e.values()]))}}))},O0=vi(`@usine/engine/ReconcileInterval`,{defaultValue:()=>`3 minutes`});T(function*(){let e=yield*V1,t=yield*D0,n=yield*g0,r=yield*v1,i=yield*YO,a=O(`RunEngine.submit`)(function*(n){let r=yield*jR(n).pipe(kg(YO,i)),a=yield*e.recordAndClaim(n,r);return S(a.supersededRun)&&(yield*t.stop(a.supersededRun.value)),S(a.openedRun)&&(yield*t.launch(a.openedRun.value)),a.result},zg),o=O(`RunEngine.approve`)(function*(n,r,i){(yield*e.approve(n,r,i))?(yield*k(`Run approved`,{runId:n,eventId:r.id,channel:i.channel,approver:yr(i.approver,()=>`none`)}),yield*t.resume(n)):yield*A(`Approval was already recorded; the Run is unchanged`,{runId:n,eventId:r.id})},zg),s=O(`RunEngine.retry`)(function*(n,r=m1){(yield*e.retry(n,r))?yield*t.resume(n):yield*A(`Retry changed nothing; the Run already waits for its next Attempt`,{runId:n})},zg),c=O(`RunEngine.runAgain`)(function*(n,r){let i=yield*e.runAgain(n,r);return i._tag===`Claimed`&&(yield*t.launch(i.runId)),i},zg),l=O(`RunEngine.cancel`)(function*(n){let i=yield*e.cancel(n);if(i._tag===`AlreadyClosed`){yield*A(`Cancel was a no-op; the run was already closed`,{runId:n});return}yield*k(`Run canceled`,{runId:n,openAttempt:vr(i.openAttempt,{onNone:()=>`none`,onSome:({id:e})=>e})}),S(i.openAttempt)&&(yield*t.holdSlot({attemptId:i.openAttempt.value.id,worker:i.openAttempt.value.worker,runId:n,loop:i.loop,itemKey:i.itemKey,reason:`cancel`}));let a=S(i.openAttempt)?yield*r.interrupt(i.openAttempt.value.id,`cancel`).pipe($h):Si(void 0);if(yield*t.stop(n),S(i.openAttempt)&&(yield*t.releaseKept({attemptId:i.openAttempt.value.id,worker:i.openAttempt.value.worker,runId:n,loop:i.loop,itemKey:i.itemKey,reason:`cancel`})),yield*t.continueWithNewest(n),S(i.openAttempt)&&Di(a))return yield*new cz({attemptId:i.openAttempt.value.id,cause:a.failure})},zg),u=O(`RunEngine.intervene`)(function*(t,n,i){yield*D({runId:t,attemptId:n,action:i.action._tag});let a=yield*e.snapshot(t),o=a.attempts.at(-1);if(a.run.state._tag!==`Running`||o?.id!==n||S(o.outcome))return yield*k(`Operator input rejected for an inactive Attempt`,{runId:t,attemptId:n}),yield*new uz({runId:t,attemptId:n,message:`This attempt is no longer running`});yield*r.intervene(n,i).pipe(dg(e=>new uz({runId:t,attemptId:n,message:kk(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,DefectFailure:({message:e})=>e,AgentFailure:({message:e})=>e})})),pg(e=>e_(`Operator input delivery failed`,{runId:t,attemptId:n,message:e.message})))}),d=O(`RunEngine.resolveFailure`)(function*(n,r,i){yield*D({runId:n,attemptId:r}),(yield*e.resolveFailure(n,r,i))&&(yield*k(`The operator resolved the Agent's question or blocker; the Item's queued Events get their turn`,{runId:n,attemptId:r}),yield*t.continueWithNewest(n))},zg),f=O(`RunEngine.revoke`)(function*(n,r){let i=yield*e.revoke(n,r);return yield*Ph(i,t.stop,{concurrency:`unbounded`,discard:!0}),i},zg),p=O(`RunEngine.inspect`)(function*(t){return yield*e.snapshot(t)}),m=O(`RunEngine.transcript`)(function*(t){return yield*e.transcript(t)}),h=O(`RunEngine.discardLeftovers`)(function*(t){if(yield*D({worker:t}),(yield*r.workers).includes(t)){let n=yield*e.openAttempts(t);return yield*k(`Leftovers kept; the Worker is configured or still runs Attempts, so its Attempts stay tracked`,{worker:t,running:n}),yield*new dz({worker:t,running:n})}let n=yield*e.discardLeftovers(t);return yield*k(`Discarded the leftovers of the Attempts on a Worker that is not configured; startup no longer reconciles them`,{worker:t,attempts:n.length}),yield*r.discard(t,n),n.length});return yield*t.recoverWorkspaces(),yield*t.reconcile(),yield*_g(yield*O0).pipe(Zh(t.reconcile()),pg(e=>t_(`Periodic Run reconcile failed; the next one tries again`,{errorTag:e._tag})),gg,Vg,qg),{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 k0=class extends Rr()(`@usine/engine/RunEngine`){},A0=(e,t)=>e.changes.pipe(RO(e=>e!==t),KO,E(vr({onNone:()=>Hh,onSome:e=>w(e)}))),j0=Zk.make(`HEAD`),M0=class extends NE(`@usine/orchestrator/LoopAgentResolutionError`)(`LoopAgentResolutionError`,{loop:aA,agent:fN,message:z}){},N0=O(`TriggerRouting.resolveLoop`)(function*(e,t){yield*D({loop:t.name,agent:t.agent});let n=new Map(e.agents.map(e=>[e.name,e])).get(t.agent);if(n===void 0)return yield*new M0({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:hN(r,e.config.settings.parentModel)}}),P0=O(`TriggerRouting.resolveLoops`)(function*(e){let t=[];for(let n of e.loops){let r=yield*$h(N0(e,n));Oi(r)?t.push(r.success):yield*t_(`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}),F0=e=>e.trigger.on===`schedule`?y():b(e.maxCycles),I0=e=>new kR({event:new iA({id:nA.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:F0(e.loop),repository:e.repository.name,revision:e.revision,task:e.task,agent:e.agent,parentModel:e.parentModel}),L0=e=>kk(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`})}),R0=e=>vr(e.expression,{onNone:()=>({configFile:e.file,configStage:e.stage}),onSome:t=>({configFile:e.file,configStage:e.stage,expression:t})}),z0=class extends V(`@usine/orchestrator/RepositoryPollFailure`)({repository:Xk,errorTag:z,message:j}){},B0=class extends V(`@usine/orchestrator/RepositoryPoll`)({repository:Xk,completedAt:_E}){},V0=class extends V(`@usine/orchestrator/PollCycle`)({repositoryPolls:N(B0).pipe(TT(w([]))),repositories:R.check(HT(0)),changedItems:R.check(HT(0)),submissions:N(BR),revokedRuns:R.check(HT(0)),failures:N(z0),preflightFindings:N(Hq),nextPollAt:B(_E)}){},H0=e=>{let t={errorTag:e._tag,message:e.message};return e._tag===`ConfigFileError`?{...t,...R0(e)}:e._tag===`ExpressionCheckError`||e._tag===`ExpressionEvaluationError`?{...t,expression:e.source}:t},U0=e=>{let t=e.flatMap(e=>vr(e,{onNone:()=>[],onSome:e=>[K_(e)]}));return t.length===0?y():z_(Math.max(...t))},W0=class extends V(`@usine/orchestrator/LoopEvaluationFailure`)({loop:aA,stage:F([`if`,`prompt`]),expression:yE(ZH),errorTag:z,message:j}){},G0=class extends V(`@usine/orchestrator/FailingItem`)({stream:F([`issue`,`pr`]),number:rI,updatedAt:vE,contentHash:U1,failures:yT(W0)}){},K0=e=>e.stream===`issue`?new kK({number:e.number,updatedAt:e.updatedAt}):new AK({number:e.number,updatedAt:e.updatedAt}),q0=(e,t,n)=>{let[r,...i]=n;return r===void 0?y():b(new G0({stream:e._tag===`ChangedIssue`?`issue`:`pr`,number:rI.make(e.number),updatedAt:e.updatedAt,contentHash:t,failures:[r,...i]}))},J0=e=>e.stage===`if`?`if:`:vr(e.expression,{onNone:()=>`prompt`,onSome:e=>`prompt {{ ${e} }}`}),Y0=(e,t)=>t.failures.map(n=>new z0({repository:e,errorTag:n.errorTag,message:`Loop "${n.loop}": ${J0(n)} failed on ${t.stream===`issue`?`issue`:`pull request`} #${t.number}: ${n.message}`})),X0=e=>vr(e,{onNone:()=>[],onSome:({failures:e})=>e}),Z0=(e,t)=>e.loop===t.loop&&e.stage===t.stage,Q0=O(`PollingTriggers.logItemEvaluation`)(function*(e,t,n,r){yield*D({repository:e,item:t});for(let i of Mr(r)){let r=vr(n,{onNone:()=>[],onSome:e=>e.contentHash===i.contentHash?e.failures:[]});for(let n of i.failures){let a={repository:e,item:t,contentHash:i.contentHash,loop:n.loop,stage:n.stage,expression:C(n.expression),errorTag:n.errorTag,message:n.message};r.some(e=>Z0(e,n))?yield*A(`Loop evaluation still fails on unchanged Item content`,a):yield*t_(`Loop evaluation failed on an Item; its other Loops and the repository's other Items continue`,a)}}let i=X0(r);for(let r of X0(n))i.some(e=>Z0(e,r))||(yield*k(`Loop evaluation no longer fails on the Item`,{repository:e,item:t,loop:r.loop,stage:r.stage}))}),$0=Hw(N(fz)),e2=M({labels:iq.fields.labels}),t2=M({labels:cq.fields.labels}),n2=(e,t)=>Hw(e===`issue`?e2:t2)(t).pipe(E(({labels:e})=>$0(e.nodes.map(({name:e})=>e)))),r2=(e,t)=>new RH({repository:e.repository,itemKey:e.itemKey,message:t}),i2=e=>T(function*(){let t=S(e.goneAt);if(e.source===`issue`){let n=yield*Hw(iq)(e.payload).pipe(dg(t=>r2(e,t.message)));return{itemKey:e.itemKey,kind:`issue`,number:rI.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*$0(n.labels.nodes.map(({name:e})=>e)).pipe(dg(t=>r2(e,t.message))),conflicting:!1}}if(e.source===`pr`){let n=yield*Hw(cq)(e.payload).pipe(dg(t=>r2(e,t.message))),r=n.merged?`pr-merged`:n.state===`OPEN`&&!t?`pr-open`:`pr-closed`;return{itemKey:e.itemKey,kind:`pr`,number:rI.make(e.number),title:n.title,url:n.url,state:r,linkedPullRequests:[],labels:yield*$0(n.labels.nodes.map(({name:e})=>e)).pipe(dg(t=>r2(e,t.message))),conflicting:r===`pr-open`&&n.mergeable===`CONFLICTING`}}return yield*r2(e,`Unsupported item projection source: ${e.source}`)}),a2=O(`settledItemState`)(function*(e){yield*D({itemKey:e});let t=yield*(yield*e0).get(e);if(x(t))return y();let n=yield*$h(i2(t.value));if(Di(n))return yield*A(`Stored Item payload doesn't decode; treating the Item as open`,{itemKey:e,message:n.failure.message}),y();let{state:r}=n.success;return Cz(r)?b(r):y()}),o2=(e,t)=>e.canApprove||e.canResolveFailure&&!t,s2=O(`PollingTriggers.closeAsksOfClosedItems`)(function*(e){yield*D({repository:e});let t=yield*p1,n=(yield*t.asks()).filter(t=>tA(t.repository)===tA(e));for(let e of n){let n={askId:e.id,itemKey:e.itemKey,repository:e.repository},r=yield*a2(e.itemKey);x(r)?yield*A(`Cycle-budget Ask stays open; its Item is open or not stored`,n):(yield*t.close(e.id,`ItemClosed`))&&(yield*k(`Item is closed; its cycle-budget Ask leaves Needs attention`,{...n,itemState:r.value}))}}),c2=tT(nI).pipe(ST(aE(vT([rT(`github`),Xk,rI])))),l2=Xw(c2),u2=(e,t)=>l2([`github`,Xk.make(tA(e)),rI.make(t)]),d2={labels:[],findings:[],catalogChanged:!1,nextPollAt:y()},f2=O(`PollingTriggers.applyLabelCatalog`)(function*(e,t,n){yield*D({repository:e});let r=yield*yU,i=yield*bU,a={labelEntityTag:t,entityTagChanged:!1,confirmedLabels:y(),failures:[],nextPollAt:y()};if(Di(n)){let t=n.failure;return t._tag===`GitHubRateLimitError`?(yield*e_(`Label catalog rate-limited; kept the stored catalog and deferred label provisioning`,{repository:e,operation:t.operation,retryAt:J_(t.retryAt)}),{...a,nextPollAt:b(t.retryAt)}):(yield*t_(`Label catalog request failed; kept the stored catalog, deferred label provisioning, and evaluated items anyway`,{repository:e,...H0(t)}),{...a,failures:[new z0({repository:e,errorTag:t._tag,message:t.message})]})}let o=n.success;if(!(o instanceof RK)){let t=yield*r.get(e);return x(t)?(yield*e_(`Repository label catalog unchanged (304) but its projection is missing; refetching next cycle and deferring label provisioning`,{repository:e}),{...a,labelEntityTag:y(),entityTagChanged:!0}):(yield*A(`Repository label catalog unchanged (304)`,{repository:e}),{...a,confirmedLabels:b(t.value.labels)})}let s=o.labels.map(({name:e,color:t,description:n})=>new oU({name:e,color:b(t),description:n}));return yield*i.replace(new lU({repository:e,labels:s})),{...a,labelEntityTag:o.entityTag,entityTagChanged:!0,confirmedLabels:b(s)}}),p2=O(`PollingTriggers.synchronizeLabels`)(function*(e,t,n){yield*D({repository:e});let r=yield*Bq,i=yield*Gq,a=yield*bU,o=yield*f2(e,n,yield*$h(r.labels(e,n))),s=yield*vr(o.confirmedLabels,{onNone:()=>w(d2),onSome:n=>i.reconcile(e,t,n)}),c={labelEntityTag:s.catalogChanged?y():o.labelEntityTag,entityTagChanged:o.entityTagChanged||s.catalogChanged,failures:o.failures,preflightFindings:s.findings,nextPollAt:U0([o.nextPollAt,s.nextPollAt])};return s.catalogChanged&&(yield*a.replace(new lU({repository:e,labels:s.labels})).pipe(dg(e=>({_tag:`InterruptedRepositoryCycle`,error:e,failures:c.failures,preflightFindings:c.preflightFindings,nextPollAt:c.nextPollAt})))),c}),m2=O(`PollingTriggers.observeItem`)(function*(e,t){yield*D({repository:e,item:t.number});let n=yield*Bq,r=yield*t0,i=yield*p1,a=u2(e,t.number),o=yield*i.generation(a),s=yield*n.snapshot(e,t),c=new W1({itemKey:a,repository:e,source:H1.make(t._tag===`ChangedIssue`?`issue`:`pr`),number:rI.make(t.number),contentHash:U1.make(s.contentHash),payload:s.payload});return yield*r.upsert(c),yield*A(`Fetched changed-item snapshot`,{repository:e,item:c.number,stream:c.source,contentHash:c.contentHash}),{snapshot:s,projection:c,cycleGeneration:o}}),h2=O(`PollingTriggers.markItemGone`)(function*(e,t){return yield*D({repository:e,item:t}),yield*(yield*t0).markGone(u2(e,t),yield*B_)}),g2=(e,t,{projection:n,cycleGeneration:r})=>rA.make(JSON.stringify([e.name,tA(t.name),n.number,n.contentHash,...r===0?[]:[r]])),_2=(e,t,n)=>T(function*(){return yield*(yield*eU).evaluateBoolean(e.trigger.if,zY(e.trigger.on),{repo:BY(t),item:n})}),v2=(e,t,n)=>T(function*(){let r=yield*eU,i=BY(t);return yield*r.evaluateBooleanEach(e.trigger.if,zY(e.trigger.on),n.map(e=>({repo:i,item:e})))}),y2=O(`PollingTriggers.evaluateItem`)(function*(e,t,n){let{projection:r,cycleGeneration:i}=n;yield*D({repository:e.name,item:r.number});let a=yield*o1,o=yield*k0,s=t.filter(({loop:e})=>e.trigger.on===r.source),c=r.payload,l={repo:BY(e),item:c};if(s.length===0)return yield*A(`Item projected without any matching repository Loop`,{repository:e.name,item:r.number,stream:r.source}),{submissions:[],revokedRuns:0,failures:[]};let u=[],d=r.source===`pr`?Zk.make(yield*Hw(Qk)(c.headRefOid).pipe(dg(()=>new eK({operation:`fetch-pull-request-snapshot`,message:`The pull request payload has no valid head commit`,detail:`pull request #${r.number} has no full headRefOid`})))):j0,f=[],p=0;for(let{agent:t,loop:m,parentModel:h}of s){yield*D({loop:m.name,agent:t.name});let s=yield*$h(_2(m,e,c));if(Di(s)){f.push(new W0({loop:m.name,stage:`if`,expression:b(s.failure.source),errorTag:s.failure._tag,message:s.failure.message}));continue}if(!s.success){yield*A(`Item did not match its loop expression`,{repository:e.name,loop:m.name,agent:t.name,item:r.number});let n=yield*o.revoke(m.name,r.itemKey);p+=n.length,n.length>0&&(yield*k(`Item stopped matching; revoked its unstarted runs`,{repository:e.name,loop:m.name,agent:t.name,item:r.number,runIds:n.join(`, `)}));continue}let g=g2(m,e,n),_=yield*B_,v=yield*$h(a.renderPrompt(m,l));if(Di(v)){f.push(new W0({loop:m.name,stage:`prompt`,expression:v.failure.expression,errorTag:v.failure._tag,message:v.failure.message}));continue}let ee=yield*o.submit(I0({dedupKey:g,cycleGeneration:i,itemKey:r.itemKey,loop:m,payload:c,receivedAt:_,repository:e,revision:d,task:lF.make(v.success),agent:t,parentModel:h}));yield*k(`Submitted matching item state`,{repository:e.name,loop:m.name,agent:t.name,item:r.number,contentHash:r.contentHash,revision:d,result:ee._tag,...L0(ee)}),u.push(ee)}return{submissions:u,revokedRuns:p,failures:f}}),b2=O(`PollingTriggers.revokeMissingItem`)(function*(e,t,n,r){yield*D({repository:e.name,item:r});let i=yield*k0,a=u2(e.name,r),o=0;for(let{agent:s,loop:c}of t.filter(({loop:e})=>e.trigger.on===n)){let t=yield*i.revoke(c.name,a);o+=t.length,t.length>0&&(yield*k(`Item is gone from GitHub; revoked its unstarted runs`,{repository:e.name,loop:c.name,agent:s.name,item:r,runIds:t.join(`, `)}))}return o}),x2=T(function*(){let e=new Set,t=yield*sD({capacity:128,strategy:`dropping`}),n=yield*Lk(0),r=({repository:e,item:t})=>`${tA(e)}:${t.number}`,i=e=>vr(e,{onNone:()=>Bh,onSome:e=>Vk(n,t=>Math.max(t,K_(e)))});return{offer:O(`PollingTriggers.hint`)(function*(n,a,o=y()){yield*D({repository:n,item:a.number}),yield*i(o);let s={repository:n,item:a},c=r(s);e.has(c)?yield*A(`Self-write Hint coalesced with a pending Item fetch`,{repository:n,item:a.number}):(e.add(c),(yield*lD(t,s))?yield*A(`Self-write Hint queued`,{repository:n,item:a.number}):(e.delete(c),yield*e_(`Self-write Hint queue full; the normal poll will refresh the Item`,{repository:n,item:a.number})))},zg),take:Bg(n=>n(hD(t)).pipe(Qh(t=>zh(()=>e.delete(r(t)))))),defer:i,awaitBackoff:T(function*(){for(;;){let e=yield*Rk(n),t=yield*op;if(e<=t)return;yield*k(`GitHub request backoff delays polling and self-write Hints`,{sleepMs:e-t}),yield*_g(eo(e-t))}})}}),S2=class e extends Rr()(`@usine/orchestrator/ItemHints`){static layer=Xf(e,x2)},C2=no(10),w2={revokedRuns:0,failures:[],nextPollAt:y()},T2=O(`PollingTriggers.checkOpenIssues`)(function*(e,t){yield*D({repository:e.name});let n=yield*e0,r=yield*Bq,i=yield*n.openIssues(e.name);if(i.length===0)return yield*A(`No open issues to check against GitHub`,{repository:e.name}),w2;let a=yield*$h(r.missingIssues(e.name,i));if(Di(a)){let t=a.failure;return t._tag===`GitHubRateLimitError`?(yield*e_(`Open-issue check rate-limited; checking again in 10 minutes`,{repository:e.name,openIssues:i.length,operation:t.operation,retryAt:J_(t.retryAt)}),{...w2,nextPollAt:b(t.retryAt)}):(yield*t_(`Open-issue check failed; checking again in 10 minutes`,{repository:e.name,openIssues:i.length,...H0(t)}),{...w2,failures:[new z0({repository:e.name,errorTag:t._tag,message:t.message})]})}let o=0;for(let n of a.success){let r=yield*b2(e,t,`issue`,n),i=yield*h2(e.name,n);o+=r,yield*k(`GitHub no longer has an open issue; it leaves the open lanes`,{repository:e.name,item:n,revokedRuns:r,projectionMarkedGone:i})}return yield*A(`Checked open issues against GitHub`,{repository:e.name,openIssues:i.length,missingIssues:a.success.length}),{...w2,revokedRuns:o}}),E2=4,D2=class extends V(`@usine/orchestrator/OpenPullRequest`)({number:AK.fields.number,updatedAt:vE,baseRefName:xE(EK),mergeable:j.pipe(DT(w(`UNKNOWN`))),checksUnsettled:lT.pipe(DT(w(!0)))}){},O2=(e,t)=>t._tag===`PullRequestSnapshot`&&t.payload.state===`OPEN`?b(new D2({number:e.number,updatedAt:e.updatedAt,baseRefName:b(t.payload.baseRefName),mergeable:t.payload.mergeable,checksUnsettled:t.payload.statusCheckRollup?.state===`PENDING`||t.payload.statusCheckRollup?.state===`EXPECTED`||t.payload.statusCheckRollup===null&&t.payload.mergeStateStatus===`BLOCKED`})):y(),k2=O(`PollingTriggers.readBaseRef`)(function*(e,t,n,r){yield*D({repository:e,baseRefName:t});let i=yield*$h((yield*Bq).baseRefHead(e,t,n));if(Di(i)){let a=i.failure;return a._tag===`GitHubRateLimitError`?yield*a:(yield*e_(`Could not read the base branch head; refreshing its open pull requests in this poll`,{repository:e,baseRefName:t,pullRequests:r.join(`, `),...H0(a)}),{_tag:`Unreadable`,recorded:n})}let a=i.success;return x(n)?(yield*k(`Base branch head recorded; refreshing its open pull requests once`,{repository:e,baseRefName:t,head:a.sha,pullRequests:r.join(`, `)}),{_tag:`Moved`,head:a}):n.value.sha===a.sha?{_tag:`Unchanged`,head:a}:(yield*k(`Base branch head moved; refreshing its open pull requests`,{repository:e,baseRefName:t,previousHead:n.value.sha,head:a.sha,pullRequests:r.join(`, `)}),{_tag:`Moved`,head:a})}),A2=(e,t)=>{if(x(e.baseRefName))return b(`baseUnrecorded`);let n=t.get(e.baseRefName.value);return n?._tag===`Moved`?b(`baseMoved`):n?._tag===`Unreadable`?b(`baseUnreadable`):e.mergeable===`UNKNOWN`?b(`mergeableUnknown`):e.checksUnsettled?b(`checksUnsettled`):y()},j2=O(`PollingTriggers.openPullRequestRefresh`)(function*(e,t,n,r){if(yield*D({repository:e}),t.length===0)return{refreshed:[],baseRefHeads:[]};let i=new Map;for(let{number:e,baseRefName:n}of t){if(x(n))continue;let t=i.get(n.value)??[];t.push(e),i.set(n.value,t)}let a=new Map(yield*Ph(i,([t,r])=>k2(e,t,Sr(n.find(e=>e.baseRefName===t)),r).pipe(ng(e=>[t,e])),{concurrency:E2})),o=t.filter(({number:e})=>!r.has(e)),s=o.flatMap(e=>Mr(Or(A2(e,a),t=>({pullRequest:e,reason:t}))));if(s.length===0)yield*A(`No open pull request needs a refresh`,{repository:e,openPullRequests:t.length,baseRefReads:a.size});else{let t=da(s,({reason:e})=>e);yield*k(`Refreshing open pull requests`,{repository:e,baseRefReads:a.size,refreshed:s.length,skipped:o.length-s.length,...Object.fromEntries(Object.entries(t).map(([e,t])=>[e,t.map(({pullRequest:e})=>e.number).join(`, `)]))})}return{refreshed:s.map(({pullRequest:e})=>e),baseRefHeads:[...a.values()].flatMap(e=>e._tag===`Unreadable`?Mr(e.recorded):[e.head]).sort((e,t)=>e.baseRefName.localeCompare(t.baseRefName))}}),M2=4,N2=4,P2=z.pipe(L(`GitHubPollWatchKey`)),F2=class extends V(`@usine/orchestrator/StoredPollCursor`)({boardVersion:rT(5),openPullRequests:N(D2),baseRefHeads:N(DK).pipe(DT(w([]))),cursor:OK,labelEntityTag:yE(TK),watches:N(P2).check(XT()),failingItems:N(G0).pipe(DT(w([])))}){},I2=e=>c1.make(`github-poll:${tA(e.name)}`),L2=({loop:e})=>P2.make(JSON.stringify([e.name,e.trigger.on,e.trigger.if])),R2=(e,t)=>e.config.repos.map(n=>{let r=t.filter(({loop:e})=>e.trigger.on!==`schedule`&&BJ(e.selector,n));return{repository:n,declaredLabels:e.config.labels,loops:r,watches:r.map(L2).sort()}}),z2=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),B2=class e extends Rr()(`@usine/orchestrator/PollingTriggers`){static layer=Xf(e,T(function*(){let e=yield*d1,t=yield*p1,n=yield*Bq,r=yield*o0,i=yield*Lk(y()),a=yield*Lk(new Map),o=yield*S2,s=yield*ID(1),c=yield*Lk({instance:y(),repositories:new Set}),l=yield*Lk(new Map),u=e=>new F2({boardVersion:5,openPullRequests:[],baseRefHeads:[],cursor:OK.empty,labelEntityTag:y(),watches:e,failingItems:[]}),d=O(`PollingTriggers.readCursor`)(function*(t){yield*D({repository:t.repository.name});let n=yield*e.read(I2(t.repository),F2);return x(n)?u(t.watches):z2(n.value.watches,t.watches)?n.value:(yield*k(`Watched loops changed; re-polling the repository from scratch`,{repository:t.repository.name,previousWatches:n.value.watches.length,currentWatches:t.watches.length}),u(t.watches))}),f=O(`PollingTriggers.writeCursor`)(function*(t,n){yield*D({repository:t.repository.name}),yield*e.write(I2(t.repository),F2,n)}),p=O(`PollingTriggers.checkOpenIssuesWhenDue`)(function*(e){yield*D({repository:e.repository.name});let t=I2(e.repository),n=yield*op,r=(yield*Rk(l)).get(t);return r!==void 0&&n-r<ro(C2)?(yield*A(`Open issues were checked less than 10 minutes ago; skipped`,{repository:e.repository.name,lastCheckedAt:J_(R_(r))}),w2):(yield*Vk(l,e=>new Map(e).set(t,n)),yield*T2(e.repository,e.loops))}),m=O(`PollingTriggers.pollRepository`)(function*(e){yield*D({repository:e.repository.name});let r=(yield*t.pendingResets()).filter(({repository:t})=>tA(t)===tA(e.repository.name)),i=r.length>0?u(e.watches):yield*d(e);r.length>0&&(yield*k(`Cycle budget reset requests fresh repository polling`,{repository:e.repository.name,items:r.map(({itemKey:e})=>e)}));let a=yield*p2(e.repository.name,e.declaredLabels,i.labelEntityTag);return yield*o.defer(a.nextPollAt),yield*T(function*(){let s=yield*n.changes(e.repository.name,i.cursor);yield*o.defer(s.backoffUntil);let l=(yield*Rk(c)).repositories.has(I2(e.repository))?[]:i.failingItems,u=s._tag===`RepositoryChanges`?s.items:[],d=new Set(u.map(({number:e})=>e)),m=yield*j2(e.repository.name,i.openPullRequests,i.baseRefHeads,new Set([...d,...l.map(({number:e})=>e)])),h=new Map([...l.map(e=>[e.number,K0(e)]),...m.refreshed.map(({number:e,updatedAt:t})=>[e,new AK({number:e,updatedAt:t})])]);for(let e of u)h.set(e.number,e);s._tag===`RepositoryChanges`&&(yield*k(`Repository changed`,{repository:e.repository.name,changedItems:s.items.length,backlog:s.backlog}));let g=new Set([...m.refreshed,...l].map(({number:e})=>e).filter(e=>!d.has(e)));l.length>0&&(yield*k(`Evaluating Items whose Loops failed before this process started or the instance was reloaded`,{repository:e.repository.name,items:l.map(({number:e})=>e).join(`, `)}));let _=U0([s.nextPollAt,a.nextPollAt]);yield*A(`Refreshing detected Items and open pull requests`,{repository:e.repository.name,detection:s._tag,openPullRequests:i.openPullRequests.length,refreshedPullRequests:m.refreshed.length,items:h.size});let v=new Map(i.failingItems.map(e=>[e.number,e])),ee=yield*Ph(h.values(),t=>T(function*(){let n=yield*m2(e.repository.name,t),r=yield*y2(e.repository,e.loops,n),i=q0(t,n.projection.contentHash,r.failures);return yield*Q0(e.repository.name,t.number,Sr(v.get(t.number)),i),{_tag:`Evaluated`,item:t,observation:n,cycle:r,failing:i}}).pipe(sg(`GitHubItemNotFoundError`,n=>T(function*(){if(!g.has(t.number))return yield*n;let r=yield*b2(e.repository,e.loops,t._tag===`ChangedIssue`?`issue`:`pr`,t.number),a=yield*h2(e.repository.name,t.number);return yield*e_(`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:N2}),te=ee.flatMap(e=>e._tag===`Evaluated`?[e]:[]),ne=ee.reduce((e,t)=>e+(t._tag===`Missing`?t.revokedRuns:0),0),re=te.map(({cycle:e})=>e),ie=yield*p(e);yield*o.defer(ie.nextPollAt),yield*s2(e.repository.name);let ae=[...i.failingItems.filter(({number:e})=>!h.has(e)),...te.flatMap(({failing:e})=>Mr(e))].sort((e,t)=>e.number-t.number),oe=[...i.openPullRequests.filter(({number:e})=>!h.has(e)),...te.flatMap(({item:e,observation:t})=>Mr(O2(e,t.snapshot)))],se=m.baseRefHeads.filter(({baseRefName:e})=>oe.some(t=>Fr(t.baseRefName,e))),ce=new F2({boardVersion:5,cursor:s.cursor,labelEntityTag:a.labelEntityTag,watches:e.watches,openPullRequests:oe,baseRefHeads:se,failingItems:ae});return(s._tag===`RepositoryChanges`||h.size>0||a.entityTagChanged||!Le(se,i.baseRefHeads))&&(yield*f(e,ce)),yield*Vk(c,t=>({...t,repositories:new Set([...t.repositories,I2(e.repository)])})),yield*Ph(r,t.acknowledgeReset,{discard:!0}),{changedItems:s._tag===`RepositoryChanges`?s.items.length:0,submissions:re.flatMap(({submissions:e})=>e),revokedRuns:re.reduce((e,t)=>e+t.revokedRuns,ne+ie.revokedRuns),failures:[...a.failures,...ie.failures,...ae.flatMap(t=>Y0(e.repository.name,t))],preflightFindings:a.preflightFindings,nextPollAt:U0([_,ie.nextPollAt])}}).pipe(dg(t=>({_tag:`InterruptedRepositoryCycle`,error:t,failures:[...a.failures,...i.failingItems.flatMap(t=>Y0(e.repository.name,t))],preflightFindings:a.preflightFindings,nextPollAt:a.nextPollAt})))}),h=(yield*Cg()).pipe(_i(o1,p1,eU,Bq,e0,t0,Gq,yU,bU,k0)),g=O(`PollingTriggers.poll`)(function*(e){yield*o.awaitBackoff,yield*Vk(c,t=>Fr(t.instance,e)?t:{instance:b(e),repositories:new Set});let t=new Set((yield*r.states).filter(e=>e.paused).map(e=>e.loop));for(let n of e.loops)n.trigger.on!==`schedule`&&t.has(n.name)&&(yield*A(`Paused Loop skipped during repository polling`,{loop:n.name}));let n=R2(e,(yield*P0(e)).filter(({loop:e})=>!t.has(e.name))),s=yield*Ph(n,e=>$h(m(e)).pipe(ng(t=>({repository:e,result:t}))),{concurrency:M2}),l=[],u=[],d=[],f=[],p=yield*B_;for(let{repository:e,result:t}of s){if(Oi(t)){l.push(t.success),f.push(...t.success.preflightFindings),yield*Vk(a,t=>new Map(t).set(tA(e.repository.name),new B0({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*e_(`GitHub rate limit reached; delaying the next cycle`,{repository:e.repository.name,operation:r.operation,retryAt:J_(r.retryAt)}),d.push(b(r.retryAt)),yield*o.defer(b(r.retryAt))):(yield*t_(`Repository poll cycle failed; siblings were unaffected`,{repository:e.repository.name,...H0(r)}),u.push(new z0({repository:e.repository.name,errorTag:r._tag,message:r.message})))}let h=yield*Rk(a),g=new V0({repositoryPolls:n.flatMap(({repository:e})=>Mr(Sr(h.get(tA(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:U0([...l.map(({nextPollAt:e})=>e),...d])});return yield*zk(i,b(g)),g},Eg(h),s.withPermits(1)),_=O(`PollingTriggers.refreshHint`)(function*(e,t){yield*D({repository:t.repository,item:t.item.number}),yield*o.awaitBackoff;let n=new Set((yield*r.states).filter(e=>e.paused).map(e=>e.loop)),i=R2(e,(yield*P0(e)).filter(({loop:e})=>!n.has(e.name))).find(({repository:e})=>tA(e.name)===tA(t.repository));if(i===void 0){yield*k(`Self-write Hint ignored for an unmanaged repository`,{repository:t.repository,item:t.item.number});return}let a=yield*m2(i.repository.name,t.item),s=yield*y2(i.repository,i.loops,a);for(let e of s.failures)yield*e_(`Self-write Hint could not evaluate a Loop on the Item`,{repository:t.repository,item:t.item.number,loop:e.loop,stage:e.stage,errorTag:e.errorTag,message:e.message});yield*k(`Self-write Hint refreshed the Item`,{repository:t.repository,item:t.item.number,submissions:s.submissions.length,revokedRuns:s.revokedRuns,failures:s.failures.length})},Eg(h),(e,t,n)=>e.pipe(og(e=>T(function*(){e._tag===`GitHubRateLimitError`&&(yield*o.defer(b(e.retryAt))),yield*e_(`Self-write Hint refresh failed; the normal poll will retry`,{repository:n.repository,item:n.item.number,...H0(e)})})),s.withPermits(1))),v=(e,t,n,r)=>T(function*(){let i=Math.max(n,r),a=t;for(;;){let t=i-(yield*op);if(t<=0)return;let n=yield*vg([_g(eo(t)).pipe(ng(()=>({_tag:`Due`}))),o.take.pipe(ng(e=>({_tag:`Hint`,hint:e}))),A0(e,a).pipe(ng(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*op);s>0?yield*k(`Instance reloaded; the next poll waits for the time GitHub asked for`,{sleepMs:s}):yield*k(`Instance reloaded; polling now instead of after poll_interval`)}});return{latest:Rk(i),poll:g,run:e=>T(function*(){let t=yield*e.get,n=yield*op,r=yield*$h(g(t));if(Di(r)){let e=t.config.settings.pollInterval*1e3;yield*t_(`Poll cycle could not read Loop runtime state; retrying`,{errorTag:r.failure._tag,message:r.failure.message,operation:r.failure.operation,sleepMs:e}),yield*_g(eo(e));return}let i=r.success,a=n+t.config.settings.pollInterval*1e3,o=vr(i.nextPollAt,{onNone:()=>0,onSome:K_}),s=yield*op,c=Math.max(0,Math.max(a,o)-s);yield*k(`Poll cycle complete`,{repositories:i.repositories,changedItems:i.changedItems,submissions:i.submissions.length,revokedRuns:i.revokedRuns,failures:i.failures.length,preflightFindings:i.preflightFindings.length,sleepMs:c}),yield*v(e,t,a,o)}).pipe(Vg),hint:o.offer}})).pipe(rp(S2.layer))},V2=4,H2=6e4,U2=e=>{let t={errorTag:e._tag,message:e.message};return e._tag===`ConfigFileError`?{...t,...R0(e)}:e._tag===`ExpressionCheckError`||e._tag===`ExpressionEvaluationError`?{...t,expression:e.source}:t},W2=class extends H(`@usine/orchestrator/ScheduleAgentFailure`)(`ScheduleAgentFailure`,{loop:aA,agent:fN,message:j}){},G2=class extends H(`@usine/orchestrator/ScheduleTickFailure`)(`ScheduleTickFailure`,{loop:aA,repository:Xk,scheduledAt:_E,errorTag:z,message:j}){},K2=class extends H(`@usine/orchestrator/ScheduleCronFailure`)(`ScheduleCronFailure`,{loop:aA,cron:j,tz:j,message:j}){},q2=P([W2,K2,G2]),J2=class extends V(`@usine/orchestrator/ScheduleCycle`)({loops:R.check(HT(0)),fanout:R.check(HT(0)),submissions:N(BR),skipped:R.check(HT(0)),alreadyFired:R.check(HT(0)),failures:N(q2),nextTickAt:B(_E)}){},Y2=e=>e.loops.flatMap(t=>{let n=t.trigger;return n.on===`schedule`?[{loop:t,repositories:e.config.repos.filter(e=>BJ(t.selector,e)),trigger:n}]:[]}),X2=(e,t)=>{let n=W_(t);return n.setUTCSeconds(0,0),L_(km(e,n)?n:Mm(e,n))},Z2=(e,t)=>L_(jm(e,W_(t))),Q2=(e,t)=>vr(U_(e,t),{onNone:()=>J_(e),onSome:Y_}),$2=e=>e.length===0?y():z_(Math.min(...e.map(K_))),e4=e=>nI.make(JSON.stringify([`github`,tA(e.name)])),t4=(e,t,n)=>rA.make(JSON.stringify([e.name,tA(t.name),J_(n)])),n4=e=>({tick:{scheduledAt:J_(e.scheduledAt),scheduledAtLocal:e.scheduledAtLocal,cron:e.trigger.cron,tz:e.trigger.tz}});(class e extends Rr()(`@usine/orchestrator/ScheduleTriggers`){static layer=Xf(e,T(function*(){let e=yield*o1,t=yield*eU,n=yield*k0,r=yield*o0,i=yield*Lk(y()),a=yield*Lk({instance:y(),ticks:new Map}),o=new WeakMap,s=e=>{let t=o.get(e);if(t!==void 0)return t;let n=Om(e.cron,e.tz);return o.set(e,n),n},c=O(`ScheduleTriggers.submitTick`)(function*(r,i){yield*D({loop:r.loop.name,repository:r.repository.name,agent:r.agent.name,scheduledAt:J_(r.scheduledAt)});let a=n4(r),o={repo:BY(r.repository),item:a};if(!(yield*t.evaluateBoolean(r.trigger.if,zY(`schedule`),o)))return yield*A(`Scheduled Tick did not match its expression`,{loop:r.loop.name,repository:r.repository.name,agent:r.agent.name,scheduledAt:J_(r.scheduledAt)}),y();let s=t4(r.loop,r.repository,r.scheduledAt),c=yield*e.renderPrompt(r.loop,o),l=yield*n.submit(I0({cycleGeneration:aI.make(0),agent:r.agent,dedupKey:s,itemKey:e4(r.repository),loop:r.loop,payload:a,receivedAt:i,repository:r.repository,revision:j0,task:lF.make(c),parentModel:r.parentModel}));return yield*k(`Submitted scheduled Tick`,{loop:r.loop.name,repository:r.repository.name,agent:r.agent.name,scheduledAt:J_(r.scheduledAt),scheduledAtLocal:r.scheduledAtLocal,result:l._tag,...L0(l)}),b(l)}),l=O(`ScheduleTriggers.tick`)(function*(e){let t=yield*B_,n=new Set((yield*r.states).filter(e=>e.paused).map(e=>e.loop));for(let t of e.loops)t.trigger.on===`schedule`&&n.has(t.name)&&(yield*A(`Paused Loop skipped during schedule evaluation`,{loop:t.name}));let o=Y2(e).filter(({loop:e})=>!n.has(e.name)),l=yield*Bk(a,t=>{let n=Fr(t.instance,e)?t:{instance:b(e),ticks:new Map};return[n.ticks,n]}),u=[],d=[],f=[],p=new Map,m=[],h=0;for(let n of o){n.repositories.length===0&&(yield*e_(`Schedule loop selected no repositories`,{loop:n.loop.name}));let r=yield*qh({try:()=>{let e=s(n.trigger),r=X2(e,t);return{latest:r,latestLocal:Q2(r,n.trigger.tz),next:Z2(e,t)}},catch:e=>e}).pipe($h);if(Di(r)){yield*t_(`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 K2({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=K_(i.latest),o=l.get(n.loop.name);if(o!==void 0&&o>=a){h+=1,yield*A(`Tick already fired`,{loop:n.loop.name,scheduledAt:J_(i.latest)});continue}let c=yield*$h(N0(e,n.loop));if(Di(c)){let e=c.failure;yield*t_(`Schedule loop could not resolve its Agent`,{loop:e.loop,agent:e.agent,errorTag:e._tag,message:e.message}),d.push(new W2({loop:e.loop,agent:e.agent,message:e.message}))}else if(n.repositories.length!==0){p.set(n.loop.name,a),yield*k(`Schedule tick due`,{loop:n.loop.name,agent:c.success.agent.name,cron:n.trigger.cron,tz:n.trigger.tz,scheduledAt:J_(i.latest),scheduledAtLocal:i.latestLocal,repositories:n.repositories.length,nextTickAt:J_(i.next)});for(let e of n.repositories)u.push({agent:c.success.agent,loop:n.loop,parentModel:c.success.parentModel,repository:e,scheduledAt:i.latest,scheduledAtLocal:i.latestLocal,trigger:n.trigger})}}yield*D({schedules:o.length,fanout:u.length});let g=yield*Ph(u,e=>$h(c(e,t)).pipe(ng(t=>({candidate:e,result:t}))),{concurrency:V2}),_=[],v=[],ee=new Set,te=new Set,ne=0;for(let{candidate:e,result:t}of g){if(Oi(t)){S(t.success)?(_.push(t.success.value),ee.add(e.loop.name)):ne+=1;continue}let n=t.failure;te.add(e.loop.name),yield*t_(`Scheduled Tick failed; sibling fanout was unaffected`,{loop:e.loop.name,repository:e.repository.name,agent:e.agent.name,scheduledAt:J_(e.scheduledAt),...U2(n)}),v.push(new G2({loop:e.loop.name,repository:e.repository.name,scheduledAt:e.scheduledAt,errorTag:n._tag,message:n.message}))}yield*Vk(a,e=>{let t=new Map(e.ticks);for(let[e,n]of p)ee.has(e)&&!te.has(e)&&t.set(e,n);return{...e,ticks:t}});let re=new J2({loops:o.length,fanout:u.length,submissions:_,skipped:ne,alreadyFired:h,failures:[...d,...f,...v],nextTickAt:$2(m)});return yield*zk(i,b(re)),re}),u=(e,t,n)=>yg(_g(eo(n)),A0(e,t).pipe(Zh(k(`Instance reloaded; evaluating schedules now instead of after the sleep`))));return{latest:Rk(i),run:e=>T(function*(){let t=yield*e.get,n=yield*$h(l(t));if(Di(n)){yield*t_(`Schedule cycle could not read Loop runtime state; retrying`,{errorTag:n.failure._tag,message:n.failure.message,operation:n.failure.operation,sleepMs:H2}),yield*u(e,t,H2);return}let r=n.success,i=yield*op,a=vr(r.nextTickAt,{onNone:()=>i+H2,onSome:K_}),o=Math.min(H2,Math.max(0,a-i)),s={loops:r.loops,fanout:r.fanout,submissions:r.submissions.length,skipped:r.skipped,alreadyFired:r.alreadyFired,failures:r.failures.length,nextTickAt:vr(r.nextTickAt,{onNone:()=>`none`,onSome:J_}),sleepMs:o};r.fanout===0&&r.failures.length===0?yield*A(`Schedule cycle complete`,s):yield*k(`Schedule cycle complete`,s),yield*u(e,t,o)}).pipe(Vg),tick:l}}))});var r4=class extends H(`@usine/orchestrator/ApprovalNeed`)(`ApprovalNeed`,{id:j,repository:Xk,runId:HA,loop:aA,item:I(jH)}){},i4=class extends H(`@usine/orchestrator/RunFailureNeed`)(`RunFailureNeed`,{id:j,repository:Xk,runId:HA,loop:aA,failure:Iz}){},a4=class extends H(`@usine/orchestrator/PollFailureNeed`)(`PollFailureNeed`,{id:j,failure:z0}){},o4=class extends H(`@usine/orchestrator/PreflightFindingNeed`)(`PreflightFindingNeed`,{id:j,finding:Hq}){},s4=class extends H(`@usine/orchestrator/BoardProjectionNeed`)(`BoardProjectionNeed`,{id:j,failure:RH}){},c4=class extends H(`@usine/orchestrator/ScheduleFailureNeed`)(`ScheduleFailureNeed`,{id:j,failure:q2}){},l4=class extends H(`@usine/orchestrator/ConfigFileNeed`)(`ConfigFileNeed`,{id:j,kind:F([`loop`,`agent`]),error:rU}){},u4=class extends H(`@usine/orchestrator/UnconfiguredWorkerNeed`)(`UnconfiguredWorkerNeed`,M({id:j,worker:EN,attempts:R.check(HT(1)),running:R.check(HT(0))}).check(NT(({attempts:e,running:t})=>t<=e,{message:`Expected no more open attempts than attempts`}))){},d4=class extends H(`@usine/orchestrator/UnconfirmedStopNeed`)(`UnconfirmedStopNeed`,{id:j,repository:Xk,runId:HA,loop:aA,attemptNumber:cF,worker:EN}){},f4=class extends H(`@usine/orchestrator/UnresponsiveWorkerNeed`)(`UnresponsiveWorkerNeed`,{id:j,worker:EN,lastAnsweredAt:j,attempts:N(M({attemptId:sF,attemptNumber:cF,runId:HA,repository:Xk,loop:aA})).check(GT(1))}){},p4=P([class extends H(`CycleBudgetNeed`)(`CycleBudgetNeed`,{id:j,ask:uI,itemLabel:j,itemUrl:I(j)}){},r4,s4,i4,a4,o4,c4,l4,u4,d4,f4,class extends H(`@usine/orchestrator/WorkerPreflightNeed`)(`WorkerPreflightNeed`,{id:j,worker:EN,message:j}){}]),m4=F([`clear`,`active`,`needs-you`]),h4=class extends V(`@usine/orchestrator/ProjectView`)({repository:Xk,status:m4,runs:N(CH),board:zH,labels:N(BH),preflightFindings:N(Hq)}){},g4=class extends V(`@usine/orchestrator/LoopView`)({name:aA,trigger:j,agent:fN,paused:lT}){},_4=class extends H(`@usine/orchestrator/ReadyOverview`)(`Ready`,{projects:N(h4),loops:N(g4),needsYou:N(p4),dismissedNeeds:N(p4).pipe(TT(w([])))}){},v4=class extends H(`@usine/orchestrator/NeedsSetupOverview`)(`NeedsSetup`,{errorTag:z,projects:N(h4),loops:N(g4),needsYou:N(p4),dismissedNeeds:N(p4).pipe(TT(w([])))}){},y4=P([_4,v4]),b4=500,x4=500,S4=e=>kk(e,{GitHubPushFailure:({message:e})=>new Oz({message:e}),InfraFailure:({message:e})=>new kz({message:e}),DefectFailure:({message:e})=>new Az({message:e}),AgentFailure:({message:e})=>new jz({message:e}),BlockedFailure:({message:e})=>new Mz({message:e}),QuestionFailure:({question:e})=>new Nz({question:e}),RunawayFailure:({ceiling:e})=>new Pz({ceiling:e}),ChildSessionBudgetFailure:({attemptedChildren:e,maxChildren:t})=>new Fz({attemptedChildren:e,maxChildren:t})}),C4=e=>kk(e,{Succeeded:()=>new Lz,Failed:({failure:e})=>new Rz({failure:S4(e)}),Canceled:()=>new zz}),w4=e=>{switch(e.kind){case`local`:return new Vz;case`ssh`:return vr(e.provisioner,{onSome:({provider:e})=>new Uz({provider:e}),onNone:()=>new Hz({destination:yr(e.destination,()=>jN.make(e.name)),port:C(e.port)})});case`exe.dev`:return new Hz({destination:jN.make(`${e.name}.exe.xyz`),port:null});case`cloudflare`:return new Wz}},T4=e=>new Map(e.map(e=>[e.name,w4(e)])),E4=(e,t)=>new Kz({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:J_(e.startedAt),outcome:vr(e.outcome,{onNone:()=>null,onSome:C4}),endedAt:vr(e.endedAt,{onNone:()=>null,onSome:J_}),salvage:C(e.salvage),start:C(e.start),reattachedAt:vr(e.reattachedAt,{onNone:()=>null,onSome:J_}),outOfMemory:C(e.outOfMemory)});O(`Operator.readUnrecordedEnds`)(function*(e,t){let n=yield*Ph(t.attempts.filter(e=>S(e.outcome)&&x(e.endedAt)),t=>e.transcript(new TB({attemptId:t.id,before:y(),limit:1})).pipe(ng(e=>[t.id,e.at(-1)?.receivedAt])),{concurrency:4});return new Map(n.flatMap(([e,t])=>t===void 0?[]:[[e,t]]))});var D4=O(`Operator.readRunningEvents`)(function*(e,t){let n=t.flatMap(({run:e})=>e.state._tag===`Running`?[e.id]:[]),r=yield*e.events(n);return yield*A(`Read the Events of the running Runs`,{running:n.length,events:r.length}),new Map(r.map(({runId:e,event:t})=>[e,t]))}),O4=(e,t,n)=>{let r=OA(e.run.state),i=C(e.step.result),a=i?.facts.find(e=>e._tag===`PullRequest`);return new CH({id:e.run.id,itemKey:e.itemKey,loop:e.run.loop,repository:e.repository,agent:e.agent.name,agentBrain:e.agent.brain,state:e.run.state._tag,loopPaused:t.has(e.run.loop),openedAt:J_(e.run.openedAt),closedAt:vr(e.closedAt,{onNone:()=>null,onSome:J_}),task:e.task,attempts:e.attempts.map(e=>E4(e,n)),approval:vr(e.approval,{onNone:()=>null,onSome:({approvedAt:e,source:t})=>new SH({approvedAt:J_(e),source:C(t)})}),runAgain:C(e.runAgain),resultMessage:i?.message??null,pullRequestUrl:a?.url.toString()??null,...r,canResolveFailure:r.canResolveFailure&&!Fr(e.resolvedFailureAttemptId,e.attempts.at(-1)?.id)})},k4=e=>kk(e,{Started:e=>e,SessionEvent:e=>e,Final:e=>e,Failed:({failure:e})=>new EB({failure:S4(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}),A4=e=>{let t={sequence:e.sequence,attemptId:e.attemptId,receivedAt:J_(e.receivedAt),direction:e.direction,payload:k4(e.envelope.payload)};return e.envelope._tag===`InboundEnvelope`&&`target`in e.envelope?new OB({...t,target:e.envelope.target,operator:e.envelope.operator}):new OB(t)},j4=e=>[...e].sort((e,t)=>e.sequence-t.sequence).map(A4),M4=O(`Operator.readTranscriptPage`)(function*(e,t,n){yield*D({attemptId:t,before:C(n)});let r=yield*e.transcript(new TB({attemptId:t,before:n,limit:501})),i=r.length>b4,a=i?r.slice(1):r,o=a[0];return yield*A(`Read operator transcript page`,{attemptId:t,before:C(n),returned:a.length,hasEarlier:i}),{events:j4(a),earlier:i&&o!==void 0?[new kB({attemptId:t,before:o.sequence})]:[]}});O(`Operator.readTranscript`)(function*(e,t,n){yield*D({runId:t.run.id,request:n._tag});let r=yield*kk(n,{ColdTranscriptRequest:()=>Ph(t.attempts,t=>M4(e,t.id,y()),{concurrency:4}).pipe(ng(e=>({events:e.flatMap(({events:e})=>e).sort((e,t)=>e.sequence-t.sequence),earlier:e.flatMap(({earlier:e})=>e)}))),TailTranscriptRequest:({after:n})=>Ph(t.attempts,t=>e.transcript(new wB({attemptId:t.id,after:n,limit:x4})),{concurrency:4}).pipe(ng(e=>({events:j4(e.flat()).slice(0,x4),earlier:[]}))),EarlierTranscriptRequest:({attemptId:n,before:r})=>t.attempts.some(e=>e.id===n)?M4(e,n,b(r)):new NB({runId:t.run.id,attemptId:n})});return yield*A(`Read operator transcript`,{runId:t.run.id,request:n._tag,events:r.events.length,earlier:r.earlier.length}),r});var N4=Ww(rE),P4=e=>new jH({itemKey:e.itemKey,kind:e.kind,number:e.number,title:e.title,url:e.url,state:e.state}),F4=(e,t,n,r,i,a)=>{let o=da(n,({itemKey:e})=>e),s=t.map(e=>({item:e,runs:o[e.itemKey]??[],related:new Set})),c=`/${tA(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=N4(n);if(x(t)||t.value.protocol!==`https:`||t.value.host!==`github.com`)continue;let r=l.get(t.value.pathname.toLowerCase());r!==void 0&&(e.related.add(r),r.related.add(e))}}let d=new Set,f=[];for(let e of s){if(d.has(e))continue;d.add(e);let t=[e];for(let e of t)for(let n of e.related)d.has(n)||(d.add(n),t.push(n));let n=ia(t,({item:e},{item:t})=>(e.kind===t.kind?0:e.kind===`issue`?-1:1)||lr(e.number,t.number)),r=n[0],o=t.flatMap(({item:e,runs:t})=>t.map(t=>({item:e,run:t}))).sort(({run:e},{run:t})=>t.openedAt.localeCompare(e.openedAt)||t.id.localeCompare(e.id)),s=o.find(({run:e})=>e.canCancel),c=t.filter(({item:e})=>e.kind===`pr`).sort(({item:e},{item:t})=>Number(t.state===`pr-open`)-Number(e.state===`pr-open`)||t.number-e.number),l=s?.item??c[0]?.item??r.item,[p=null]=c.flatMap(({item:{number:e,url:t,state:n}})=>n===`pr-open`||n===`pr-merged`?[new MH({number:e,url:t,state:n})]:[]),m=o.find(({item:e,run:t})=>o2(t,Cz(e.state)))??s??o[0],h=o.map(({run:e})=>e).reverse(),g=new NH({...P4(l),title:r.item.title,labels:l.labels,items:n.map(({item:e})=>P4(e)),pullRequest:p,runs:h,run:m?.run??null,needsYou:o.some(({item:e,run:t})=>o2(t,Cz(e.state)))||t.some(({item:e})=>u.has(e.itemKey)),conflicting:l.conflicting,loops:[...new Set(n.flatMap(({item:e})=>i.get(e.itemKey)??[]))],usage:gH(h,a)});f.push({view:g,running:s?.run.state===`Running`?s.run:void 0})}return f},I4=e=>e.flatMap(e=>`label`in e?[e.label]:[]),L4=e=>e.flatMap(e=>`state`in e?[e.state]:[]),R4=e=>[...e].sort((e,t)=>e.localeCompare(t)).map(e=>fz.make(e)).map(e=>({lane:new Ez({name:yz.make(e),sources:[new wz({label:e})]}),origin:`proposed`})),z4=(e,t)=>e.lanes.length>0?e.lanes.map(e=>({lane:e,origin:`authored`})):R4(t),B4=e=>kH.make(`${e.origin}:${e.lane.name}`),V4=(e,t)=>{let n=new Set(e.labels.map(pz));return t.find(({lane:e})=>I4(e.sources).some(e=>n.has(pz(e))))},H4=(e,t)=>t.find(({lane:t})=>L4(t.sources).includes(e.state)),U4=(e,t)=>Cz(e.state)?H4(e,t):V4(e,t)??H4(e,t),W4=O(`Board.runningLane`)(function*(e,t,n,r,i){let a={repository:e.name,itemKey:t.itemKey,runId:n.id,loop:n.loop};if(yield*D(a),Cz(t.state))return;let o=V4(t,r);if(o!==void 0)return yield*A(`Placing the running card in the lane its Item's labels match`,{...a,lane:o.lane.name}),o;let s=i.get(n.id);if(s===void 0){yield*A(`No Event read for the card's running Run; placing it by its Item's state`,a);return}let c=yield*n2(t.kind,s.payload).pipe(ng(b),og(e=>e_(`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(rg(y()))));if(x(c))return;let l=V4({labels:c.value},r);return yield*A(l===void 0?`No lane label when the card's running Run was triggered; placing it by its Item's state`:`Keeping the card in the lane its running Run was triggered from`,{...a,lane:l?.lane.name??`none`}),l}),G4=O(`Board.project`)((e,t,n,r,i=[],a=new Map,o=new Map,s=new Map)=>T(function*(){yield*D({repository:e.name});let c=yield*Ph(n,e=>i2(e).pipe($h)),l=[],u=[];for(let e of c)Oi(e)?l.push(e.success):(u.push(e.failure),yield*t_(`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=z4(e,t),f=F4(e.name,l,r,i,a,o);yield*A(`Projected Task cards from linked Items`,{repository:e.name,items:l.length,tasks:f.length,runs:r.length,watchedTasks:f.filter(({view:e})=>e.loops.length>0).length,runningTasks:f.filter(({running:e})=>e!==void 0).length});let p=new Map;for(let e of d)p.set(B4(e),[]);let m=[];for(let{view:t,running:n}of f){let r=(n===void 0?void 0:yield*W4(e,t,n,d,s))??U4(t,d);r===void 0?m.push(t):p.get(B4(r))?.push(t)}let h=e=>e.sort((e,t)=>t.number-e.number);return new zH({failures:u,lanes:[...d.map(e=>{let t=I4(e.lane.sources),n={id:B4(e),name:e.lane.name,sources:e.lane.sources,origin:e.origin,items:h(p.get(B4(e))??[])};return e.origin===`authored`&&t.length>0?new FH({...n,origin:e.origin,labels:t}):new IH(n)}),new IH({id:kH.make(`fallback:unmapped`),name:yz.make(`Unmapped`),sources:[],origin:`fallback`,items:h(m)})]})})),K4=class e extends Rr()(`@usine/orchestrator/LoopMatches`){static layer=Xf(e,T(function*(){let e=yield*eU;return{matching:O(`LoopMatches.matching`)(function*(e,t,n){yield*D({repository:t.name,items:n.length});let r=e.loops.filter(e=>e.trigger.on!==`schedule`&&BJ(e.selector,t)),i=n.filter(({goneAt:e})=>x(e)),a=new Map,o=0;for(let e of r){let n=i.filter(({source:t})=>t===e.trigger.on);if(n.length===0)continue;let r=yield*$h(v2(e,t,n.map(({payload:e})=>e)));if(Di(r)){o+=n.length,yield*A(`Loop trigger could not be checked; it matches no stored Item`,{repository:t.name,loop:e.name,items:n.length,errorTag:r.failure._tag,message:r.failure.message});continue}let s=new Set;for(let[i,a]of aa(n,r.success))Oi(a)?a.success&&s.add(i):(o+=1,yield*A(`Loop trigger could not be evaluated on a stored Item`,{repository:t.name,loop:e.name,item:i.number,errorTag:a.failure._tag,message:a.failure.message}));a.set(e,s)}let s=[];for(let e of i)for(let t of r)a.get(t)?.has(e)===!0&&s.push({loop:t,item:e});return yield*A(`Matched Loop triggers against stored Items`,{repository:t.name,loops:r.length,items:n.length,matches:s.length,failures:o}),s},kg(eU,e))}}))},q4=10,J4=class extends H(`@usine/github/LabelAdded`)(`LabelAdded`,{at:_E,label:IK}){},Y4=class extends H(`@usine/github/LabelRemoved`)(`LabelRemoved`,{at:_E,label:IK}){},X4=class extends H(`@usine/github/Commented`)(`Commented`,{at:_E,url:z}){},Z4=F([`APPROVED`,`CHANGES_REQUESTED`,`COMMENTED`,`DISMISSED`]),Q4=class extends H(`@usine/github/Reviewed`)(`Reviewed`,{at:_E,url:z,state:Z4}){};P([J4,Y4,X4,Q4]);var $4=`
|
|
285
|
-
__typename
|
|
286
|
-
... on LabeledEvent { createdAt actor { __typename login } label { name color description } }
|
|
287
|
-
... on UnlabeledEvent { createdAt actor { __typename login } label { name color description } }
|
|
288
|
-
... on IssueComment { createdAt url author { __typename login } }`,e3=`
|
|
289
|
-
query UsineItemTimeline($owner: String!, $name: String!, $number: Int!, $since: DateTime!, $after: String) {
|
|
290
|
-
repository(owner: $owner, name: $name) {
|
|
291
|
-
issueOrPullRequest(number: $number) {
|
|
292
|
-
... on Issue {
|
|
293
|
-
timelineItems(first: 100, after: $after, since: $since, itemTypes: [LABELED_EVENT, UNLABELED_EVENT, ISSUE_COMMENT]) {
|
|
294
|
-
pageInfo { hasNextPage endCursor }
|
|
295
|
-
nodes {${$4}
|
|
296
|
-
}
|
|
297
|
-
}
|
|
298
|
-
}
|
|
299
|
-
... on PullRequest {
|
|
300
|
-
timelineItems(first: 100, after: $after, since: $since, itemTypes: [LABELED_EVENT, UNLABELED_EVENT, ISSUE_COMMENT, PULL_REQUEST_REVIEW]) {
|
|
301
|
-
pageInfo { hasNextPage endCursor }
|
|
302
|
-
nodes {${$4}
|
|
303
|
-
... on PullRequestReview { createdAt submittedAt url state author { __typename login } }
|
|
304
|
-
}
|
|
305
|
-
}
|
|
306
|
-
}
|
|
307
|
-
}
|
|
308
|
-
}
|
|
309
|
-
}
|
|
310
|
-
`,t3=I(M({__typename:j,login:j})),n3=M({name:PK,color:FK,description:I(j)}),r3=e=>M({__typename:rT(e),createdAt:vE,actor:t3,label:n3}),i3=P([r3(`LabeledEvent`),r3(`UnlabeledEvent`),M({__typename:rT(`IssueComment`),createdAt:vE,url:z,author:t3}),M({__typename:rT(`PullRequestReview`),createdAt:vE,submittedAt:I(vE),url:z,state:F([...Z4.literals,`PENDING`]),author:t3})]),a3=M({repository:yE(M({issueOrPullRequest:yE(M({timelineItems:M({pageInfo:M({hasNextPage:lT,endCursor:I(j)}),nodes:N(I(i3))})}))}))}),o3=(e,t)=>{let n=t=>t!==null&&t.__typename===`Bot`&&t.login===e,r=e=>new IK({name:e.name,color:e.color,description:Sr(e.description)});switch(t.__typename){case`LabeledEvent`:return n(t.actor)?[new J4({at:t.createdAt,label:r(t.label)})]:[];case`UnlabeledEvent`:return n(t.actor)?[new Y4({at:t.createdAt,label:r(t.label)})]:[];case`IssueComment`:return n(t.author)?[new X4({at:t.createdAt,url:t.url})]:[];case`PullRequestReview`:{let e=t.state;return!n(t.author)||e===`PENDING`?[]:[new Q4({at:t.submittedAt??t.createdAt,url:t.url,state:e})]}}},s3=class e extends Rr()(`@usine/github/GitHubItemHistory`){static layer=Xf(e,T(function*(){let e=yield*wK,t=yield*LW,n=O(`GitHubItemHistory.timelinePage`)(function*(n,r,i,a){let o=yield*e.installationToken(),{name:s,owner:c}=eA(n),l=yield*JK(t,o,`fetch-item-timeline`,e3,{owner:c,name:s,number:r,since:i,after:a},a3);if(x(l.repository))return yield*cK(`fetch-item-timeline`,`repository "${n}" is null: deleted, renamed, or no longer accessible`);let u=l.repository.value.issueOrPullRequest;if(x(u))return yield*new tK({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*cK(`fetch-item-timeline`,`GitHub returned hasNextPage for the timeline without an endCursor`):{nodes:f,next:b(d.endCursor)}:{nodes:f,next:y()}});return{appChanges:O(`GitHubItemHistory.appChanges`)(function*(t,r,i){yield*D({repository:t,item:r});let{appSlug:a}=yield*e.installation(),o=J_(i),s=[],c=y(),l=0;do{let e=yield*n(t,r,o,C(c));s.push(...e.nodes),c=e.next,l+=1}while(S(c)&&l<q4);if(S(c))return yield*cK(`fetch-item-timeline`,`the timeline of ${t}#${r} since ${o} has more than ${q4} pages`);let u=s.flatMap(e=>e===null?[]:o3(a,e));return yield*A(`Read the App's changes from an Item timeline`,{repository:t,item:r,since:o,pages:l,timelineItems:s.length,appChanges:u.length}),u})}}))},c3=class extends H(`@usine/orchestrator/LabelAddedView`)(`LabelAdded`,{at:j,label:BH}){},l3=class extends H(`@usine/orchestrator/LabelRemovedView`)(`LabelRemoved`,{at:j,label:BH}){},u3=class extends H(`@usine/orchestrator/CommentedView`)(`Commented`,{at:j,url:j}){},d3=class extends H(`@usine/orchestrator/ReviewedView`)(`Reviewed`,{at:j,url:j,state:Z4}){},f3=class extends H(`@usine/orchestrator/BoardMovedView`)(`BoardMoved`,{at:j,fromLane:yz,toLane:yz}){},p3=P([c3,l3,u3,d3,f3]),m3=class extends V(`@usine/orchestrator/AttemptGitHubChangesView`)({attemptId:sF,changes:N(p3)}){},h3=class extends V(`@usine/orchestrator/RunGitHubChangesView`)({attempts:N(m3)}){},g3=1e3,_3=6e4,v3=1e3,y3=1e4,b3=(e,t)=>{let n=new Map,r=[];for(let i of t){let[t,...a]=e.filter(e=>SF(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}},x3=e=>t=>{let n=K_(t.at),r=n-v3,i=K_(e.at),a=pz(e.label.name);return r-r%1e3<=i&&i<=n+y3&&(e._tag===`LabelAdded`?t.added:t.removed).some(e=>pz(e)===a)},S3=(e,t)=>{let n=new Set,r=[];for(let i of t){let t=i._tag===`LabelAdded`||i._tag===`LabelRemoved`?e.find(x3(i)):void 0;t===void 0?r.push(i):n.add(t)}return{moves:e.filter(e=>n.has(e)),rest:r}},C3=e=>new BH({name:fz.make(e.name),color:e.color,description:C(e.description)}),w3=e=>kk(e,{LabelAdded:({at:e,label:t})=>new c3({at:J_(e),label:C3(t)}),LabelRemoved:({at:e,label:t})=>new l3({at:J_(e),label:C3(t)}),Commented:({at:e,url:t})=>new u3({at:J_(e),url:t}),Reviewed:({at:e,url:t,state:n})=>new d3({at:J_(e),url:t,state:n})}),T3=e=>new f3({at:J_(e.at),fromLane:yz.make(e.fromLane),toLane:yz.make(e.toLane)}),E3=T(function*(){let e=yield*aH,t=yield*s3,n=yield*m0,r=yield*Lk(new Map),i=O(`RunGitHubChanges.windowFor`)(function*(t){let n=yF(t);if(S(n))return n;let[r]=yield*e.transcript(new TB({attemptId:t.id,before:y(),limit:1}));return r===void 0?(yield*k(`An ended Attempt has neither an end time nor a transcript; no GitHub change is placed in it`,{attemptId:t.id}),y()):b(new vF({attemptId:t.id,startedAt:t.startedAt,endedAt:b(r.receivedAt)}))});return{read:O(`RunGitHubChanges.read`)(function*(a){yield*D({runId:a});let o=yield*e.inspect(a),s=Gw(c2)(o.itemKey);if(x(s))return yield*A(`The Run has no GitHub Item, so it has no GitHub changes`,{runId:a}),new h3({attempts:[]});let[,,c]=s.value,l=o.repository;yield*D({repository:l,item:c});let u=e=>new h3({attempts:o.attempts.map(({id:t})=>new m3({attemptId:t,changes:e.get(t)??[]}))}),d=yield*Rk(r),f=o.attempts.filter(({id:e})=>!d.has(e));if(f.length===0)return yield*A(`Served the Run's GitHub changes from the Attempt cache`,{runId:a,attempts:o.attempts.length}),u(d);let p=yield*e.forItems([o.itemKey]),m=(yield*Ph([...new Map([...p.flatMap(({attempts:e})=>e),...o.attempts].map(e=>[e.id,e])).values()],i)).flatMap(Mr),h=yield*op,g=new Map,_=[],v=f.flatMap(e=>{let t=m.find(({attemptId:t})=>t===e.id);return t===void 0?(g.set(e.id,[]),_.push(e.id),[]):[t]});if(v.length>0){let e=Math.min(...v.map(({startedAt:e})=>K_(e))),r=R_(e-e%1e3),[i,s]=yield*Nh([t.appChanges(l,c,r),n.onItem(o.itemKey,q_(r,{milliseconds:y3}))],{concurrency:`unbounded`}),{moves:u,rest:d}=S3(s,i),{attributed:f,ambiguous:p}=b3(m,d);p.length>0&&(yield*k(`Left out GitHub changes that overlapping Attempts on the Item could each have made`,{runId:a,repository:l,item:c,changes:p.length,at:p.map(({at:e})=>J_(e)).join(`, `)}));for(let e of v){let t=[...(f.get(e.attemptId)??[]).map(e=>({at:K_(e.at),view:w3(e)})),...u.flatMap(t=>{let n=K_(t.at);return K_(e.startedAt)<=n&&vr(e.endedAt,{onNone:()=>!0,onSome:e=>n<=K_(e)})?[{at:n,view:T3(t)}]:[]})];g.set(e.attemptId,t.sort((e,t)=>e.at-t.at).map(({view:e})=>e)),S(e.endedAt)&&h-K_(e.endedAt.value)>=_3&&_.push(e.attemptId)}yield*k(`Read the App's GitHub changes on a Run's Item`,{runId:a,repository:l,item:c,since:J_(r),appChanges:i.length,boardMoves:s.length,boardMoveChanges:i.length-d.length,placed:v.reduce((e,{attemptId:t})=>e+(f.get(t)?.length??0),0),cachedAttempts:_.length})}let ee=yield*Hk(r,e=>{let t=new Map(e);for(let e of _)t.set(e,g.get(e)??[]);for(let e of[...t.keys()].slice(0,Math.max(0,t.size-g3)))t.delete(e);return t});return u(new Map([...ee,...g]))})}});(class e extends Rr()(`@usine/orchestrator/RunGitHubChanges`){static layer=Xf(e,E3)});var D3=500,O3=class extends V(`@usine/orchestrator/TaskItemView`)({...jH.fields,labels:N(fz),conflicting:lT}){},k3=class extends V(`@usine/orchestrator/TaskLaneView`)({id:kH,name:yz}){},A3=class extends V(`@usine/orchestrator/TaskCommentView`)({runId:HA,kind:bN,url:j,postedAt:I(j),attemptEndedAt:I(j)}){},j3=class extends V(`@usine/orchestrator/TaskView`)({repository:Xk,number:rI,title:j,current:nI,lane:k3,needsYou:lT,items:yT(O3),runs:N(CH),comments:N(A3)}){},M3=vr({onNone:()=>null,onSome:J_}),N3=e=>{let t=(t,n)=>new A3({runId:e.run.id,kind:t.kind,url:t.url.toString(),postedAt:M3(t.at),attemptEndedAt:M3(n)}),n=ra(e.attempts,e=>Ir(e.outcome,({_tag:e})=>e===`Succeeded`)).pipe(kr(({endedAt:e})=>e)),r=vr(e.step.result,{onNone:()=>[],onSome:({facts:e})=>e.flatMap(e=>e._tag===`Comment`?[t(e,n)]:[])}),i=e.attempts.flatMap(e=>e.comments.map(n=>t(n,e.endedAt))),a=({postedAt:e,attemptEndedAt:t})=>e??t??``;return va([...r,...i].sort((e,t)=>a(t).localeCompare(a(e))),(e,t)=>e.url===t.url)},P3=T(function*(){let e=yield*aH,t=yield*o0,n=yield*e0,r=yield*yU,i=yield*p1;return{read:O(`TaskReader.read`)(function*(a,o,s){yield*D({repository:o,item:s});let c=a.config.repos.find(({name:e})=>tA(e)===tA(o));if(c===void 0)return yield*k(`Task read refused; the repository is not a registered Project`,{repository:o,item:s}),yield*new VH({repository:o});let[l,u,d,f]=yield*Nh([n.list(c.name,{limit:D3}),r.get(c.name),t.states,i.asks()],{concurrency:`unbounded`}),p=yield*e.forItems(l.map(({itemKey:e})=>e)),m=yield*D4(e,p),h=new Set(d.filter(e=>e.paused).map(e=>e.loop)),g=T4(a.config.workers),_=(yield*G4(c,vr(u,{onNone:()=>[],onSome:({labels:e})=>e.map(({name:e})=>e)}),l,p.map(e=>O4(e,h,g)),f.map(({itemKey:e})=>e),new Map,new Map,m)).lanes.flatMap(e=>e.items.map(t=>({lane:e,task:t}))).find(({task:e})=>e.items.some(e=>e.number===s));if(_===void 0)return yield*k(`Task read found no Task; the Item is not among the Project's newest Board Items`,{repository:c.name,item:s,window:D3}),yield*new HH({repository:c.name,item:s});let{lane:v,task:ee}=_,te=new Set(ee.items.map(({itemKey:e})=>e)),ne=yield*Ph(l.filter(({itemKey:e})=>te.has(e)),e=>i2(e).pipe($h)),re=new Map;for(let e of ne){if(Di(e)){yield*t_(`Task Item could not be projected; the other Items are shown`,{repository:c.name,itemKey:e.failure.itemKey,message:e.failure.message});continue}let{itemKey:t,kind:n,number:r,title:i,url:a,state:o,labels:s,conflicting:l}=e.success;re.set(t,new O3({itemKey:t,kind:n,number:r,title:i,url:a,state:o,labels:s,conflicting:l}))}let[ie,...ae]=ee.items.flatMap(({itemKey:e})=>{let t=re.get(e);return t===void 0?[]:[t]});if(ie===void 0)return yield*new HH({repository:c.name,item:s});let oe=new Set(ee.runs.map(({id:e})=>e)),se=p.filter(({run:e})=>oe.has(e.id)).sort((e,t)=>K_(t.run.openedAt)-K_(e.run.openedAt)||t.run.id.localeCompare(e.run.id)).flatMap(N3),ce=new j3({repository:c.name,number:ie.number,title:ee.title,current:ee.itemKey,lane:new k3({id:v.id,name:v.name}),needsYou:ee.needsYou,items:[ie,...ae],runs:[...ee.runs].reverse(),comments:se});return yield*A(`Read a Task`,{repository:c.name,item:s,origin:ce.number,lane:v.name,items:ce.items.length,runs:ce.runs.length,comments:se.length}),ce})}});(class e extends Rr()(`@usine/orchestrator/TaskReader`){static layer=Xf(e,P3)});var F3=F([`binary`,`version`,`login`]),I3=class extends NE(`HarnessUnavailableError`)(`HarnessUnavailableError`,{harness:lN,capability:F3,message:z}){};P([class extends H(`HarnessReady`)(`HarnessReady`,{harness:lN}){},I3]),Vw(I3),fr(cr,({harness:e})=>e);var L3=class e extends Rr()(`@usine/orchestrator/WorkerStatus`){static idle=Jf(e)({slots:w([]),queue:w([]),preflights:w([]),unavailable:w([]),machines:w([]),provisioning:w([])})},R3=class extends V(`@usine/orchestrator/LoopSelectorView`)({repos:I(N(Xk)),tags:I(N(nJ))}){},z3=class extends V(`@usine/orchestrator/LoopFileView`)({name:aA,file:tU,stream:F([`issue`,`pr`,`schedule`]),condition:ZH,cron:I(VJ),timeZone:I(HJ),selector:I(R3),repositories:N(Xk),approval:sA,maxCycles:iI,permissions:lA,priority:I(XJ),step:wN,agent:fN,prompt:YJ,paused:lT,undeclaredLabels:N(fz)}){},B3=class extends V(`@usine/orchestrator/QuarantinedLoopView`)({name:z,file:tU,error:rU}){},V3=class extends V(`@usine/orchestrator/AgentFileView`)({name:fN,file:tU,harness:lN,model:cN,effort:uN,parentModel:I(cN),parentEffort:I(uN),resolvedParentModel:I(cN),resolvedParentEffort:uN,persona:pN,loops:N(aA)}){},H3=class extends V(`@usine/orchestrator/InvalidAgentView`)({name:z,file:tU,error:rU}){},U3=class extends V(`@usine/orchestrator/GatewayView`)({domain:FN,destination:jN,adminPort:IN,adminTokenEnv:z,llmProviders:N(LN)}){},W3=class extends V(`@usine/orchestrator/WorkerSlotsView`)({capacity:R,leased:R}){},G3=class extends H(`@usine/orchestrator/PassedCheckView`)(`Passed`,{checkedAt:j}){},K3=class extends H(`@usine/orchestrator/DegradedCheckView`)(`Degraded`,{checkedAt:j,message:j}){},q3=class extends H(`@usine/orchestrator/DeferredCheckView`)(`Deferred`,{checkedAt:j,message:j}){},J3=class extends H(`@usine/orchestrator/FailedCheckView`)(`Failed`,{checkedAt:j,capability:I(Jz),message:j}){},Y3=P([G3,K3,q3,J3]),X3=class extends V(`@usine/orchestrator/HarnessPreflightView`)({harness:lN,check:Y3}){},Z3=class extends V(`@usine/orchestrator/ContainerView`)({image:I(zN),cpus:I(VN),memoryMib:I(HN),pids:I(UN)}){},Q3=class extends V(`@usine/orchestrator/WorkerConfigurationView`)({name:EN,kind:DN,maxConcurrentAttempts:R,destination:I(jN),port:I(MN),identityFile:I(NN),root:I(PN),gateway:I(U3),container:I(Z3),containerLimits:I(WN).pipe(TT(w(null))),provisioner:I(lB).pipe(TT(w(null))),machines:N(aB).pipe(TT(w([]))),provisioning:I(oB).pipe(TT(w(null))),slots:I(W3),prerequisites:I(Y3),harnesses:N(X3)}){},$3=class extends V(`@usine/orchestrator/RemovedWorkerView`)({name:EN,running:R}){},e6=class extends V(`@usine/orchestrator/LabelStateView`)({name:fz,onGitHub:I(lT),color:I(j),description:I(j),declared:lT,failure:I(Hq)}){},t6=class extends H(`@usine/orchestrator/LabelLaneSourceView`)(`Label`,{label:e6}){},n6=class extends H(`@usine/orchestrator/StateLaneSourceView`)(`State`,{state:bz}){},r6=P([t6,n6]),i6=class extends V(`@usine/orchestrator/LaneConfigurationView`)({name:yz,sources:N(r6)}){},a6=class extends V(`@usine/orchestrator/RepositoryConfigurationView`)({name:Xk,tags:N(nJ),lanes:N(i6),declaredLabels:N(e6),loops:N(aA)}){},o6=class extends V(`@usine/orchestrator/SettingsView`)({pollInterval:R,maxChildren:R,maxAttemptMinutes:I(R),maxAttemptTokens:I(R),parentModel:I(cN),parentEffort:I(uN),operator:I(aN),webhooks:F([`off`,`deliveries`,`endpoint`]),webhooksPublicUrl:I(j),tracing:I(M({otlpUrl:j,serviceName:j}))}){},s6=class extends V(`@usine/orchestrator/ConfigurationView`)({labels:N(gz),loops:N(z3),quarantinedLoops:N(B3),agents:N(V3),invalidAgents:N(H3),workers:N(Q3),removedWorkers:N($3),repositories:N(a6),settings:o6}){},c6=e=>{let t=e.slice(e.lastIndexOf(`/`)+1).replace(/\.md$/u,``);return t===``?e:t},l6=e=>kk(e,{Passed:({checkedAt:e})=>new G3({checkedAt:J_(e)}),Degraded:({checkedAt:e,message:t})=>new K3({checkedAt:J_(e),message:t}),Deferred:({checkedAt:e,message:t})=>new q3({checkedAt:J_(e),message:t}),Failed:({checkedAt:e,capability:t,message:n})=>new J3({checkedAt:J_(e),capability:C(t),message:n})}),u6=e=>e.kind===`ssh`?{destination:C(e.destination),provisioner:fB(e),port:C(e.port),identityFile:C(e.identityFile),root:e.root,gateway:vr(e.gateway,{onNone:()=>null,onSome:e=>new U3({domain:e.domain,destination:e.destination,adminPort:e.adminPort,adminTokenEnv:e.adminTokenEnv,llmProviders:e.llmProviders})}),container:new Z3({image:C(e.container.image),cpus:C(e.container.cpus),memoryMib:C(e.container.memoryMib),pids:C(e.container.pids)})}:{destination:null,provisioner:null,port:null,identityFile:null,root:null,gateway:null,container:null},d6=T(function*(){let e=yield*o0,t=yield*yU,n=yield*B2,r=yield*L3,i=O(`OperatorConfiguration.repository`)(function*(e,n,r){let i=Or(yield*t.get(n.name),({labels:e})=>new Map(e.map(e=>[pz(e.name),e]))),a=new Map(e.config.labels.map(e=>[pz(e.name),e])),o=e=>{let t=pz(e),o=kr(i,e=>Sr(e.get(t))),s=a.get(t);return new e6({name:e,onGitHub:vr(i,{onNone:()=>null,onSome:()=>S(o)}),color:C(br(kr(o,({color:e})=>e),()=>kr(Sr(s),({color:e})=>e))),description:C(br(kr(o,({description:e})=>e),()=>kr(Sr(s),({description:e})=>e))),declared:s!==void 0,failure:r.find(e=>e.repository===n.name&&pz(e.label)===t)??null})};return new a6({name:n.name,tags:n.tags,lanes:n.lanes.map(e=>new i6({name:e.name,sources:e.sources.map(e=>`label`in e?new t6({label:o(e.label)}):new n6({state:e.state}))})),declaredLabels:e.config.labels.map(({name:e})=>o(e)),loops:e.loops.filter(e=>BJ(e.selector,n)).map(({name:e})=>e)})});return{view:O(`OperatorConfiguration.view`)(function*(t){let{config:a}=t,[o,s,c,l,u,d]=yield*Nh([e.states,n.latest,r.slots,r.preflights,r.machines,r.provisioning],{concurrency:`unbounded`}),f=new Set(o.filter(e=>e.paused).map(e=>e.loop)),p=vr(s,{onNone:()=>[],onSome:({preflightFindings:e})=>e}),m=yield*Ph(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 z3({name:e.name,file:tU.make(`loops/${e.name}.md`),stream:e.trigger.on,condition:e.trigger.if,cron:e.trigger.on===`schedule`?e.trigger.cron:null,timeZone:e.trigger.on===`schedule`?e.trigger.tz:null,selector:vr(e.selector,{onNone:()=>null,onSome:({repos:e,tags:t})=>new R3({repos:C(e),tags:C(t)})}),repositories:a.repos.filter(t=>BJ(e.selector,t)).map(({name:e})=>e),approval:e.approval,maxCycles:e.maxCycles,permissions:e.permissions,priority:C(e.priority),step:e.step,agent:e.agent,prompt:e.body,paused:f.has(e.name),undeclaredLabels:h(e.name)})),_=t.agents.map(e=>new V3({name:e.name,file:tU.make(`agents/${e.name}.md`),harness:e.harness,model:e.model,effort:e.effort,parentModel:C(e.parentModel),parentEffort:C(e.parentEffort),resolvedParentModel:C(hN(e.agent,a.settings.parentModel)),resolvedParentEffort:gN(e.agent,a.settings.parentEffort),persona:e.persona,loops:t.loops.filter(({agent:t})=>t===e.name).map(({name:e})=>e)})),v=new Map(c.map(e=>[e.worker,e])),ee=new Map(l.map(e=>[e.worker,e])),te=new Set(a.workers.map(({name:e})=>e)),ne=a.workers.map(e=>{let t=v.get(e.name),n=ee.get(e.name);return new Q3({name:e.name,kind:e.kind,maxConcurrentAttempts:e.maxConcurrentAttempts,...u6(e),slots:t===void 0?null:new W3({capacity:t.capacity,leased:t.leased}),prerequisites:n===void 0?null:C(Or(n.prerequisites,l6)),harnesses:(n?.harnesses??[]).map(({harness:e,check:t})=>new X3({harness:e,check:l6(t)})),containerLimits:n===void 0?null:C(n.containerLimits),machines:u.filter(t=>t.worker===e.name).map(uB),provisioning:C(Or(Sr(d.find(t=>t.worker===e.name)),dB))})}),{settings:re,webhooks:ie,tracing:ae}=a,oe=new s6({labels:t.config.labels,loops:g,quarantinedLoops:t.quarantinedLoops.map(({file:e,error:t})=>new B3({name:c6(e),file:e,error:t})),agents:_,invalidAgents:t.invalidAgents.map(({file:e,error:t})=>new H3({name:c6(e),file:e,error:t})),workers:ne,removedWorkers:c.filter(({worker:e,leased:t})=>!te.has(e)&&t>0).map(({worker:e,leased:t})=>new $3({name:e,running:t})),repositories:m,settings:new o6({pollInterval:re.pollInterval,maxChildren:re.maxChildren,maxAttemptMinutes:C(re.maxAttemptMinutes),maxAttemptTokens:C(re.maxAttemptTokens),parentModel:C(re.parentModel),parentEffort:C(re.parentEffort),operator:C(a.operator),webhooks:ie.mode,webhooksPublicUrl:ie.mode===`endpoint`?ie.publicUrl.href:null,tracing:vr(ae,{onNone:()=>null,onSome:({otlpUrl:e,serviceName:t})=>({otlpUrl:e.href,serviceName:t})})})});return yield*A(`Read the configuration view`,{loops:g.length,quarantinedLoops:oe.quarantinedLoops.length,agents:_.length,invalidAgents:oe.invalidAgents.length,workers:ne.length,runningWorkers:c.length,repositories:m.length}),oe})}});(class e extends Rr()(`@usine/orchestrator/OperatorConfiguration`){static layer=Xf(e,d6)});var f6=200,p6=10,m6=100,h6=500,g6=class extends H(`@usine/orchestrator/WorkerSilentView`)(`WorkerSilent`,{worker:EN,lastAnsweredAt:j}){},_6=class extends H(`@usine/orchestrator/ProviderRetryingView`)(`ProviderRetrying`,{agent:fN,message:z,retries:FP,since:j}){},v6=P([g6,_6]),y6=class extends V(`@usine/orchestrator/RunningAttemptView`)({run:CH,attempt:Kz,item:I(jH),lastActivityAt:I(j),warnings:N(v6)}){},b6=class extends H(`@usine/orchestrator/SuppressedForOperatorView`)(`SuppressedForOperator`,{run:CH}){},x6=class extends H(`@usine/orchestrator/ClosedUnchangedView`)(`ClosedUnchanged`,{run:CH}){},S6=class extends H(`@usine/orchestrator/RunFailedView`)(`RunFailed`,{run:CH}){},C6=class extends H(`@usine/orchestrator/LoopPausedView`)(`LoopPaused`,{}){},w6=class extends H(`@usine/orchestrator/CycleBudgetUsedUpView`)(`CycleBudgetUsedUp`,{ask:uI}){},T6=class extends H(`@usine/orchestrator/AwaitingApprovalView`)(`AwaitingApproval`,{run:CH}){},E6=class extends H(`@usine/orchestrator/QueuedForWorkerView`)(`QueuedForWorker`,{run:CH,ahead:I(R.check(HT(0))),creating:I(aB).pipe(TT(w(null)))}){},D6=class extends H(`@usine/orchestrator/WaitingForStopView`)(`WaitingForStop`,{run:CH,stop:DH}){},O6=class extends H(`@usine/orchestrator/AwaitingPollView`)(`AwaitingPoll`,{}){},k6=P([T6,b6,w6,S6,x6,C6,D6,E6,O6]),A6=class extends V(`@usine/orchestrator/StalledItemView`)({repository:Xk,loop:aA,item:jH,reason:k6}){},j6=class extends V(`@usine/orchestrator/ClosedRunView`)({run:CH,item:I(jH),closedAt:j}){},M6=class extends V(`@usine/orchestrator/WorkerView`)({name:EN,slots:W3,preflight:I(Y3),machines:N(aB).pipe(TT(w([]))),provisioning:I(oB).pipe(TT(w(null)))}){},N6=class extends V(`@usine/orchestrator/RepositoryPollView`)({repository:Xk,polledAt:I(j)}){},P6=class extends V(`@usine/orchestrator/DeskView`)({running:N(y6),notMoving:N(A6),lastOutcomes:N(j6),workers:N(M6),polls:N(N6)}){},F6=({runs:e,sighting:t,paused:n,ask:r,ahead:i,creating:a,stop:o})=>{let s=e.find(({state:e})=>AA.some(t=>t===e));if(s!==void 0){let e=s.attempts.at(-1)?.outcome===null;if(S(o)&&s.state!==`Waiting`&&!e)return b(new D6({run:s,stop:o.value}));switch(s.state){case`Running`:return y();case`Waiting`:return b(new T6({run:s}));default:return b(new E6({run:s,ahead:i.get(s.id)??null,creating:a.get(s.id)??null}))}}if(n)return b(new C6);let c=t=>Sr(e.find(({id:e})=>e===t)),l=kr(kr(t,({suppressedBy:e})=>e),c);if(S(l))return b(new b6({run:l.value}));if(S(r))return b(new w6({ask:r.value}));let u=kr(kr(t,({run:e})=>e),c);return S(u)?b(u.value.state===`Failed`?new S6({run:u.value}):new x6({run:u.value})):b(new O6)},I6=[`AwaitingApproval`,`SuppressedForOperator`,`CycleBudgetUsedUp`,`RunFailed`,`ClosedUnchanged`,`LoopPaused`,`WaitingForStop`,`QueuedForWorker`,`AwaitingPoll`],L6=dr([fr(lr,({reason:e})=>I6.indexOf(e._tag)),fr(cr,({repository:e})=>e),fr(ur(lr),({item:e})=>e.number),fr(cr,({loop:e})=>e)]),R6=({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`)},z6=e=>{let t=null,n=new Map,r=null;for(let i of e){R6(i)&&(r=i);let e=i.envelope.payload;if(e._tag===`WorkerUnresponsive`)t=new g6({worker:e.worker,lastAnsweredAt:J_(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 _6({agent:t.session.agent,message:t.message,retries:t.retries,since:n.get(t.session.id)?.since??J_(i.receivedAt)})):(t._tag===`ProviderRecovered`||t._tag===`SessionIdle`||t._tag===`SessionFinished`)&&n.delete(t.session.id)}}return{lastActivityAt:r===null?null:J_(r.receivedAt),warnings:[...t===null?[]:[t],...n.values()]}},B6=e=>K_(e.checkedAt),V6=e=>{let t=[...Mr(e.prerequisites),...e.harnesses.map(({check:e})=>e)],n=t.filter(({_tag:e})=>e===`Failed`),r=t.filter(({_tag:e})=>e===`Degraded`);return Sr((n.length>0?n:r.length>0?r:t).reduce((e,t)=>e===void 0||B6(t)>B6(e)?t:e,void 0))},H6=e=>{let t=e.attempts.at(-1);return e.closedAt??t?.endedAt??t?.startedAt??e.openedAt},U6=({run:e,attempts:t})=>t.length===0&&e.state._tag===`Canceled`&&e.state.reason._tag!==`OperatorCanceled`,W6=T(function*(){let e=yield*aH,t=yield*o0,n=yield*p1,r=yield*e0,i=yield*B2,a=yield*K4,o=yield*L3,s=yield*x0,c=O(`Operator.desk.recentActivity`)(function*(t){yield*D({attemptId:t.id});let[n,r]=yield*Nh([e.transcript(new TB({attemptId:t.id,before:y(),limit:f6})),e.transcript(new SB({attemptId:t.id}))],{concurrency:`unbounded`});return z6([...n,...r])});return{desk:O(`Operator.desk`)(function*(l){let[u,d,f,p,m,h,g,_,v,ee,te]=yield*Nh([e.list({closedLimit:0}),e.closed({limit:m6}),t.states,n.asks(),o.slots,o.queue,o.preflights,i.latest,s.list,o.machines,o.provisioning],{concurrency:`unbounded`}),ne=ee.map(uB),re=new Map(ne.flatMap(e=>e.state===`creating`&&e.runId!==null?[[e.runId,e]]:[])),ie=new Map(h.map(({runId:e,ahead:t})=>[e,t])),ae=new Set(f.filter(e=>e.paused).map(e=>e.loop)),oe=T4(l.config.workers),se=yield*Ph(l.config.repos,e=>T(function*(){let t=yield*r.list(e.name,{limit:h6});return{repository:e,items:t,matches:yield*a.matching(l,e,t)}}),{concurrency:4}),ce=new Map;for(let{items:e}of se)for(let t of e){let e=yield*$h(i2(t));if(Di(e))continue;let{itemKey:n,kind:r,number:i,title:a,url:o,state:s}=e.success;ce.set(n,new jH({itemKey:n,kind:r,number:i,title:a,url:o,state:s}))}let le=se.flatMap(({matches:e})=>e),ue=[...new Set(le.map(({item:e})=>e.itemKey))],[de,fe]=yield*Nh([e.forItems(ue),e.sightings(ue)],{concurrency:`unbounded`}),pe=new Map([...u,...de].map(e=>[e.run.id,O4(e,ae,oe)])),me=[...pe.values()].sort((e,t)=>t.openedAt.localeCompare(e.openedAt)||t.id.localeCompare(e.id)),he=e=>kr(Sr(v.find(t=>t.itemKey===e)),e=>Or(Sr(pe.get(e.runId)?.attempts.find(({id:t})=>t===e.attemptId)),({number:t})=>new DH({runId:e.runId,attemptNumber:t,worker:e.worker}))),ge=[];for(let{loop:e,item:t}of le){let n=ce.get(t.itemKey);if(n===void 0)continue;let r=F6({runs:me.filter(n=>n.loop===e.name&&n.itemKey===t.itemKey),sighting:Sr(fe.find(n=>n.loop===e.name&&n.itemKey===t.itemKey)),paused:ae.has(e.name),ask:Sr(p.find(({itemKey:e})=>e===t.itemKey)),ahead:ie,creating:re,stop:he(t.itemKey)});x(r)||(yield*A(`Matched Item is not moving`,{repository:t.repository,loop:e.name,item:t.number,reason:r.value._tag,...kk(r.value,{AwaitingApproval:({run:e})=>({runId:e.id}),SuppressedForOperator:({run:e})=>({runId:e.id}),CycleBudgetUsedUp:({ask:e})=>({askId:e.id}),RunFailed:({run:e})=>({runId:e.id}),ClosedUnchanged:({run:e})=>({runId:e.id,state:e.state}),LoopPaused:()=>({}),WaitingForStop:({run:e,stop:t})=>({runId:e.id,unstoppedRunId:t.runId,attemptNumber:t.attemptNumber,worker:t.worker}),QueuedForWorker:({run:e,ahead:t})=>({runId:e.id,ahead:t}),AwaitingPoll:()=>({})})}),ge.push(new A6({repository:t.repository,loop:e.name,item:n,reason:r.value})))}let _e=yield*Ph(me.flatMap(e=>{let t=e.attempts.at(-1);return e.state===`Running`&&t!==void 0&&t.outcome===null?[{run:e,attempt:t}]:[]}),({run:e,attempt:t})=>ng(c(t),n=>new y6({run:e,attempt:t,item:ce.get(e.itemKey)??null,...n})),{concurrency:4}),ve=d.filter(e=>!U6(e)).map(e=>{let t=O4(e,ae,oe);return new j6({run:t,item:ce.get(t.itemKey)??null,closedAt:H6(t)})}).sort((e,t)=>t.closedAt.localeCompare(e.closedAt)).slice(0,p6),ye=new Map(m.map(e=>[e.worker,e])),be=new Map(g.map(e=>[e.worker,e])),xe=new Set(l.config.workers.map(({name:e})=>e)),Se=[...l.config.workers.map(({name:e})=>e),...m.map(({worker:e})=>e).filter(e=>!xe.has(e))].map(e=>{let t=ye.get(e),n=be.get(e);return new M6({name:e,slots:new W3({capacity:t?.capacity??l.config.workers.find(t=>t.name===e)?.maxConcurrentAttempts??0,leased:t?.leased??0}),preflight:C(Or(kr(Sr(n),V6),l6)),machines:ne.filter(t=>t.worker===e),provisioning:C(Or(Sr(te.find(t=>t.worker===e)),dB))})}),Ce=vr(_,{onNone:()=>[],onSome:({repositoryPolls:e})=>e}),we=l.config.repos.map(({name:e})=>{let t=Ce.find(({repository:t})=>tA(t)===tA(e));return new N6({repository:e,polledAt:t===void 0?null:J_(t.completedAt)})});return yield*A(`Built the operator desk`,{running:_e.length,matches:le.length,notMoving:ge.length,lastOutcomes:ve.length,workers:Se.length}),new P6({running:_e,notMoving:[...ge].sort(L6),lastOutcomes:ve,workers:Se,polls:we})})}});(class e extends Rr()(`@usine/orchestrator/OperatorDesk`){static layer=Xf(e,W6).pipe(rp(K4.layer))});var G6=R.check(HT(0)),K6=R.check(HT(1)),q6=R.check(HT(0)),J6=FT.check(UT({minimum:0,maximum:1})),Y6=j.check(PT(/^\d{4}-\d{2}-\d{2}$/u,{message:`Expected a UTC day as YYYY-MM-DD`})),X6=F([`7d`,`30d`,`all`]),Z6=F([`day`,`week`]),Q6=class extends V(`@usine/orchestrator/TaskDoneView`)({repository:Xk,number:rI,mergedAt:j,durationMillis:q6}){},$6=class extends V(`@usine/orchestrator/TaskPeriodView`)({start:Y6,tasks:G6,medianMillis:I(q6),firstTimeRight:G6,operatorActions:G6}){},e8=class extends V(`@usine/orchestrator/LoopShareView`)({loop:aA,share:J6}){},t8=class extends V(`@usine/orchestrator/LoopRunTimeView`)({loop:aA,runs:K6,medianMillis:q6}){},n8=class extends V(`@usine/orchestrator/TaskTimeView`)({tasks:K6,loops:N(e8),waiting:J6,runs:N(t8)}){},r8=class extends V(`@usine/orchestrator/TaskCostView`)({tasks:K6,medianUsd:TP,estimate:lT}){},i8=class extends V(`@usine/orchestrator/TaskTokensView`)({tasks:K6,medianTokens:dP,loops:N(e8),cost:I(r8)}){},a8=class extends V(`@usine/orchestrator/UntimedTasksView`)({tasks:K6,before:Y6}){},o8=class extends V(`@usine/orchestrator/StatisticsView`)({window:X6,from:j,to:j,bucket:Z6,loops:N(aA),tasks:N(Q6),medianMillis:I(q6),periods:N($6),firstTimeRight:G6,operatorActions:G6,time:I(n8),tokens:I(i8),untimed:I(a8),unmetered:G6}){},s8=class extends V(`@usine/orchestrator/DurationSummaryView`)({count:K6,medianMillis:q6}){},c8=class extends V(`@usine/orchestrator/OutcomeCountsView`)({succeeded:G6,failed:G6,canceled:G6}){},l8=class extends V(`@usine/orchestrator/PoolTokensView`)({pool:kP,tokens:dP}){},u8=class extends V(`@usine/orchestrator/CostSummaryView`)({usd:TP,meanUsd:TP,estimate:lT,priced:K6}){},d8=class extends V(`@usine/orchestrator/UsageSummaryView`)({measured:G6,tokens:dP,meanTokens:I(dP),pools:N(l8),cost:I(u8)}){},f8={outcomes:c8,time:I(s8),usage:d8},p8=class extends V(`@usine/orchestrator/LoopStatisticsView`)({loop:aA,...f8}){},m8=class extends V(`@usine/orchestrator/AgentStatisticsView`)({agent:fN,...f8}){},h8=class extends V(`@usine/orchestrator/BrainStatisticsView`)({brain:dN,...f8}){},g8=class extends V(`@usine/orchestrator/ThroughputPeriodView`)({start:Y6,...c8.fields}){},_8=class extends V(`@usine/orchestrator/WorkerQueueWaitView`)({worker:EN,wait:s8}){},v8=class extends V(`@usine/orchestrator/AttemptCountView`)({attempts:K6,runs:G6}){},y8=class extends V(`@usine/orchestrator/WorkerUtilizationView`)({worker:EN,slots:K6,occupiedMillis:q6,share:J6}){},b8=class extends V(`@usine/orchestrator/NeedsAttentionPeriodView`)({start:Y6,approvals:G6,failures:G6}){},x8=class extends V(`@usine/orchestrator/NeedsAttentionView`)({approvals:G6,failures:G6,periods:N(b8),approvalWait:I(s8),retryWait:I(s8),resolutionWait:I(s8),failureWait:I(s8)}){},S8=class extends V(`@usine/orchestrator/RunStatisticsView`)({window:X6,from:j,to:j,bucket:Z6,runs:c8,runTime:I(s8),attemptTime:I(s8),unmeasuredAttempts:G6,throughput:N(g8),loops:N(p8),agents:N(m8),brains:N(h8),queueWait:N(_8),attemptsPerRun:N(v8),utilization:N(y8),needsAttention:x8}){},C8=(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})=>tA(e)))}),w8=e=>e.map(e=>`"${e}"`).join(`, `),T8=(e,t,n)=>{let r=[],i=()=>r.length===0?y():b(new rU({file:e,stage:`reference`,expression:y(),message:r.map(({message:e})=>e).join(`
|
|
311
|
-
`),details:r}));if(n.agentNames.has(t.agent)||r.push({path:[`agent`],message:`Unknown agent "${t.agent}": agents/${t.agent}.md is missing or invalid. Fix the agent file, or set agent to an existing agent.`}),x(t.selector))return i();if(S(t.selector.value.repos)){let e=t.selector.value.repos.value.filter(e=>!n.repoNames.has(tA(e)));e.length>0&&r.push({path:[`selector`,`repos`],message:`Unknown repositories in selector.repos: ${w8(e)}. Add them under repos in usine.yaml.`})}if(S(t.selector.value.tags)){let e=t.selector.value.tags.value.filter(e=>!n.registryTags.has(e));e.length>0&&r.push({path:[`selector`,`tags`],message:`Unknown tags in selector.tags: ${w8(e)}. Add them to a repository's tags in usine.yaml.`})}return i()},E8=class extends V(`@usine/config/LoadedInstance`)(M({config:RJ,agents:N(Jq),invalidAgents:N(Yq),loops:N(ZJ),quarantinedLoops:N(QJ),warnings:N(nY)}).check(NT(({agents:e,config:t,loops:n})=>{let r=C8(t,e);return n.every(e=>x(T8($J(e.name),e,r)))},{message:`Expected every loop to reference only loaded agents and registry entries`}))){},D8=R.check(HT(0)).pipe(L(`ConfigurationRevisionNumber`)),O8=F([`settings`,`worker`,`repository`,`label`,`loop`,`agent`]),k8=z.pipe(L(`ConfigurationEntityId`)),A8=class extends V(`@usine/config/ConfigurationEntityKey`)({kind:O8,identifier:k8}){get key(){return`${this.kind}:${this.identifier}`}},j8=class extends V(`@usine/config/ConfigurationEntity`)({key:A8,value:IE}){},M8=class extends V(`@usine/config/ConfigurationChange`)({key:A8,before:B(IE),after:B(IE),position:$w(R.check(HT(0)))}){};(class e extends V(`@usine/config/Configuration`)(M({number:D8,instance:B(E8)}).check(NT(({number:e,instance:t})=>e===0===x(t),{message:`Only an uninitialized configuration has revision zero`}))){get actor(){return kr(this.instance,({config:e})=>e.operator)}static empty=new e({number:D8.make(0),instance:y()})}),V(`@usine/config/ConfigurationRevision`)({number:D8.check(VT(0)),actor:B(aN),time:_E,message:B(j),changes:N(M8)}),NE(`@usine/config/StaleRevision`)(`StaleRevision`,{expected:D8,actual:D8});var N8=class extends NE(`@usine/config/ConfigurationInvalid`)(`ConfigurationInvalid`,{problems:yT(rU)}){};NE(`@usine/config/ConfigurationStoreError`)(`ConfigurationStoreError`,{operation:j,cause:eE()}),NE(`@usine/config/ConfigurationRevertBlocked`)(`ConfigurationRevertBlocked`,{entities:yT(A8)});var P8=F([`workers`,`webhooks`,`tracing`]),F8=e=>M({added:N(e),removed:N(e),changed:N(e)});V(`@usine/orchestrator/InstanceReload`)({loops:F8(aA),agents:F8(fN),labels:F8(fz),repos:F8(Xk),workers:F8(EN),settingsChanged:lT,operatorChanged:lT,quarantinedLoops:N(QJ),invalidAgents:N(Yq)});var I8=class extends V(`ConfigurationEntityRequest`)({kind:j,identifier:k8}){},L8=class extends V(`ConfigurationRevisionQuery`)({kind:$w(j),identifier:$w(k8),before:$w(D8),limit:R.check(UT({minimum:1,maximum:100}))}){},R8=class extends V(`ConfigurationWrite`)({expected:D8,message:$w(j)}){},z8=P([M({...R8.fields,value:IE,text:$w(iT),position:$w(R.check(HT(0)))}),M({...R8.fields,text:j,value:$w(iT),position:$w(R.check(HT(0)))})]),B8=class extends V(`ConfigurationEntityView`)({key:A8,value:IE,text:j,number:D8}){},V8=class extends V(`ConfigurationRevisionSummary`)({number:D8,actor:I(aN),time:_E,message:I(j),entities:N(A8)}){},H8=class extends V(`ConfigurationRevisionPage`)({revisions:N(V8),nextBefore:I(D8)}){};NE(`ConfigurationNotFound`)(`ConfigurationNotFound`,{message:j});var U8=class e extends V(`ConfigurationRevisionView`)({...V8.fields,changes:N(M({key:A8,before:I(IE),after:I(IE),position:$w(R)}))}){static fromRevision(t){return new e({...t,actor:C(t.actor),message:C(t.message),entities:t.changes.map(({key:e})=>e),changes:t.changes.map(e=>({...e,before:C(e.before),after:C(e.after)}))})}},W8=class extends V(`@usine/orchestrator/UpgradeRequest`)({timing:$q,version:xE(Qq)}){},G8=class extends V(`@usine/orchestrator/UpgradeView`)({running:j,channel:Xq,mode:Zq,supported:lT,available:I(Qq),phase:F([`idle`,`waiting`,`installing`,`failed`]),message:I(j),outcome:I(tJ)}){},K8=`~effect/http-api/HttpApiSchema/Stream`;function q8(e){let t=typeof e==`string`?gG(e):e;return e=>e.ast.checks!==void 0||p5(e.ast)?e.annotate({httpApiStatus:t}):e.annotateKey({httpApiStatus:t})}var J8=(e=>dT.pipe(q8(e)))(204),Y8=e=>Qw(e)&&pe(e,K8),X8=e=>Y8(e)&&e._tag===`StreamSse`,Z8=e=>Y8(e)&&e._tag===`StreamUint8Array`,Q8=e=>Y8(e)&&e._tag===`StreamNdjson`,$8=`~effect/http-api/HttpApiSchema/Upgrade`,e5=e=>Qw(e)&&pe(e,$8),t5=`~effect/http-api/HttpApiSchema/WithHeaders`,n5=`~effect/http-api/HttpApiSchema/WithHeadersValue`,r5=e=>({[n5]:n5,body:e.body,headers:e.headers}),i5=e=>Qw(e)&&pe(e,`~effect/http-api/HttpApiSchema/WithHeaders`);function a5(e,t,n){return Zw(e.ast,{[t5]:t5,schema:t,headers:n})}function o5(e,t){return e.annotate({"~httpApiEncoding":{_tag:t._tag,contentType:t.contentType??s5(t._tag)}})}function s5(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 c5(e){return t=>o5(t,{_tag:`FormUrlEncoded`,...e})}var l5=e=>{if(qb(e)||qb(GS(e)))return!0;let t=e.encoding?.[0].to;return t!==void 0&&qb(t)},u5=dC(`~httpApiEncoding`),d5=dC(`~httpApiWithHeaders`),f5=dC(`httpApiStatus`);function p5(e){let t=uC(e);return t!==void 0&&`httpApiStatus`in t}function m5(e){return p5(e)?f5(e):e.checks===void 0?e.context?.annotations?.httpApiStatus:void 0}var h5={_tag:`Json`,contentType:`application/json`},g5={_tag:`FormUrlEncoded`,contentType:`application/x-www-form-urlencoded`};function _5(e){return u5(e)??h5}function v5(e,t){return u5(e)||(qU(t)?h5:g5)}function y5(e){let t=_5(e);if(t._tag===`Multipart`)throw Error(`Multipart is not supported in response`);return t}function b5(e){return m5(e)??200}function x5(e){return i5(e)?m5(e.ast)??b5(e.schema.ast):b5(e.ast)}function S5(e){return i5(e)&&u5(e.ast)===void 0?y5(e.schema.ast):y5(e.ast)}function C5(e){return m5(e)??500}function w5(e){return i5(e)?m5(e.ast)??C5(e.schema.ast):C5(e.ast)}function T5(e){let t=e.toLowerCase().trim(),n=t.indexOf(`;`);return n===-1?t:t.slice(0,n).trim()}var E5=`~effect/http-api/HttpApiEndpoint`;function D5(e){let t=[];for(let{schemas:n}of e.payload.values())t.push(...n);return t}function O5(e){let t=Array.from(e.success);return Yi(t)?t:[J8]}function k5(e){let t=new Set(e.error),n=e.disableCodecs?i:R5;for(let r of e.middlewares){let e=r;for(let r of e.error)t.add(n(r))}return Array.from(t)}var A5={[E5]:E5,pipe(){return e(this,arguments)},prefix(e){return M5({...j5(this),path:oG(this.path,e)})},middleware(e){return M5({...j5(this),middlewares:new Set([...this.middlewares,e])})},annotate(e,t){return M5({...j5(this),annotations:ai(this.annotations,e,t)})},annotateMerge(e){return M5({...j5(this),annotations:hi(this.annotations,e)})}},j5=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 M5(e){function t(){}return Object.setPrototypeOf(t,A5),Object.assign(t,e)}var N5=e=>(t,n,r)=>{let a=r?.disableCodecs??!1,o=a?i:FE;return M5({identifier:t,path:n,method:e,params:P5(r?.params,o),query:P5(r?.query,o),headers:P5(r?.headers,o),payload:F5(r?.payload,e,a),success:L5(r?.success,e,r?.payload!==void 0,a),error:z5(r?.error,a),annotations:ni(),middlewares:new Set,disableCodecs:a})};function P5(e,t){if(e!==void 0)return Qw(e)?t(e):t(M(e))}function F5(e,t,n){let r=new Map;if(e===void 0)return r;let a=Array.isArray(e)?e:Qw(e)?[e]:[M(e).pipe(c5())],o=n?i:Y5,s=!1;for(let e of a){if(Y8(e)){if(X8(e))throw Error(`StreamSse is response-only and cannot be used as a payload`);if(!qU(t))throw Error(`${t} endpoints cannot declare a streaming payload`);if(s)throw Error(`Multiple streaming payloads are not supported`);s=!0;let n=T5(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=v5(e.ast,t),i=T5(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 I5=`effect/http-api/stream/failure`;function L5(e,t,n,r){if(e===void 0)return new Set;let i=Gi(e);return B5(i,t,n),new Set(r?i:i.map(R5))}var R5=f(e=>Y8(e)||e5(e)?e:i5(e)?a5(e,Y8(e.schema)?e.schema:J5(e.schema,S5(e)),FE(e.headers)):q5(e));function z5(e,t){if(e===void 0)return new Set;let n=Gi(e);for(let e of n){let t=i5(e)?e.schema:e;if(Y8(t))throw Error(`Streaming schemas are not supported in error responses`);if(e5(t))throw Error(`Upgrade schemas are not supported in error responses`)}return H5(n,w5),new Set(t?n:n.map(R5))}function B5(e,t,n){if(e.some(e5)){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=i5(n)?n.schema:n,a=x5(n);if(Y8(e)){if(U5(e,t),r)throw Error(`Multiple streaming success responses are not supported`);r=!0;let n=V5(i,a);if(n.noContent)throw Error(`Cannot combine no-content and streaming success responses for status: ${a}`);if(n.bufferedContentTypes.has(T5(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=V5(i,a),r=l5(e.ast);if(t.stream!==void 0){if(r)throw Error(`Cannot combine no-content and streaming success responses for status: ${a}`);let e=S5(n);if(T5(e.contentType)===T5(t.stream.contentType))throw Error(`Cannot combine buffered and streaming success responses for status ${a} and content-type: ${e.contentType}`)}r||t.bufferedContentTypes.add(T5(S5(n).contentType)),t.noContent=t.noContent||r}}H5(e,x5)}function V5(e,t){let n=e.get(t);return n===void 0&&(n={bufferedContentTypes:new Set,noContent:!1},e.set(t,n)),n}function H5(e,t){let n=new Map;for(let r of e){let e=t(r),i=d5(r.ast),a=i5(r)?r.schema:i?.body??r,o=l5(a.ast)?``:T5(Y8(a)?a.contentType:S5(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(i5(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 U5(e,t){if(t===`HEAD`)throw Error(`HEAD endpoints cannot declare streaming success responses`);if(X8(e)&&W5(e.events.ast))throw Error(`SSE event name is reserved: ${I5}`)}function W5(e){return G5(GS(e),new Set)}function G5(e,t){if(t.has(e))return!1;if(t.add(e),$b(e))return e.types.some(e=>G5(e,t));if(ex(e))return G5(e.thunk(),t);if(!Qb(e))return!1;let n=e.propertySignatures.find(e=>e.name===`event`);return n!==void 0&&K5(n.type,t)}function K5(e,t){if(t.has(e))return!1;t.add(e);let n=GS(e);return n===e?Yb(e)?e.literal===I5:$b(e)?e.types.some(e=>K5(e,t)):ex(e)?K5(e.thunk(),t):!1:K5(n,t)}function q5(e){let t=y5(e.ast),n=d5(e.ast);return n===void 0?J5(e,t):e.annotate({"~httpApiWithHeaders":{...n,bodyCodec:J5(n.body,t),headersCodec:FE(n.headers)}})}function J5(e,t){switch(t._tag){case`Json`:return PE(e);case`FormUrlEncoded`:return FE(e);case`Text`:case`Uint8Array`:return e}}function Y5(e,t){switch(v5(e.ast,t)._tag){case`Json`:return PE(e);case`FormUrlEncoded`:return FE(e);case`Text`:case`Uint8Array`:case`Multipart`:return e}}var X5=N5(`GET`),Z5=N5(`POST`),Q5=N5(`PUT`),$5=N5(`DELETE`),e7=`~effect/http-api/HttpApi`,t7={[e7]:e7,pipe(){return e(this,arguments)},add(...e){let t={...this.groups};for(let n of e)Et(t,n.identifier,n);return r7({...n7(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(hi(e.annotations,r.annotations)))}return r7({...n7(this),groups:t})},prefix(e){return r7({...n7(this),groups:zi(this.groups,t=>t.prefix(e))})},middleware(e){return r7({...n7(this),groups:zi(this.groups,t=>t.middleware(e))})},annotate(e,t){return r7({...n7(this),annotations:ai(this.annotations,e,t)})},annotateMerge(e){return r7({...n7(this),annotations:hi(this.annotations,e)})}},n7=e=>({identifier:e.identifier,groups:e.groups,annotations:e.annotations}),r7=e=>{function t(){}return Object.setPrototypeOf(t,t7),Object.assign(t,e)},i7=e=>r7({identifier:e,groups:{},annotations:ni()}),a7=(e,t)=>{let n=Object.values(e.groups);for(let r of n){let n=hi(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:hi(n,e.annotations),successes:o7(O5(e),x5),errors:o7(k5(e),w5)})}},o7=(e,t)=>{let n=new Map;return e.forEach(r),n;function r(e){let r=i5(e)?e.schema:e;if(Y8(r)||e5(r))return;let i=t(e),a=n.get(i);a===void 0?n.set(i,[e]):a.push(e)}},s7=class extends Rr()(`effect/http-api/HttpApi/ParseOptions`){},c7=class extends Rr()(`effect/http-api/HttpApi/ParamsParseOptions`){},l7=class extends Rr()(`effect/http-api/HttpApi/QueryParseOptions`){},u7=class extends Rr()(`effect/http-api/HttpApi/HeadersParseOptions`){},d7=class extends Rr()(`effect/http-api/HttpApi/PayloadParseOptions`){},f7=class extends Rr()(`effect/http-api/HttpApi/SuccessParseOptions`){},p7=class extends Rr()(`effect/http-api/HttpApi/ErrorParseOptions`){},m7=e=>{let t=si(e,s7);return{params:si(e,c7)??t,query:si(e,l7)??t,headers:si(e,u7)??t,payload:si(e,d7)??t,success:si(e,f7)??t,error:si(e,p7)??t}},h7=`~effect/http-api/HttpApiMiddleware`,g7=`~effect/http-api/HttpApiMiddleware/Security`,_7=()=>(e,t)=>{let n=St(),r;n!==0&&(Ct(2),r=new globalThis.Error,Ct(n));class i extends Rr()(e){}let a=i;if(Object.defineProperty(i,"stack",{get(){return r?.stack}}),a[h7]=h7,a.error=v7(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[g7]=g7,a.security=t.security}return a};function v7(e){return e===void 0?new Set:new Set(Array.isArray(e)?e:[e])}var y7=new Set;function b7(e){if(e===void 0)return y7;let t=xS(e.ast);return Qb(t)&&t.indexSignatures.length===0?new Set(t.propertySignatures.map(e=>String(e.name))):void 0}function x7(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=tG(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 S7=(e,t)=>T(function*(){let n=yield*Cg(),r=t.httpClient.pipe(t?.baseUrl===void 0?i:UW(mW(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)}})}a7(e,{predicate:t?.predicate,onGroup(e){t.onGroup?.(e)},onEndpoint(e){let{group:n,endpoint:r,errors:i,successes:o,mergedAnnotations:s}=e,c=m7(s),l=T7(r.path,r.params),u={orElse:Y7},d=new Map;for(let[e,t]of i.entries()){let n=j7(t);for(let[t,r]of n.entries())k7(d,e,t,E7(r,c.error,c.headers))}for(let[e,t]of d.entries()){let n=A7(t);u[e]=e=>E(lg(n(e),t=>Wh(ef(qd(new RU({reason:new WU({request:e.request,response:e})})),t))),Uh)}let f=new Map;for(let[e,t]of o.entries()){let n=j7(t);for(let[t,r]of n.entries())k7(f,e,t,E7(r,c.success,c.headers))}for(let e of I7(r)){let t=P7(e)?e.schema:e;k7(f,x5(e),t.contentType,L7(e,c.success,c.headers))}for(let[e,t]of f.entries())u[e]=A7(t);let p=F7(r);p!==void 0&&(u[101]=e=>ng(e.upgrade,t=>({headers:e.headers,socket:t})));let m=Uk(r.params,e=>qw(e,c.params)),h=[],g;for(let e of D5(r))Z8(e)||Q8(e)?g=e:h.push(e);let _=Uk(g,e=>({contentType:e.contentType,encode:Z7(e,c.payload)})),v=Yi(h)?qw(qU(r.method)?Q7(h,r.method):P(h),c.payload):void 0,ee=Uk(r.headers,e=>qw(e,c.headers)),te=Uk(r.query,e=>qw(e,c.query)),ne=Array.from(e.middleware,e=>`${e.key}/Client`),re=$g(function*(e){let i=rW(r.method)(r.path);if(e!==void 0){if(m!==void 0){let t=yield*m(e.params);i=pW(i,l(t))}if(_!==void 0&&EO(e.payload)){let t=yield*Cg();i=yW(i,IU(GO(_.encode(e.payload),t),_.contentType))}else if(v!==void 0){if(qU(r.method)){if(e.payload instanceof FormData)i=xW(i,e.payload);else{let t=yield*v(e.payload);i=yW(i,t)}}else{let t=yield*v(e.payload);i=_W(i,t)}}else if(_!==void 0)return yield*new Pw(new My({message:`Expected a Stream payload`},e.payload));if(ee!==void 0){let t=yield*ee(e.headers);i=lW(i,t)}if(te!==void 0){let t=yield*te(e.query);i=_W(i,t)}}p!==void 0&&(i=fW(i,p.protocol));let o=yield*a(n,r,i,ne,ne.length-1);if(e?.responseMode===`response-only`)return o;let s=(u[o.status]??u.orElse)(o,e?.sseOptions),c=yield*t.transformResponse===void 0?s:t.transformResponse(s);return e?.responseMode===`decoded-and-response`?[c,o]:c});t.onEndpoint({...e,endpointFn:re})}})}),C7=(e,t)=>E(LW,n=>w7(e,{...t,httpClient:t?.transformClient?t.transformClient(n):n})),w7=(e,t)=>{let n={};return S7(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(rg(n))},T7=(e,t)=>{if(t===void 0||!e.includes(`:`))return t=>e;let n=b7(t);return t=>x7(e,n,(e,n)=>{let r=t[e];if(r!==void 0)return encodeURIComponent(r);if(!n)throw Error(`Missing path parameter: ${e}`)})};function E7(e,t,n){let r=e.some(e=>i5(e)||d5(e.ast)!==void 0),i=Hw(r?P(e.map(e=>O7(e,t,n))):q7(e),t);return e=>E(e.arrayBuffer,r?t=>i({body:t,headers:e.headers}):i)}var D7=M({body:aT,headers:aT});function O7(e,t,n){let r=d5(e.ast),i=r===void 0?i5(e)?{body:e.schema,headers:e.headers,toValue:r5}:{body:e,headers:aT,toValue:e=>e.body}:{body:r.bodyCodec,headers:r.headersCodec,toValue:r.transformation.decode},a=Hw(J7(i.body).pipe(ST(i.body)),t),o=Hw(i.headers,n);return D7.pipe(ST(i5(e)?e:tT(e),Tb({decode:e=>Nh({body:a(e.body),headers:o(e.headers)}).pipe(ng(i.toValue),dg(e=>e.issue)),encode:(e,t)=>Uh(new Py({message:`Decode only schema`},e,t))})))}function k7(e,t,n,r){let i=T5(n),a=e.get(t);a===void 0?e.set(t,[{contentType:i,decode:r}]):a.push({contentType:i,decode:r})}function A7(e){let t=e[0];return e.length===1&&t!==void 0?t.decode:(t,n)=>{let r=T5(t.headers[`content-type`]??``),i=e.find(e=>e.contentType===r);return i===void 0?M7(t,r,e):i.decode(t,n)}}function j7(e){let t=new Map;for(let n of e){let e=l5((i5(n)?n.schema:n).ast)?``:T5(S5(n).contentType),r=t.get(e);r===void 0?t.set(e,[n]):r.push(n)}return t}function M7(e,t,n){let r=Array.from(new Set(n.map(e=>e.contentType))).join(`, `);return Uh(new RU({reason:new GU({request:e.request,response:e,description:`Unsupported response content-type for status ${e.status}: ${t||`<missing>`}. Expected one of: ${r}`})}))}var N7=`effect/http-api/stream/failure`,P7=e=>i5(e);function F7(e){for(let t of e.success)if(e5(t))return t}function I7(e){let t=[];for(let n of e.success)Y8(i5(n)?n.schema:n)&&t.push(n);return t}function L7(e,t,n){let r=P7(e),i=R7(r?e.schema:e,t),a=(e,t)=>ng(Cg(),n=>GO(i(e,t),n));if(!r)return a;let o=Hw(e.headers,n);return(e,t)=>E(o(e.headers),n=>ng(a(e,t),e=>r5({body:e,headers:n})))}function R7(e,t){if(Z8(e))return e=>e.stream;if(Q8(e)){let n=Hw(PE(e.schema),t),r=P_(e.maxElementBytes);return e=>e.stream.pipe(VO(pR({ignoreEmptyLines:!0,maxLineBytes:r})),BO(t=>aR(t)?t.reason===`LineTooLarge`?new RU({reason:new GU({request:e.request,response:e,description:`NDJSON line exceeds maxElementBytes of ${r} bytes`})}):B7(t):t),IO(e=>n(e)))}let n=V7(e,t);return(t,r)=>H7(t.stream,e,n(r))}var z7=e=>aR(e)&&e.kind===`Pack`,B7=e=>new Pw(new My({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 V7(e,t){let n=P([M({id:eT(j),event:rT(N7),data:aE(PE(dE(e.error,eE())))}),e.events]),r=yR(n,void 0,t);return e=>e===void 0?r:yR(n,e,t)}function H7(e,t,n){let r=OO(e.pipe(HO,VO(n)),e=>zh(()=>{let t;return Rh(()=>t===void 0?E(e,e=>{for(let n=0;n<e.length;n++){let r=e[n];if(r.event===N7&&Ud(r.data)){if(n===0)return Wh(r.data);t=r.data,e=e.slice(0,n);break}}return w(e)}):Wh(t))}));return t.sseMode===`data`?FO(r,e=>e.data):r}var U7=jT(globalThis.ArrayBuffer,{expected:`ArrayBuffer`}),W7=U7.pipe(ST(lE,Eb({decode(e){return new Uint8Array(e)},encode(e){return e.byteLength===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}}))),G7=U7.pipe(ST(j,Eb({decode(e){return new TextDecoder().decode(e)},encode(e){let t=new TextEncoder().encode(e);return t.byteLength===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}}))),K7=G7.pipe(ST(P([rT(``).pipe(ST(sT,Eb({decode:()=>void 0,encode:()=>``}))),oE])));function q7(e){return P(e.map(t));function t(e){return J7(e).pipe(ST(e))}}function J7(e){switch(y5(e.ast)._tag){case`Json`:return Kb(GS(e.ast))?K7.pipe(ST(aT,Eb({decode:e=>e===void 0?null:e,encode:e=>e===null?void 0:e}))):K7;case`FormUrlEncoded`:return G7.pipe(ST(bE,Eb({decode:e=>Vv(new URLSearchParams(e)),encode:Xv})));case`Uint8Array`:return W7;case`Text`:return G7}}var Y7=e=>Uh(new RU({reason:new GU({request:e.request,response:e})})),X7=Nw(SU);function Z7(e,t){if(Z8(e))return e=>e;let n=qw(yT(PE(e.schema)),t);return e=>e.pipe(LO(e=>n(e)),VO(sR()),zO(z7,NO))}function Q7(e,t){return P(e.map(e=>e9(e,t)))}var $7=new WeakMap;function e9(e,t){let n=e.ast,r=$7.get(n);if(r!==void 0)return r;let i=v5(n,t),a=X7.pipe(ST(e,Tb({decode(e,t){return Uh(new Py({message:`Encode only schema`},e,t))},encode(e,t){switch(i._tag){case`Multipart`:return Uh(new Py({message:`Payload must be a FormData`},e,t));case`Json`:try{return w(AU(JSON.stringify(e),i.contentType))}catch{return Uh(new My({expected:`a JSON-serializable request body`},e,t))}case`Text`:return typeof e==`string`?w(AU(e,i.contentType)):Uh(new My({message:`Expected a string`},e,t));case`FormUrlEncoded`:return de(e)?w(MU(Vv(e),i.contentType)):Uh(new My({message:`Expected a record`},e,t));case`Uint8Array`:return e instanceof Uint8Array?w(EU(e,i.contentType)):Uh(new My({message:`Expected a Uint8Array`},e,t))}}})));return $7.set(n,a),a}var t9=`~effect/http-api/HttpApiGroup`,n9={[t9]:t9,add(...e){let t={...this.endpoints};for(let n of e)Et(t,n.identifier,n);return i9({...r9(this),endpoints:t})},prefix(e){return i9({...r9(this),endpoints:zi(this.endpoints,t=>t.prefix(e))})},middleware(e){return i9({...r9(this),endpoints:zi(this.endpoints,t=>t.middleware(e))})},annotateMerge(e){return i9({...r9(this),annotations:hi(this.annotations,e)})},annotate(e,t){return i9({...r9(this),annotations:ai(this.annotations,e,t)})},annotateEndpointsMerge(e){return i9({...r9(this),endpoints:zi(this.endpoints,t=>t.annotateMerge(e))})},annotateEndpoints(e,t){return i9({...r9(this),endpoints:zi(this.endpoints,n=>n.annotate(e,t))})},pipe(){return e(this,arguments)}},r9=e=>({identifier:e.identifier,topLevel:e.topLevel,endpoints:e.endpoints,annotations:e.annotations}),i9=e=>{function t(){}return Object.setPrototypeOf(t,n9),t.key=`effect/http-api/HttpApiGroup/${e.identifier}`,Object.assign(t,e)},a9=(e,t)=>i9({identifier:e,topLevel:t?.topLevel??!1,endpoints:{},annotations:ni()}),o9={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},s9=class extends ME(`@usine/orchestrator/OperatorHttpError`)({error:F(Bi(o9)),message:j}){get status(){return o9[this.error]}},c9=[...new Set(Object.values(o9))].map(e=>s9.check(NT(t=>t.status===e)).annotate({httpApiStatus:e})),l9=class extends _7()(`@usine/orchestrator/OperatorHttpPolicy`,{error:c9}){},u9=P([AT(`WorkerCapabilityError`,{worker:EN,capability:Jz,message:j}),AT(`ExecutorOperationError`,{operation:qz,message:j}),AT(`CredentialUnavailableError`,{repository:Xk,message:j})]),d9=class extends ME(`@usine/orchestrator/RestartRequiredRefusal`)({error:rT(`RestartRequiredError`),message:j,blocks:yT(P8),fields:yT(z)},{httpApiStatus:409}){},f9=class extends ME(`@usine/orchestrator/ReloadPreflightRefusal`)({error:rT(`ReloadPreflightError`),message:j,agents:N(fN),workers:N(EN),cause:u9},{httpApiStatus:409}){},p9=class extends ME(`@usine/orchestrator/FactoryConfigRefusal`)({error:rT(`FactoryConfigError`),message:j,file:tU,stage:nU},{httpApiStatus:422}){},m9=class extends ME(`StaleRevisionRefusal`)({error:rT(`StaleRevision`),message:j,expected:D8,current:D8},{httpApiStatus:409}){},h9=class extends ME(`ConfigurationInvalidRefusal`)({error:rT(`ConfigurationInvalid`),message:j,problems:yT(M({entity:A8,path:N(P([j,cT])),message:j}))},{httpApiStatus:422}){},g9=class extends ME(`ConfigurationRevertRefusal`)({error:rT(`ConfigurationRevertBlocked`),message:j,entities:yT(A8)},{httpApiStatus:409}){},_9=[m9,h9,g9,d9,f9,p9],v9={number:sE.pipe(ST(D8))},y9=I8.fields,b9=$w(iT),x9=P([j,yT(j).pipe(ST(j,Eb({decode:e=>e[0],encode:e=>[e]})))]),S9=x9.pipe(ST(sE),ST(pB)),C9=P([M({after:b9,before:b9,attempt:b9}).pipe(ST(tT(AB),Eb({decode:()=>new AB,encode:()=>({})}))),M({after:S9,before:b9,attempt:b9}).pipe(ST(tT(jB),Eb({decode:({after:e})=>new jB({after:e}),encode:({after:e})=>({after:e})}))),M({after:b9,before:S9,attempt:x9.pipe(ST(sF))}).pipe(ST(tT(MB),Eb({decode:({before:e,attempt:t})=>new MB({before:e,attemptId:t}),encode:({before:e,attemptId:t})=>({before:e,attempt:t})})))]),w9=j.check(PT(/^[A-Za-z0-9_.-]+$/u,{message:`Expected a repository path segment`})),T9=M({ok:rT(!0)}),E9={runId:HA},D9={loop:aA},O9=M({window:x9.pipe(ST(X6),DT(w(`30d`)))}),k9=i7(`OperatorApi`).add(a9(`operator`).add(X5(`upgradeStatus`,`/api/upgrade`,{success:G8}),X5(`serverVersion`,`/api/version`,{success:j}),Z5(`requestUpgrade`,`/api/upgrade`,{payload:W8,success:T9}),X5(`overview`,`/api/overview`,{success:y4}),Z5(`dismissNeed`,`/api/attention/dismiss`,{payload:sN,success:T9}),Z5(`undoDismissNeed`,`/api/attention/undo`,{payload:sN,success:T9}),X5(`agents`,`/api/agents`,{success:N(fN)}),Z5(`editAndRetry`,`/api/runs/:runId/edit-and-retry`,{params:E9,payload:bH,success:T9}),Z5(`runAgain`,`/api/runs/:runId/run-again`,{params:E9,payload:bH,success:h1}),Z5(`intervene`,`/api/runs/:runId/intervene`,{params:E9,payload:xH,success:T9}),Z5(`resetCycleBudget`,`/api/cycle-budgets/reset`,{payload:M({askId:lI}),success:T9}),X5(`detail`,`/api/runs/:runId`,{params:E9,query:C9,success:OH}),X5(`githubChanges`,`/api/runs/:runId/github-changes`,{params:E9,success:h3}),Z5(`approve`,`/api/runs/:runId/approve`,{params:E9,success:T9}),Z5(`resolveFailure`,`/api/runs/:runId/resolve-failure`,{params:E9,payload:M({attemptId:sF}),success:T9}),Z5(`retry`,`/api/runs/:runId/retry`,{params:E9,success:T9}),Z5(`cancel`,`/api/runs/:runId/cancel`,{params:E9,success:T9}),Z5(`moveBoardItem`,`/api/projects/:owner/:repository/items/:item/lane`,{params:{owner:w9,repository:w9,item:sE.pipe(ST(rI))},payload:M({toLane:kH}),success:T9}),Z5(`discardLeftovers`,`/api/workers/:worker/discard-leftovers`,{params:{worker:EN},success:T9}),Z5(`pause`,`/api/loops/:loop/pause`,{params:D9,success:T9}),Z5(`unpause`,`/api/loops/:loop/unpause`,{params:D9,success:T9})).add(X5(`task`,`/api/projects/:owner/:repository/tasks/:item`,{params:{owner:w9,repository:w9,item:sE.pipe(ST(rI))},success:j3})).add(X5(`configurationCapabilities`,`/api/configuration/capabilities`,{success:M({harnesses:N(lN),efforts:N(uN)})}),X5(`configurationRepositories`,`/api/configuration/repositories`,{success:N(Xk)}),X5(`configurationLabels`,`/api/configuration/labels/:repository`,{params:{repository:Xk},success:N(IK)}),X5(`configurationRevisions`,`/api/configuration/revisions`,{query:M({kind:$w(x9),identifier:$w(x9.pipe(ST(k8))),before:$w(x9.pipe(ST(sE),ST(D8))),limit:x9.pipe(ST(sE),ST(L8.fields.limit),DT(w(`50`)))}),success:H8,error:_9}),X5(`configurationRevision`,`/api/configuration/revisions/:number`,{params:v9,success:U8,error:_9}),X5(`configurationEntity`,`/api/configuration/entities/:kind/:identifier`,{params:y9,success:B8,error:_9}),Q5(`replaceConfigurationEntity`,`/api/configuration/entities/:kind/:identifier`,{params:y9,payload:z8,success:U8,error:_9}),$5(`deleteConfigurationEntity`,`/api/configuration/entities/:kind/:identifier`,{params:y9,payload:R8,success:U8,error:_9}),Z5(`revertConfigurationRevision`,`/api/configuration/revisions/:number/revert`,{params:v9,payload:R8,success:U8,error:_9})).add(X5(`configuration`,`/api/configuration`,{success:s6})).add(X5(`desk`,`/api/desk`,{success:P6})).add(X5(`statistics`,`/api/statistics`,{query:O9,success:o8}),X5(`runStatistics`,`/api/statistics/runs`,{query:O9,success:S8})).annotate(d7,{onExcessProperty:`error`}).middleware(l9)),A9=()=>C7(k9,{baseUrl:globalThis.location.origin}),j9=e=>Xg(E(A9(),t=>e(t.operator)).pipe(kg(KW,!1),Tg(eG))),M9=e=>e instanceof Error?e.message:String(e),N9=e=>`${e.harness} · ${e.model} · ${e.effort}`,P9=e=>{switch(e){case`issue`:return`Issue`;case`pr`:return`PR`;case`schedule`:return`Schedule`;default:return e}},F9=(e,t=Date.now())=>{let n=Math.max(0,t-Date.parse(e));return n<6e4?`now`:n<36e5?`${Math.floor(n/6e4)}m`:n<864e5?`${Math.floor(n/36e5)}h`:`${Math.floor(n/864e5)}d`},I9=(e,t)=>{let n=F9(e,t);return n===`now`?`just now`:`${n} ago`},L9=e=>{let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())} ${n(t.getHours())}:${n(t.getMinutes())}`},R9=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],z9=e=>{let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${t.getDate()} ${R9[t.getMonth()]} ${n(t.getHours())}:${n(t.getMinutes())}`},B9=e=>`${e.getDate()} ${R9[e.getMonth()]}`,V9=e=>{let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`},H9=e=>{let t=Math.max(0,Math.round(e/1e3));if(t<60)return`${t}s`;let n=Math.round(t/60);return n<60?`${n} min`:n%60==0?`${Math.floor(n/60)} h`:`${Math.floor(n/60)} h ${n%60} min`},U9=e=>new Intl.NumberFormat(`en`,{notation:`compact`,maximumFractionDigits:1}).format(e),W9=e=>e>0&&e<.005?`under $0.01`:`$${e.toFixed(2)}`,G9=e=>({claude:`Claude Code`,codex:`Codex`,pi:`Pi`})[e],K9=e=>({apiKeys:`API keys`,claudePlan:`Claude plan`,chatgptPlan:`ChatGPT plan`})[e],q9=e=>e%1440==0?`${e/1440}-day`:e%60==0?`${e/60}-hour`:`${e}-minute`,J9=`Loading…`,Y9=`Could not load the page`,X9=`Try again`;export{FH as $,JT as $t,v4 as A,Nr as An,lT as At,ZJ as B,y as Bn,j as Bt,m9 as C,ga as Cn,oN as Ct,k8 as D,Oi as Dn,eA as Dt,j8 as E,Di as En,Xk as Et,W$ as F,Tr as Fn,rT as Ft,Xq as G,Hw as Gt,RJ as H,b as Hn,P as Ht,G$ as I,x as In,F as It,rU as J,aE as Jt,Zq as K,Ww as Kt,n1 as L,S as Ln,I as Lt,_4 as M,Sr as Mn,R as Mt,p4 as N,yr as Nn,IE as Nt,A8 as O,jr as On,kk as Ot,c2 as P,C as Pn,LE as Pt,IH as Q,HT as Qt,P$ as R,Or as Rn,cT as Rt,s9 as S,Wg as Sn,sN as St,R8 as T,Bi as Tn,AA as Tt,kJ as U,Mr as Un,Gw as Ut,uJ as V,br as Vn,M as Vt,FJ as W,ST as Wt,NH as X,UT as Xt,tU as Y,Vw as Yt,zH as Z,IT as Zt,q9 as _,$h as _n,GN as _t,z9 as a,J_ as an,jB as at,h9 as b,w as bn,fN as bt,G9 as c,K_ as cn,Cz as ct,K9 as d,og as dn,UF as dt,GT as en,bH as et,L9 as f,Uh as fn,IF as ft,W9 as g,dg as gn,lF as gt,X9 as h,ng as hn,zF as ht,B9 as i,Bw as in,MB as it,h4 as j,kr as jn,sE as jt,N8 as k,Ir as kn,N as kt,J9 as l,rg as ln,fz as lt,P9 as m,e_ as mn,HF as mt,N9 as n,$w as nn,xH as nt,H9 as o,G_ as on,pB as ot,U9 as p,E as pn,RF as pt,Jq as q,Xw as qt,V9 as r,PE as rn,AB as rt,F9 as s,W_ as sn,bz as st,I9 as t,eT as tn,OH as tt,Y9 as u,sg as un,rI as ut,j9 as v,Xg as vn,KN as vt,W8 as w,Xi as wn,HA as wt,g9 as x,qh as xn,uN as xt,M9 as y,Zg as yn,JN as yt,N$ as z,vr as zn,hT as zt};
|