holycodex 0.16.10-dev.116.1 → 0.16.11-dev.120.1

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/dist/agent.js CHANGED
@@ -1,59 +1,38 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var mp="0.15";function br(e,t=new WeakSet){if(t.has(e))return;t.add(e);for(let r of Reflect.ownKeys(e)){let n=Object.getOwnPropertyDescriptor(e,r);if(n&&"value"in n&&hp(n.value))br(n.value,t)}Object.freeze(e)}function hp(e){return typeof e==="object"&&e!==null}var tc={comma:",",tab:"\t",pipe:"|"},Dr=tc.comma;function bt(e){let t=0,r=e.length;while(t<r&&e[t]===" ")t++;while(r>t&&e[r-1]===" ")r--;return t===0&&r===e.length?e:e.slice(t,r)}function kg(e){return e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t").replace(/[\u0000-\u001F]/g,(t)=>`\\u${t.charCodeAt(0).toString(16).padStart(4,"0")}`)}function Cg(e){let t="",r=0;while(r<e.length){if(e[r]==="\\"){if(r+1>=e.length)throw SyntaxError("Invalid escape sequence: backslash at end of string");let n=e[r+1];if(n==="n"){t+=`
4
- `,r+=2;continue}if(n==="t"){t+="\t",r+=2;continue}if(n==="r"){t+="\r",r+=2;continue}if(n==="\\"){t+="\\",r+=2;continue}if(n==='"'){t+='"',r+=2;continue}if(n==="u"){if(r+6>e.length)throw SyntaxError(`Invalid escape sequence: truncated \\u escape at "${e.slice(r,r+6)}"`);let o=e.slice(r+2,r+6);if(!/^[0-9a-f]{4}$/i.test(o))throw SyntaxError(`Invalid escape sequence: \\u must be followed by 4 hex digits, got "${o}"`);let i=Number.parseInt(o,16);if(i>=55296&&i<=57343)throw SyntaxError(`Invalid escape sequence: \\u${o} is a lone surrogate. Supplementary code points MUST appear as literal UTF-8`);t+=String.fromCodePoint(i),r+=6;continue}throw SyntaxError(`Invalid escape sequence: \\${n}`)}t+=e[r],r++}return t}function sc(e,t){let r=t+1;while(r<e.length){if(e[r]==="\\"&&r+1<e.length){r+=2;continue}if(e[r]==='"')return r;r++}return-1}function dt(e,t,r=0){let n=!1,o=r;while(o<e.length){if(e[o]==="\\"&&o+1<e.length&&n){o+=2;continue}if(e[o]==='"'){n=!n,o++;continue}if(e[o]===t&&!n)return o;o++}return-1}var ke=class extends SyntaxError{constructor(e,t){let r=t?.line!==void 0?`Line ${t.line}: `:"";super(r+e,t?.cause!==void 0?{cause:t.cause}:void 0);this.name="ToonDecodeError",this.line=t?.line,this.source=t?.source}};function ft(e,t){try{return t()}catch(r){if(r instanceof ke)throw r;if(r instanceof Error)throw new ke(r.message,{line:e.lineNumber,source:e.raw,cause:r});throw r}}var ZA=/^[ \t]*/;function QA(){return{lineNumber:0,blankLines:[]}}function XA(e,t,r,n){t.lineNumber++;let o=t.lineNumber;if(o===1&&e[0]==="\uFEFF")e=e.slice(1);if(e[e.length-1]==="\r")e=e.slice(0,-1);let i=ZA.exec(e)[0],s=i.indexOf("\t"),a=n&&s!==-1?s:i.length,c=n||s===-1?0:i.split("\t").length-1,l=tT(e.slice(a));if(s===-1&&l[0]==="#")return;let u=eT(a-c,r)+c;if(!l){t.blankLines.push({lineNumber:o,indent:a,depth:u});return}if(n){if(s!==-1)throw new ke("Tabs are not allowed in indentation in strict mode",{line:o,source:e});if(a>0&&a%r!==0)throw new ke(`Indentation must be exact multiple of ${r}, but found ${a} spaces`,{line:o,source:e})}return{raw:e,indent:a,content:l,depth:u,lineNumber:o}}function eT(e,t){return Math.floor(e/t)}function tT(e){let t=e.length;while(t>0&&e[t-1]===" ")t--;return t===e.length?e:e.slice(0,t)}var Pg=Symbol("fetch-line");function rT(e){return{buffer:[],done:!1,lastLine:void 0,scanState:QA(),indentSize:e.indentSize,strict:e.strict}}function*Ng(e){while(e.buffer.length===0&&!e.done){let t=yield Pg;if(t===void 0){e.done=!0;return}let r=XA(t,e.scanState,e.indentSize,e.strict);if(r!==void 0)e.buffer.push(r)}}function*$t(e){return yield*Ng(e),e.buffer[0]}function*Pt(e){yield*Ng(e);let t=e.buffer[0];if(t!==void 0)e.buffer.shift(),e.lastLine=t;return t}function*nT(e,t){let r=e[Symbol.iterator](),n=t.next();while(!n.done)if(n.value===Pg){let o=r.next();n=t.next(o.done?void 0:o.value)}else yield n.value,n=t.next()}var oT=/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:e[+-]?\d+)?$/i;function Fg(e){return e==="true"||e==="false"||e==="null"}function iT(e){if(!e)return!1;if(!oT.test(e))return!1;let t=Number(e);return!Number.isNaN(t)&&Number.isFinite(t)}function rc(e,t){let r=e.trimStart(),n=-1;if(r.startsWith('"')){let T=sc(r,0);if(T===-1)return{kind:"notHeader"};if(!r.slice(T+1).startsWith("["))return{kind:"notHeader"};let I=e.length-r.length+T+1;n=e.indexOf("[",I)}else n=dt(e,"[");if(n===-1)return{kind:"notHeader"};let o=dt(e,":");if(o!==-1&&o<n)return{kind:"notHeader"};let i=dt(e,"]",n);if(i===-1)return{kind:"notHeader"};let s=i+1,a=s,c=dt(e,"{",i);if(c!==-1&&c<dt(e,":",i)){let T=e.slice(i+1,c);if(T!==""){let C=T.trim();return{kind:"invalid",reason:C===""?"Unexpected whitespace between bracket segment and field list":`Unexpected content "${C}" between bracket segment and field list`}}let I=gp(e,c);if(I!==-1)a=I+1}if(s=dt(e,":",Math.max(i,a)),s===-1)return{kind:"notHeader"};let l=Math.max(i+1,a),u=e.slice(l,s);if(u!==""){let T=u.trim();return{kind:"invalid",reason:T===""?"Unexpected whitespace between bracket segment and colon":`Unexpected content "${T}" between bracket segment and colon`}}let d;if(n>0){let T=e.slice(0,n);if(T!==T.trimEnd())return{kind:"invalid",reason:"Unexpected whitespace between key and bracket segment"};d=T.startsWith('"')?nc(T):T}let f=bt(e.slice(s+1)),g=e.slice(n+1,i),y;try{y=aT(g,t)}catch(T){return{kind:"invalid",reason:T.message}}let{length:O,delimiter:m,keyed:x}=y,D;if(c!==-1&&c<s){let T=gp(e,c);if(T!==-1&&T<s){let I=e.slice(c+1,T),C=uT(I,m);if(C!==void 0)return{kind:"invalid",reason:`Header delimiter mismatch: bracket declares "${Og(m)}" but field list contains unquoted "${Og(C)}"`};try{D=Mg(I,m)}catch(L){return{kind:"invalid",reason:L.message}}}}let k=D?Lg(D):void 0,H=k?`Duplicate field name "${k}" in field list`:void 0;if(x&&!D)return{kind:"invalid",reason:"Keyed header requires a field list"};if(D&&f)return{kind:"invalid",reason:H??"Unexpected content after fields-bearing header colon"};return{kind:"header",header:{key:d,length:O,delimiter:m,fields:D,keyed:x},inlineValues:f||void 0,strictError:H}}var sT=/^(?:0|[1-9]\d*)$/;function aT(e,t){let r=e,n=t;if(r.endsWith("\t"))n=tc.tab,r=r.slice(0,-1);else if(r.endsWith("|"))n=tc.pipe,r=r.slice(0,-1);let o=!1;if(r.endsWith(":"))o=!0,r=r.slice(0,-1);if(!sT.test(r))throw SyntaxError(`Invalid array length: "${e}" (expected non-negative integer with no leading zeros)`);return{length:Number.parseInt(r,10),delimiter:n,keyed:o}}function Mg(e,t){return cT(e,t).map((r)=>{let n=bt(r);if(!n)throw SyntaxError("Empty field name in field list");let o=dt(n,"{");if(o===-1)return{name:nc(n)};let i=bt(n.slice(0,o));if(!i)throw SyntaxError("Missing field name before nested field group");let s=gp(n,o);if(s===-1)throw SyntaxError("Unmatched brace in field list");if(s!==n.length-1)throw SyntaxError("Unexpected content after nested field group");let a=Mg(n.slice(o+1,s),t);return{name:nc(i),children:a}})}function cT(e,t){let r=[],n="",o=!1,i=0,s=0;while(s<e.length){let a=e[s];if(a==="\\"&&s+1<e.length&&o){n+=a+e[s+1],s+=2;continue}if(a==='"'){o=!o,n+=a,s++;continue}if(!o){if(a==="{")i++;else if(a==="}")i--;else if(a===t&&i===0){r.push(n),n="",s++;continue}}n+=a,s++}return r.push(n),r}function gp(e,t){let r=!1,n=0,o=t;while(o<e.length){let i=e[o];if(i==="\\"&&o+1<e.length&&r){o+=2;continue}if(i==='"'){r=!r,o++;continue}if(!r){if(i==="{")n++;else if(i==="}"){if(n--,n===0)return o}}o++}return-1}function Lg(e){let t=new Set;for(let r of e){if(t.has(r.name))return r.name;if(t.add(r.name),r.children){let n=Lg(r.children);if(n!==void 0)return n}}}function Sp(e){let t=0;for(let r of e)t+=r.children?Sp(r.children):1;return t}var lT=[",","\t","|"];function uT(e,t){for(let r of lT){if(r===t)continue;if(dt(e,r)!==-1)return r}}function Og(e){if(e==="\t")return"\\t";return e}function bp(e,t){let r=[],n="",o=!1,i=0;while(i<e.length){let s=e[i];if(s==="\\"&&i+1<e.length&&o){n+=s+e[i+1],i+=2;continue}if(s==='"'){o=!o,n+=s,i++;continue}if(s===t&&!o){r.push(bt(n)),n="",i++;continue}n+=s,i++}if(n||r.length>0)r.push(bt(n));return r}function _p(e){return e.map((t)=>ac(t))}function ac(e){let t=bt(e);if(!t)return"";if(t.startsWith('"'))return nc(t);if(Fg(t)){if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null}if(iT(t)){let r=Number.parseFloat(t);return Object.is(r,-0)?0:r}return t}function nc(e){let t=bt(e);if(t.startsWith('"')){let r=sc(t,0);if(r===-1)throw SyntaxError("Unterminated string: missing closing quote");if(r!==t.length-1)throw SyntaxError("Unexpected characters after closing quote");return Cg(t.slice(1,r))}return t}function pT(e,t){let r=dt(e,":",t);if(r===-1)throw SyntaxError("Missing colon after key");return{key:bt(e.slice(t,r)),end:r+1}}function dT(e,t){let r=sc(e,t);if(r===-1)throw SyntaxError("Unterminated quoted key");let n=Cg(e.slice(t+1,r)),o=r+1;if(o>=e.length||e[o]!==":")throw SyntaxError("Missing colon after key");return o++,{key:n,end:o}}function Dg(e,t){return e[t]==='"'?dT(e,t):pT(e,t)}function qg(e){return e.trim().startsWith("[")&&dt(e,":")!==-1}function fT(e){return dt(e,":")!==-1}function ao(e,t,r,n,o){if(n.strict&&e!==t)throw new ke(`Expected ${t} ${r}, but got ${e}`,{line:o.lineNumber,source:o.raw})}function mT(e,t,r){if(e?.depth===t&&e.content.startsWith("- "))throw new ke(`Expected ${r} list-form items, but found more`,{line:e.lineNumber,source:e.raw})}function hT(e,t,r){if(e?.depth===t&&!e.content.startsWith("- ")&&Ug(e.content,r.delimiter))throw new ke(`Expected ${r.length} tabular rows, but found more`,{line:e.lineNumber,source:e.raw})}function wp(e,t,r,n,o){if(!n)return;let i=r.find((s)=>s.lineNumber>e&&s.lineNumber<t);if(i)throw new ke(`Blank lines inside ${o} are not allowed in strict mode`,{line:i.lineNumber})}function Ug(e,t){let r=dt(e,":"),n=dt(e,t);if(r===-1)return!0;if(n!==-1&&n<r)return!0;return!1}function gT(e){return{indentSize:e?.indentSize??e?.indent??2,strict:e?.strict??!0}}function yT(e,t){let r=gT(t);return nT(e,xT(rT(r),r))}function*xT(e,t){let r=yield*$t(e);if(!r){yield{type:"startObject"},yield{type:"endObject"};return}if(bt(r.content)==="[]"){yield*Pt(e),yield{type:"startArray",length:0},yield{type:"endArray"},yield*vg(e,t.strict);return}if(qg(r.content)){let i=ft(r,()=>ic(rc(r.content,Dr),t.strict));if(i){yield*Pt(e),yield*oc(i.header,i.inlineValues,e,0,t,r),yield*vg(e,t.strict);return}}yield*Pt(e);let n=yield*$t(e);if(n===void 0&&!Tg(r)){yield{type:"primitive",value:ft(r,()=>ac(r.content))};return}if(!Tg(r)&&n?.depth===0)throw new ke("Top-level document must start with a key-value or array-header line",{line:r.lineNumber,source:r.raw});let o=t.strict?new Set:void 0;yield{type:"startObject"},yield*ls(r,e,0,t,o);while(!0){let i=yield*$t(e);if(!i)break;if(i.depth!==0){if(t.strict)throw jg(i,0);Hg(i),yield*Pt(e);continue}yield*Pt(e),yield*ls(i,e,0,t,o)}yield{type:"endObject"}}function ST(e,t,r){if(r&&e.depth>t+1)throw new ke(`Indentation depth jump: expected depth ${t+1}, but found ${e.depth}`,{line:e.lineNumber,source:e.raw})}function jg(e,t){return new ke(`Over-indented line: expected depth ${t}, but found ${e.depth}`,{line:e.lineNumber,source:e.raw})}function Hg(e){if(e.content.startsWith("- ")||e.content==="-"||dt(e.content,":")!==-1)return;throw new ke("Unexpected bare token line outside root primitive position",{line:e.lineNumber,source:e.raw})}function $g(e){return new ke("Keyless keyed header is only valid at the document root",{line:e.lineNumber,source:e.raw})}function bT(e){return new ke("Keyless array header is only valid at the document root or as a list item",{line:e.lineNumber,source:e.raw})}function _T(e){return new ke("Keyless header with a field list is only valid at the document root",{line:e.lineNumber,source:e.raw})}function*vg(e,t){if(!t)return;let r=yield*$t(e);if(r)throw new ke("Unexpected content after the document root",{line:r.lineNumber,source:r.raw})}function yp(e,t,r){if(!r)return;if(r.has(e))throw new ke(`Duplicate sibling key "${e}"`,{line:t.lineNumber,source:t.raw});r.add(e)}function*ls(e,t,r,n,o){let i=e.content,s=ft(e,()=>ic(rc(i,Dr),n.strict));if(s&&s.header.key!==void 0){yp(s.header.key,e,o),yield{type:"key",key:s.header.key},yield*oc(s.header,s.inlineValues,t,r,n,e);return}if(s&&s.header.key===void 0&&n.strict)throw s.header.keyed?$g(e):bT(e);let{key:a,end:c}=ft(e,()=>Dg(i,0)),l=bt(i.slice(c));if(yp(a,e,o),yield{type:"key",key:a},!l){let u=yield*$t(t);if(u&&u.depth>r){ST(u,r,n.strict),yield{type:"startObject"},yield*wT(t,r+1,n),yield{type:"endObject"};return}yield{type:"startObject"},yield{type:"endObject"};return}if(l==="[]"){yield{type:"startArray",length:0},yield{type:"endArray"};return}yield{type:"primitive",value:ft(e,()=>ac(l))}}function*wT(e,t,r){let n,o=r.strict?new Set:void 0;while(!0){let i=yield*$t(e);if(!i||i.depth<t)break;if(n===void 0&&i.depth>=t)n=i.depth;if(i.depth===n)yield*Pt(e),yield*ls(i,e,n,r,o);else if(n!==void 0&&i.depth>n){if(r.strict)throw jg(i,n);Hg(i),yield*Pt(e)}else break}}function*oc(e,t,r,n,o,i){if(e.keyed){yield*OT(e,r,n,o,i);return}if(yield{type:"startArray",length:e.length},t){yield*ET(e,t,o,i),yield{type:"endArray"};return}if(e.fields&&e.fields.length>0){yield*vT(e,r,n,o,i),yield{type:"endArray"};return}yield*AT(e,r,n,o,i),yield{type:"endArray"}}function*ET(e,t,r,n){if(!bt(t)){ao(0,e.length,"inline-form values",r,n);return}let o=ft(n,()=>bp(t,e.delimiter)),i=ft(n,()=>_p(o));ao(i.length,e.length,"inline-form values",r,n);for(let s of i)yield{type:"primitive",value:s}}function*OT(e,t,r,n,o){let i=r+1,s=Sp(e.fields),a=n.strict?new Set:void 0,c=0,l,u,d=o;yield{type:"startObject"};while(!0){let f=yield*$t(t);if(!f||f.depth<=r)break;if(f.depth>i){if(n.strict)throw new ke("Unexpected indentation inside keyed tabular object",{line:f.lineNumber,source:f.raw});yield*Pt(t);continue}if(dt(f.content,":")===-1){if(n.strict)throw new ke("Expected entry row inside keyed tabular object",{line:f.lineNumber,source:f.raw});yield*Pt(t);continue}if(yield*Pt(t),l===void 0)l=f.lineNumber;u=f.lineNumber,d=f;let{key:g,end:y}=ft(f,()=>Dg(f.content,0));yp(g,f,a),yield{type:"key",key:g};let O=bt(f.content.slice(y)),m=O===""?[]:ft(f,()=>bp(O,e.delimiter));ao(m.length,s,"keyed entry cells",n,f);let x=ft(f,()=>_p(m));yield*Bg(e.fields,x),c++}if(ao(c,e.length,"keyed entries",n,d),n.strict&&l!==void 0&&u!==void 0)wp(l,u,t.scanState.blankLines,n.strict,"keyed tabular object");yield{type:"endObject"}}function*vT(e,t,r,n,o){let i=r+1,s=0,a,c,l=o;while(!n.strict||s<e.length){let u=yield*$t(t);if(!u||u.depth<i)break;if(u.depth===i){if(!Ug(u.content,e.delimiter))break;if(a===void 0)a=u.lineNumber;c=u.lineNumber,l=u,yield*Pt(t);let d=ft(u,()=>bp(u.content,e.delimiter));ao(d.length,Sp(e.fields),"tabular row values",n,u);let f=ft(u,()=>_p(d));yield*Bg(e.fields,f),s++}else break}if(ao(s,e.length,"tabular rows",n,l),n.strict&&a!==void 0&&c!==void 0)wp(a,c,t.scanState.blankLines,n.strict,"tabular array");if(n.strict)hT(yield*$t(t),i,e)}function*AT(e,t,r,n,o){let i=r+1,s=0,a,c,l=o;while(!n.strict||s<e.length){let u=yield*$t(t);if(!u||u.depth<i)break;let d=u.content.startsWith("- ")||u.content==="-";if(u.depth===i&&d){if(a===void 0)a=u.lineNumber;c=u.lineNumber,l=u,yield*TT(t,i,n);let f=t.lastLine;if(f)c=f.lineNumber,l=f;s++}else break}if(ao(s,e.length,"list-form items",n,l),n.strict&&a!==void 0&&c!==void 0)wp(a,c,t.scanState.blankLines,n.strict,"list-form array");if(n.strict)mT(yield*$t(t),i,e.length)}function*TT(e,t,r){let n=yield*Pt(e);if(!n)throw ReferenceError("Expected list item");let o;if(n.content==="-"){yield{type:"startObject"},yield{type:"endObject"};return}else if(n.content.startsWith("- "))o=n.content.slice(2);else throw new ke('Expected list item to start with "- "',{line:n.lineNumber,source:n.raw});if(!bt(o)){yield{type:"startObject"},yield{type:"endObject"};return}if(bt(o)==="[]"){yield{type:"startArray",length:0},yield{type:"endArray"};return}let i={...n,content:o};if(qg(o)){let a=ft(i,()=>ic(rc(o,Dr),r.strict));if(a)if(a.header.keyed||a.header.fields!==void 0){if(r.strict)throw a.header.keyed?$g(i):_T(i)}else{yield*oc(a.header,a.inlineValues,e,t,r,i);return}}let s=ft(i,()=>ic(rc(o,Dr),r.strict));if(s&&s.header.key!==void 0&&s.header.fields!==void 0){let a=s.header,c=r.strict?new Set([a.key]):void 0;yield{type:"startObject"},yield{type:"key",key:a.key},yield*oc(a,s.inlineValues,e,t+1,r,i),yield*Ag(e,t+1,r,c),yield{type:"endObject"};return}if(fT(o)){let a=r.strict?new Set:void 0;yield{type:"startObject"},yield*ls(i,e,t+1,r,a),yield*Ag(e,t+1,r,a),yield{type:"endObject"};return}yield{type:"primitive",value:ft(i,()=>ac(o))}}function*Ag(e,t,r,n){while(!0){let o=yield*$t(e);if(!o||o.depth<t)break;if(o.depth===t&&!o.content.startsWith("- "))yield*Pt(e),yield*ls(o,e,t,r,n);else break}}function Tg(e){let t=e.content;if(t.startsWith('"')){let r=sc(t,0);if(r===-1)return!1;return t.slice(r+1).includes(":")}else return t.includes(":")}function ic(e,t){if(e.kind==="notHeader")return;if(e.kind==="invalid"){if(t)throw SyntaxError(e.reason);return}if(t&&e.strictError!==void 0)throw SyntaxError(e.strictError);return{header:e.header,inlineValues:e.inlineValues}}function*Bg(e,t){let r=0;function*n(o){yield{type:"startObject"};for(let i of o){if(!i.children&&r>=t.length)continue;if(yield{type:"key",key:i.name},i.children)yield*n(i.children);else yield{type:"primitive",value:t[r++]}}yield{type:"endObject"}}yield*n(e)}function cs(e,t,r){if(t==="__proto__"){Object.defineProperty(e,t,{value:r,enumerable:!0,writable:!0,configurable:!0});return}e[t]=r}function IT(e){let t={stack:[],root:void 0};for(let r of e)RT(t,r);return kT(t)}function RT(e,t){let{stack:r}=e;switch(t.type){case"startObject":{let n={};if(r.length===0)r.push({type:"object",obj:n});else{let o=r[r.length-1];if(o.type==="object"){if(o.currentKey===void 0)throw Error("Object startObject event without preceding key");cs(o.obj,o.currentKey,n),o.currentKey=void 0}else if(o.type==="array")o.arr.push(n);r.push({type:"object",obj:n})}break}case"endObject":{if(r.length===0)throw Error("Unexpected endObject event");let n=r.pop();if(n.type!=="object")throw Error("Mismatched endObject event");if(r.length===0)e.root=n.obj;break}case"startArray":{let n=[];if(r.length===0)r.push({type:"array",arr:n});else{let o=r[r.length-1];if(o.type==="object"){if(o.currentKey===void 0)throw Error("Array startArray event without preceding key");cs(o.obj,o.currentKey,n),o.currentKey=void 0}else if(o.type==="array")o.arr.push(n);r.push({type:"array",arr:n})}break}case"endArray":{if(r.length===0)throw Error("Unexpected endArray event");let n=r.pop();if(n.type!=="array")throw Error("Mismatched endArray event");if(r.length===0)e.root=n.arr;break}case"key":{if(r.length===0)throw Error("Key event outside of object context");let n=r[r.length-1];if(n.type!=="object")throw Error("Key event outside of object context");n.currentKey=t.key;break}case"primitive":if(r.length===0)e.root=t.value;else{let n=r[r.length-1];if(n.type==="object"){if(n.currentKey===void 0)throw Error("Primitive event without preceding key in object");cs(n.obj,n.currentKey,t.value),n.currentKey=void 0}else if(n.type==="array")n.arr.push(t.value)}break}}function kT(e){if(e.stack.length!==0)throw Error("Incomplete event stream: unclosed objects or arrays");if(e.root===void 0)throw Error("No root value built from events");return e.root}var CT=new RegExp("(?:^\uFEFF?|\\n) *#"),PT=class{constructor(e){if(CT.test(e))throw TypeError(`Raw string must not contain a line starting with "#": ${JSON.stringify(e)}`);this.value=e}};function ds(e){return e instanceof PT}var NT=/[\uD800-\uDFFF]/;function so(e){if(e===null)return null;if(ds(e))return e;if(typeof e==="object"&&e!==null&&"toJSON"in e&&typeof e.toJSON==="function"){let t=e.toJSON();if(t!==e)return so(t)}if(typeof e==="string")return Ig(e,"string value"),e;if(typeof e==="boolean")return e;if(typeof e==="number"){if(Object.is(e,-0))return 0;if(!Number.isFinite(e))return null;return e}if(typeof e==="bigint"){if(e>=Number.MIN_SAFE_INTEGER&&e<=Number.MAX_SAFE_INTEGER)return Number(e);return e.toString()}if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(so);if(e instanceof Set)return Array.from(e).map(so);if(e instanceof Map)return Object.fromEntries(Array.from(e,([t,r])=>[String(t),so(r)]));if(MT(e)){let t={};for(let r in e)if(Object.hasOwn(e,r))Ig(r,"object key"),cs(t,r,so(e[r]));return t}return null}function Ig(e,t){if(!NT.test(e))return;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n<55296||n>57343)continue;let o=n<=56319,i=e.charCodeAt(r+1);if(o&&i>=56320&&i<=57343){r++;continue}throw TypeError(`Cannot encode ${t} containing an unpaired surrogate U+${n.toString(16).toUpperCase()} at index ${r}`)}}function FT(e){return e===null||typeof e==="string"||typeof e==="number"||typeof e==="boolean"}function lo(e){return FT(e)||ds(e)}function co(e){return Array.isArray(e)}function qr(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)&&!ds(e)}function us(e){return Object.keys(e).length===0}function MT(e){if(e===null||typeof e!=="object")return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function ps(e){return e.length===0||e.every((t)=>lo(t))}function LT(e){return e.length===0||e.every((t)=>co(t))}function Wg(e){return e.length===0||e.every((t)=>qr(t))}var DT=/^[+-]?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i;function qT(e){if(!Object.values(tc).includes(e))throw TypeError(`Invalid delimiter ${JSON.stringify(e)}. Valid delimiters are: comma (,), tab (\\t), pipe (|)`)}function UT(e){return/^[A-Z_][\w.]*$/i.test(e)}function jT(e,t=Dr){if(!e)return!1;if(/^[ \t]|[ \t]$/.test(e))return!1;if(Fg(e)||HT(e))return!1;if(e.includes(":"))return!1;if(e.includes('"')||e.includes("\\"))return!1;if(/[[\]{}]/.test(e))return!1;if(/[\u0000-\u001F]/.test(e))return!1;if(e.includes(t))return!1;if(e.startsWith("-"))return!1;if(e.startsWith("#"))return!1;return!0}function HT(e){return DT.test(e)}function fs(e,t){if(ds(e))return e.value;if(e===null)return"null";if(typeof e==="boolean")return String(e);if(typeof e==="number")return String(e);return $T(e,t)}function $T(e,t=Dr){if(jT(e,t))return e;return`"${kg(e)}"`}function oi(e){if(UT(e))return e;return`"${kg(e)}"`}function Ep(e,t=Dr){return e.map((r)=>fs(r,t)).join(t)}function Lr(e,t){let r=t?.key,n=t?.fields,o=t?.delimiter??",",i="";if(r!=null)i+=oi(r);if(i+=`[${e}${t?.keyed?":":""}${o!==Dr?o:""}]`,n)i+=`{${Kg(n,o)}}`;return i+=":",i}function Kg(e,t){return e.map((r)=>oi(r.name)+(r.children?`{${Kg(r.children,t)}}`:"")).join(t)}function cc(e){if(e.length===0)return;let t=Object.keys(e[0]);if(t.length===0)return;for(let n of e){if(Object.keys(n).length!==t.length)return;for(let o of t)if(!Object.hasOwn(n,o))return}let r=[];for(let n of t){let o=BT(n,e.map((i)=>i[n]));if(!o)return;r.push(o)}return r}function Op(e){let t=Object.values(e);if(t.length<2)return;if(!t.every((r)=>qr(r)&&!us(r)))return;return cc(t)}function Vg(e,t){let r=[];return zg(e,t,r),r}function BT(e,t){if(t.every((n)=>lo(n)))return{name:e};if(!t.every((n)=>qr(n)&&!us(n)))return;let r=cc(t);if(!r)return;return{name:e,children:r}}function zg(e,t,r){for(let n of t){let o=e[n.name];if(n.children)zg(o,n.children,r);else r.push(o)}}function*WT(e,t,r){if(lo(e)){let n=fs(e,t.delimiter);if(n!=="")yield n;return}if(co(e))yield*Yg(void 0,e,r,t);else if(qr(e)){let n=Op(e);if(n){yield*Gg(void 0,e,n,r,t);return}yield*ni(e,r,t)}}function*ni(e,t,r){for(let[n,o]of Object.entries(e))yield*KT(n,o,t,r)}function*KT(e,t,r,n){let o=oi(e);if(lo(t))yield Bt(r,`${o}: ${fs(t,n.delimiter)}`,n.indentSize);else if(co(t))yield*Yg(e,t,r,n);else if(qr(t)){let i=Op(t);if(i){yield*Gg(e,t,i,r,n);return}if(yield Bt(r,`${o}:`,n.indentSize),!us(t))yield*ni(t,r+1,n)}}function*Gg(e,t,r,n,o){let i=Object.entries(t);yield Bt(n,Lr(i.length,{key:e,fields:r,delimiter:o.delimiter,keyed:!0}),o.indentSize),yield*Jg(i,r,n+1,o)}function*Jg(e,t,r,n){for(let[o,i]of e){let s=Vg(i,t);yield Bt(r,`${oi(o)}: ${Ep(s,n.delimiter)}`,n.indentSize)}}function*Yg(e,t,r,n){if(t.length===0){yield Bt(r,e!=null?`${oi(e)}: []`:"[]",n.indentSize);return}if(ps(t)){yield Bt(r,lc(t,n.delimiter,e),n.indentSize);return}if(LT(t)){if(t.every((o)=>ps(o))){yield*VT(e,t,r,n);return}}if(Wg(t)){let o=cc(t);if(o)yield*zT(e,t,o,r,n);else yield*Rg(e,t,r,n);return}yield*Rg(e,t,r,n)}function*VT(e,t,r,n){yield Bt(r,Lr(t.length,{key:e,delimiter:n.delimiter}),n.indentSize);for(let o of t)if(ps(o)){let i=lc(o,n.delimiter);yield er(r+1,i,n.indentSize)}}function lc(e,t,r){let n=Lr(e.length,{key:r,delimiter:t}),o=Ep(e,t);if(e.length===0)return n;return`${n} ${o}`}function*zT(e,t,r,n,o){yield Bt(n,Lr(t.length,{key:e,fields:r,delimiter:o.delimiter}),o.indentSize),yield*Zg(t,r,n+1,o)}function*Zg(e,t,r,n){for(let o of e)yield Bt(r,Ep(Vg(o,t),n.delimiter),n.indentSize)}function*Rg(e,t,r,n){yield Bt(r,Lr(t.length,{key:e,delimiter:n.delimiter}),n.indentSize);for(let o of t)yield*vp(o,r+1,n)}function*GT(e,t,r){if(us(e)){yield Bt(t,"-",r.indentSize);return}let n=Object.entries(e),[o,i]=n[0],s=n.slice(1);if(co(i)&&Wg(i)){let c=cc(i);if(c){if(yield er(t,Lr(i.length,{key:o,fields:c,delimiter:r.delimiter}),r.indentSize),yield*Zg(i,c,t+2,r),s.length>0)yield*ni(Object.fromEntries(s),t+1,r);return}}if(qr(i)){let c=Op(i);if(c){let l=Object.entries(i);if(yield er(t,Lr(l.length,{key:o,fields:c,delimiter:r.delimiter,keyed:!0}),r.indentSize),yield*Jg(l,c,t+2,r),s.length>0)yield*ni(Object.fromEntries(s),t+1,r);return}}let a=oi(o);if(lo(i))yield er(t,`${a}: ${fs(i,r.delimiter)}`,r.indentSize);else if(co(i))if(i.length===0)yield er(t,`${a}: []`,r.indentSize);else if(ps(i))yield er(t,`${a}${lc(i,r.delimiter)}`,r.indentSize);else{yield er(t,`${a}${Lr(i.length,{delimiter:r.delimiter})}`,r.indentSize);for(let c of i)yield*vp(c,t+2,r)}else if(qr(i)){if(yield er(t,`${a}:`,r.indentSize),!us(i))yield*ni(i,t+2,r)}if(s.length>0)yield*ni(Object.fromEntries(s),t+1,r)}function*vp(e,t,r){if(lo(e))yield er(t,fs(e,r.delimiter),r.indentSize);else if(co(e))if(ps(e))yield er(t,lc(e,r.delimiter),r.indentSize);else{yield er(t,Lr(e.length,{delimiter:r.delimiter}),r.indentSize);for(let n of e)yield*vp(n,t+1,r)}else if(qr(e))yield*GT(e,t,r)}function Bt(e,t,r){return" ".repeat(r*e)+t}function er(e,t,r){return Bt(e,"- "+t,r)}function JT(e,t){let r=t("",e,[]);if(r===void 0)return xp(e,t,[]);return Ap(e,r,t,[])}function Ap(e,t,r,n){if(ds(t)&&!lo(e))return xp(e,r,n);return xp(so(t),r,n)}function xp(e,t,r){if(qr(e))return YT(e,t,r);if(co(e))return ZT(e,t,r);return e}function YT(e,t,r){let n={};for(let[o,i]of Object.entries(e)){let s=[...r,o],a=t(o,i,s);if(a===void 0)continue;cs(n,o,Ap(i,a,t,s))}return n}function ZT(e,t,r){let n=[];for(let o=0;o<e.length;o++){let i=e[o],s=[...r,o],a=t(String(o),i,s);if(a===void 0)continue;n.push(Ap(i,a,t,s))}return n}function et(e,t){return Array.from(QT(e,t)).join(`
5
- `)}function Qg(e,t){return XT(e.split(`
6
- `),t)}function QT(e,t){let r=so(e),n=eI(t);return WT(n.replacer?JT(r,n.replacer):r,n,0)}function XT(e,t){return IT(yT(e,tI(t)))}function eI(e){let t=e?.delimiter??Dr;return qT(t),{indentSize:e?.indentSize??e?.indent??2,delimiter:t,replacer:e?.replacer}}function tI(e){return{indentSize:e?.indentSize??e?.indent??2,strict:e?.strict??!0}}class _t extends Error{code;details;constructor(e,t,r={},n){super(t,n);this.name="CoreError",this.code=e,this.details=r,br(this.details),Object.freeze(this)}}var Tp=(e)=>typeof e==="function",p=function(e,t){if(typeof e==="function")return function(){if(e(arguments))return t.apply(this,arguments);return(r)=>t(r,...arguments)};switch(e){case 0:case 1:throw RangeError(`Invalid arity ${e}`);case 2:return function(r,n){if(arguments.length>=2)return t(r,n);return function(o){return t(o,r)}};case 3:return function(r,n,o){if(arguments.length>=3)return t(r,n,o);return function(i){return t(i,r,n)}};case 4:return function(r,n,o,i){if(arguments.length>=4)return t(r,n,o,i);return function(s){return t(s,r,n,o)}};case 5:return function(r,n,o,i,s){if(arguments.length>=5)return t(r,n,o,i,s);return function(a){return t(a,r,n,o,i)}};default:return function(){if(arguments.length>=e)return t.apply(this,arguments);let r=arguments;return function(n){return t(n,...r)}}}};var te=(e)=>e;var ms=(e)=>()=>e,hs=ms(!0),bn=ms(!1);var uc=ms(void 0),gs=uc;function h(e,t,r,n,o,i,s,a,c){switch(arguments.length){case 1:return e;case 2:return t(e);case 3:return r(t(e));case 4:return n(r(t(e)));case 5:return o(n(r(t(e))));case 6:return i(o(n(r(t(e)))));case 7:return s(i(o(n(r(t(e))))));case 8:return a(s(i(o(n(r(t(e)))))));case 9:return c(a(s(i(o(n(r(t(e))))))));default:{let l=arguments[0];for(let u=1;u<arguments.length;u++)l=arguments[u](l);return l}}}var xs=(e)=>(t,r)=>t===r||e(t,r),rI=(e,t)=>e===t,nI=()=>rI;var oI=nI();var Ip=p(2,(e,t)=>xs((r,n)=>e(t(r),t(n)))),Xg=Ip(oI,(e)=>e.getTime());var ey=(e)=>xs((t,r)=>{if(t.length!==r.length)return!1;for(let n=0;n<t.length;n++)if(!e(t[n],r[n]))return!1;return!0});var Ss,B=(e,t)=>{if(!Ss)globalThis["effect/GlobalValue"]??=new Map,Ss=globalThis["effect/GlobalValue"];if(!Ss.has(e))Ss.set(e,t());return Ss.get(e)};var Ve=(e)=>typeof e==="string",Nt=(e)=>typeof e==="number",uo=(e)=>typeof e==="boolean",_n=(e)=>typeof e==="bigint",po=(e)=>typeof e==="symbol";var wn=Tp,ty=(e)=>e===void 0;var ry=(e)=>!1;var bs=(e)=>typeof e==="object"&&e!==null,mt=(e)=>bs(e)||wn(e),v=p(2,(e,t)=>mt(e)&&(t in e)),_s=p(2,(e,t)=>v(e,"_tag")&&e._tag===t),fo=(e)=>e===null||e===void 0,ny=(e)=>e!==null&&e!==void 0;var dc=(e)=>e instanceof Date,Rp=(e)=>typeof e==="string"||v(e,Symbol.iterator),kp=(e)=>bs(e)&&!Array.isArray(e);var oy=(e)=>v(e,"then")&&wn(e.then);var mo=(e)=>`BUG: ${e} - please report an issue at https://github.com/Effect-TS/effect/issues`;class si{self;called=!1;constructor(e){this.self=e}next(e){return this.called?{value:e,done:!0}:(this.called=!0,{value:this.self,done:!1})}return(e){return{value:e,done:!0}}throw(e){throw e}[Symbol.iterator](){return new si(this.self)}}var iI=335903614,sI=4150755663,aI=1481765933,cI=1284865837,lI=9007199254740992,uI=134217728;class Pp{_state;constructor(e,t,r,n){if(fo(t)&&fo(e))t=Math.random()*4294967295>>>0,e=0;else if(fo(t))t=e,e=0;if(fo(n)&&fo(r))n=this._state?this._state[3]:sI,r=this._state?this._state[2]:iI;else if(fo(n))n=r,r=0;return this._state=new Int32Array([0,0,r>>>0,((n||0)|1)>>>0]),this._next(),iy(this._state,this._state[0],this._state[1],e>>>0,t>>>0),this._next(),this}getState(){return[this._state[0],this._state[1],this._state[2],this._state[3]]}setState(e){this._state[0]=e[0],this._state[1]=e[1],this._state[2]=e[2],this._state[3]=e[3]|1}integer(e){return Math.round(this.number()*Number.MAX_SAFE_INTEGER)%e}number(){let e=(this._next()&67108863)*1,t=(this._next()&134217727)*1;return(e*uI+t)/lI}_next(){let e=this._state[0]>>>0,t=this._state[1]>>>0;pI(this._state,e,t,aI,cI),iy(this._state,this._state[0],this._state[1],this._state[2],this._state[3]);let r=e>>>18,n=(t>>>18|e<<14)>>>0;r=(r^e)>>>0,n=(n^t)>>>0;let o=(n>>>27|r<<5)>>>0,i=e>>>27,s=(-i>>>0&31)>>>0;return(o>>>i|o<<s)>>>0}}function pI(e,t,r,n,o){let i=(r>>>16)*(o&65535)>>>0,s=(r&65535)*(o>>>16)>>>0,a=(r&65535)*(o&65535)>>>0,c=(r>>>16)*(o>>>16)+((s>>>16)+(i>>>16))>>>0;if(s=s<<16>>>0,a=a+s>>>0,a>>>0<s>>>0)c=c+1>>>0;if(i=i<<16>>>0,a=a+i>>>0,a>>>0<i>>>0)c=c+1>>>0;c=c+Math.imul(r,n)>>>0,c=c+Math.imul(t,o)>>>0,e[0]=c,e[1]=a}function iy(e,t,r,n,o){let i=t+n>>>0,s=r+o>>>0;if(s>>>0<r>>>0)i=i+1|0;e[0]=i,e[1]=s}var Cp=Symbol.for("effect/Utils/YieldWrap");class Ur{#e;constructor(e){this.#e=e}[Cp](){return this.#e}}function Np(e){if(typeof e==="object"&&e!==null&&Cp in e)return e[Cp]();throw Error(mo("yieldWrapGet"))}var wt=B("effect/Utils/isStructuralRegion",()=>({enabled:!1,tester:void 0}));var sy={effect_internal_function:(e)=>e()},dI={effect_internal_function:(e)=>{try{return e()}finally{}}},fI=sy.effect_internal_function(()=>Error().stack)?.includes("effect_internal_function")===!0,ze=fI?sy.effect_internal_function:dI.effect_internal_function,_D=function*(){}.constructor;var Fp=B(Symbol.for("effect/Hash/randomHashCache"),()=>new WeakMap),P=Symbol.for("effect/Hash"),w=(e)=>{if(wt.enabled===!0)return 0;switch(typeof e){case"number":return mc(e);case"bigint":return ie(e.toString(10));case"boolean":return ie(String(e));case"symbol":return ie(String(e));case"string":return ie(e);case"undefined":return ie("undefined");case"function":case"object":if(e===null)return ie("null");else if(e instanceof Date){if(Number.isNaN(e.getTime()))return ie("Invalid Date");return w(e.toISOString())}else if(e instanceof URL)return w(e.href);else if(hI(e))return e[P]();else return ws(e);default:throw Error(`BUG: unhandled typeof ${typeof e} - please report an issue at https://github.com/Effect-TS/effect/issues`)}},ws=(e)=>{if(!Fp.has(e))Fp.set(e,mc(Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)));return Fp.get(e)},V=(e)=>(t)=>t*53^e,fc=(e)=>e&3221225471|e>>>1&1073741824,hI=(e)=>v(e,P),mc=(e)=>{if(e!==e||e===1/0)return 0;let t=e|0;if(t!==e)t^=e*4294967295;while(e>4294967295)t^=e/=4294967295;return fc(t)},ie=(e)=>{let t=5381,r=e.length;while(r)t=t*33^e.charCodeAt(--r);return fc(t)},gI=(e,t)=>{let r=12289;for(let n=0;n<t.length;n++)r^=h(ie(t[n]),V(w(e[t[n]])));return fc(r)},hc=(e)=>gI(e,Object.keys(e)),Ft=(e)=>{let t=6151;for(let r=0;r<e.length;r++)t=h(t,V(w(e[r])));return fc(t)},Z=function(){if(arguments.length===1){let r=arguments[0];return function(n){return Object.defineProperty(r,P,{value(){return n},enumerable:!1}),n}}let e=arguments[0],t=arguments[1];return Object.defineProperty(e,P,{value(){return t},enumerable:!1}),t};var R=Symbol.for("effect/Equal");function E(){if(arguments.length===1)return(e)=>gc(e,arguments[0]);return gc(arguments[0],arguments[1])}function gc(e,t){if(e===t)return!0;let r=typeof e;if(r!==typeof t)return!1;if(r==="object"||r==="function"){if(e!==null&&t!==null){if(Es(e)&&Es(t))if(w(e)===w(t)&&e[R](t))return!0;else return wt.enabled&&wt.tester?wt.tester(e,t):!1;else if(e instanceof Date&&t instanceof Date){let n=e.getTime(),o=t.getTime();return n===o||Number.isNaN(n)&&Number.isNaN(o)}else if(e instanceof URL&&t instanceof URL)return e.href===t.href}if(wt.enabled){if(e===null||t===null)return!1;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((n,o)=>gc(n,t[o]));if(Object.getPrototypeOf(e)===Object.prototype&&Object.getPrototypeOf(t)===Object.prototype){let n=Object.keys(e),o=Object.keys(t);if(n.length===o.length){for(let i of n)if(!((i in t)&&gc(e[i],t[i])))return wt.tester?wt.tester(e,t):!1;return!0}}return wt.tester?wt.tester(e,t):!1}}return wt.enabled&&wt.tester?wt.tester(e,t):!1}var Es=(e)=>v(e,R),Os=()=>E;var Y=Symbol.for("nodejs.util.inspect.custom"),re=(e)=>{try{if(v(e,"toJSON")&&wn(e.toJSON)&&e.toJSON.length===0)return e.toJSON();else if(Array.isArray(e))return e.map(re)}catch{return{}}return ly(e)},Mp="[Circular]";function yI(e){try{return e.toISOString()}catch{return"Invalid Date"}}function xI(e){try{let t=e.toString();return typeof t==="string"?t:String(t)}catch{return"[toString threw]"}}function vs(e){return Ve(e)?JSON.stringify(e):String(e)}function _r(e,t){let r=t?.space??0,n=new WeakSet,o=!r?"":Nt(r)?" ".repeat(r):r,i=(l)=>o.repeat(l),s=(l,u)=>{let d=l?.constructor;return d&&d!==Object.prototype.constructor&&d.name?`${d.name}(${u})`:u},a=(l)=>{try{return Reflect.ownKeys(l)}catch{return["[ownKeys threw]"]}};function c(l,u=0){if(Array.isArray(l)){if(n.has(l))return Mp;if(n.add(l),!o||l.length<=1)return`[${l.map((f)=>c(f,u)).join(",")}]`;let d=l.map((f)=>c(f,u+1)).join(`,
7
- `+i(u+1));return`[
8
- ${i(u+1)}${d}
9
- ${i(u)}]`}if(dc(l))return yI(l);if(!t?.ignoreToString&&v(l,"toString")&&wn(l.toString)&&l.toString!==Object.prototype.toString&&l.toString!==Array.prototype.toString){let d=xI(l);if(l instanceof Error&&l.cause)return`${d} (cause: ${c(l.cause,u)})`;return d}if(Ve(l))return JSON.stringify(l);if(Nt(l)||l==null||uo(l)||po(l))return String(l);if(_n(l))return String(l)+"n";if(l instanceof Set||l instanceof Map){if(n.has(l))return Mp;return n.add(l),`${l.constructor.name}(${c(Array.from(l),u)})`}if(mt(l)){if(n.has(l))return Mp;n.add(l);let d=a(l);if(!o||d.length<=1){let g=`{${d.map((y)=>`${vs(y)}:${c(l[y],u)}`).join(",")}}`;return s(l,g)}let f=`{
10
- ${d.map((g)=>`${i(u+1)}${vs(g)}: ${c(l[g],u+1)}`).join(`,
3
+ var As="0.15";function yt(e,t=new WeakSet){if(t.has(e))return;t.add(e);for(let n of Reflect.ownKeys(e)){let r=Object.getOwnPropertyDescriptor(e,n);if(r&&"value"in r&&lh(r.value))yt(r.value,t)}Object.freeze(e)}function lh(e){return typeof e==="object"&&e!==null}var Ao={comma:",",tab:"\t",pipe:"|"},kt=Ao.comma;function Ne(e){let t=0,n=e.length;while(t<n&&e[t]===" ")t++;while(n>t&&e[n-1]===" ")n--;return t===0&&n===e.length?e:e.slice(t,n)}function Iu(e){return e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t").replace(/[\u0000-\u001F]/g,(t)=>`\\u${t.charCodeAt(0).toString(16).padStart(4,"0")}`)}function _u(e){let t="",n=0;while(n<e.length){if(e[n]==="\\"){if(n+1>=e.length)throw SyntaxError("Invalid escape sequence: backslash at end of string");let r=e[n+1];if(r==="n"){t+=`
4
+ `,n+=2;continue}if(r==="t"){t+="\t",n+=2;continue}if(r==="r"){t+="\r",n+=2;continue}if(r==="\\"){t+="\\",n+=2;continue}if(r==='"'){t+='"',n+=2;continue}if(r==="u"){if(n+6>e.length)throw SyntaxError(`Invalid escape sequence: truncated \\u escape at "${e.slice(n,n+6)}"`);let o=e.slice(n+2,n+6);if(!/^[0-9a-f]{4}$/i.test(o))throw SyntaxError(`Invalid escape sequence: \\u must be followed by 4 hex digits, got "${o}"`);let i=Number.parseInt(o,16);if(i>=55296&&i<=57343)throw SyntaxError(`Invalid escape sequence: \\u${o} is a lone surrogate. Supplementary code points MUST appear as literal UTF-8`);t+=String.fromCodePoint(i),n+=6;continue}throw SyntaxError(`Invalid escape sequence: \\${r}`)}t+=e[n],n++}return t}function No(e,t){let n=t+1;while(n<e.length){if(e[n]==="\\"&&n+1<e.length){n+=2;continue}if(e[n]==='"')return n;n++}return-1}function ve(e,t,n=0){let r=!1,o=n;while(o<e.length){if(e[o]==="\\"&&o+1<e.length&&r){o+=2;continue}if(e[o]==='"'){r=!r,o++;continue}if(e[o]===t&&!r)return o;o++}return-1}var ne=class extends SyntaxError{constructor(e,t){let n=t?.line!==void 0?`Line ${t.line}: `:"";super(n+e,t?.cause!==void 0?{cause:t.cause}:void 0);this.name="ToonDecodeError",this.line=t?.line,this.source=t?.source}};function we(e,t){try{return t()}catch(n){if(n instanceof ne)throw n;if(n instanceof Error)throw new ne(n.message,{line:e.lineNumber,source:e.raw,cause:n});throw n}}var fh=/^[ \t]*/;function dh(){return{lineNumber:0,blankLines:[]}}function ph(e,t,n,r){t.lineNumber++;let o=t.lineNumber;if(o===1&&e[0]==="\uFEFF")e=e.slice(1);if(e[e.length-1]==="\r")e=e.slice(0,-1);let i=fh.exec(e)[0],s=i.indexOf("\t"),a=r&&s!==-1?s:i.length,l=r||s===-1?0:i.split("\t").length-1,m=hh(e.slice(a));if(s===-1&&m[0]==="#")return;let c=mh(a-l,n)+l;if(!m){t.blankLines.push({lineNumber:o,indent:a,depth:c});return}if(r){if(s!==-1)throw new ne("Tabs are not allowed in indentation in strict mode",{line:o,source:e});if(a>0&&a%n!==0)throw new ne(`Indentation must be exact multiple of ${n}, but found ${a} spaces`,{line:o,source:e})}return{raw:e,indent:a,content:m,depth:c,lineNumber:o}}function mh(e,t){return Math.floor(e/t)}function hh(e){let t=e.length;while(t>0&&e[t-1]===" ")t--;return t===e.length?e:e.slice(0,t)}var ku=Symbol("fetch-line");function gh(e){return{buffer:[],done:!1,lastLine:void 0,scanState:dh(),indentSize:e.indentSize,strict:e.strict}}function*Tu(e){while(e.buffer.length===0&&!e.done){let t=yield ku;if(t===void 0){e.done=!0;return}let n=ph(t,e.scanState,e.indentSize,e.strict);if(n!==void 0)e.buffer.push(n)}}function*Ge(e){return yield*Tu(e),e.buffer[0]}function*Me(e){yield*Tu(e);let t=e.buffer[0];if(t!==void 0)e.buffer.shift(),e.lastLine=t;return t}function*yh(e,t){let n=e[Symbol.iterator](),r=t.next();while(!r.done)if(r.value===ku){let o=n.next();r=t.next(o.done?void 0:o.value)}else yield r.value,r=t.next()}var xh=/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:e[+-]?\d+)?$/i;function Au(e){return e==="true"||e==="false"||e==="null"}function Sh(e){if(!e)return!1;if(!xh.test(e))return!1;let t=Number(e);return!Number.isNaN(t)&&Number.isFinite(t)}function Oo(e,t){let n=e.trimStart(),r=-1;if(n.startsWith('"')){let k=No(n,0);if(k===-1)return{kind:"notHeader"};if(!n.slice(k+1).startsWith("["))return{kind:"notHeader"};let M=e.length-n.length+k+1;r=e.indexOf("[",M)}else r=ve(e,"[");if(r===-1)return{kind:"notHeader"};let o=ve(e,":");if(o!==-1&&o<r)return{kind:"notHeader"};let i=ve(e,"]",r);if(i===-1)return{kind:"notHeader"};let s=i+1,a=s,l=ve(e,"{",i);if(l!==-1&&l<ve(e,":",i)){let k=e.slice(i+1,l);if(k!==""){let j=k.trim();return{kind:"invalid",reason:j===""?"Unexpected whitespace between bracket segment and field list":`Unexpected content "${j}" between bracket segment and field list`}}let M=Os(e,l);if(M!==-1)a=M+1}if(s=ve(e,":",Math.max(i,a)),s===-1)return{kind:"notHeader"};let m=Math.max(i+1,a),c=e.slice(m,s);if(c!==""){let k=c.trim();return{kind:"invalid",reason:k===""?"Unexpected whitespace between bracket segment and colon":`Unexpected content "${k}" between bracket segment and colon`}}let u;if(r>0){let k=e.slice(0,r);if(k!==k.trimEnd())return{kind:"invalid",reason:"Unexpected whitespace between key and bracket segment"};u=k.startsWith('"')?Co(k):k}let g=Ne(e.slice(s+1)),x=e.slice(r+1,i),S;try{S=bh(x,t)}catch(k){return{kind:"invalid",reason:k.message}}let{length:b,delimiter:y,keyed:p}=S,h;if(l!==-1&&l<s){let k=Os(e,l);if(k!==-1&&k<s){let M=e.slice(l+1,k),j=Ih(M,y);if(j!==void 0)return{kind:"invalid",reason:`Header delimiter mismatch: bracket declares "${xu(y)}" but field list contains unquoted "${xu(j)}"`};try{h=Ou(M,y)}catch(q){return{kind:"invalid",reason:q.message}}}}let _=h?Cu(h):void 0,I=_?`Duplicate field name "${_}" in field list`:void 0;if(p&&!h)return{kind:"invalid",reason:"Keyed header requires a field list"};if(h&&g)return{kind:"invalid",reason:I??"Unexpected content after fields-bearing header colon"};return{kind:"header",header:{key:u,length:b,delimiter:y,fields:h,keyed:p},inlineValues:g||void 0,strictError:I}}var Eh=/^(?:0|[1-9]\d*)$/;function bh(e,t){let n=e,r=t;if(n.endsWith("\t"))r=Ao.tab,n=n.slice(0,-1);else if(n.endsWith("|"))r=Ao.pipe,n=n.slice(0,-1);let o=!1;if(n.endsWith(":"))o=!0,n=n.slice(0,-1);if(!Eh.test(n))throw SyntaxError(`Invalid array length: "${e}" (expected non-negative integer with no leading zeros)`);return{length:Number.parseInt(n,10),delimiter:r,keyed:o}}function Ou(e,t){return vh(e,t).map((n)=>{let r=Ne(n);if(!r)throw SyntaxError("Empty field name in field list");let o=ve(r,"{");if(o===-1)return{name:Co(r)};let i=Ne(r.slice(0,o));if(!i)throw SyntaxError("Missing field name before nested field group");let s=Os(r,o);if(s===-1)throw SyntaxError("Unmatched brace in field list");if(s!==r.length-1)throw SyntaxError("Unexpected content after nested field group");let a=Ou(r.slice(o+1,s),t);return{name:Co(i),children:a}})}function vh(e,t){let n=[],r="",o=!1,i=0,s=0;while(s<e.length){let a=e[s];if(a==="\\"&&s+1<e.length&&o){r+=a+e[s+1],s+=2;continue}if(a==='"'){o=!o,r+=a,s++;continue}if(!o){if(a==="{")i++;else if(a==="}")i--;else if(a===t&&i===0){n.push(r),r="",s++;continue}}r+=a,s++}return n.push(r),n}function Os(e,t){let n=!1,r=0,o=t;while(o<e.length){let i=e[o];if(i==="\\"&&o+1<e.length&&n){o+=2;continue}if(i==='"'){n=!n,o++;continue}if(!n){if(i==="{")r++;else if(i==="}"){if(r--,r===0)return o}}o++}return-1}function Cu(e){let t=new Set;for(let n of e){if(t.has(n.name))return n.name;if(t.add(n.name),n.children){let r=Cu(n.children);if(r!==void 0)return r}}}function Ps(e){let t=0;for(let n of e)t+=n.children?Ps(n.children):1;return t}var wh=[",","\t","|"];function Ih(e,t){for(let n of wh){if(n===t)continue;if(ve(e,n)!==-1)return n}}function xu(e){if(e==="\t")return"\\t";return e}function Ns(e,t){let n=[],r="",o=!1,i=0;while(i<e.length){let s=e[i];if(s==="\\"&&i+1<e.length&&o){r+=s+e[i+1],i+=2;continue}if(s==='"'){o=!o,r+=s,i++;continue}if(s===t&&!o){n.push(Ne(r)),r="",i++;continue}r+=s,i++}if(r||n.length>0)n.push(Ne(r));return n}function Fs(e){return e.map((t)=>Fo(t))}function Fo(e){let t=Ne(e);if(!t)return"";if(t.startsWith('"'))return Co(t);if(Au(t)){if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null}if(Sh(t)){let n=Number.parseFloat(t);return Object.is(n,-0)?0:n}return t}function Co(e){let t=Ne(e);if(t.startsWith('"')){let n=No(t,0);if(n===-1)throw SyntaxError("Unterminated string: missing closing quote");if(n!==t.length-1)throw SyntaxError("Unexpected characters after closing quote");return _u(t.slice(1,n))}return t}function _h(e,t){let n=ve(e,":",t);if(n===-1)throw SyntaxError("Missing colon after key");return{key:Ne(e.slice(t,n)),end:n+1}}function kh(e,t){let n=No(e,t);if(n===-1)throw SyntaxError("Unterminated quoted key");let r=_u(e.slice(t+1,n)),o=n+1;if(o>=e.length||e[o]!==":")throw SyntaxError("Missing colon after key");return o++,{key:r,end:o}}function Ru(e,t){return e[t]==='"'?kh(e,t):_h(e,t)}function Pu(e){return e.trim().startsWith("[")&&ve(e,":")!==-1}function Th(e){return ve(e,":")!==-1}function tn(e,t,n,r,o){if(r.strict&&e!==t)throw new ne(`Expected ${t} ${n}, but got ${e}`,{line:o.lineNumber,source:o.raw})}function Ah(e,t,n){if(e?.depth===t&&e.content.startsWith("- "))throw new ne(`Expected ${n} list-form items, but found more`,{line:e.lineNumber,source:e.raw})}function Oh(e,t,n){if(e?.depth===t&&!e.content.startsWith("- ")&&Nu(e.content,n.delimiter))throw new ne(`Expected ${n.length} tabular rows, but found more`,{line:e.lineNumber,source:e.raw})}function Ds(e,t,n,r,o){if(!r)return;let i=n.find((s)=>s.lineNumber>e&&s.lineNumber<t);if(i)throw new ne(`Blank lines inside ${o} are not allowed in strict mode`,{line:i.lineNumber})}function Nu(e,t){let n=ve(e,":"),r=ve(e,t);if(n===-1)return!0;if(r!==-1&&r<n)return!0;return!1}function Ch(e){return{indentSize:e?.indentSize??e?.indent??2,strict:e?.strict??!0}}function Rh(e,t){let n=Ch(t);return yh(e,Ph(gh(n),n))}function*Ph(e,t){let n=yield*Ge(e);if(!n){yield{type:"startObject"},yield{type:"endObject"};return}if(Ne(n.content)==="[]"){yield*Me(e),yield{type:"startArray",length:0},yield{type:"endArray"},yield*Su(e,t.strict);return}if(Pu(n.content)){let i=we(n,()=>Po(Oo(n.content,kt),t.strict));if(i){yield*Me(e),yield*Ro(i.header,i.inlineValues,e,0,t,n),yield*Su(e,t.strict);return}}yield*Me(e);let r=yield*Ge(e);if(r===void 0&&!bu(n)){yield{type:"primitive",value:we(n,()=>Fo(n.content))};return}if(!bu(n)&&r?.depth===0)throw new ne("Top-level document must start with a key-value or array-header line",{line:n.lineNumber,source:n.raw});let o=t.strict?new Set:void 0;yield{type:"startObject"},yield*mr(n,e,0,t,o);while(!0){let i=yield*Ge(e);if(!i)break;if(i.depth!==0){if(t.strict)throw Fu(i,0);Du(i),yield*Me(e);continue}yield*Me(e),yield*mr(i,e,0,t,o)}yield{type:"endObject"}}function Nh(e,t,n){if(n&&e.depth>t+1)throw new ne(`Indentation depth jump: expected depth ${t+1}, but found ${e.depth}`,{line:e.lineNumber,source:e.raw})}function Fu(e,t){return new ne(`Over-indented line: expected depth ${t}, but found ${e.depth}`,{line:e.lineNumber,source:e.raw})}function Du(e){if(e.content.startsWith("- ")||e.content==="-"||ve(e.content,":")!==-1)return;throw new ne("Unexpected bare token line outside root primitive position",{line:e.lineNumber,source:e.raw})}function Lu(e){return new ne("Keyless keyed header is only valid at the document root",{line:e.lineNumber,source:e.raw})}function Fh(e){return new ne("Keyless array header is only valid at the document root or as a list item",{line:e.lineNumber,source:e.raw})}function Dh(e){return new ne("Keyless header with a field list is only valid at the document root",{line:e.lineNumber,source:e.raw})}function*Su(e,t){if(!t)return;let n=yield*Ge(e);if(n)throw new ne("Unexpected content after the document root",{line:n.lineNumber,source:n.raw})}function Cs(e,t,n){if(!n)return;if(n.has(e))throw new ne(`Duplicate sibling key "${e}"`,{line:t.lineNumber,source:t.raw});n.add(e)}function*mr(e,t,n,r,o){let i=e.content,s=we(e,()=>Po(Oo(i,kt),r.strict));if(s&&s.header.key!==void 0){Cs(s.header.key,e,o),yield{type:"key",key:s.header.key},yield*Ro(s.header,s.inlineValues,t,n,r,e);return}if(s&&s.header.key===void 0&&r.strict)throw s.header.keyed?Lu(e):Fh(e);let{key:a,end:l}=we(e,()=>Ru(i,0)),m=Ne(i.slice(l));if(Cs(a,e,o),yield{type:"key",key:a},!m){let c=yield*Ge(t);if(c&&c.depth>n){Nh(c,n,r.strict),yield{type:"startObject"},yield*Lh(t,n+1,r),yield{type:"endObject"};return}yield{type:"startObject"},yield{type:"endObject"};return}if(m==="[]"){yield{type:"startArray",length:0},yield{type:"endArray"};return}yield{type:"primitive",value:we(e,()=>Fo(m))}}function*Lh(e,t,n){let r,o=n.strict?new Set:void 0;while(!0){let i=yield*Ge(e);if(!i||i.depth<t)break;if(r===void 0&&i.depth>=t)r=i.depth;if(i.depth===r)yield*Me(e),yield*mr(i,e,r,n,o);else if(r!==void 0&&i.depth>r){if(n.strict)throw Fu(i,r);Du(i),yield*Me(e)}else break}}function*Ro(e,t,n,r,o,i){if(e.keyed){yield*Mh(e,n,r,o,i);return}if(yield{type:"startArray",length:e.length},t){yield*Uh(e,t,o,i),yield{type:"endArray"};return}if(e.fields&&e.fields.length>0){yield*$h(e,n,r,o,i),yield{type:"endArray"};return}yield*jh(e,n,r,o,i),yield{type:"endArray"}}function*Uh(e,t,n,r){if(!Ne(t)){tn(0,e.length,"inline-form values",n,r);return}let o=we(r,()=>Ns(t,e.delimiter)),i=we(r,()=>Fs(o));tn(i.length,e.length,"inline-form values",n,r);for(let s of i)yield{type:"primitive",value:s}}function*Mh(e,t,n,r,o){let i=n+1,s=Ps(e.fields),a=r.strict?new Set:void 0,l=0,m,c,u=o;yield{type:"startObject"};while(!0){let g=yield*Ge(t);if(!g||g.depth<=n)break;if(g.depth>i){if(r.strict)throw new ne("Unexpected indentation inside keyed tabular object",{line:g.lineNumber,source:g.raw});yield*Me(t);continue}if(ve(g.content,":")===-1){if(r.strict)throw new ne("Expected entry row inside keyed tabular object",{line:g.lineNumber,source:g.raw});yield*Me(t);continue}if(yield*Me(t),m===void 0)m=g.lineNumber;c=g.lineNumber,u=g;let{key:x,end:S}=we(g,()=>Ru(g.content,0));Cs(x,g,a),yield{type:"key",key:x};let b=Ne(g.content.slice(S)),y=b===""?[]:we(g,()=>Ns(b,e.delimiter));tn(y.length,s,"keyed entry cells",r,g);let p=we(g,()=>Fs(y));yield*Uu(e.fields,p),l++}if(tn(l,e.length,"keyed entries",r,u),r.strict&&m!==void 0&&c!==void 0)Ds(m,c,t.scanState.blankLines,r.strict,"keyed tabular object");yield{type:"endObject"}}function*$h(e,t,n,r,o){let i=n+1,s=0,a,l,m=o;while(!r.strict||s<e.length){let c=yield*Ge(t);if(!c||c.depth<i)break;if(c.depth===i){if(!Nu(c.content,e.delimiter))break;if(a===void 0)a=c.lineNumber;l=c.lineNumber,m=c,yield*Me(t);let u=we(c,()=>Ns(c.content,e.delimiter));tn(u.length,Ps(e.fields),"tabular row values",r,c);let g=we(c,()=>Fs(u));yield*Uu(e.fields,g),s++}else break}if(tn(s,e.length,"tabular rows",r,m),r.strict&&a!==void 0&&l!==void 0)Ds(a,l,t.scanState.blankLines,r.strict,"tabular array");if(r.strict)Oh(yield*Ge(t),i,e)}function*jh(e,t,n,r,o){let i=n+1,s=0,a,l,m=o;while(!r.strict||s<e.length){let c=yield*Ge(t);if(!c||c.depth<i)break;let u=c.content.startsWith("- ")||c.content==="-";if(c.depth===i&&u){if(a===void 0)a=c.lineNumber;l=c.lineNumber,m=c,yield*Bh(t,i,r);let g=t.lastLine;if(g)l=g.lineNumber,m=g;s++}else break}if(tn(s,e.length,"list-form items",r,m),r.strict&&a!==void 0&&l!==void 0)Ds(a,l,t.scanState.blankLines,r.strict,"list-form array");if(r.strict)Ah(yield*Ge(t),i,e.length)}function*Bh(e,t,n){let r=yield*Me(e);if(!r)throw ReferenceError("Expected list item");let o;if(r.content==="-"){yield{type:"startObject"},yield{type:"endObject"};return}else if(r.content.startsWith("- "))o=r.content.slice(2);else throw new ne('Expected list item to start with "- "',{line:r.lineNumber,source:r.raw});if(!Ne(o)){yield{type:"startObject"},yield{type:"endObject"};return}if(Ne(o)==="[]"){yield{type:"startArray",length:0},yield{type:"endArray"};return}let i={...r,content:o};if(Pu(o)){let a=we(i,()=>Po(Oo(o,kt),n.strict));if(a)if(a.header.keyed||a.header.fields!==void 0){if(n.strict)throw a.header.keyed?Lu(i):Dh(i)}else{yield*Ro(a.header,a.inlineValues,e,t,n,i);return}}let s=we(i,()=>Po(Oo(o,kt),n.strict));if(s&&s.header.key!==void 0&&s.header.fields!==void 0){let a=s.header,l=n.strict?new Set([a.key]):void 0;yield{type:"startObject"},yield{type:"key",key:a.key},yield*Ro(a,s.inlineValues,e,t+1,n,i),yield*Eu(e,t+1,n,l),yield{type:"endObject"};return}if(Th(o)){let a=n.strict?new Set:void 0;yield{type:"startObject"},yield*mr(i,e,t+1,n,a),yield*Eu(e,t+1,n,a),yield{type:"endObject"};return}yield{type:"primitive",value:we(i,()=>Fo(o))}}function*Eu(e,t,n,r){while(!0){let o=yield*Ge(e);if(!o||o.depth<t)break;if(o.depth===t&&!o.content.startsWith("- "))yield*Me(e),yield*mr(o,e,t,n,r);else break}}function bu(e){let t=e.content;if(t.startsWith('"')){let n=No(t,0);if(n===-1)return!1;return t.slice(n+1).includes(":")}else return t.includes(":")}function Po(e,t){if(e.kind==="notHeader")return;if(e.kind==="invalid"){if(t)throw SyntaxError(e.reason);return}if(t&&e.strictError!==void 0)throw SyntaxError(e.strictError);return{header:e.header,inlineValues:e.inlineValues}}function*Uu(e,t){let n=0;function*r(o){yield{type:"startObject"};for(let i of o){if(!i.children&&n>=t.length)continue;if(yield{type:"key",key:i.name},i.children)yield*r(i.children);else yield{type:"primitive",value:t[n++]}}yield{type:"endObject"}}yield*r(e)}function pr(e,t,n){if(t==="__proto__"){Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0});return}e[t]=n}function qh(e){let t={stack:[],root:void 0};for(let n of e)Vh(t,n);return zh(t)}function Vh(e,t){let{stack:n}=e;switch(t.type){case"startObject":{let r={};if(n.length===0)n.push({type:"object",obj:r});else{let o=n[n.length-1];if(o.type==="object"){if(o.currentKey===void 0)throw Error("Object startObject event without preceding key");pr(o.obj,o.currentKey,r),o.currentKey=void 0}else if(o.type==="array")o.arr.push(r);n.push({type:"object",obj:r})}break}case"endObject":{if(n.length===0)throw Error("Unexpected endObject event");let r=n.pop();if(r.type!=="object")throw Error("Mismatched endObject event");if(n.length===0)e.root=r.obj;break}case"startArray":{let r=[];if(n.length===0)n.push({type:"array",arr:r});else{let o=n[n.length-1];if(o.type==="object"){if(o.currentKey===void 0)throw Error("Array startArray event without preceding key");pr(o.obj,o.currentKey,r),o.currentKey=void 0}else if(o.type==="array")o.arr.push(r);n.push({type:"array",arr:r})}break}case"endArray":{if(n.length===0)throw Error("Unexpected endArray event");let r=n.pop();if(r.type!=="array")throw Error("Mismatched endArray event");if(n.length===0)e.root=r.arr;break}case"key":{if(n.length===0)throw Error("Key event outside of object context");let r=n[n.length-1];if(r.type!=="object")throw Error("Key event outside of object context");r.currentKey=t.key;break}case"primitive":if(n.length===0)e.root=t.value;else{let r=n[n.length-1];if(r.type==="object"){if(r.currentKey===void 0)throw Error("Primitive event without preceding key in object");pr(r.obj,r.currentKey,t.value),r.currentKey=void 0}else if(r.type==="array")r.arr.push(t.value)}break}}function zh(e){if(e.stack.length!==0)throw Error("Incomplete event stream: unclosed objects or arrays");if(e.root===void 0)throw Error("No root value built from events");return e.root}var Wh=new RegExp("(?:^\uFEFF?|\\n) *#"),Kh=class{constructor(e){if(Wh.test(e))throw TypeError(`Raw string must not contain a line starting with "#": ${JSON.stringify(e)}`);this.value=e}};function yr(e){return e instanceof Kh}var Gh=/[\uD800-\uDFFF]/;function en(e){if(e===null)return null;if(yr(e))return e;if(typeof e==="object"&&e!==null&&"toJSON"in e&&typeof e.toJSON==="function"){let t=e.toJSON();if(t!==e)return en(t)}if(typeof e==="string")return vu(e,"string value"),e;if(typeof e==="boolean")return e;if(typeof e==="number"){if(Object.is(e,-0))return 0;if(!Number.isFinite(e))return null;return e}if(typeof e==="bigint"){if(e>=Number.MIN_SAFE_INTEGER&&e<=Number.MAX_SAFE_INTEGER)return Number(e);return e.toString()}if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(en);if(e instanceof Set)return Array.from(e).map(en);if(e instanceof Map)return Object.fromEntries(Array.from(e,([t,n])=>[String(t),en(n)]));if(Hh(e)){let t={};for(let n in e)if(Object.hasOwn(e,n))vu(n,"object key"),pr(t,n,en(e[n]));return t}return null}function vu(e,t){if(!Gh.test(e))return;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r<55296||r>57343)continue;let o=r<=56319,i=e.charCodeAt(n+1);if(o&&i>=56320&&i<=57343){n++;continue}throw TypeError(`Cannot encode ${t} containing an unpaired surrogate U+${r.toString(16).toUpperCase()} at index ${n}`)}}function Jh(e){return e===null||typeof e==="string"||typeof e==="number"||typeof e==="boolean"}function rn(e){return Jh(e)||yr(e)}function nn(e){return Array.isArray(e)}function Tt(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)&&!yr(e)}function hr(e){return Object.keys(e).length===0}function Hh(e){if(e===null||typeof e!=="object")return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function gr(e){return e.length===0||e.every((t)=>rn(t))}function Yh(e){return e.length===0||e.every((t)=>nn(t))}function Mu(e){return e.length===0||e.every((t)=>Tt(t))}var Zh=/^[+-]?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i;function Xh(e){if(!Object.values(Ao).includes(e))throw TypeError(`Invalid delimiter ${JSON.stringify(e)}. Valid delimiters are: comma (,), tab (\\t), pipe (|)`)}function Qh(e){return/^[A-Z_][\w.]*$/i.test(e)}function eg(e,t=kt){if(!e)return!1;if(/^[ \t]|[ \t]$/.test(e))return!1;if(Au(e)||tg(e))return!1;if(e.includes(":"))return!1;if(e.includes('"')||e.includes("\\"))return!1;if(/[[\]{}]/.test(e))return!1;if(/[\u0000-\u001F]/.test(e))return!1;if(e.includes(t))return!1;if(e.startsWith("-"))return!1;if(e.startsWith("#"))return!1;return!0}function tg(e){return Zh.test(e)}function xr(e,t){if(yr(e))return e.value;if(e===null)return"null";if(typeof e==="boolean")return String(e);if(typeof e==="number")return String(e);return ng(e,t)}function ng(e,t=kt){if(eg(e,t))return e;return`"${Iu(e)}"`}function Dn(e){if(Qh(e))return e;return`"${Iu(e)}"`}function Ls(e,t=kt){return e.map((n)=>xr(n,t)).join(t)}function _t(e,t){let n=t?.key,r=t?.fields,o=t?.delimiter??",",i="";if(n!=null)i+=Dn(n);if(i+=`[${e}${t?.keyed?":":""}${o!==kt?o:""}]`,r)i+=`{${$u(r,o)}}`;return i+=":",i}function $u(e,t){return e.map((n)=>Dn(n.name)+(n.children?`{${$u(n.children,t)}}`:"")).join(t)}function Do(e){if(e.length===0)return;let t=Object.keys(e[0]);if(t.length===0)return;for(let r of e){if(Object.keys(r).length!==t.length)return;for(let o of t)if(!Object.hasOwn(r,o))return}let n=[];for(let r of t){let o=rg(r,e.map((i)=>i[r]));if(!o)return;n.push(o)}return n}function Us(e){let t=Object.values(e);if(t.length<2)return;if(!t.every((n)=>Tt(n)&&!hr(n)))return;return Do(t)}function ju(e,t){let n=[];return Bu(e,t,n),n}function rg(e,t){if(t.every((r)=>rn(r)))return{name:e};if(!t.every((r)=>Tt(r)&&!hr(r)))return;let n=Do(t);if(!n)return;return{name:e,children:n}}function Bu(e,t,n){for(let r of t){let o=e[r.name];if(r.children)Bu(o,r.children,n);else n.push(o)}}function*og(e,t,n){if(rn(e)){let r=xr(e,t.delimiter);if(r!=="")yield r;return}if(nn(e))yield*zu(void 0,e,n,t);else if(Tt(e)){let r=Us(e);if(r){yield*qu(void 0,e,r,n,t);return}yield*Fn(e,n,t)}}function*Fn(e,t,n){for(let[r,o]of Object.entries(e))yield*ig(r,o,t,n)}function*ig(e,t,n,r){let o=Dn(e);if(rn(t))yield Je(n,`${o}: ${xr(t,r.delimiter)}`,r.indentSize);else if(nn(t))yield*zu(e,t,n,r);else if(Tt(t)){let i=Us(t);if(i){yield*qu(e,t,i,n,r);return}if(yield Je(n,`${o}:`,r.indentSize),!hr(t))yield*Fn(t,n+1,r)}}function*qu(e,t,n,r,o){let i=Object.entries(t);yield Je(r,_t(i.length,{key:e,fields:n,delimiter:o.delimiter,keyed:!0}),o.indentSize),yield*Vu(i,n,r+1,o)}function*Vu(e,t,n,r){for(let[o,i]of e){let s=ju(i,t);yield Je(n,`${Dn(o)}: ${Ls(s,r.delimiter)}`,r.indentSize)}}function*zu(e,t,n,r){if(t.length===0){yield Je(n,e!=null?`${Dn(e)}: []`:"[]",r.indentSize);return}if(gr(t)){yield Je(n,Lo(t,r.delimiter,e),r.indentSize);return}if(Yh(t)){if(t.every((o)=>gr(o))){yield*sg(e,t,n,r);return}}if(Mu(t)){let o=Do(t);if(o)yield*ag(e,t,o,n,r);else yield*wu(e,t,n,r);return}yield*wu(e,t,n,r)}function*sg(e,t,n,r){yield Je(n,_t(t.length,{key:e,delimiter:r.delimiter}),r.indentSize);for(let o of t)if(gr(o)){let i=Lo(o,r.delimiter);yield it(n+1,i,r.indentSize)}}function Lo(e,t,n){let r=_t(e.length,{key:n,delimiter:t}),o=Ls(e,t);if(e.length===0)return r;return`${r} ${o}`}function*ag(e,t,n,r,o){yield Je(r,_t(t.length,{key:e,fields:n,delimiter:o.delimiter}),o.indentSize),yield*Wu(t,n,r+1,o)}function*Wu(e,t,n,r){for(let o of e)yield Je(n,Ls(ju(o,t),r.delimiter),r.indentSize)}function*wu(e,t,n,r){yield Je(n,_t(t.length,{key:e,delimiter:r.delimiter}),r.indentSize);for(let o of t)yield*Ms(o,n+1,r)}function*cg(e,t,n){if(hr(e)){yield Je(t,"-",n.indentSize);return}let r=Object.entries(e),[o,i]=r[0],s=r.slice(1);if(nn(i)&&Mu(i)){let l=Do(i);if(l){if(yield it(t,_t(i.length,{key:o,fields:l,delimiter:n.delimiter}),n.indentSize),yield*Wu(i,l,t+2,n),s.length>0)yield*Fn(Object.fromEntries(s),t+1,n);return}}if(Tt(i)){let l=Us(i);if(l){let m=Object.entries(i);if(yield it(t,_t(m.length,{key:o,fields:l,delimiter:n.delimiter,keyed:!0}),n.indentSize),yield*Vu(m,l,t+2,n),s.length>0)yield*Fn(Object.fromEntries(s),t+1,n);return}}let a=Dn(o);if(rn(i))yield it(t,`${a}: ${xr(i,n.delimiter)}`,n.indentSize);else if(nn(i))if(i.length===0)yield it(t,`${a}: []`,n.indentSize);else if(gr(i))yield it(t,`${a}${Lo(i,n.delimiter)}`,n.indentSize);else{yield it(t,`${a}${_t(i.length,{delimiter:n.delimiter})}`,n.indentSize);for(let l of i)yield*Ms(l,t+2,n)}else if(Tt(i)){if(yield it(t,`${a}:`,n.indentSize),!hr(i))yield*Fn(i,t+2,n)}if(s.length>0)yield*Fn(Object.fromEntries(s),t+1,n)}function*Ms(e,t,n){if(rn(e))yield it(t,xr(e,n.delimiter),n.indentSize);else if(nn(e))if(gr(e))yield it(t,Lo(e,n.delimiter),n.indentSize);else{yield it(t,_t(e.length,{delimiter:n.delimiter}),n.indentSize);for(let r of e)yield*Ms(r,t+1,n)}else if(Tt(e))yield*cg(e,t,n)}function Je(e,t,n){return" ".repeat(n*e)+t}function it(e,t,n){return Je(e,"- "+t,n)}function ug(e,t){let n=t("",e,[]);if(n===void 0)return Rs(e,t,[]);return $s(e,n,t,[])}function $s(e,t,n,r){if(yr(t)&&!rn(e))return Rs(e,n,r);return Rs(en(t),n,r)}function Rs(e,t,n){if(Tt(e))return lg(e,t,n);if(nn(e))return fg(e,t,n);return e}function lg(e,t,n){let r={};for(let[o,i]of Object.entries(e)){let s=[...n,o],a=t(o,i,s);if(a===void 0)continue;pr(r,o,$s(i,a,t,s))}return r}function fg(e,t,n){let r=[];for(let o=0;o<e.length;o++){let i=e[o],s=[...n,o],a=t(String(o),i,s);if(a===void 0)continue;r.push($s(i,a,t,s))}return r}function ge(e,t){return Array.from(dg(e,t)).join(`
5
+ `)}function Ku(e,t){return pg(e.split(`
6
+ `),t)}function dg(e,t){let n=en(e),r=mg(t);return og(r.replacer?ug(n,r.replacer):n,r,0)}function pg(e,t){return qh(Rh(e,hg(t)))}function mg(e){let t=e?.delimiter??kt;return Xh(t),{indentSize:e?.indentSize??e?.indent??2,delimiter:t,replacer:e?.replacer}}function hg(e){return{indentSize:e?.indentSize??e?.indent??2,strict:e?.strict??!0}}class $e extends Error{code;details;constructor(e,t,n={},r){super(t,r);this.name="CoreError",this.code=e,this.details=n,yt(this.details),Object.freeze(this)}}var Fe=(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 r=0,o=t.length;r<o;r++)n=t[r](n);return n}}},js={pipe(){return Fe(this,arguments)}},Sr=function(){function e(){}return e.prototype=js,e}();var N=function(e,t){if(typeof e==="function")return function(){return e(arguments)?t.apply(this,arguments):(n)=>t(n,...arguments)};switch(e){case 0:case 1:throw RangeError(`Invalid arity ${e}`);case 2:return function(n,r){if(arguments.length>=2)return t(n,r);return function(o){return t(o,n)}};case 3:return function(n,r,o){if(arguments.length>=3)return t(n,r,o);return function(i){return t(i,n,r)}};default:return function(){if(arguments.length>=e)return t.apply(this,arguments);let n=arguments;return function(r){return t(r,...n)}}}};var ce=(e)=>e;var Bs=(e)=>()=>e,qs=Bs(!0);var Er=Bs(void 0),Vs=Er;function br(e){let t=new WeakMap;return(n)=>{let r=t.get(n);if(r!==void 0)return r;let o=e(n);return t.set(n,o),o}}function Ln(e){let t=new WeakMap;return(n)=>{let r=t.get(n);if(r!==void 0)return r;let o=e(n);if(t.set(n,o),o!==n)t.set(o,o);return o}}var vr=(e)=>{let t=new Set(Reflect.ownKeys(e));if(e.constructor===Object)return t;if(e instanceof Error)t.delete("stack");let n=Object.getPrototypeOf(e),r=n;while(r!==null&&r!==Object.prototype){let o=Reflect.ownKeys(r);for(let i=0;i<o.length;i++)t.add(o[i]);r=Object.getPrototypeOf(r)}if(t.has("constructor")&&typeof e.constructor==="function"&&n===e.constructor.prototype)t.delete("constructor");return t},wr=new WeakSet,Ir=(e)=>new Uint8Array(e.buffer,e.byteOffset,e.byteLength);var Mo=0,Gu=()=>{Mo++};function _r(e){return typeof e==="string"}function kr(e){return typeof e==="number"}function Ju(e){return typeof e==="boolean"}function Hu(e){return typeof e==="symbol"}function Yu(e){return _r(e)||kr(e)||Hu(e)}function on(e){return typeof e==="function"}function Zu(e){return e!=null}function Xu(e){return!0}function $o(e){return typeof e==="object"&&e!==null||on(e)}var W=N(2,(e,t)=>$o(e)&&(t in e));function Qu(e){return W(e,Symbol.iterator)||_r(e)}var re="~effect/Hash",V=(e)=>{switch(typeof e){case"number":return Ar(e);case"bigint":return Ie(e.toString(10));case"string":return Ie(e);case"function":case"object":if(e===null)break;else if(e instanceof Date){if(Number.isNaN(e.getTime()))return Ie("Invalid Date");return Ie(e.toISOString())}else if(e instanceof RegExp)return Ie(e.toString());else{if(wr.has(e))return jo(e);let t=tl.get(e);if(t!==void 0)return t;if(Ks.has(e))return Gu(),Ie("[Circular]");Ks.add(e);let n=Mo,r;try{if(re in e)r=e[re]();else if(typeof e==="function")r=jo(e);else if(e instanceof DataView)r=Bo(Ir(e));else if(Array.isArray(e)||ArrayBuffer.isView(e))r=Bo(e);else if(e instanceof Map)r=gg(e);else if(e instanceof Set)r=yg(e);else r=Js(e)}finally{Ks.delete(e)}if(n===Mo)tl.set(e,r);return r}}return Mt(nl(Ie(String(e))))},jo=(e)=>{if(!Ws.has(e))Ws.set(e,Mt(Math.random()*4294967296|0));return Ws.get(e)},nl=(e)=>(e^=e>>>16,e=Math.imul(e,2246822507),e^=e>>>13,e=Math.imul(e,3266489909),e^e>>>16),ue=N(2,(e,t)=>nl(Math.imul(e,2654435761)+Math.imul(t,2246822507))),Mt=(e)=>e&3221225471|e>>>1&1073741824;var zs=new DataView(new ArrayBuffer(8)),Ar=(e)=>{let t=e|0;if(t===e)return Mt(t);return zs.setFloat64(0,e!==e?NaN:e),Mt(ue(zs.getInt32(0),zs.getInt32(4)))},Ie=(e)=>{let t=5381,n=e.length;while(n)t=t*33^e.charCodeAt(--n);return Mt(t)},Gs=(e,t)=>{let n=12289;for(let r of t)n^=ue(V(r),V(e[r]));return Mt(n)},Js=(e)=>Gs(e,vr(e)),rl=(e,t)=>(n)=>{let r=e;for(let o of n)r^=t(o);return Mt(r)},Bo=(e)=>{let t=6151;for(let n of e)t=ue(t,V(n));return Mt(t)},gg=rl(Ie("Map"),([e,t])=>ue(V(e),V(t))),el=Ie("Set"),yg=rl(el,(e)=>ue(el,V(e))),Ws=new WeakMap,tl=new WeakMap,Ks=new WeakSet;var oe="~effect/Equal";function le(){if(arguments.length===1)return(e)=>an(e,arguments[0]);return an(arguments[0],arguments[1])}function an(e,t){if(e===t)return!0;if(e==null||t==null)return!1;let n=typeof e;if(n!==typeof t)return!1;if(n==="number"&&e!==e&&t!==t)return!0;if(n!=="object"&&n!=="function")return!1;if(wr.has(e)||wr.has(t))return!1;return xg(e,t)}function xg(e,t){let n=qo.length;for(let i=n;i-- >0;)if(qo[i]===e&&Hs[i]===t)return!0;if(n)return ol(e,t);let r=il.get(e);if(!r)il.set(e,r=new WeakMap);let o=r.get(t);if(o===void 0)r.set(t,o=ol(e,t));return o}function ol(e,t){qo.push(e),Hs.push(t);try{return Sg(e,t)}finally{qo.pop(),Hs.pop()}}var qo=[],Hs=[],il=new WeakMap;function Sg(e,t){if(V(e)!==V(t))return!1;else if(e instanceof Date){if(!(t instanceof Date))return!1;let r=e.getTime(),o=t.getTime();return r===o||Number.isNaN(r)&&Number.isNaN(o)}else if(e instanceof RegExp)return t instanceof RegExp&&e.toString()===t.toString();let n=cl(e);if(n!==cl(t)||typeof e==="function"&&!n)return!1;else if(n)return e[oe](t);else if(Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return!1;return Eg(e,t)}else if(ArrayBuffer.isView(e)){let r=e instanceof DataView;if(!ArrayBuffer.isView(t)||e.byteLength!==t.byteLength||r!==t instanceof DataView)return!1;if(r)return sl(Ir(e),Ir(t));return sl(e,t)}else if(e instanceof Map){if(!(t instanceof Map)||e.size!==t.size)return!1;return al(e,t,vg,wg)}else if(e instanceof Set){if(!(t instanceof Set)||e.size!==t.size)return!1;return al(e,t,V,an)}return bg(e,t)}function Eg(e,t){for(let n=0;n<e.length;n++)if(!an(e[n],t[n]))return!1;return!0}function sl(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 bg(e,t){let n=vr(e),r=vr(t);if(n.size!==r.size)return!1;for(let o of n)if(!r.has(o)||!an(e[o],t[o]))return!1;return!0}function al(e,t,n,r){let o=new Map;for(let i of t){let s=n(i),a=o.get(s);if(a)a.push(i);else o.set(s,[i])}e:for(let i of e){let s=o.get(n(i));if(s){for(let a=0;a<s.length;a++)if(r(i,s[a])){s[a]=s[s.length-1],s.pop();continue e}}return!1}return!0}var vg=(e)=>V(e[0]),wg=(e,t)=>an(e[0],t[0])&&an(e[1],t[1]);var cl=(e)=>W(e,oe);var Ys=(e)=>e.length>0;function $t(e,t,n){if(t==="__proto__")Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0});else e[t]=n}function ul(e,t){for(let n of Reflect.ownKeys(t))if(Object.prototype.propertyIsEnumerable.call(t,n))$t(e,n,t[n])}var Vo=Symbol.for("~effect/Redactable"),_g=(e)=>W(e,Vo);function zo(e){if(_g(e))return Xs(e);return e}function Xs(e){return e[Vo](globalThis[Mn]?.context??kg)}var Mn="~effect/Fiber/currentFiber",ll=new Map,kg={"~effect/Context":{},base:ll,depth:0,mapUnsafe:ll,pipe(){return Fe(this,arguments)}};function G(e,t){let n=t?.space??0,r=new WeakSet,o=!n?"":typeof n==="number"?" ".repeat(n):n,i=(c)=>o.repeat(c),s=(c,u)=>{let g=c?.constructor;return g&&g!==Object.prototype.constructor&&g.name?`${g.name}(${u})`:u},a=(c)=>{try{return Reflect.ownKeys(c)}catch{return["[ownKeys threw]"]}};function l(c,u=0){try{return m(c,u)}catch{if(typeof c==="object"&&c!==null||typeof c==="function")r.delete(c);return"[inspection threw]"}}function m(c,u=0){if(typeof c==="string")return JSON.stringify(c);if(typeof c==="number"||c==null||typeof c==="boolean"||typeof c==="symbol")return String(c);if(typeof c==="bigint")return String(c)+"n";if(typeof c==="object"||typeof c==="function"){if(r.has(c))return Tg;r.add(c);let g;if(Vo in c)g=l(Xs(c),u);else if(Array.isArray(c))g=!o||c.length<=1?`[${c.map((x)=>l(x,u)).join(",")}]`:`[
7
+ ${i(u+1)}${c.map((x)=>l(x,u+1)).join(`,
8
+ `+i(u+1))}
9
+ ${i(u)}]`;else if(c instanceof Date)g=Ag(c);else if(!t?.ignoreToString&&W(c,"toString")&&typeof c.toString==="function"&&c.toString!==Object.prototype.toString&&c.toString!==Array.prototype.toString){let x=Og(c);g=c instanceof Error&&c.cause!==void 0?`${x} (cause: ${l(c.cause,u)})`:x}else if(Symbol.iterator in c)g=`${c.constructor.name}(${l(Array.from(c),u)})`;else{let x=a(c);if(!o||x.length<=1){let S=`{${x.map((b)=>`${$n(b)}:${l(fl(c,b),u)}`).join(",")}}`;g=s(c,S)}else{let S=`{
10
+ ${x.map((b)=>`${i(u+1)}${$n(b)}: ${l(fl(c,b),u+1)}`).join(`,
11
11
  `)}
12
- ${i(u)}}`;return s(l,f)}return String(l)}return c(e,0)}var se=(e)=>JSON.stringify(e,null,2),RD={toJSON(){return re(this)},[Y](){return this.toJSON()},toString(){return se(this.toJSON())}};var jr=(e,t=2)=>{if(typeof e==="string")return e;try{return typeof e==="object"?yc(e,t):String(e)}catch{return String(e)}},yc=(e,t)=>{let r=[],n=JSON.stringify(e,(o,i)=>typeof i==="object"&&i!==null?r.includes(i)?void 0:r.push(i)&&(ho.fiberRefs!==void 0&&ay(i)?i[Lp](ho.fiberRefs):i):i,t);return r=void 0,n},Lp=Symbol.for("effect/Inspectable/Redactable"),ay=(e)=>typeof e==="object"&&e!==null&&(Lp in e),ho=B("effect/Inspectable/redactableState",()=>({fiberRefs:void 0})),cy=(e,t)=>{let r=ho.fiberRefs;ho.fiberRefs=e;try{return t()}finally{ho.fiberRefs=r}},ly=(e)=>{if(ay(e)&&ho.fiberRefs!==void 0)return e[Lp](ho.fiberRefs);return e};var b=(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 r=e;for(let n=0,o=t.length;n<o;n++)r=t[n](r);return r}}};var yo="Async",xo="Commit",Et="Failure",As="OnFailure",ai="OnSuccess",ci="OnSuccessAndFailure",Ot="Success",xc="Sync",uy="Tag",So="UpdateRuntimeFlags",li="While",ui="Iterator",Sc="WithRuntime",pi="Yield",Ts="RevertFlags";var SI="3.22.2",Is=()=>SI;var dy=Symbol.for("effect/Effect"),fy=Symbol.for("effect/Stream"),my=Symbol.for("effect/Sink"),hy=Symbol.for("effect/Channel"),En={_R:(e)=>e,_E:(e)=>e,_A:(e)=>e,_V:Is()},bI={_A:(e)=>e,_In:(e)=>e,_L:(e)=>e,_E:(e)=>e,_R:(e)=>e},_I={_Env:(e)=>e,_InErr:(e)=>e,_InElem:(e)=>e,_InDone:(e)=>e,_OutErr:(e)=>e,_OutElem:(e)=>e,_OutDone:(e)=>e},Hr={[dy]:En,[fy]:En,[my]:bI,[hy]:_I,[R](e){return this===e},[P](){return Z(this,ws(this))},[Symbol.iterator](){return new si(new Ur(this))},pipe(){return b(this,arguments)}},Rs={[P](){return Z(this,hc(this))},[R](e){let t=Object.keys(this),r=Object.keys(e);if(t.length!==r.length)return!1;for(let n of t)if(!((n in e)&&E(this[n],e[n])))return!1;return!0}},On={...Hr,_op:xo},qp={...On,...Rs},gy=function(){function e(){}return e.prototype=On,e}();var xy=Symbol.for("effect/Option"),Sy={...Hr,[xy]:{_A:(e)=>e},[Y](){return this.toJSON()},toString(){return se(this.toJSON())}},wI=Object.assign(Object.create(Sy),{_tag:"Some",_op:"Some",[R](e){return Up(e)&&Hp(e)&&E(this.value,e.value)},[P](){return Z(this,V(w(this._tag))(w(this.value)))},toJSON(){return{_id:"Option",_tag:this._tag,value:re(this.value)}}}),EI=w("None"),OI=Object.assign(Object.create(Sy),{_tag:"None",_op:"None",[R](e){return Up(e)&&jp(e)},[P](){return EI},toJSON(){return{_id:"Option",_tag:this._tag}}}),Up=(e)=>v(e,xy),jp=(e)=>e._tag==="None",Hp=(e)=>e._tag==="Some",bc=Object.create(OI),ks=(e)=>{let t=Object.create(wI);return t.value=e,t};var $p=Symbol.for("effect/Either"),_y={...Hr,[$p]:{_R:(e)=>e},[Y](){return this.toJSON()},toString(){return se(this.toJSON())}},vI=Object.assign(Object.create(_y),{_tag:"Right",_op:"Right",[R](e){return _c(e)&&Wp(e)&&E(this.right,e.right)},[P](){return V(w(this._tag))(w(this.right))},toJSON(){return{_id:"Either",_tag:this._tag,right:re(this.right)}}}),AI=Object.assign(Object.create(_y),{_tag:"Left",_op:"Left",[R](e){return _c(e)&&Bp(e)&&E(this.left,e.left)},[P](){return V(w(this._tag))(w(this.left))},toJSON(){return{_id:"Either",_tag:this._tag,left:re(this.left)}}}),_c=(e)=>v(e,$p),Bp=(e)=>e._tag==="Left",Wp=(e)=>e._tag==="Right",wy=(e)=>{let t=Object.create(AI);return t.left=e,t},Ey=(e)=>{let t=Object.create(vI);return t.right=e,t};var G=Ey;var K=wy;var Kp=_c,ge=Bp,He=Wp;var wc=p(2,(e,t)=>ge(e)?K(t(e.left)):G(e.right)),Oy=p(2,(e,t)=>He(e)?G(t(e.right)):K(e.left)),Cs=p(2,(e,{onLeft:t,onRight:r})=>ge(e)?t(e.left):r(e.right));var vy=Cs({onLeft:te,onRight:te});var Vp=p(2,(e,t)=>{if(He(e))return e.right;throw t(e.left)}),Ay=Vp(()=>Error("getOrThrow called on a Left"));var zp=(e)=>e.length>0;var Ty=(e)=>(t,r)=>t===r?0:e(t,r);var Iy=Ty((e,t)=>e<t?-1:1);var Ec=p(2,(e,t)=>Ty((r,n)=>e(t(r),t(n))));var Gp=(e)=>p(2,(t,r)=>e(t,r)===1);var A=()=>bc,M=ks;var be=jp,de=Hp,Ae=p(2,(e,{onNone:t,onSome:r})=>be(e)?t():r(e.value));var pe=p(2,(e,t)=>be(e)?t():e.value),tr=p(2,(e,t)=>be(e)?t():e),Ry=p(2,(e,t)=>be(e)?M(t()):e);var $r=(e)=>e==null?A():M(e);var vt=pe(uc),ky=(e)=>(...t)=>{try{return M(e(...t))}catch{return A()}};var rr=p(2,(e,t)=>be(e)?A():M(t(e.value)));var nr=p(2,(e,t)=>be(e)?A():t(e.value));var Cy=p(2,(e,t)=>be(e)?A():$r(t(e.value)));var kI=(e)=>p(2,(t,r)=>be(t)?!1:e(t.value,r)),CI=Os(),Py=kI(CI),Ny=p(2,(e,t)=>be(e)?!1:t(e.value));var Fy=(...e)=>e;var bo=(e)=>Array(e),Yp=p(2,(e,t)=>{let r=Math.max(1,Math.floor(e)),n=Array(r);for(let o=0;o<r;o++)n[o]=t(o);return n});var fe=(e)=>Array.isArray(e)?e:Array.from(e),Zp=(e)=>Array.isArray(e)?e:[e];var My=p(2,(e,{onEmpty:t,onNonEmpty:r})=>le(e)?r(Pe(e),or(e)):t());var di=p(2,(e,t)=>[t,...e]);var Ly=p(2,(e,t)=>[...e,t]),Qp=p(2,(e,t)=>fe(e).concat(fe(t)));var Xp=Array.isArray,NI=(e)=>e.length===0,Dy=NI,vn=zp,le=zp;var qy=(e,t)=>e<0||e>=t.length,FI=(e,t)=>Math.floor(Math.min(Math.max(0,e),t.length)),MI=p(2,(e,t)=>{let r=Math.floor(t);return qy(r,e)?A():M(e[r])}),ed=p(2,(e,t)=>{let r=Math.floor(t);if(qy(r,e))throw Error(`Index ${r} out of bounds`);return e[r]});var Br=MI(0),Pe=ed(0),Uy=(e)=>le(e)?M(td(e)):A(),td=(e)=>e[e.length-1];var or=(e)=>e.slice(1);var LI=(e,t)=>{let r=0;for(let n of e){if(!t(n,r))break;r++}return r},jy=p(2,(e,t)=>qI(e,LI(e,t))),Hy=p(2,(e,t)=>{let r=fe(e);return r.slice(FI(t,r),r.length)});var rd=(e)=>Array.from(e).reverse(),Wr=p(2,(e,t)=>{let r=Array.from(e);return r.sort(t),r});var nd=p(2,(e,t)=>$y(e,t,Fy)),$y=p(3,(e,t,r)=>{let n=fe(e),o=fe(t);if(le(n)&&le(o)){let i=[r(Pe(n),Pe(o))],s=Math.min(n.length,o.length);for(let a=1;a<s;a++)i[a]=r(n[a],o[a]);return i}return[]});var DI=Os();var qI=p(2,(e,t)=>{let r=Array.from(e),n=Math.floor(t);if(le(r)){if(n>=1)return UI(r,n);return[[],r]}return[r,[]]}),UI=p(2,(e,t)=>{let r=Math.max(1,Math.floor(t));return r>=e.length?[fi(e),[]]:[di(e.slice(1,r),Pe(e)),e.slice(r)]});var fi=(e)=>e.slice();var jI=p(3,(e,t,r)=>{let n=fe(e),o=fe(t);if(le(n)){if(le(o))return By(r)(Qp(n,o));return n}return o}),An=p(2,(e,t)=>jI(e,t,DI));var Kr=()=>[],tt=(e)=>[e],ir=p(2,(e,t)=>e.map(t)),Ps=p(2,(e,t)=>{if(Dy(e))return[];let r=[];for(let n=0;n<e.length;n++){let o=t(e[n],n);for(let i=0;i<o.length;i++)r.push(o[i])}return r}),Oc=Ps(te),vc=p(2,(e,t)=>{let r=fe(e),n=[];for(let o=0;o<r.length;o++){let i=t(r[o],o);if(de(i))n.push(i.value)}return n});var mi=p(3,(e,t,r)=>fe(e).reduce((n,o,i)=>r(n,o,i),t));var od=(e,t)=>{let r=[],n=e,o;while(de(o=t(n))){let[i,s]=o.value;r.push(i),n=s}return r};var Tn=ey;var By=p(2,(e,t)=>{let r=fe(e);if(le(r)){let n=[Pe(r)],o=or(r);for(let i of o)if(n.every((s)=>!t(i,s)))n.push(i);return n}return[]}),id=(e)=>By(e,Os());var Vr=p(2,(e,t)=>fe(e).join(t));var Ky=Symbol.for("effect/Chunk");function WI(e,t,r,n,o){for(let i=t;i<Math.min(e.length,t+o);i++)r[n+i-t]=e[i];return r}var Vy=[],KI=(e)=>xs((t,r)=>t.length===r.length&&zr(t).every((n,o)=>e(n,hi(r,o)))),VI=KI(E),zI={[Ky]:{_A:(e)=>e},toString(){return se(this.toJSON())},toJSON(){return{_id:"Chunk",values:zr(this).map(re)}},[Y](){return this.toJSON()},[R](e){return zy(e)&&VI(this,e)},[P](){return Z(this,Ft(zr(this)))},[Symbol.iterator](){switch(this.backing._tag){case"IArray":return this.backing.array[Symbol.iterator]();case"IEmpty":return Vy[Symbol.iterator]();default:return zr(this)[Symbol.iterator]()}},pipe(){return b(this,arguments)}},Le=(e)=>{let t=Object.create(zI);switch(t.backing=e,e._tag){case"IEmpty":{t.length=0,t.depth=0,t.left=t,t.right=t;break}case"IConcat":{t.length=e.left.length+e.right.length,t.depth=1+Math.max(e.left.depth,e.right.depth),t.left=e.left,t.right=e.right;break}case"IArray":{t.length=e.array.length,t.depth=0,t.left=Er,t.right=Er;break}case"ISingleton":{t.length=1,t.depth=0,t.left=Er,t.right=Er;break}case"ISlice":{t.length=e.length,t.depth=e.chunk.depth+1,t.left=Er,t.right=Er;break}}return t},zy=(e)=>v(e,Ky),Er=Le({_tag:"IEmpty"}),Wt=()=>Er,Ns=(...e)=>YI(e),Ne=(e)=>Le({_tag:"ISingleton",a:e}),Ac=(e)=>zy(e)?e:Fs(fe(e)),sd=(e,t,r)=>{switch(e.backing._tag){case"IArray":{WI(e.backing.array,0,t,r,e.length);break}case"IConcat":{sd(e.left,t,r),sd(e.right,t,r+e.left.length);break}case"ISingleton":{t[r]=e.backing.a;break}case"ISlice":{let n=0,o=r;while(n<e.length)t[o]=hi(e,n),n+=1,o+=1;break}}};var GI=(e)=>{switch(e.backing._tag){case"IEmpty":return Vy;case"IArray":return e.backing.array;default:{let t=Array(e.length);return sd(e,t,0),e.backing={_tag:"IArray",array:t},e.left=Er,e.right=Er,e.depth=0,t}}},zr=GI,JI=(e)=>{switch(e.backing._tag){case"IEmpty":case"ISingleton":return e;case"IArray":return Le({_tag:"IArray",array:rd(e.backing.array)});case"IConcat":return Le({_tag:"IConcat",left:In(e.backing.right),right:In(e.backing.left)});case"ISlice":return Fs(rd(zr(e)))}},In=JI;var Fs=(e)=>e.length===0?Wt():e.length===1?Ne(e[0]):Le({_tag:"IArray",array:e}),YI=(e)=>Fs(e),hi=p(2,(e,t)=>{switch(e.backing._tag){case"IEmpty":throw Error("Index out of bounds");case"ISingleton":{if(t!==0)throw Error("Index out of bounds");return e.backing.a}case"IArray":{if(t>=e.length||t<0)throw Error("Index out of bounds");return e.backing.array[t]}case"IConcat":return t<e.left.length?hi(e.left,t):hi(e.right,t-e.left.length);case"ISlice":return hi(e.backing.chunk,t+e.backing.offset)}}),Gy=p(2,(e,t)=>Mt(e,Ne(t))),rt=p(2,(e,t)=>Mt(Ne(t),e));var ad=p(2,(e,t)=>{if(t<=0)return e;else if(t>=e.length)return Er;else switch(e.backing._tag){case"ISlice":return Le({_tag:"ISlice",chunk:e.backing.chunk,offset:e.backing.offset+t,length:e.backing.length-t});case"IConcat":{if(t>e.left.length)return ad(e.right,t-e.left.length);return Le({_tag:"IConcat",left:ad(e.left,t),right:e.right})}default:return Le({_tag:"ISlice",chunk:e,offset:t,length:e.length-t})}});var Mt=p(2,(e,t)=>{if(e.backing._tag==="IEmpty")return t;if(t.backing._tag==="IEmpty")return e;let r=t.depth-e.depth;if(Math.abs(r)<=1)return Le({_tag:"IConcat",left:e,right:t});else if(r<-1)if(e.left.depth>=e.right.depth){let n=Mt(e.right,t);return Le({_tag:"IConcat",left:e.left,right:n})}else{let n=Mt(e.right.right,t);if(n.depth===e.depth-3){let o=Le({_tag:"IConcat",left:e.right.left,right:n});return Le({_tag:"IConcat",left:e.left,right:o})}else{let o=Le({_tag:"IConcat",left:e.left,right:e.right.left});return Le({_tag:"IConcat",left:o,right:n})}}else if(t.right.depth>=t.left.depth){let n=Mt(e,t.left);return Le({_tag:"IConcat",left:n,right:t.right})}else{let n=Mt(e,t.left.left);if(n.depth===t.depth-3){let o=Le({_tag:"IConcat",left:n,right:t.left.right});return Le({_tag:"IConcat",left:o,right:t.right})}else{let o=Le({_tag:"IConcat",left:t.left.right,right:t.right});return Le({_tag:"IConcat",left:n,right:o})}}});var Jy=(e)=>e.length===0,sr=(e)=>e.length>0;var cd=(e)=>hi(e,0),ar=cd;var cr=(e)=>ad(e,1);var Rn=5,ld=Math.pow(2,5),Yy=ld-1,Zy=ld/2,Qy=ld/4;function ZI(e){return e-=e>>1&1431655765,e=(e&858993459)+(e>>2&858993459),e=e+(e>>4)&252645135,e+=e>>8,e+=e>>16,e&127}function kn(e,t){return t>>>e&Yy}function Cn(e){return 1<<e}function Tc(e,t){return ZI(e&t-1)}var Xy=(e,t)=>({value:e,previous:t});function _o(e,t,r,n){let o=n;if(!e){let i=n.length;o=Array(i);for(let s=0;s<i;++s)o[s]=n[s]}return o[t]=r,o}function ud(e,t,r){let n=r.length-1,o=0,i=0,s=r;if(e)o=i=t;else{s=Array(n);while(o<t)s[i++]=r[o++]}++o;while(o<=n)s[i++]=r[o++];if(e)s.length=n;return s}function ex(e,t,r,n){let o=n.length;if(e){let c=o;while(c>=t)n[c--]=n[c];return n[t]=r,n}let i=0,s=0,a=Array(o+1);while(i<t)a[s++]=n[i++];a[t]=r;while(i<o)a[++s]=n[i++];return a}class Jr{_tag="EmptyNode";modify(e,t,r,n,o,i){let s=r(A());if(be(s))return new Jr;return++i.value,new wo(e,n,o,s)}}function Kt(e){return _s(e,"EmptyNode")}function XI(e){return Kt(e)||e._tag==="LeafNode"||e._tag==="CollisionNode"}function Ic(e,t){return Kt(e)?!1:t===e.edit}class wo{edit;hash;key;value;_tag="LeafNode";constructor(e,t,r,n){this.edit=e,this.hash=t,this.key=r,this.value=n}modify(e,t,r,n,o,i){if(E(o,this.key)){let a=r(this.value);if(a===this.value)return this;else if(be(a))return--i.value,new Jr;if(Ic(this,e))return this.value=a,this;return new wo(e,n,o,a)}let s=r(A());if(be(s))return this;return++i.value,tx(e,t,this.hash,this,n,new wo(e,n,o,s))}}class pd{edit;hash;children;_tag="CollisionNode";constructor(e,t,r){this.edit=e,this.hash=t,this.children=r}modify(e,t,r,n,o,i){if(n===this.hash){let a=Ic(this,e),c=this.updateCollisionList(a,e,this.hash,this.children,r,o,i);if(c===this.children)return this;return c.length>1?new pd(e,this.hash,c):c[0]}let s=r(A());if(be(s))return this;return++i.value,tx(e,t,this.hash,this,n,new wo(e,n,o,s))}updateCollisionList(e,t,r,n,o,i,s){let a=n.length;for(let l=0;l<a;++l){let u=n[l];if("key"in u&&E(i,u.key)){let d=u.value,f=o(d);if(f===d)return n;if(be(f))return--s.value,ud(e,l,n);return _o(e,l,new wo(t,r,i,f),n)}}let c=o(A());if(be(c))return n;return++s.value,_o(e,a,new wo(t,r,i,c),n)}}class gi{edit;mask;children;_tag="IndexedNode";constructor(e,t,r){this.edit=e,this.mask=t,this.children=r}modify(e,t,r,n,o,i){let s=this.mask,a=this.children,c=kn(t,n),l=Cn(c),u=Tc(s,l),d=s&l,f=Ic(this,e);if(!d){let x=new Jr().modify(e,t+Rn,r,n,o,i);if(!x)return this;return a.length>=Zy?tR(e,c,x,s,a):new gi(e,s|l,ex(f,u,x,a))}let g=a[u],y=g.modify(e,t+Rn,r,n,o,i);if(g===y)return this;let O=s,m;if(Kt(y)){if(O&=~l,!O)return new Jr;if(a.length<=2&&XI(a[u^1]))return a[u^1];m=ud(f,u,a)}else m=_o(f,u,y,a);if(f)return this.mask=O,this.children=m,this;return new gi(e,O,m)}}class dd{edit;size;children;_tag="ArrayNode";constructor(e,t,r){this.edit=e,this.size=t,this.children=r}modify(e,t,r,n,o,i){let s=this.size,a=this.children,c=kn(t,n),l=a[c],u=(l||new Jr).modify(e,t+Rn,r,n,o,i);if(l===u)return this;let d=Ic(this,e),f;if(Kt(l)&&!Kt(u))++s,f=_o(d,c,u,a);else if(!Kt(l)&&Kt(u)){if(--s,s<=Qy)return eR(e,s,c,a);f=_o(d,c,new Jr,a)}else f=_o(d,c,u,a);if(d)return this.size=s,this.children=f,this;return new dd(e,s,f)}}function eR(e,t,r,n){let o=Array(t-1),i=0,s=0;for(let a=0,c=n.length;a<c;++a)if(a!==r){let l=n[a];if(l&&!Kt(l))o[i++]=l,s|=1<<a}return new gi(e,s,o)}function tR(e,t,r,n,o){let i=[],s=n,a=0;for(let c=0;s;++c){if(s&1)i[c]=o[a++];s>>>=1}return i[t]=r,new dd(e,a+1,i)}function rR(e,t,r,n,o,i){if(r===o)return new pd(e,r,[i,n]);let s=kn(t,r),a=kn(t,o);if(s===a)return(c)=>new gi(e,Cn(s)|Cn(a),[c]);else{let c=s<a?[n,i]:[i,n];return new gi(e,Cn(s)|Cn(a),c)}}function tx(e,t,r,n,o,i){let s=void 0,a=t;while(!0){let c=rR(e,a,r,n,o,i);if(typeof c==="function")s=Xy(c,s),a=a+Rn;else{let l=c;while(s!=null)l=s.value(l),s=s.previous;return l}}}var rx="effect/HashMap",Rc=Symbol.for(rx),oR={[Rc]:Rc,[Symbol.iterator](){return new Cc(this,(e,t)=>[e,t])},[P](){let e=w(rx);for(let t of this)e^=h(w(t[0]),V(w(t[1])));return Z(this,e)},[R](e){if(sx(e)){if(e._size!==this._size)return!1;for(let t of this){let r=h(e,Pc(t[0],w(t[0])));if(be(r))return!1;else if(!E(t[1],r.value))return!1}return!0}return!1},toString(){return se(this.toJSON())},toJSON(){return{_id:"HashMap",values:Array.from(this).map(re)}},[Y](){return this.toJSON()},pipe(){return b(this,arguments)}},fd=(e,t,r,n)=>{let o=Object.create(oR);return o._editable=e,o._edit=t,o._root=r,o._size=n,o};class Cc{map;f;v;constructor(e,t){this.map=e,this.f=t,this.v=nx(this.map._root,this.f,void 0)}next(){if(be(this.v))return{done:!0,value:void 0};let e=this.v.value;return this.v=kc(e.cont),{done:!1,value:e.value}}[Symbol.iterator](){return new Cc(this.map,this.f)}}var kc=(e)=>e?ox(e[0],e[1],e[2],e[3],e[4]):A(),nx=(e,t,r=void 0)=>{switch(e._tag){case"LeafNode":{if(de(e.value))return M({value:t(e.key,e.value.value),cont:r});return kc(r)}case"CollisionNode":case"ArrayNode":case"IndexedNode":{let n=e.children;return ox(n.length,n,0,t,r)}default:return kc(r)}},ox=(e,t,r,n,o)=>{while(r<e){let i=t[r++];if(i&&!Kt(i))return nx(i,n,[e,t,r,n,o])}return kc(o)},iR=fd(!1,0,new Jr,0),yi=()=>iR;var ix=(e)=>{let t=Fc(yi());for(let r of e)Eo(t,r[0],r[1]);return lx(t)},sx=(e)=>v(e,Rc),ax=(e)=>e&&Kt(e._root),cx=p(2,(e,t)=>Pc(e,t,w(t))),Pc=p(3,(e,t,r)=>{let n=e._root,o=0;while(!0)switch(n._tag){case"LeafNode":return E(t,n.key)?n.value:A();case"CollisionNode":{if(r===n.hash){let i=n.children;for(let s=0,a=i.length;s<a;++s){let c=i[s];if("key"in c&&E(t,c.key))return c.value}}return A()}case"IndexedNode":{let i=kn(o,r),s=Cn(i);if(n.mask&s){n=n.children[Tc(n.mask,s)],o+=Rn;break}return A()}case"ArrayNode":{if(n=n.children[kn(o,r)],n){o+=Rn;break}return A()}default:return A()}});var md=p(2,(e,t)=>de(Pc(e,t,w(t))));var Eo=p(3,(e,t,r)=>Mc(e,t,()=>M(r))),sR=p(3,(e,t,r)=>{if(e._editable)return e._root=t,e._size=r,e;return t===e._root?e:fd(e._editable,e._edit,t,r)}),Nc=(e)=>new Cc(e,(t)=>t);var Ms=(e)=>e._size;var Fc=(e)=>fd(!0,e._edit+1,e._root,e._size),lx=(e)=>(e._editable=!1,e);var Mc=p(3,(e,t,r)=>ux(e,t,w(t),r)),ux=p(4,(e,t,r,n)=>{let o={value:e._size},i=e._root.modify(e._editable?e._edit:NaN,0,n,r,t,o);return h(e,sR(i,o.value))});var Lc=p(2,(e,t)=>Mc(e,t,A));var px=p(2,(e,t)=>xi(e,yi(),(r,n,o)=>Eo(r,o,t(n,o))));var hd=p(2,(e,t)=>xi(e,void 0,(r,n,o)=>t(n,o))),xi=p(3,(e,t,r)=>{let n=e._root;if(n._tag==="LeafNode")return de(n.value)?r(t,n.value.value,n.key):t;if(n._tag==="EmptyNode")return t;let o=[n.children],i;while(i=o.pop())for(let s=0,a=i.length;s<a;){let c=i[s++];if(c&&!Kt(c))if(c._tag==="LeafNode"){if(de(c.value))t=r(t,c.value.value,c.key)}else o.push(c.children)}return t});var fx="effect/HashSet",Dc=Symbol.for(fx),aR={[Dc]:Dc,[Symbol.iterator](){return Nc(this._keyMap)},[P](){return Z(this,V(w(this._keyMap))(w(fx)))},[R](e){if(mx(e))return Ms(this._keyMap)===Ms(e._keyMap)&&E(this._keyMap,e._keyMap);return!1},toString(){return se(this.toJSON())},toJSON(){return{_id:"HashSet",values:Array.from(this).map(re)}},[Y](){return this.toJSON()},pipe(){return b(this,arguments)}},qc=(e)=>{let t=Object.create(aR);return t._keyMap=e,t},mx=(e)=>v(e,Dc),cR=qc(yi()),Ls=()=>cR,hx=(e)=>{let t=Uc(Ls());for(let r of e)Si(t,r);return jc(t)},gx=(...e)=>{let t=Uc(Ls());for(let r of e)Si(t,r);return jc(t)},yx=p(2,(e,t)=>md(e._keyMap,t));var xx=(e)=>Ms(e._keyMap),Uc=(e)=>qc(Fc(e._keyMap)),jc=(e)=>(e._keyMap._editable=!1,e),gd=p(2,(e,t)=>{let r=Uc(e);return t(r),jc(r)}),Si=p(2,(e,t)=>e._keyMap._editable?(Eo(t,!0)(e._keyMap),e):qc(Eo(t,!0)(e._keyMap))),yd=p(2,(e,t)=>e._keyMap._editable?(Lc(t)(e._keyMap),e):qc(Lc(t)(e._keyMap))),Sx=p(2,(e,t)=>gd(e,(r)=>{for(let n of t)yd(r,n)}));var bx=p(2,(e,t)=>gd(Ls(),(r)=>{_x(e,(n)=>Si(r,n));for(let n of t)Si(r,n)}));var _x=p(2,(e,t)=>hd(e._keyMap,(r,n)=>t(n))),wx=p(3,(e,t,r)=>xi(e._keyMap,t,(n,o,i)=>r(n,i)));var Or=Ls,Ex=hx,Oo=gx,Ox=yx;var Ds=xx;var vo=Si,xd=yd,Sd=Sx;var Yr=bx;var Ao=wx;var _i="Die",Pn="Empty",Nn="Fail",To="Interrupt",Io="Parallel",Ro="Sequential";var Tx="effect/Cause",wd=Symbol.for(Tx),pR={_E:(e)=>e},wi={[wd]:pR,[P](){return h(w(Tx),V(w(fR(this))),Z(this))},[R](e){return Ix(e)&&dR(this,e)},pipe(){return b(this,arguments)},toJSON(){switch(this._tag){case"Empty":return{_id:"Cause",_tag:this._tag};case"Die":return{_id:"Cause",_tag:this._tag,defect:re(this.defect)};case"Interrupt":return{_id:"Cause",_tag:this._tag,fiberId:this.fiberId.toJSON()};case"Fail":return{_id:"Cause",_tag:this._tag,failure:re(this.error)};case"Sequential":case"Parallel":return{_id:"Cause",_tag:this._tag,left:re(this.left),right:re(this.right)}}},toString(){return ur(this)},[Y](){return this.toJSON()}},Zr=(()=>{let e=Object.create(wi);return e._tag=Pn,e})(),Ei=(e)=>{let t=Object.create(wi);return t._tag=Nn,t.error=e,t},Lt=(e)=>{let t=Object.create(wi);return t._tag=_i,t.defect=e,t},lr=(e)=>{let t=Object.create(wi);return t._tag=To,t.fiberId=e,t},Po=(e,t)=>{let r=Object.create(wi);return r._tag=Io,r.left=e,r.right=t,r},nt=(e,t)=>{let r=Object.create(wi);return r._tag=Ro,r.left=e,r.right=t,r},Ix=(e)=>v(e,wd),Ed=(e)=>e._tag===Pn,Rx=(e)=>e._tag===Nn;var Hc=(e)=>{if(e._tag===Pn)return!0;return ko(e,!0,(t,r)=>{switch(r._tag){case Pn:return M(t);case _i:case Nn:case To:return M(!1);default:return A()}})};var $c=(e)=>de(kx(e)),Oi=(e)=>Kc(void 0,hR)(e),Od=(e)=>In(ko(e,Wt(),(t,r)=>r._tag===Nn?M(h(t,rt(r.error))):A())),vd=(e)=>In(ko(e,Wt(),(t,r)=>r._tag===_i?M(h(t,rt(r.defect))):A())),Ad=(e)=>ko(e,Or(),(t,r)=>r._tag===To?M(h(t,vo(r.fiberId))):A()),Td=(e)=>Id(e,(t)=>t._tag===Nn?M(t.error):A()),Bc=(e)=>{let t=Td(e);switch(t._tag){case"None":return G(e);case"Some":return K(t.value)}};var kx=(e)=>Id(e,(t)=>t._tag===To?M(t.fiberId):A());var Wc=(e)=>Rd(e,{onEmpty:Zr,onFail:()=>Zr,onDie:Lt,onInterrupt:lr,onSequential:nt,onParallel:Po}),Cx=(e)=>Rd(e,{onEmpty:Zr,onFail:Lt,onDie:Lt,onInterrupt:lr,onSequential:nt,onParallel:Po});var dR=(e,t)=>{let r=Ne(e),n=Ne(t);while(sr(r)&&sr(n)){let[o,i]=h(ar(r),ko([Or(),Wt()],([c,l],u)=>{let[d,f]=bd(u);return M([h(c,Yr(d)),h(l,Mt(f))])})),[s,a]=h(ar(n),ko([Or(),Wt()],([c,l],u)=>{let[d,f]=bd(u);return M([h(c,Yr(d)),h(l,Mt(f))])}));if(!E(o,s))return!1;r=i,n=a}return!0},fR=(e)=>mR(Ne(e),Wt()),mR=(e,t)=>{while(!0){let[r,n]=h(e,mi([Or(),Wt()],([i,s],a)=>{let[c,l]=bd(a);return[h(i,Yr(c)),h(s,Mt(l))]})),o=Ds(r)>0?h(t,rt(r)):t;if(Jy(n))return In(o);e=n,t=o}throw Error(mo("Cause.flattenCauseLoop"))},Id=p(2,(e,t)=>{let r=[e];while(r.length>0){let n=r.pop(),o=t(n);switch(o._tag){case"None":{switch(n._tag){case Ro:case Io:{r.push(n.right),r.push(n.left);break}}break}case"Some":return o}}return A()});var bd=(e)=>{let t=e,r=[],n=Or(),o=Wt();while(t!==void 0)switch(t._tag){case Pn:{if(r.length===0)return[n,o];t=r.pop();break}case Nn:{if(n=vo(n,Ns(t._tag,t.error)),r.length===0)return[n,o];t=r.pop();break}case _i:{if(n=vo(n,Ns(t._tag,t.defect)),r.length===0)return[n,o];t=r.pop();break}case To:{if(n=vo(n,Ns(t._tag,t.fiberId)),r.length===0)return[n,o];t=r.pop();break}case Ro:{switch(t.left._tag){case Pn:{t=t.right;break}case Ro:{t=nt(t.left.left,nt(t.left.right,t.right));break}case Io:{t=Po(nt(t.left.left,t.right),nt(t.left.right,t.right));break}default:{o=rt(o,t.right),t=t.left;break}}break}case Io:{r.push(t.right),t=t.left;break}}throw Error(mo("Cause.evaluateCauseLoop"))};var hR={emptyCase:hs,failCase:bn,dieCase:bn,interruptCase:hs,sequentialCase:(e,t,r)=>t&&r,parallelCase:(e,t,r)=>t&&r};var vx="SequentialCase",Ax="ParallelCase",Rd=p(2,(e,{onDie:t,onEmpty:r,onFail:n,onInterrupt:o,onParallel:i,onSequential:s})=>Kc(e,void 0,{emptyCase:()=>r,failCase:(a,c)=>n(c),dieCase:(a,c)=>t(c),interruptCase:(a,c)=>o(c),sequentialCase:(a,c,l)=>s(c,l),parallelCase:(a,c,l)=>i(c,l)})),ko=p(3,(e,t,r)=>{let n=t,o=e,i=[];while(o!==void 0){let s=r(n,o);switch(n=de(s)?s.value:n,o._tag){case Ro:{i.push(o.right),o=o.left;break}case Io:{i.push(o.right),o=o.left;break}default:{o=void 0;break}}if(o===void 0&&i.length>0)o=i.pop()}return n}),Kc=p(3,(e,t,r)=>{let n=[e],o=[];while(n.length>0){let s=n.pop();switch(s._tag){case Pn:{o.push(G(r.emptyCase(t)));break}case Nn:{o.push(G(r.failCase(t,s.error)));break}case _i:{o.push(G(r.dieCase(t,s.defect)));break}case To:{o.push(G(r.interruptCase(t,s.fiberId)));break}case Ro:{n.push(s.right),n.push(s.left),o.push(K({_tag:vx}));break}case Io:{n.push(s.right),n.push(s.left),o.push(K({_tag:Ax}));break}}}let i=[];while(o.length>0){let s=o.pop();switch(s._tag){case"Left":{switch(s.left._tag){case vx:{let a=i.pop(),c=i.pop(),l=r.sequentialCase(t,a,c);i.push(l);break}case Ax:{let a=i.pop(),c=i.pop(),l=r.parallelCase(t,a,c);i.push(l);break}}break}case"Right":{i.push(s.right);break}}}if(i.length===0)throw Error("BUG: Cause.reduceWithContext - please report an issue at https://github.com/Effect-TS/effect/issues");return i.pop()}),ur=(e,t)=>{if(Oi(e))return"All fibers interrupted without errors.";return qs(e).map(function(r){if(t?.renderErrorCause!==!0||r.cause===void 0)return r.stack;return`${r.stack} {
13
- ${Px(r.cause," ")}
14
- }`}).join(`
15
- `)},Px=(e,t)=>{let r=e.stack.split(`
16
- `),n=`${t}[cause]: ${r[0]}`;for(let o=1,i=r.length;o<i;o++)n+=`
17
- ${t}${r[o]}`;if(e.cause)n+=` {
18
- ${Px(e.cause,`${t} `)}
19
- ${t}}`;return n},_d=(e)=>{let t=typeof e==="object"&&e!==null,r=Error.stackTraceLimit;Error.stackTraceLimit=1;let n=Error(gR(e),t&&"cause"in e&&typeof e.cause<"u"?{cause:_d(e.cause)}:void 0);if(Error.stackTraceLimit=r,n.message==="")n.message="An error has occurred";if(Error.stackTraceLimit=r,n.name=e instanceof Error?e.name:"Error",t){if(Co in e)n.span=e[Co];Object.keys(e).forEach((o)=>{if(!(o in n))n[o]=e[o]})}return n.stack=SR(`${n.name}: ${n.message}`,e instanceof Error&&e.stack?e.stack:"",n.span),n},gR=(e)=>{if(typeof e==="string")return e;if(typeof e==="object"&&e!==null&&e instanceof Error)return e.message;try{if(v(e,"toString")&&wn(e.toString)&&e.toString!==Object.prototype.toString&&e.toString!==globalThis.Array.prototype.toString)return e.toString()}catch{}return yc(e)},yR=/\((.*)\)/g,xR=B("effect/Tracer/spanToTrace",()=>new WeakMap),SR=(e,t,r)=>{let n=[e],o=t.startsWith(e)?t.slice(e.length).split(`
20
- `):t.split(`
21
- `);for(let i=1;i<o.length;i++){if(o[i].includes(" at new BaseEffectError")||o[i].includes(" at new YieldableError")){i++;continue}if(o[i].includes("Generator.next"))break;if(o[i].includes("effect_internal_function"))break;n.push(o[i].replace(/at .*effect_instruction_i.*\((.*)\)/,"at $1").replace(/EffectPrimitive\.\w+/,"<anonymous>"))}if(r){let i=r,s=0;while(i&&i._tag==="Span"&&s<10){let a=xR.get(i);if(typeof a==="function"){let c=a();if(typeof c==="string"){let l=c.matchAll(yR),u=!1;for(let[,d]of l)u=!0,n.push(` at ${i.name} (${d})`);if(!u)n.push(` at ${i.name} (${c.replace(/^at /,"")})`)}else n.push(` at ${i.name}`)}else n.push(` at ${i.name}`);i=vt(i.parent),s++}}return n.join(`
22
- `)},Co=Symbol.for("effect/SpanAnnotation"),qs=(e)=>Kc(e,void 0,{emptyCase:()=>[],dieCase:(t,r)=>[_d(r)],failCase:(t,r)=>[_d(r)],interruptCase:()=>[],parallelCase:(t,r,n)=>[...r,...n],sequentialCase:(t,r,n)=>[...r,...n]});var Nx=Symbol.for("effect/Context/Tag"),js=Symbol.for("effect/Context/Reference"),bR="effect/STM",_R=Symbol.for(bR),Fx={...Hr,_op:"Tag",[_R]:En,[Nx]:{_Service:(e)=>e,_Identifier:(e)=>e},toString(){return se(this.toJSON())},toJSON(){return{_id:"Tag",key:this.key,stack:this.stack}},[Y](){return this.toJSON()},of(e){return e},context(e){return Pd(this,e)}},wR={...Fx,[js]:js},Mx=(e)=>{let t=Error.stackTraceLimit;Error.stackTraceLimit=2;let r=Error();Error.stackTraceLimit=t;let n=Object.create(Fx);return Object.defineProperty(n,"stack",{get(){return r.stack}}),n.key=e,n};var Lx=()=>(e,t)=>{let r=Error.stackTraceLimit;Error.stackTraceLimit=2;let n=Error();Error.stackTraceLimit=r;function o(){}return Object.setPrototypeOf(o,wR),o.key=e,o.defaultValue=t.defaultValue,Object.defineProperty(o,"stack",{get(){return n.stack}}),o},Cd=Symbol.for("effect/Context"),ER={[Cd]:{_Services:(e)=>e},[R](e){if(Dx(e)){if(this.unsafeMap.size===e.unsafeMap.size){for(let t of this.unsafeMap.keys())if(!e.unsafeMap.has(t)||!E(this.unsafeMap.get(t),e.unsafeMap.get(t)))return!1;return!0}}return!1},[P](){return Z(this,mc(this.unsafeMap.size))},pipe(){return b(this,arguments)},toString(){return se(this.toJSON())},toJSON(){return{_id:"Context",services:Array.from(this.unsafeMap).map(re)}},[Y](){return this.toJSON()}},Fn=(e)=>{let t=Object.create(ER);return t.unsafeMap=e,t},OR=(e)=>{let t=Error(`Service not found${e.key?`: ${String(e.key)}`:""}`);if(e.stack){let r=e.stack.split(`
23
- `);if(r.length>2){let n=r[2].match(/at (.*)/);if(n)t.message=t.message+` (defined at ${n[1]})`}}if(t.stack){let r=t.stack.split(`
24
- `);r.splice(1,3),t.stack=r.join(`
25
- `)}return t},Dx=(e)=>v(e,Cd);var qx=(e)=>v(e,js),vR=Fn(new Map),Ux=()=>vR,Pd=(e,t)=>Fn(new Map([[e.key,t]])),jx=p(3,(e,t,r)=>{let n=new Map(e.unsafeMap);return n.set(t.key,r),Fn(n)}),kd=B("effect/Context/defaultValueCache",()=>new Map),Nd=(e)=>{if(kd.has(e.key))return kd.get(e.key);let t=e.defaultValue();return kd.set(e.key,t),t},Hx=(e,t)=>e.unsafeMap.has(t.key)?e.unsafeMap.get(t.key):Nd(t),Fd=p(2,(e,t)=>{if(!e.unsafeMap.has(t.key)){if(js in t)return Nd(t);throw OR(t)}return e.unsafeMap.get(t.key)}),$x=Fd;var Bx=p(2,(e,t)=>{if(!e.unsafeMap.has(t.key))return qx(t)?ks(Nd(t)):bc;return ks(e.unsafeMap.get(t.key))}),Wx=p(2,(e,t)=>{let r=new Map(e.unsafeMap);for(let[n,o]of t.unsafeMap)r.set(n,o);return Fn(r)});var At=Mx;var Mn=Ux,Vx=Pd,vr=jx,Hs=$x;var $s=Fd,Ln=Bx,Bs=Wx;var Ws=Lx;var Ld=Symbol.for("effect/Duration"),Zx=BigInt(0),zx=BigInt(24),Vc=BigInt(60),Dd=BigInt(1000),Gx=BigInt(1e6),Jx=BigInt(1e9),AR=/^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/,Qr=(e)=>{if(Qx(e))return e;else if(Nt(e))return zc(e);else if(_n(e))return Md(e);else if(Array.isArray(e)&&e.length===2&&e.every(Nt)){if(e[0]===-1/0||e[1]===-1/0||Number.isNaN(e[0])||Number.isNaN(e[1]))return qd;if(e[0]===1/0||e[1]===1/0)return kR;return Md(BigInt(Math.round(e[0]*1e9))+BigInt(Math.round(e[1])))}else if(Ve(e)){let t=AR.exec(e);if(t){let[r,n,o]=t,i=Number(n);switch(o){case"nano":case"nanos":return Md(BigInt(n));case"micro":case"micros":return CR(BigInt(n));case"milli":case"millis":return zc(i);case"second":case"seconds":return PR(i);case"minute":case"minutes":return NR(i);case"hour":case"hours":return FR(i);case"day":case"days":return MR(i);case"week":case"weeks":return LR(i)}}}throw Error("Invalid DurationInput")};var Yx={_tag:"Millis",millis:0},TR={_tag:"Infinity"},IR={[Ld]:Ld,[P](){return Z(this,hc(this.value))},[R](e){return Qx(e)&&HR(this,e)},toString(){return`Duration(${BR(this)})`},toJSON(){switch(this.value._tag){case"Millis":return{_id:"Duration",_tag:"Millis",millis:this.value.millis};case"Nanos":return{_id:"Duration",_tag:"Nanos",hrtime:qR(this)};case"Infinity":return{_id:"Duration",_tag:"Infinity"}}},[Y](){return this.toJSON()},pipe(){return b(this,arguments)}},Ar=(e)=>{let t=Object.create(IR);if(Nt(e))if(isNaN(e)||e<=0)t.value=Yx;else if(!Number.isFinite(e))t.value=TR;else if(!Number.isInteger(e))t.value={_tag:"Nanos",nanos:BigInt(Math.round(e*1e6))};else t.value={_tag:"Millis",millis:e};else if(e<=Zx)t.value=Yx;else t.value={_tag:"Nanos",nanos:e};return t},Qx=(e)=>v(e,Ld);var RR=(e)=>{switch(e.value._tag){case"Millis":return e.value.millis===0;case"Nanos":return e.value.nanos===Zx;case"Infinity":return!1}},qd=Ar(0),kR=Ar(1/0),Md=(e)=>Ar(e),CR=(e)=>Ar(e*Dd),zc=(e)=>Ar(e),PR=(e)=>Ar(e*1000),NR=(e)=>Ar(e*60000),FR=(e)=>Ar(e*3600000),MR=(e)=>Ar(e*86400000),LR=(e)=>Ar(e*604800000),Gc=(e)=>UR(e,{onMillis:(t)=>t,onNanos:(t)=>Number(t)/1e6});var DR=(e)=>{let t=Qr(e);switch(t.value._tag){case"Infinity":throw Error("Cannot convert infinite duration to nanos");case"Nanos":return t.value.nanos;case"Millis":return BigInt(Math.round(t.value.millis*1e6))}},qR=(e)=>{let t=Qr(e);switch(t.value._tag){case"Infinity":return[1/0,0];case"Nanos":return[Number(t.value.nanos/Jx),Number(t.value.nanos%Jx)];case"Millis":return[Math.floor(t.value.millis/1000),Math.round(t.value.millis%1000*1e6)]}},UR=p(2,(e,t)=>{let r=Qr(e);switch(r.value._tag){case"Nanos":return t.onNanos(r.value.nanos);case"Infinity":return t.onMillis(1/0);case"Millis":return t.onMillis(r.value.millis)}}),Ud=p(3,(e,t,r)=>{let n=Qr(e),o=Qr(t);if(n.value._tag==="Infinity"||o.value._tag==="Infinity")return r.onMillis(Gc(n),Gc(o));else if(n.value._tag==="Nanos"||o.value._tag==="Nanos"){let i=n.value._tag==="Nanos"?n.value.nanos:BigInt(Math.round(n.value.millis*1e6)),s=o.value._tag==="Nanos"?o.value.nanos:BigInt(Math.round(o.value.millis*1e6));return r.onNanos(i,s)}return r.onMillis(n.value.millis,o.value.millis)});var jR=(e,t)=>Ud(e,t,{onMillis:(r,n)=>r===n,onNanos:(r,n)=>r===n});var Xx=p(2,(e,t)=>Ud(e,t,{onMillis:(r,n)=>r<=n,onNanos:(r,n)=>r<=n}));var eS=p(2,(e,t)=>Ud(e,t,{onMillis:(r,n)=>r>=n,onNanos:(r,n)=>r>=n})),HR=p(2,(e,t)=>jR(Qr(e),Qr(t))),$R=(e)=>{let t=Qr(e);if(t.value._tag==="Infinity")return{days:1/0,hours:1/0,minutes:1/0,seconds:1/0,millis:1/0,nanos:1/0};let r=DR(t),n=r/Gx,o=n/Dd,i=o/Vc,s=i/Vc,a=s/zx;return{days:Number(a),hours:Number(s%zx),minutes:Number(i%Vc),seconds:Number(o%Vc),millis:Number(n%Dd),nanos:Number(r%Gx)}},BR=(e)=>{let t=Qr(e);if(t.value._tag==="Infinity")return"Infinity";if(RR(t))return"0";let r=$R(t),n=[];if(r.days!==0)n.push(`${r.days}d`);if(r.hours!==0)n.push(`${r.hours}h`);if(r.minutes!==0)n.push(`${r.minutes}m`);if(r.seconds!==0)n.push(`${r.seconds}s`);if(r.millis!==0)n.push(`${r.millis}ms`);if(r.nanos!==0)n.push(`${r.nanos}ns`);return n.join(" ")};var rS=Symbol.for("effect/MutableRef"),WR={[rS]:rS,toString(){return se(this.toJSON())},toJSON(){return{_id:"MutableRef",current:re(this.current)}},[Y](){return this.toJSON()},pipe(){return b(this,arguments)}},Jc=(e)=>{let t=Object.create(WR);return t.current=e,t};var vi=(e)=>e.current;var Yc=p(2,(e,t)=>(e.current=t,e));var Hd="effect/FiberId",Ai=Symbol.for(Hd),Zc="None",jd="Runtime",KR="Composite",VR=ie(`${Hd}-${Zc}`);class iS{[Ai]=Ai;_tag=Zc;id=-1;startTimeMillis=-1;[P](){return VR}[R](e){return $d(e)&&e._tag===Zc}toString(){return se(this.toJSON())}toJSON(){return{_id:"FiberId",_tag:this._tag}}[Y](){return this.toJSON()}}class sS{id;startTimeMillis;[Ai]=Ai;_tag=jd;constructor(e,t){this.id=e,this.startTimeMillis=t}[P](){return Z(this,ie(`${Hd}-${this._tag}-${this.id}-${this.startTimeMillis}`))}[R](e){return $d(e)&&e._tag===jd&&this.id===e.id&&this.startTimeMillis===e.startTimeMillis}toString(){return se(this.toJSON())}toJSON(){return{_id:"FiberId",_tag:this._tag,id:this.id,startTimeMillis:this.startTimeMillis}}[Y](){return this.toJSON()}}var aS=new iS;var $d=(e)=>v(e,Ai);var Qc=(e)=>{switch(e._tag){case Zc:return Or();case jd:return Oo(e.id);case KR:return h(Qc(e.left),Yr(Qc(e.right)))}},oS=B(Symbol.for("effect/Fiber/Id/_fiberCounter"),()=>Jc(0));var Xc=(e)=>Array.from(Qc(e)).map((r)=>`#${r}`).join(",");var cS=()=>{let e=vi(oS);return h(oS,Yc(e+1)),new sS(e,Date.now())};var Vt=aS;var uS=Xc;var el=cS;var Ti=yi;var pS=ix,dS=ax,Bd=cx;var Wd=Eo,Kd=Nc;var fS=Mc;var mS=px;var Vd=xi;var Vs=Symbol.for("effect/List"),Gd=(e)=>fe(e),zR=(e)=>Ip(Tn(e),Gd),GR=zR(E),JR={[Vs]:Vs,_tag:"Cons",toString(){return se(this.toJSON())},toJSON(){return{_id:"List",_tag:"Cons",values:Gd(this).map(re)}},[Y](){return this.toJSON()},[R](e){return gS(e)&&this._tag===e._tag&&GR(this,e)},[P](){return Z(this,Ft(Gd(this)))},[Symbol.iterator](){let e=!1,t=this;return{next(){if(e)return this.return();if(t._tag==="Nil")return e=!0,this.return();let r=t.head;return t=t.tail,{done:e,value:r}},return(r){if(!e)e=!0;return{done:!0,value:r}}}},pipe(){return b(this,arguments)}},tl=(e,t)=>{let r=Object.create(JR);return r.head=e,r.tail=t,r},YR=ie("Nil"),ZR={[Vs]:Vs,_tag:"Nil",toString(){return se(this.toJSON())},toJSON(){return{_id:"List",_tag:"Nil"}},[Y](){return this.toJSON()},[P](){return YR},[R](e){return gS(e)&&this._tag===e._tag},[Symbol.iterator](){return{next(){return{done:!0,value:void 0}}}},pipe(){return b(this,arguments)}},hS=Object.create(ZR),gS=(e)=>v(e,Vs),Tr=(e)=>e._tag==="Nil",Jd=(e)=>e._tag==="Cons";var QR=()=>hS,Xr=(e,t)=>tl(e,t),Dn=QR,zs=(e)=>tl(e,hS);var yS=p(2,(e,t)=>ek(t,e)),XR=p(2,(e,t)=>Xr(t,e)),ek=p(2,(e,t)=>{if(Tr(e))return t;else if(Tr(t))return e;else{let r=tl(t.head,e),n=r,o=t.tail;while(!Tr(o)){let i=tl(o.head,e);n.tail=i,n=i,o=o.tail}return r}});var xS=p(3,(e,t,r)=>{let n=t,o=e;while(!Tr(o))n=r(n,o.head),o=o.tail;return n});var SS=(e)=>{let t=Dn(),r=e;while(!Tr(r))t=XR(t,r.head),r=r.tail;return t};var t2=Object.assign(Object.create(Array.prototype),{[P](){return Z(this,Ft(this))},[R](e){if(Array.isArray(e)&&this.length===e.length)return this.every((t,r)=>E(t,e[r]));else return!1}}),Ii=function(){function e(t){if(t)Object.assign(this,t)}return e.prototype=Rs,e}();var rk=Symbol.for("effect/DifferContextPatch");function bS(e){return e}var Js={...Ii.prototype,[rk]:{_Value:bS,_Patch:bS}},nk=Object.assign(Object.create(Js),{_tag:"Empty"}),ok=Object.create(nk),Zd=()=>ok,ik=Object.assign(Object.create(Js),{_tag:"AndThen"}),sk=(e,t)=>{let r=Object.create(ik);return r.first=e,r.second=t,r},ak=Object.assign(Object.create(Js),{_tag:"AddService"}),ck=(e,t)=>{let r=Object.create(ak);return r.key=e,r.service=t,r},lk=Object.assign(Object.create(Js),{_tag:"RemoveService"}),uk=(e)=>{let t=Object.create(lk);return t.key=e,t},pk=Object.assign(Object.create(Js),{_tag:"UpdateService"}),dk=(e,t)=>{let r=Object.create(pk);return r.key=e,r.update=t,r},_S=(e,t)=>{let r=new Map(e.unsafeMap),n=Zd();for(let[o,i]of t.unsafeMap.entries())if(r.has(o)){let s=r.get(o);if(r.delete(o),!E(s,i))n=Gs(dk(o,()=>i))(n)}else r.delete(o),n=Gs(ck(o,i))(n);for(let[o]of r.entries())n=Gs(uk(o))(n);return n},Gs=p(2,(e,t)=>sk(e,t)),wS=p(2,(e,t)=>{if(e._tag==="Empty")return t;let r=!1,n=Ne(e),o=new Map(t.unsafeMap);while(sr(n)){let s=ar(n),a=cr(n);switch(s._tag){case"Empty":{n=a;break}case"AddService":{o.set(s.key,s.service),n=a;break}case"AndThen":{n=rt(rt(a,s.second),s.first);break}case"RemoveService":{o.delete(s.key),n=a;break}case"UpdateService":{o.set(s.key,s.update(o.get(s.key))),r=!0,n=a;break}}}if(!r)return Fn(o);let i=new Map;for(let[s]of t.unsafeMap)if(o.has(s))i.set(s,o.get(s)),o.delete(s);for(let[s,a]of o)i.set(s,a);return Fn(i)});var mk=Symbol.for("effect/DifferHashSetPatch");function Qd(e){return e}var nl={...Ii.prototype,[mk]:{_Value:Qd,_Key:Qd,_Patch:Qd}},hk=Object.assign(Object.create(nl),{_tag:"Empty"}),gk=Object.create(hk),Xd=()=>gk,yk=Object.assign(Object.create(nl),{_tag:"AndThen"}),xk=(e,t)=>{let r=Object.create(yk);return r.first=e,r.second=t,r},Sk=Object.assign(Object.create(nl),{_tag:"Add"}),bk=(e)=>{let t=Object.create(Sk);return t.value=e,t},_k=Object.assign(Object.create(nl),{_tag:"Remove"}),wk=(e)=>{let t=Object.create(_k);return t.value=e,t},ES=(e,t)=>{let[r,n]=Ao([e,Xd()],([o,i],s)=>{if(Ox(s)(o))return[xd(s)(o),i];return[o,rl(bk(s))(i)]})(t);return Ao(n,(o,i)=>rl(wk(i))(o))(r)},rl=p(2,(e,t)=>xk(e,t)),OS=p(2,(e,t)=>{if(e._tag==="Empty")return t;let r=t,n=Ne(e);while(sr(n)){let o=ar(n),i=cr(n);switch(o._tag){case"Empty":{n=i;break}case"AndThen":{n=rt(o.first)(rt(o.second)(i));break}case"Add":{r=vo(o.value)(r),n=i;break}case"Remove":r=xd(o.value)(r),n=i}}return r});var Ok=Symbol.for("effect/DifferReadonlyArrayPatch");function vS(e){return e}var Zs={...Ii.prototype,[Ok]:{_Value:vS,_Patch:vS}},vk=Object.assign(Object.create(Zs),{_tag:"Empty"}),Ak=Object.create(vk),ef=()=>Ak,Tk=Object.assign(Object.create(Zs),{_tag:"AndThen"}),Ik=(e,t)=>{let r=Object.create(Tk);return r.first=e,r.second=t,r},Rk=Object.assign(Object.create(Zs),{_tag:"Append"}),kk=(e)=>{let t=Object.create(Rk);return t.values=e,t},Ck=Object.assign(Object.create(Zs),{_tag:"Slice"}),Pk=(e,t)=>{let r=Object.create(Ck);return r.from=e,r.until=t,r},Nk=Object.assign(Object.create(Zs),{_tag:"Update"}),Fk=(e,t)=>{let r=Object.create(Nk);return r.index=e,r.patch=t,r},AS=(e)=>{let t=0,r=ef();while(t<e.oldValue.length&&t<e.newValue.length){let n=e.oldValue[t],o=e.newValue[t],i=e.differ.diff(n,o);if(!E(i,e.differ.empty))r=Ys(r,Fk(t,i));t=t+1}if(t<e.oldValue.length)r=Ys(r,Pk(0,t));if(t<e.newValue.length)r=Ys(r,kk(Hy(t)(e.newValue)));return r},Ys=p(2,(e,t)=>Ik(e,t)),TS=p(3,(e,t,r)=>{if(e._tag==="Empty")return t;let n=t.slice(),o=tt(e);while(vn(o)){let i=Pe(o),s=or(o);switch(i._tag){case"Empty":{o=s;break}case"AndThen":{s.unshift(i.first,i.second),o=s;break}case"Append":{for(let a of i.values)n.push(a);o=s;break}case"Slice":{n=n.slice(i.from,i.until),o=s;break}case"Update":{n[i.index]=r.patch(i.patch,n[i.index]),o=s;break}}}return n});var IS=Symbol.for("effect/Differ"),Lk={[IS]:{_P:te,_V:te},pipe(){return b(this,arguments)}},qn=(e)=>{let t=Object.create(Lk);return t.empty=e.empty,t.diff=e.diff,t.combine=e.combine,t.patch=e.patch,t},tf=()=>qn({empty:Zd(),combine:(e,t)=>Gs(t)(e),diff:(e,t)=>_S(e,t),patch:(e,t)=>wS(t)(e)});var rf=()=>qn({empty:Xd(),combine:(e,t)=>rl(t)(e),diff:(e,t)=>ES(e,t),patch:(e,t)=>OS(t)(e)});var nf=(e)=>qn({empty:ef(),combine:(t,r)=>Ys(t,r),diff:(t,r)=>AS({oldValue:t,newValue:r,differ:e}),patch:(t,r)=>TS(t,r,e)});var ol=()=>RS((e,t)=>t),RS=(e)=>qn({empty:te,combine:(t,r)=>{if(t===te)return r;if(r===te)return t;return(n)=>r(t(n))},diff:(t,r)=>{if(E(t,r))return te;return ms(r)},patch:(t,r)=>e(r,t(r))});var Qs=255,kS=8,il=(e)=>e&Qs,sl=(e)=>e>>kS&Qs,No=(e,t)=>(e&Qs)+((t&e&Qs)<<kS),sf=No(0,0),CS=(e)=>No(e,e),PS=(e)=>No(e,0);var NS=p(2,(e,t)=>No(il(e)&~t,sl(e)));var af=p(2,(e,t)=>e|t);var FS=(e)=>~e>>>0&Qs;var Dk=0,en=1,LS=2,cf=4,al=16,lf=32;var DS=(e)=>cl(e,lf);var uf=p(2,(e,t)=>e|t);var tn=(e)=>pf(e)&&!qk(e),pf=(e)=>cl(e,en);var cl=p(2,(e,t)=>(e&t)!==0),df=(...e)=>e.reduce((t,r)=>t|r,0),qS=df(Dk);var ff=(e)=>cl(e,cf);var qk=(e)=>cl(e,al);var Xs=p(2,(e,t)=>No(e^t,t)),ea=p(2,(e,t)=>e&(FS(il(t))|sl(t))|il(t)&sl(t));var mf=qn({empty:sf,diff:(e,t)=>Xs(e,t),combine:(e,t)=>af(t)(e),patch:(e,t)=>ea(t,e)});var US=CS,gf=PS;var yf=NS;var Sf=(e,t)=>({_tag:"Par",left:e,right:t}),ll=(e,t)=>({_tag:"Seq",left:e,right:t});var HS=(e)=>{let t=zs(e),r=Dn();while(!0){let[n,o]=xS(t,[$S(),Dn()],([i,s],a)=>{let[c,l]=Uk(a);return[Wk(i,c),yS(s,l)]});if(r=jk(r,n),Tr(o))return SS(r);t=o}throw Error("BUG: BlockedRequests.flatten - please report an issue at https://github.com/Effect-TS/effect/issues")},Uk=(e)=>{let t=e,r=$S(),n=Dn(),o=Dn();while(!0)switch(t._tag){case"Empty":{if(Tr(n))return[r,o];t=n.head,n=n.tail;break}case"Par":{n=Xr(t.right,n),t=t.left;break}case"Seq":{let i=t.left,s=t.right;switch(i._tag){case"Empty":{t=s;break}case"Par":{let{left:a,right:c}=i;t=Sf(ll(a,s),ll(c,s));break}case"Seq":{let{left:a,right:c}=i;t=ll(a,ll(c,s));break}case"Single":{t=i,o=Xr(s,o);break}}break}case"Single":{if(r=Bk(r,t),Tr(n))return[r,o];t=n.head,n=n.tail;break}}throw Error("BUG: BlockedRequests.step - please report an issue at https://github.com/Effect-TS/effect/issues")},jk=(e,t)=>{if(Tr(e))return zs(xf(t));if(Kk(t))return e;let r=Zk(e.head),n=Vk(t);if(r.length===1&&n.length===1&&E(r[0],n[0]))return Xr(Yk(e.head,xf(t)),e.tail);return Xr(xf(t),e)};var Hk=Symbol.for("effect/RequestBlock/RequestBlockParallel"),$k={_R:(e)=>e};class ul{map;[Hk]=$k;constructor(e){this.map=e}}var $S=()=>new ul(Ti());var Bk=(e,t)=>new ul(fS(e.map,t.dataSource,(r)=>Ry(rr(r,Gy(t.blockedRequest)),()=>Ne(t.blockedRequest)))),Wk=(e,t)=>new ul(Vd(e.map,t.map,(r,n,o)=>Wd(r,o,Ae(Bd(r,o),{onNone:()=>n,onSome:(i)=>Mt(n,i)})))),Kk=(e)=>dS(e.map),Vk=(e)=>Array.from(Kd(e.map)),xf=(e)=>Jk(mS(e.map,(t)=>Ne(t))),zk=Symbol.for("effect/RequestBlock/RequestBlockSequential"),Gk={_R:(e)=>e};class bf{map;[zk]=Gk;constructor(e){this.map=e}}var Jk=(e)=>new bf(e),Yk=(e,t)=>new bf(Vd(t.map,e.map,(r,n,o)=>Wd(r,o,Ae(Bd(r,o),{onNone:()=>Wt(),onSome:(i)=>Mt(i,n)}))));var Zk=(e)=>Array.from(Kd(e.map)),BS=(e)=>Array.from(e.map);var Ri="Pending",pl="Done";var Xk="effect/Deferred",KS=Symbol.for(Xk),VS={_E:(e)=>e,_A:(e)=>e},zS=(e)=>({_tag:Ri,joiners:e}),GS=(e)=>({_tag:pl,effect:e});class ki{self;called=!1;constructor(e){this.self=e}next(e){return this.called?{value:e,done:!0}:(this.called=!0,{value:this.self,done:!1})}return(e){return{value:e,done:!0}}throw(e){throw e}[Symbol.iterator](){return new ki(this.self)}}var ml=(e,t)=>{let r=new $e("Blocked");return r.effect_instruction_i0=e,r.effect_instruction_i1=t,r},Ef=(e)=>{let t=new $e("RunBlocked");return t.effect_instruction_i0=e,t},Un=Symbol.for("effect/Effect");class Of{patch;op;_op=Ts;constructor(e,t){this.patch=e,this.op=t}}class $e{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[Un]=En;constructor(e){this._op=e}[R](e){return this===e}[P](){return Z(this,ws(this))}pipe(){return b(this,arguments)}toJSON(){return{_id:"Effect",_op:this._op,effect_instruction_i0:re(this.effect_instruction_i0),effect_instruction_i1:re(this.effect_instruction_i1),effect_instruction_i2:re(this.effect_instruction_i2)}}toString(){return se(this.toJSON())}[Y](){return this.toJSON()}[Symbol.iterator](){return new ki(new Ur(this))}}class vf{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[Un]=En;constructor(e){this._op=e,this._tag=e}[R](e){return Li(e)&&e._op==="Failure"&&E(this.effect_instruction_i0,e.effect_instruction_i0)}[P](){return h(ie(this._tag),V(w(this.effect_instruction_i0)),Z(this))}get cause(){return this.effect_instruction_i0}pipe(){return b(this,arguments)}toJSON(){return{_id:"Exit",_tag:this._op,cause:this.cause.toJSON()}}toString(){return se(this.toJSON())}[Y](){return this.toJSON()}[Symbol.iterator](){return new ki(new Ur(this))}}class Af{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[Un]=En;constructor(e){this._op=e,this._tag=e}[R](e){return Li(e)&&e._op==="Success"&&E(this.effect_instruction_i0,e.effect_instruction_i0)}[P](){return h(ie(this._tag),V(w(this.effect_instruction_i0)),Z(this))}get value(){return this.effect_instruction_i0}pipe(){return b(this,arguments)}toJSON(){return{_id:"Exit",_tag:this._op,value:re(this.value)}}toString(){return se(this.toJSON())}[Y](){return this.toJSON()}[Symbol.iterator](){return new ki(new Ur(this))}}var Ci=(e)=>v(e,Un),Ge=(e)=>{let t=new $e(Sc);return t.effect_instruction_i0=e,t},nb=p(3,(e,t,r)=>$n((n)=>W(e,(o)=>W(Hn(me(()=>n(t(o)))),(i)=>me(()=>r(o,i)).pipe(zt({onFailure:(s)=>{switch(i._tag){case Et:return ot(nt(i.effect_instruction_i0,s));case Ot:return ot(s)}},onSuccess:()=>i})))))),rn=p(2,(e,t)=>W(e,()=>ne(t))),nn=(e)=>rn(e,void 0),Tf=function(){let e=new $e(xo);switch(arguments.length){case 2:{e.effect_instruction_i0=arguments[0],e.commit=arguments[1];break}case 3:{e.effect_instruction_i0=arguments[0],e.effect_instruction_i1=arguments[1],e.commit=arguments[2];break}case 4:{e.effect_instruction_i0=arguments[0],e.effect_instruction_i1=arguments[1],e.effect_instruction_i2=arguments[2],e.commit=arguments[3];break}default:throw Error(mo("you're not supposed to end up here"))}return e},ta=(e,t=Vt)=>{let r=new $e(yo),n=void 0;return r.effect_instruction_i0=(o)=>{n=e(o)},r.effect_instruction_i1=t,ia(r,(o)=>Ci(n)?n:Fe)},ob=(e,t=Vt)=>me(()=>ta(e,t)),jn=(e,t=Vt)=>Tf(e,function(){let r=void 0,n=void 0;function o(c){if(r)r(c);else if(n===void 0)n=c}let i=new $e(yo);i.effect_instruction_i0=(c)=>{if(r=c,n)c(n)},i.effect_instruction_i1=t;let s=void 0,a=void 0;if(this.effect_instruction_i0.length!==1)a=new AbortController,s=ze(()=>this.effect_instruction_i0(o,a.signal));else s=ze(()=>this.effect_instruction_i0(o));return s||a?ia(i,(c)=>{if(a)a.abort();return s??Fe}):i});var ra=p(2,(e,t)=>Pi(e,{onFailure:t,onSuccess:ne}));var JS=Symbol.for("effect/OriginalAnnotation");var hl=(e,t)=>{if(de(t))return new Proxy(e,{has(r,n){return n===Co||n===JS||n in r},get(r,n){if(n===Co)return t.value;if(n===JS)return e;return r[n]}});return e},gl=(e)=>mt(e)&&!(Co in e)?Ge((t)=>ot(Lt(hl(e,Pl(t))))):ot(Lt(e)),If=(e)=>ib(()=>Lt(new cC(e)));var Fo=(e)=>Pi(e,{onFailure:(t)=>ne(K(t)),onSuccess:(t)=>ne(G(t))}),Hn=(e)=>sb(e,{onFailure:ue,onSuccess:xe}),Be=(e)=>mt(e)&&!(Co in e)?Ge((t)=>ot(Ei(hl(e,Pl(t))))):ot(Ei(e)),Rf=(e)=>W(q(e),Be),ot=(e)=>{let t=new vf(Et);return t.effect_instruction_i0=e,t},ib=(e)=>W(q(e),ot),kf=Ge((e)=>ne(e.id())),na=(e)=>Ge((t)=>e(t.id())),W=p(2,(e,t)=>{let r=new $e(ai);return r.effect_instruction_i0=e,r.effect_instruction_i1=t,r});var Cf=(e)=>{let t=new $e("OnStep");return t.effect_instruction_i0=e,t},oa=(e)=>W(e,te);var sb=p(2,(e,t)=>zt(e,{onFailure:(r)=>ne(t.onFailure(r)),onSuccess:(r)=>ne(t.onSuccess(r))})),zt=p(2,(e,t)=>{let r=new $e(ci);return r.effect_instruction_i0=e,r.effect_instruction_i1=t.onFailure,r.effect_instruction_i2=t.onSuccess,r}),Pi=p(2,(e,t)=>zt(e,{onFailure:(r)=>{if(vd(r).length>0)return ot(Cx(r));let o=Od(r);if(o.length>0)return t.onFailure(cd(o));return ot(r)},onSuccess:t.onSuccess})),Gt=p(2,(e,t)=>me(()=>{let r=fe(e),n=bo(r.length),o=0;return rn(sa({while:()=>o<r.length,body:()=>t(r[o],o),step:(i)=>{n[o++]=i}}),n)})),Mo=p(2,(e,t)=>me(()=>{let r=fe(e),n=0;return sa({while:()=>n<r.length,body:()=>t(r[n],n),step:()=>{n++}})}));var yl=(e)=>{let t=new $e(So);return t.effect_instruction_i0=US(en),t.effect_instruction_i1=()=>e,t};var ve=p(2,(e,t)=>W(e,(r)=>q(()=>t(r)))),xl=p(2,(e,t)=>Pi(e,{onFailure:(r)=>Rf(()=>t.onFailure(r)),onSuccess:(r)=>q(()=>t.onSuccess(r))})),Lo=p(2,(e,t)=>zt(e,{onFailure:(r)=>{let n=Bc(r);switch(n._tag){case"Left":return Rf(()=>t(n.left));case"Right":return ot(n.right)}},onSuccess:ne}));var Ni=p(2,(e,t)=>$n((r)=>zt(r(e),{onFailure:(n)=>{let o=ue(n);return zt(t(o),{onFailure:(i)=>ue(nt(n,i)),onSuccess:()=>o})},onSuccess:(n)=>{let o=xe(n);return Bn(t(o),o)}}))),ia=p(2,(e,t)=>Ni(e,Rl({onFailure:(r)=>Oi(r)?nn(t(Ad(r))):Fe,onSuccess:()=>Fe})));var ne=(e)=>{let t=new Af(Ot);return t.effect_instruction_i0=e,t},me=(e)=>{let t=new $e(xo);return t.commit=e,t},q=(e)=>{let t=new $e(xc);return t.effect_instruction_i0=e,t},Sl=p((e)=>e.length===3||e.length===2&&!(mt(e[1])&&("onlyEffect"in e[1])),(e,t)=>W(e,(r)=>{let n=typeof t==="function"?t(r):t;if(Ci(n))return rn(n,r);else if(oy(n))return ta((o)=>{n.then((i)=>o(ne(r)),(i)=>o(Be(new uC(i,"An unknown error occurred in Effect.tap"))))});return ne(r)})),Pf=(e)=>Ge((t)=>{let r=t.getFiberRef(fl),n=h(r,pe(()=>t.scope()));return e(Wn(fl,M(n)))});var bl=(e)=>{let t=new $e(So);return t.effect_instruction_i0=gf(en),t.effect_instruction_i1=()=>e,t},$n=(e)=>Tf(e,function(){let t=new $e(So);return t.effect_instruction_i0=gf(en),t.effect_instruction_i1=(r)=>pf(r)?ze(()=>this.effect_instruction_i0(yl)):ze(()=>this.effect_instruction_i0(bl)),t}),Fe=ne(void 0);var Nf=(e)=>{let t=new $e(So);return t.effect_instruction_i0=e,t.effect_instruction_i1=void 0,t};var sa=(e)=>{let t=new $e(li);return t.effect_instruction_i0=e.while,t.effect_instruction_i1=e.body,t.effect_instruction_i2=e.step,t};var aa=(e)=>{let t=new $e(pi);return typeof e?.priority<"u"?yb(t,e.priority):t},_l=p(2,(e,t)=>W(e,(r)=>ve(t,(n)=>[r,n])));var wl=p(2,(e,t)=>W(e,(r)=>rn(t,r))),Bn=p(2,(e,t)=>W(e,()=>t));var ca=ob(()=>{let e=setInterval(()=>{},2147483647);return q(()=>clearInterval(e))}),ab=(e)=>W(kf,(t)=>h(e,la(t))),la=p(2,(e,t)=>W(e.interruptAsFork(t),()=>e.await)),cb={_tag:"All",syslog:0,label:"ALL",ordinal:Number.MIN_SAFE_INTEGER,pipe(){return b(this,arguments)}},lb={_tag:"Fatal",syslog:2,label:"FATAL",ordinal:50000,pipe(){return b(this,arguments)}},ub={_tag:"Error",syslog:3,label:"ERROR",ordinal:40000,pipe(){return b(this,arguments)}},Ff={_tag:"Warning",syslog:4,label:"WARN",ordinal:30000,pipe(){return b(this,arguments)}},Mf={_tag:"Info",syslog:6,label:"INFO",ordinal:20000,pipe(){return b(this,arguments)}},Lf={_tag:"Debug",syslog:7,label:"DEBUG",ordinal:1e4,pipe(){return b(this,arguments)}},pb={_tag:"Trace",syslog:7,label:"TRACE",ordinal:0,pipe(){return b(this,arguments)}},db={_tag:"None",syslog:7,label:"OFF",ordinal:Number.MAX_SAFE_INTEGER,pipe(){return b(this,arguments)}};var nC="effect/FiberRef",oC=Symbol.for(nC),iC={_A:(e)=>e},El=(e)=>Ge((t)=>xe(t.getFiberRef(e)));var Do=p(2,(e,t)=>W(El(e),t)),_f=p(2,(e,t)=>sC(e,()=>[void 0,t]));var sC=p(2,(e,t)=>Ge((r)=>{let[n,o]=t(r.getFiberRef(e));return r.setFiberRef(e,o),ne(n)}));var Wn=p(3,(e,t,r)=>nb(wl(El(t),_f(t,r)),()=>e,(n)=>_f(t,n)));var Je=(e,t)=>qo(e,{differ:ol(),fork:t?.fork??te,join:t?.join}),fb=(e)=>{let t=rf();return qo(e,{differ:t,fork:t.empty})},aC=(e)=>{let t=nf(ol());return qo(e,{differ:t,fork:t.empty})},Ol=(e)=>{let t=tf();return qo(e,{differ:t,fork:t.empty})},qo=(e,t)=>({...On,[oC]:iC,initial:e,commit(){return El(this)},diff:(n,o)=>t.differ.diff(n,o),combine:(n,o)=>t.differ.combine(n,o),patch:(n)=>(o)=>t.differ.patch(n,o),fork:t.fork,join:t.join??((n,o)=>o)}),mb=(e)=>qo(e,{differ:mf,fork:mf.empty}),Uo=B(Symbol.for("effect/FiberRef/currentContext"),()=>Ol(Mn())),Fi=B(Symbol.for("effect/FiberRef/currentSchedulingPriority"),()=>Je(0)),Df=B(Symbol.for("effect/FiberRef/currentMaxOpsBeforeYield"),()=>Je(2048)),hb=B(Symbol.for("effect/FiberRef/currentLogAnnotation"),()=>Je(Ti())),qf=B(Symbol.for("effect/FiberRef/currentLogLevel"),()=>Je(Mf)),gb=B(Symbol.for("effect/FiberRef/currentLogSpan"),()=>Je(Dn())),yb=p(2,(e,t)=>Wn(e,Fi,t));var xb=B(Symbol.for("effect/FiberRef/currentConcurrency"),()=>Je("unbounded")),Sb=B(Symbol.for("effect/FiberRef/currentRequestBatching"),()=>Je(!0)),bb=B(Symbol.for("effect/FiberRef/currentUnhandledErrorLogLevel"),()=>Je(M(Lf))),_b=B(Symbol.for("effect/FiberRef/versionMismatchErrorLogLevel"),()=>Je(M(Ff)));var ua=B(Symbol.for("effect/FiberRef/currentMetricLabels"),()=>aC(Kr()));var fl=B(Symbol.for("effect/FiberRef/currentForkScopeOverride"),()=>Je(A(),{fork:()=>A(),join:(e,t)=>e})),pa=B(Symbol.for("effect/FiberRef/currentInterruptedCause"),()=>Je(Zr,{fork:()=>Zr,join:(e,t)=>e}));var vl=Symbol.for("effect/Scope"),Al=Symbol.for("effect/CloseableScope"),Tl=(e,t)=>e.addFinalizer(()=>nn(t));var Uf=(e,t)=>e.close(t),Mi=(e,t)=>e.fork(t);var Il=function(){class e extends globalThis.Error{commit(){return Be(this)}toJSON(){let t={...this};if(this.message)t.message=this.message;if(this.cause)t.cause=this.cause;return t}[Y](){if(this.toString!==globalThis.Error.prototype.toString)return this.stack?`${this.toString()}
26
- ${this.stack.split(`
27
- `).slice(1).join(`
28
- `)}`:this.toString();else if("Bun"in globalThis)return ur(Ei(this),{renderErrorCause:!0});return this}}return Object.assign(e.prototype,qp),e}(),jo=(e,t)=>{class r extends Il{_tag=t}return Object.assign(r.prototype,e),r.prototype.name=t,r},YS=Symbol.for("effect/Cause/errors/RuntimeException"),cC=jo({[YS]:YS},"RuntimeException");var wf=Symbol.for("effect/Cause/errors/InterruptedException"),P2=jo({[wf]:wf},"InterruptedException"),wb=(e)=>v(e,wf),ZS=Symbol.for("effect/Cause/errors/IllegalArgument"),lC=jo({[ZS]:ZS},"IllegalArgumentException");var QS=Symbol.for("effect/Cause/errors/NoSuchElement"),da=jo({[QS]:QS},"NoSuchElementException");var XS=Symbol.for("effect/Cause/errors/InvalidPubSubCapacityException"),N2=jo({[XS]:XS},"InvalidPubSubCapacityException"),eb=Symbol.for("effect/Cause/errors/ExceededCapacityException"),F2=jo({[eb]:eb},"ExceededCapacityException");var tb=Symbol.for("effect/Cause/errors/Timeout"),M2=jo({[tb]:tb},"TimeoutException");var rb=Symbol.for("effect/Cause/errors/UnknownException"),uC=function(){class e extends Il{_tag="UnknownException";error;constructor(t,r){super(r??"An unknown error occurred",{cause:t});this.error=t}}return Object.assign(e.prototype,{[rb]:rb,name:"UnknownException"}),e}();var Li=(e)=>Ci(e)&&("_tag"in e)&&(e._tag==="Success"||e._tag==="Failure");var jf=(e)=>e._tag==="Success";var Eb=p(2,(e,t)=>{switch(e._tag){case Et:return ue(e.effect_instruction_i0);case Ot:return xe(t)}}),fa=(e)=>Eb(e,void 0);var Ho=(e,t)=>pC(e,t?.parallel?Po:nt),Hf=(e)=>ue(Lt(e));var ma=(e)=>ue(Ei(e)),ue=(e)=>{let t=new vf(Et);return t.effect_instruction_i0=e,t};var $f=(e)=>ue(lr(e)),dl=p(2,(e,t)=>{switch(e._tag){case Et:return ue(e.effect_instruction_i0);case Ot:return xe(t(e.effect_instruction_i0))}});var Rl=p(2,(e,{onFailure:t,onSuccess:r})=>{switch(e._tag){case Et:return t(e.effect_instruction_i0);case Ot:return r(e.effect_instruction_i0)}});var xe=(e)=>{let t=new Af(Ot);return t.effect_instruction_i0=e,t},Jt=xe(void 0);var Bf=p(3,(e,t,{onFailure:r,onSuccess:n})=>{switch(e._tag){case Et:switch(t._tag){case Ot:return ue(e.effect_instruction_i0);case Et:return ue(r(e.effect_instruction_i0,t.effect_instruction_i0))}case Ot:switch(t._tag){case Ot:return xe(n(e.effect_instruction_i0,t.effect_instruction_i0));case Et:return ue(t.effect_instruction_i0)}}}),pC=(e,t)=>{let r=Ac(e);if(!sr(r))return A();return h(cr(r),mi(h(ar(r),dl(Ne)),(n,o)=>h(n,Bf(o,{onSuccess:(i,s)=>h(i,rt(s)),onFailure:t}))),dl(In),dl((n)=>zr(n)),M)},Ob=(e)=>({...On,[KS]:VS,state:Jc(zS([])),commit(){return kl(this)},blockingOn:e});var kl=(e)=>ob((t)=>{let r=vi(e.state);switch(r._tag){case pl:return t(r.effect);case Ri:return r.joiners.push(t),dC(e,t)}},e.blockingOn);var Cl=(e,t)=>{let r=vi(e.state);if(r._tag===Ri){Yc(e.state,GS(t));for(let n=0,o=r.joiners.length;n<o;n++)r.joiners[n](t)}},dC=(e,t)=>q(()=>{let r=vi(e.state);if(r._tag===Ri){let n=r.joiners.indexOf(t);if(n>=0)r.joiners.splice(n,1)}}),fC=Ge((e)=>xe(e.currentContext)),vb=()=>fC;var $o=(e)=>W(vb(),e),mC=p(2,(e,t)=>Wn(Uo,t)(e));var Wf=p(2,(e,t)=>$o((r)=>mC(e,t(r))));var Pl=(e)=>{let t=e.currentSpan;return t!==void 0&&t._tag==="Span"?M(t):A()};var Ab=Rx;var Tb=ur;var Nl="And",Fl="Or",Ml="InvalidData",Ll="MissingData",Dl="SourceUnavailable",ql="Unsupported";var yC="effect/ConfigError",Ib=Symbol.for(yC),Di={_tag:"ConfigError",[Ib]:Ib},Ul=(e,t)=>{let r=Object.create(Di);return r._op=Nl,r.left=e,r.right=t,Object.defineProperty(r,"toString",{enumerable:!1,value(){return`${this.left} and ${this.right}`}}),Object.defineProperty(r,"message",{enumerable:!1,get(){return this.toString()}}),r},jl=(e,t)=>{let r=Object.create(Di);return r._op=Fl,r.left=e,r.right=t,Object.defineProperty(r,"toString",{enumerable:!1,value(){return`${this.left} or ${this.right}`}}),Object.defineProperty(r,"message",{enumerable:!1,get(){return this.toString()}}),r},Kf=(e,t,r={pathDelim:"."})=>{let n=Object.create(Di);return n._op=Ml,n.path=e,n.message=t,Object.defineProperty(n,"toString",{enumerable:!1,value(){return`(Invalid data at ${h(this.path,Vr(r.pathDelim))}: "${this.message}")`}}),n},Ir=(e,t,r={pathDelim:"."})=>{let n=Object.create(Di);return n._op=Ll,n.path=e,n.message=t,Object.defineProperty(n,"toString",{enumerable:!1,value(){return`(Missing data at ${h(this.path,Vr(r.pathDelim))}: "${this.message}")`}}),n},Vf=(e,t,r,n={pathDelim:"."})=>{let o=Object.create(Di);return o._op=Dl,o.path=e,o.message=t,o.cause=r,Object.defineProperty(o,"toString",{enumerable:!1,value(){return`(Source unavailable at ${h(this.path,Vr(n.pathDelim))}: "${this.message}")`}}),o},zf=(e,t,r={pathDelim:"."})=>{let n=Object.create(Di);return n._op=ql,n.path=e,n.message=t,Object.defineProperty(n,"toString",{enumerable:!1,value(){return`(Unsupported operation at ${h(this.path,Vr(r.pathDelim))}: "${this.message}")`}}),n};var Kn=p(2,(e,t)=>{switch(e._op){case Nl:return Ul(Kn(e.left,t),Kn(e.right,t));case Fl:return jl(Kn(e.left,t),Kn(e.right,t));case Ml:return Kf([...t,...e.path],e.message);case Ll:return Ir([...t,...e.path],e.message);case Dl:return Vf([...t,...e.path],e.message,e.cause);case ql:return zf([...t,...e.path],e.message)}});var Rb=p(3,(e,t,r)=>{let n=[e],o=[];while(n.length>0){let s=n.pop();switch(s._op){case Nl:{n.push(s.right),n.push(s.left),o.push(K({_op:"AndCase"}));break}case Fl:{n.push(s.right),n.push(s.left),o.push(K({_op:"OrCase"}));break}case Ml:{o.push(G(r.invalidDataCase(t,s.path,s.message)));break}case Ll:{o.push(G(r.missingDataCase(t,s.path,s.message)));break}case Dl:{o.push(G(r.sourceUnavailableCase(t,s.path,s.message,s.cause)));break}case ql:{o.push(G(r.unsupportedCase(t,s.path,s.message)));break}}}let i=[];while(o.length>0){let s=o.pop();switch(s._op){case"Left":{switch(s.left._op){case"AndCase":{let a=i.pop(),c=i.pop(),l=r.andCase(t,a,c);i.push(l);break}case"OrCase":{let a=i.pop(),c=i.pop(),l=r.orCase(t,a,c);i.push(l);break}}break}case"Right":{i.push(s.right);break}}}if(i.length===0)throw Error("BUG: ConfigError.reduceWithContext - please report an issue at https://github.com/Effect-TS/effect/issues");return i.pop()});var xC="effect/Clock",Cb=Symbol.for(xC),ha=At("effect/Clock"),SC=2147483647,Pb={unsafeSchedule(e,t){let r=Gc(t);if(r>SC)return bn;let n=!1,o=setTimeout(()=>{n=!0,e()},r);return()=>(clearTimeout(o),!n)}},Nb=function(){let e=BigInt(1e6);if(typeof performance>"u"||typeof performance.now!=="function")return()=>BigInt(Date.now())*e;let t;return()=>{if(t===void 0)t=BigInt(Date.now())*e-BigInt(Math.round(performance.now()*1e6));return t+BigInt(Math.round(performance.now()*1e6))}}(),bC=function(){let e=typeof process==="object"&&"hrtime"in process&&typeof process.hrtime.bigint==="function"?process.hrtime:void 0;if(!e)return Nb;let t=Nb()-e.bigint();return()=>t+e.bigint()}();class Fb{[Cb]=Cb;unsafeCurrentTimeMillis(){return Date.now()}unsafeCurrentTimeNanos(){return bC()}currentTimeMillis=q(()=>this.unsafeCurrentTimeMillis());currentTimeNanos=q(()=>this.unsafeCurrentTimeNanos());scheduler(){return ne(Pb)}sleep(e){return jn((t)=>{let r=Pb.unsafeSchedule(()=>t(Fe),e);return nn(q(r))})}}var Mb=()=>new Fb;var Rr=Iy;var qi=(e)=>e.replace(/[/\\^$*+?.()|[\]{}]/g,"\\$&");var qb={_tag:"Empty"};var $l=p(2,(e,t)=>{let r=zs(t),n=e;while(Jd(r)){let o=r.head;switch(o._tag){case"Empty":{r=r.tail;break}case"AndThen":{r=Xr(o.first,Xr(o.second,r.tail));break}case"MapName":{n=ir(n,o.f),r=r.tail;break}case"Nested":{n=di(n,o.name),r=r.tail;break}case"Unnested":{if(h(Br(n),Py(o.name)))n=or(n),r=r.tail;else return K(Ir(n,`Expected ${o.name} to be in path in ConfigProvider#unnested`));break}}}return G(n)});var Ub="Constant",jb="Fail",Hb="Fallback",$b="Described",Bb="Lazy",Wb="MapOrFail",Kb="Nested",Vb="Primitive",zb="Redacted",Gb="Sequence",Jb="HashMap",Yb="ZipWith";var Bl=(e,t)=>[...e,...t],TC="effect/ConfigProvider",Zb=Symbol.for(TC),Xb=At("effect/ConfigProvider"),IC="effect/ConfigProviderFlat",Qb=Symbol.for(IC),RC=(e)=>({[Zb]:Zb,pipe(){return b(this,arguments)},...e}),kC=(e)=>({[Qb]:Qb,patch:e.patch,load:(t,r,n=!0)=>e.load(t,r,n),enumerateChildren:e.enumerateChildren}),CC=(e)=>RC({load:(t)=>W(Dt(e,Kr(),t,!1),(r)=>Ae(Br(r),{onNone:()=>Be(Ir(Kr(),`Expected a single value having structure: ${t}`)),onSome:ne})),flattened:e}),e_=(e)=>{let{pathDelim:t,seqDelim:r}=Object.assign({},{pathDelim:"_",seqDelim:","},e),n=(c)=>h(c,Vr(t)),o=(c)=>c.split(t),i=()=>typeof process<"u"&&("env"in process)&&typeof process.env==="object"?process.env:{};return CC(kC({load:(c,l,u=!0)=>{let d=n(c),f=i(),g=d in f?M(f[d]):A();return h(g,Lo(()=>Ir(c,`Expected ${d} to exist in the process context`)),W((y)=>qC(y,c,l,r,u)))},enumerateChildren:(c)=>q(()=>{let l=i(),f=Object.keys(l).map((g)=>o(g.toUpperCase())).filter((g)=>{for(let y=0;y<c.length;y++){let O=h(c,ed(y)),m=g[y];if(m===void 0||O!==m)return!1}return!0}).flatMap((g)=>g.slice(c.length,c.length+1));return Ex(f)}),patch:qb}))};var PC=(e,t,r,n)=>{let o=od(r.length,(c)=>c>=n.length?A():M([e(c),c+1])),i=od(n.length,(c)=>c>=r.length?A():M([t(c),c+1])),s=Bl(r,o),a=Bl(n,i);return[s,a]},NC=(e,t)=>{let r=t;if(r._tag==="Nested"){let n=e.slice();while(r._tag==="Nested")n.push(r.name),r=r.config;return n}return e},FC={andCase:(e,t,r)=>Ul(t,r),orCase:(e,t,r)=>jl(t,r),invalidDataCase:(e,t)=>Kf(t,"<redacted>"),missingDataCase:(e,t)=>Ir(t,"<redacted>"),sourceUnavailableCase:(e,t,r,n)=>Vf(t,"<redacted>",n),unsupportedCase:(e,t)=>zf(t,"<redacted>")},MC=(e)=>Rb(e,void 0,FC),Dt=(e,t,r,n)=>{let o=r;switch(o._tag){case Ub:return ne(tt(o.value));case $b:return me(()=>Dt(e,t,o.config,n));case jb:return Be(Ir(t,o.message));case Hb:return h(me(()=>Dt(e,t,o.first,n)),ra((i)=>{if(o.condition(i))return h(Dt(e,t,o.second,n),ra((s)=>Be(jl(i,s))));return Be(i)}));case Bb:return me(()=>Dt(e,t,o.config(),n));case Wb:return me(()=>h(Dt(e,t,o.original,n),W(Gt((i)=>h(o.mapOrFail(i),Lo(Kn(NC(t,o.original))))))));case Kb:return me(()=>Dt(e,Bl(t,tt(o.name)),o.config,n));case Vb:return h($l(t,e.patch),W((i)=>h(e.load(i,o,n),W((s)=>{if(s.length===0){let a=h(Uy(i),pe(()=>"<n/a>"));return Be(Ir([],`Expected ${o.description} with name ${a}`))}return ne(s)}))));case zb:return me(()=>h(Dt(e,t,o.original,n),Lo(MC),ve(ir(o.redact))));case Gb:return h($l(t,e.patch),W((i)=>h(e.enumerateChildren(i),W(jC),W((s)=>{if(s.length===0)return me(()=>ve(Dt(e,t,o.config,!0),tt));return h(Gt(s,(a)=>Dt(e,Ly(t,`[${a}]`),o.config,!0)),ve((a)=>{let c=Oc(a);if(c.length===0)return tt(Kr());return tt(c)}))}))));case Jb:return me(()=>h($l(t,e.patch),W((i)=>h(e.enumerateChildren(i),W((s)=>h(s,Gt((a)=>Dt(e,Bl(i,tt(a)),o.valueConfig,n)),ve((a)=>{if(a.length===0)return tt(Ti());return h(UC(a),ir((c)=>pS(nd(fe(s),c))))})))))));case Yb:return me(()=>h(Dt(e,t,o.left,n),Fo,W((i)=>h(Dt(e,t,o.right,n),Fo,W((s)=>{if(ge(i)&&ge(s))return Be(Ul(i.left,s.left));if(ge(i)&&He(s))return Be(i.left);if(He(i)&&ge(s))return Be(s.left);if(He(i)&&He(s)){let a=h(t,Vr(".")),c=LC(t,a),[l,u]=PC(c,c,h(i.right,ir(G)),h(s.right,ir(G)));return h(l,nd(u),Gt(([d,f])=>h(_l(d,f),ve(([g,y])=>o.zip(g,y)))))}throw Error("BUG: ConfigProvider.fromFlatLoop - please report an issue at https://github.com/Effect-TS/effect/issues")})))))}},LC=(e,t)=>(r)=>K(Ir(e,`The element at index ${r} in a sequence at path "${t}" was missing`));var DC=(e,t)=>e.split(new RegExp(`\\s*${qi(t)}\\s*`)),qC=(e,t,r,n,o)=>{if(!o)return h(r.parse(e),xl({onFailure:Kn(t),onSuccess:tt}));return h(DC(e,n),Gt((i)=>r.parse(i.trim())),Lo(Kn(t)))},UC=(e)=>Object.keys(e[0]).map((t)=>e.map((r)=>r[t])),jC=(e)=>h(Gt(e,$C),xl({onFailure:()=>Kr(),onSuccess:Wr(Rr)}),Fo,ve(vy));var HC=/^(\[(\d+)\])$/,$C=(e)=>{let t=e.match(HC);if(t!==null){let r=t[2];return h(r!==void 0&&r.length>0?M(r):A(),nr(BC))}return A()};var BC=(e)=>{let t=Number.parseInt(e);return Number.isNaN(t)?A():M(t)};var t_=Symbol.for("effect/Console"),Wl=At("effect/Console"),r_={[t_]:t_,assert(e,...t){return q(()=>{console.assert(e,...t)})},clear:q(()=>{console.clear()}),count(e){return q(()=>{console.count(e)})},countReset(e){return q(()=>{console.countReset(e)})},debug(...e){return q(()=>{console.debug(...e)})},dir(e,t){return q(()=>{console.dir(e,t)})},dirxml(...e){return q(()=>{console.dirxml(...e)})},error(...e){return q(()=>{console.error(...e)})},group(e){return e?.collapsed?q(()=>console.groupCollapsed(e?.label)):q(()=>console.group(e?.label))},groupEnd:q(()=>{console.groupEnd()}),info(...e){return q(()=>{console.info(...e)})},log(...e){return q(()=>{console.log(...e)})},table(e,t){return q(()=>{console.table(e,t)})},time(e){return q(()=>console.time(e))},timeEnd(e){return q(()=>console.timeEnd(e))},timeLog(e,...t){return q(()=>{console.timeLog(e,...t)})},trace(...e){return q(()=>{console.trace(...e)})},warn(...e){return q(()=>{console.warn(...e)})},unsafe:console};var VC="effect/Random",n_=Symbol.for(VC),o_=At("effect/Random");class i_{seed;[n_]=n_;PRNG;constructor(e){this.seed=e,this.PRNG=new Pp(e)}get next(){return q(()=>this.PRNG.number())}get nextBoolean(){return ve(this.next,(e)=>e>0.5)}get nextInt(){return q(()=>this.PRNG.integer(Number.MAX_SAFE_INTEGER))}nextRange(e,t){return ve(this.next,(r)=>(t-e)*r+e)}nextIntBetween(e,t){return q(()=>this.PRNG.integer(t-e)+e)}shuffle(e){return zC(e,(t)=>this.nextIntBetween(0,t))}}var zC=(e,t)=>me(()=>h(q(()=>Array.from(e)),W((r)=>{let n=[];for(let o=r.length;o>=2;o=o-1)n.push(o);return h(n,Mo((o)=>h(t(o),ve((i)=>GC(r,o-1,i)))),rn(Ac(r)))}))),GC=(e,t,r)=>{let n=e[t];return e[t]=e[r],e[r]=n,e},s_=(e)=>new i_(w(e));var a_=Symbol.for("effect/Tracer"),YC=(e)=>({[a_]:a_,...e}),ga=At("effect/Tracer"),Kl=At("effect/ParentSpan"),c_=function(){return function(r){let n="";for(let o=0;o<r;o++)n+="abcdef0123456789".charAt(Math.floor(Math.random()*16));return n}}();class l_{name;parent;context;startTime;kind;_tag="Span";spanId;traceId="native";sampled=!0;status;attributes;events=[];links;constructor(e,t,r,n,o,i){this.name=e,this.parent=t,this.context=r,this.startTime=o,this.kind=i,this.status={_tag:"Started",startTime:o},this.attributes=new Map,this.traceId=t._tag==="Some"?t.value.traceId:c_(32),this.spanId=c_(16),this.links=Array.from(n)}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,r){this.events.push([e,t,r??{}])}addLinks(e){this.links.push(...e)}}var u_=YC({span:(e,t,r,n,o,i)=>new l_(e,t,r,n,o,i),context:(e)=>e()});var p_=Ws()("effect/Tracer/DisablePropagation",{defaultValue:bn});var XC=h(Mn(),vr(ha,Mb()),vr(Wl,r_),vr(o_,s_(Math.random())),vr(Xb,e_()),vr(ga,u_)),ya=B(Symbol.for("effect/DefaultServices/currentServices"),()=>Ol(XC));var tP=function(){let e=Symbol.for("effect/Data/Error/plainArgs");return{BaseEffectError:class extends Il{constructor(r){super(r?.message,r?.cause?{cause:r.cause}:void 0);if(r)Object.assign(this,r),Object.defineProperty(this,e,{value:r,enumerable:!1})}toJSON(){return{...this[e],...this}}}}.BaseEffectError}(),d_=(e)=>{let t={BaseEffectError:class extends tP{_tag=e}};return t.BaseEffectError.prototype.name=e,t.BaseEffectError};var f_=Hr;var rP=gy;class Jf extends rP{}var h_="Sequential",g_="Parallel",nP="ParallelN",Ui={_tag:h_},y_={_tag:g_},x_=(e)=>({_tag:nP,parallelism:e}),Yf=(e)=>e._tag===h_,Zf=(e)=>e._tag===g_;var Vl=Ui,zl=y_,Gl=x_;function S_(e){return new on(e)}function b_(){return S_(new Map)}var Xf=Symbol.for("effect/FiberRefs");class on{locals;[Xf]=Xf;constructor(e){this.locals=e}pipe(){return b(this,arguments)}}var iP=(e,t,r,n=!1)=>{let o=e,i=t,s=r,a=n,c=void 0;while(c===void 0)if(le(i)&&le(s)){let l=Pe(i)[0],u=or(i),d=Pe(s)[0],f=Pe(s)[1],g=or(s);if(l.startTimeMillis<d.startTimeMillis)s=g,a=!0;else if(l.startTimeMillis>d.startTimeMillis)i=u;else if(l.id<d.id)s=g,a=!0;else if(l.id>d.id)i=u;else c=[f,a]}else c=[o.initial,!0];return c},tm=p(3,(e,t,r)=>{let n=new Map(e.locals);return r.locals.forEach((o,i)=>{let s=o[0][1];if(!o[0][0][R](t)){if(!n.has(i)){if(E(s,i.initial))return;n.set(i,[[t,i.join(i.initial,s)]]);return}let a=n.get(i),[c,l]=iP(i,a,o);if(l){let u=i.diff(c,s),d=a[0][1],f=i.join(d,i.patch(u)(d));if(!E(d,f)){let g,y=a[0][0];if(y[R](t))g=[[y,f],...a.slice(1)];else g=[[t,f],...a];n.set(i,g)}}}}),new on(n)}),rm=p(2,(e,t)=>{let r=new Map;return __(e,r,t),new on(r)}),__=(e,t,r)=>{e.locals.forEach((n,o)=>{let i=n[0][1],s=o.patch(o.fork)(i);if(E(i,s))t.set(o,n);else t.set(o,[[r,s],...n])})};var xa=p(2,(e,t)=>{let r=new Map(e.locals);return r.delete(t),new on(r)}),nm=p(2,(e,t)=>{if(!e.locals.has(t))return A();return M(Pe(e.locals.get(t))[1])}),Vn=p(2,(e,t)=>h(nm(e,t),pe(()=>t.initial))),ji=p(2,(e,{fiberId:t,fiberRef:r,value:n})=>{if(e.locals.size===0)return new on(new Map([[r,[[t,n]]]]));let o=new Map(e.locals);return em(o,t,r,n),new on(o)}),em=(e,t,r,n)=>{let o=e.get(r)??[],i;if(le(o)){let[s,a]=Pe(o);if(s[R](t))if(E(a,n))return;else i=[[t,n],...o.slice(1)];else i=[[t,n],...o]}else i=[[t,n]];e.set(r,i)},w_=p(2,(e,{entries:t,forkAs:r})=>{if(e.locals.size===0)return new on(new Map(t));let n=new Map(e.locals);if(r!==void 0)__(e,n,r);return t.forEach(([o,i])=>{if(i.length===1)em(n,i[0][0],o,i[0][1]);else i.forEach(([s,a])=>{em(n,s,o,a)})}),new on(n)});var E_=Vn;var O_=w_;var v_=b_;var T_="Empty",I_="Add",R_="Remove",k_="Update",C_="AndThen",P_={_tag:T_},N_=(e,t)=>{let r=new Map(e.locals),n=P_;for(let[o,i]of t.locals.entries()){let s=Pe(i)[1],a=r.get(o);if(a!==void 0){let c=Pe(a)[1];if(!E(c,s))n=Jl({_tag:k_,fiberRef:o,patch:o.diff(c,s)})(n)}else n=Jl({_tag:I_,fiberRef:o,value:s})(n);r.delete(o)}for(let[o]of r.entries())n=Jl({_tag:R_,fiberRef:o})(n);return n},Jl=p(2,(e,t)=>({_tag:C_,first:e,second:t})),F_=p(3,(e,t,r)=>{let n=r,o=tt(e);while(le(o)){let i=Pe(o),s=or(o);switch(i._tag){case T_:{o=s;break}case I_:{n=ji(n,{fiberId:t,fiberRef:i.fiberRef,value:i.value}),o=s;break}case R_:{n=xa(n,i.fiberRef),o=s;break}case k_:{let a=Vn(n,i.fiberRef);n=ji(n,{fiberId:t,fiberRef:i.fiberRef,value:i.fiberRef.patch(i.patch)(a)}),o=s;break}case C_:{o=di(i.first)(di(i.second)(s));break}}}return n});var M_=N_;var L_=F_;var Zl="effect/FiberStatus",zn=Symbol.for(Zl),Yl="Done",D_="Running",q_="Suspended",cP=ie(`${Zl}-${Yl}`);class U_{[zn]=zn;_tag=Yl;[P](){return cP}[R](e){return Ql(e)&&e._tag===Yl}}class j_{runtimeFlags;[zn]=zn;_tag=D_;constructor(e){this.runtimeFlags=e}[P](){return h(w(Zl),V(w(this._tag)),V(w(this.runtimeFlags)),Z(this))}[R](e){return Ql(e)&&e._tag===D_&&this.runtimeFlags===e.runtimeFlags}}class H_{runtimeFlags;blockingOn;[zn]=zn;_tag=q_;constructor(e,t){this.runtimeFlags=e,this.blockingOn=t}[P](){return h(w(Zl),V(w(this._tag)),V(w(this.runtimeFlags)),V(w(this.blockingOn)),Z(this))}[R](e){return Ql(e)&&e._tag===q_&&this.runtimeFlags===e.runtimeFlags&&E(this.blockingOn,e.blockingOn)}}var $_=new U_,B_=(e)=>new j_(e),W_=(e,t)=>new H_(e,t),Ql=(e)=>v(e,zn),K_=(e)=>e._tag===Yl;var V_=$_,im=B_,z_=W_;var G_=K_;var pP=cb,dP=lb,fP=ub,mP=Ff,hP=Mf,gP=Lf,yP=pb,xP=db;var SP=h(Rr,Ec((e)=>e.ordinal));var J_=Gp(SP);var Y_=(e)=>{switch(e){case"All":return pP;case"Debug":return gP;case"Error":return fP;case"Fatal":return dP;case"Info":return hP;case"Trace":return yP;case"None":return xP;case"Warning":return mP}};var _P=Symbol.for("effect/Micro"),eu=Symbol.for("effect/Micro/MicroExit");var Z_=Symbol.for("effect/Micro/MicroCause");var wP={_E:te};class cm extends globalThis.Error{_tag;traces;[Z_];constructor(e,t,r){let n=`MicroCause.${e}`,o,i,s;if(t instanceof globalThis.Error){o=`(${n}) ${t.name}`,i=t.message;let a=i.split(`
29
- `).length;s=t.stack?`(${n}) ${t.stack.split(`
30
- `).slice(0,a+3).join(`
31
- `)}`:`${o}: ${i}`}else o=n,i=jr(t,0),s=`${o}: ${i}`;if(r.length>0)s+=`
32
- ${r.join(`
33
- `)}`;super(i);this._tag=e,this.traces=r,this[Z_]=wP,this.name=o,this.stack=s}pipe(){return b(this,arguments)}toString(){return this.stack}[Y](){return this.stack}}class ew extends cm{defect;constructor(e,t=[]){super("Die",e,t);this.defect=e}}var EP=(e,t=[])=>new ew(e,t);class tw extends cm{constructor(e=[]){super("Interrupt","interrupted",e)}}var OP=(e=[])=>new tw(e);var vP=(e)=>e._tag==="Interrupt";var Q_=Symbol.for("effect/Micro/MicroFiber"),AP={_A:te,_E:te};class rw{context;interruptible;[Q_];_stack=[];_observers=[];_exit;_children;currentOpCount=0;constructor(e,t=!0){this.context=e,this.interruptible=t,this[Q_]=AP}getRef(e){return Hx(this.context,e)}addObserver(e){if(this._exit)return e(this._exit),gs;return this._observers.push(e),()=>{let t=this._observers.indexOf(e);if(t>=0)this._observers.splice(t,1)}}_interrupted=!1;unsafeInterrupt(){if(this._exit)return;if(this._interrupted=!0,this.interruptible)this.evaluate(fm)}unsafePoll(){return this._exit}evaluate(e){if(this._exit)return;else if(this._yielded!==void 0){let n=this._yielded;this._yielded=void 0,n()}let t=this.runLoop(e);if(t===Xl)return;let r=X_.interruptChildren&&X_.interruptChildren(this);if(r!==void 0)return this.evaluate(ru(r,()=>t));this._exit=t;for(let n=0;n<this._observers.length;n++)this._observers[n](t);this._observers.length=0}runLoop(e){let t=!1,r=e;this.currentOpCount=0;try{while(!0){if(this.currentOpCount++,!t&&this.getRef(ou).shouldYield(this)){t=!0;let n=r;r=ru(CP,()=>n)}if(r=r[sm](this),r===Xl){let n=this._yielded;if(eu in n)return this._yielded=void 0,n;return Xl}}}catch(n){if(!v(r,sm))return am(`MicroFiber.runLoop: Not a valid effect: ${String(r)}`);return am(n)}}getCont(e){while(!0){let t=this._stack.pop();if(!t)return;let r=t[tu]&&t[tu](this);if(r)return{[e]:r};if(t[e])return t}}_yielded=void 0;yieldWith(e){return this._yielded=e,Xl}children(){return this._children??=new Set}}var X_=B("effect/Micro/fiberMiddleware",()=>({interruptChildren:void 0}));var nw=Symbol.for("effect/Micro/identifier"),De=Symbol.for("effect/Micro/args"),sm=Symbol.for("effect/Micro/evaluate"),$i=Symbol.for("effect/Micro/successCont"),Hi=Symbol.for("effect/Micro/failureCont"),tu=Symbol.for("effect/Micro/ensureCont"),Xl=Symbol.for("effect/Micro/Yield"),TP={_A:te,_E:te,_R:te},IP={...f_,_op:"Micro",[_P]:TP,pipe(){return b(this,arguments)},[Symbol.iterator](){return new si(new Ur(this))},toJSON(){return{_id:"Micro",op:this[nw],...De in this?{args:this[De]}:void 0}},toString(){return se(this)},[Y](){return se(this)}};function RP(e){return am("Micro.evaluate: Not implemented")}var nu=(e)=>({...IP,[nw]:e.op,[sm]:e.eval??RP,[$i]:e.contA,[Hi]:e.contE,[tu]:e.ensure}),lm=(e)=>{let t=nu(e);return function(){let r=Object.create(t);return r[De]=e.single===!1?arguments:arguments[0],r}},ow=(e)=>{let t={...nu(e),[eu]:eu,_tag:e.op,get[e.prop](){return this[De]},toJSON(){return{_id:"MicroExit",_tag:e.op,[e.prop]:this[De]}},[R](r){return FP(r)&&r._tag===e.op&&E(this[De],r[De])},[P](){return Z(this,V(ie(e.op))(w(this[De])))}};return function(r){let n=Object.create(t);return n[De]=r,n[$i]=void 0,n[Hi]=void 0,n[tu]=void 0,n}},um=ow({op:"Success",prop:"value",eval(e){let t=e.getCont($i);return t?t[$i](this[De],e):e.yieldWith(this)}}),iw=ow({op:"Failure",prop:"cause",eval(e){let t=e.getCont(Hi);while(vP(this[De])&&t&&e.interruptible)t=e.getCont(Hi);return t?t[Hi](this[De],e):e.yieldWith(this)}});var kP=lm({op:"Yield",eval(e){let t=!1;return e.getRef(ou).scheduleTask(()=>{if(t)return;e.evaluate(MP)},this[De]??0),e.yieldWith(()=>{t=!0})}}),CP=kP(0);var PP=um(void 0);var pm=lm({op:"WithMicroFiber",eval(e){return this[De](e)}});var ru=p(2,(e,t)=>{let r=Object.create(NP);return r[De]=e,r[$i]=t,r}),NP=nu({op:"OnSuccess",eval(e){return e._stack.push(this),this[De]}});var FP=(e)=>v(e,eu),sw=um,dm=iw,fm=dm(OP());var am=(e)=>dm(EP(e));var MP=sw(void 0);var LP="setImmediate"in globalThis?globalThis.setImmediate:(e)=>setTimeout(e,0);class mm{tasks=[];running=!1;scheduleTask(e,t){if(this.tasks.push(e),!this.running)this.running=!0,LP(this.afterScheduled)}afterScheduled=()=>{this.running=!1,this.runTasks()};runTasks(){let e=this.tasks;this.tasks=[];for(let t=0,r=e.length;t<r;t++)e[t]()}shouldYield(e){return e.currentOpCount>=e.getRef(cw)}flush(){while(this.tasks.length>0)this.runTasks()}}var DP=p(2,(e,t)=>pm((r)=>{let n=r.context;return r.context=t(n),jP(e,()=>(r.context=n,PP))}));var aw=p(2,(e,t)=>DP(e,Bs(t)));class cw extends Ws()("effect/Micro/currentMaxOpsBeforeYield",{defaultValue:()=>2048}){}class ou extends Ws()("effect/Micro/currentScheduler",{defaultValue:()=>new mm}){}var qP=p(2,(e,t)=>{let r=Object.create(UP);return r[De]=e,r[$i]=t.onSuccess,r[Hi]=t.onFailure,r}),UP=nu({op:"OnSuccessAndFailure",eval(e){return e._stack.push(this),this[De]}});var jP=p(2,(e,t)=>$P((r)=>qP(r(e),{onFailure:(n)=>ru(t(dm(n)),()=>iw(n)),onSuccess:(n)=>ru(t(sw(n)),()=>um(n))})));var lw=lm({op:"SetInterruptible",ensure(e){if(e.interruptible=this[De],e._interrupted&&e.interruptible)return()=>fm}}),HP=(e)=>pm((t)=>{if(t.interruptible)return e;if(t.interruptible=!0,t._stack.push(lw(!1)),t._interrupted)return fm;return e}),$P=(e)=>pm((t)=>{if(!t.interruptible)return e(te);return t.interruptible=!1,t._stack.push(lw(!0)),e(HP)});var uw=(e,t)=>{let r=new rw(ou.context(t?.scheduler??new mm));if(r.evaluate(e),t?.signal)if(t.signal.aborted)r.unsafeInterrupt();else{let n=()=>r.unsafeInterrupt();t.signal.addEventListener("abort",n,{once:!0}),r.addObserver(()=>t.signal.removeEventListener("abort",n))}return r};class iu{scheduleDrain;running=!1;tasks=new hm;constructor(e){this.scheduleDrain=e}starveInternal=(e)=>{let t=this.tasks.buckets;this.tasks.buckets=[];for(let[r,n]of t)for(let o=0;o<n.length;o++)n[o]();if(this.tasks.buckets.length===0)this.running=!1;else this.starve(e)};starve(e=0){this.scheduleDrain(e,this.starveInternal)}scheduleTask(e,t){if(this.tasks.scheduleTask(e,t),!this.running)this.running=!0,this.starve()}static cached(e){let t=new iu(e),r=new WeakMap;return(n)=>{if(n===void 0)return t;let o=r.get(n);if(o===void 0)o=new iu(e),r.set(n,o);return o}}}class hm{buckets=[];scheduleTask(e,t){let r=this.buckets.length,n=void 0,o=0;for(;o<r;o++)if(this.buckets[o][0]<=t)n=this.buckets[o];else break;if(n&&n[0]===t)n[1].push(e);else if(o===r)this.buckets.push([t,[e]]);else this.buckets.splice(o,0,[t,[e]])}}class pw{maxNextTickBeforeTimer;getRunner=iu.cached((e,t)=>{if(e>=this.maxNextTickBeforeTimer)setTimeout(()=>t(0),0);else Promise.resolve(void 0).then(()=>t(e+1))});constructor(e){this.maxNextTickBeforeTimer=e}shouldYield(e){return e.currentOpCount>e.getFiberRef(Df)?e.getFiberRef(Fi):!1}scheduleTask(e,t,r){this.getRunner(r).scheduleTask(e,t)}}var dw=B(Symbol.for("effect/Scheduler/defaultScheduler"),()=>new pw(2048));class Sa{tasks=new hm;deferred=!1;scheduleTask(e,t,r){if(this.deferred)dw.scheduleTask(e,t,r);else this.tasks.scheduleTask(e,t)}shouldYield(e){return e.currentOpCount>e.getFiberRef(Df)?e.getFiberRef(Fi):!1}flush(){while(this.tasks.buckets.length>0){let e=this.tasks.buckets;this.tasks.buckets=[];for(let[t,r]of e)for(let n=0;n<r.length;n++)r[n]()}this.deferred=!0}}var su=B(Symbol.for("effect/FiberRef/currentScheduler"),()=>Je(dw));var au=B(Symbol.for("effect/FiberRef/currentRequestMap"),()=>Je(new Map));var gm=(e,t,r,n)=>{switch(e){case void 0:return t();case"unbounded":return r();case"inherit":return Do(xb,(o)=>o==="unbounded"?r():o>1?n(o):t());default:return e>1?n(e):t()}};var ym=(e)=>e.replace(/[\s="]/g,"_"),mw=(e)=>(t)=>`${ym(t.label)}=${e-t.startTime}ms`;var hw="effect/MetricLabel",xm=Symbol.for(hw);class gw{key;value;[xm]=xm;_hash;constructor(e,t){this.key=e,this.value=t,this._hash=ie(hw+this.key+this.value)}[P](){return this._hash}[R](e){return zP(e)&&this.key===e.key&&this.value===e.value}pipe(){return b(this,arguments)}}var yw=(e,t)=>new gw(e,t),zP=(e)=>v(e,xm);var Sm=nr((e)=>Hs(e.context,p_)?e._tag==="Span"?Sm(e.parent):A():M(e));var xw=jf;var bm="InterruptSignal",_m="Stateful",wm="Resume",Em="YieldNow",cu=(e)=>({_tag:"InterruptSignal",cause:e}),Bi=(e)=>({_tag:"Stateful",onFiber:e}),Bo=(e)=>({_tag:"Resume",effect:e}),Sw=()=>({_tag:"YieldNow"});var XP="effect/FiberScope",lu=Symbol.for(XP);class _w{[lu]=lu;fiberId=Vt;roots=new Set;add(e,t){this.roots.add(t),t.addObserver(()=>{this.roots.delete(t)})}}class ww{fiberId;parent;[lu]=lu;constructor(e,t){this.fiberId=e,this.parent=t}add(e,t){this.parent.tell(Bi((r)=>{r.addChild(t),t.addObserver(()=>{r.removeChild(t)})}))}}var Ew=(e)=>new ww(e.id(),e),ba=B(Symbol.for("effect/FiberScope/Global"),()=>new _w);var r0="effect/Fiber",Om=Symbol.for(r0),vm={_E:(e)=>e,_A:(e)=>e},n0={[Om]:vm,pipe(){return b(this,arguments)}},o0="effect/Fiber",vw=Symbol.for(o0);var uu=(e)=>wl(oa(e.await),e.inheritAll);var gj={...On,commit(){return uu(this)},...n0,id:()=>Vt,await:ca,children:ne([]),inheritAll:ca,poll:ne(A()),interruptAsFork:()=>ca};var Gn="effect/FiberCurrent";var s0="effect/Logger",Aw=Symbol.for(s0),Tw={_Message:(e)=>e,_Output:(e)=>e},pu=(e)=>({[Aw]:Tw,log:e,pipe(){return b(this,arguments)}});var Sj={[Aw]:Tw,log:gs,pipe(){return b(this,arguments)}};var a0=/^[^\s"=]*$/,c0=(e,t)=>({annotations:r,cause:n,date:o,fiberId:i,logLevel:s,message:a,spans:c})=>{let l=(y)=>y.match(a0)?y:e(y),u=(y,O)=>`${ym(y)}=${l(O)}`,d=(y,O)=>" "+u(y,O),f=u("timestamp",o.toISOString());f+=d("level",s.label),f+=d("fiber",Xc(i));let g=Zp(a);for(let y=0;y<g.length;y++)f+=d("message",jr(g[y],t));if(!Ed(n))f+=d("cause",ur(n,{renderErrorCause:!0}));for(let y of c)f+=" "+mw(o.getTime())(y);for(let[y,O]of r)f+=d(y,jr(O,t));return f},l0=(e)=>`"${e.replace(/\\([\s\S])|(")/g,"\\$1$2")}"`,Iw=pu(c0(l0));var Wo={bold:"1",red:"31",green:"32",yellow:"33",blue:"34",cyan:"36",white:"37",gray:"90",black:"30",bgBrightRed:"101"},bj={None:[],All:[],Trace:[Wo.gray],Debug:[Wo.blue],Info:[Wo.green],Warning:[Wo.yellow],Error:[Wo.red],Fatal:[Wo.bgBrightRed,Wo.black]};var Rw=typeof process==="object"&&process!==null&&typeof process.stdout==="object"&&process.stdout!==null,_j=Rw&&process.stdout.isTTY===!0,wj=Rw||"Deno"in globalThis;var kw="effect/MetricBoundaries",Am=Symbol.for(kw);class Cw{values;[Am]=Am;constructor(e){this.values=e,this._hash=h(ie(kw),V(Ft(this.values)))}_hash;[P](){return this._hash}[R](e){return p0(e)&&E(this.values,e.values)}pipe(){return b(this,arguments)}}var p0=(e)=>v(e,Am),d0=(e)=>{let t=h(e,Qp(Ne(Number.POSITIVE_INFINITY)),id);return new Cw(t)};var Pw=(e)=>h(Yp(e.count-1,(t)=>e.start*Math.pow(e.factor,t)),Fs,d0);var m0="effect/MetricKeyType",Nw=Symbol.for(m0),Fw="effect/MetricKeyType/Counter",Tm=Symbol.for(Fw),h0="effect/MetricKeyType/Frequency",g0=Symbol.for(h0),y0="effect/MetricKeyType/Gauge",x0=Symbol.for(y0),Mw="effect/MetricKeyType/Histogram",Im=Symbol.for(Mw),S0="effect/MetricKeyType/Summary",b0=Symbol.for(S0),Lw={_In:(e)=>e,_Out:(e)=>e};class Dw{incremental;bigint;[Nw]=Lw;[Tm]=Tm;constructor(e,t){this.incremental=e,this.bigint=t,this._hash=ie(Fw)}_hash;[P](){return this._hash}[R](e){return Rm(e)}pipe(){return b(this,arguments)}}class qw{boundaries;[Nw]=Lw;[Im]=Im;constructor(e){this.boundaries=e,this._hash=h(ie(Mw),V(w(this.boundaries)))}_hash;[P](){return this._hash}[R](e){return km(e)&&E(this.boundaries,e.boundaries)}pipe(){return b(this,arguments)}}var Uw=(e)=>new Dw(e?.incremental??!1,e?.bigint??!1);var jw=(e)=>new qw(e);var Rm=(e)=>v(e,Tm),Hw=(e)=>v(e,g0),$w=(e)=>v(e,x0),km=(e)=>v(e,Im),Bw=(e)=>v(e,b0);var _0="effect/MetricKey",Kw=Symbol.for(_0),w0={_Type:(e)=>e},E0=Tn(E);class du{name;keyType;description;tags;[Kw]=w0;constructor(e,t,r,n=[]){this.name=e,this.keyType=t,this.description=r,this.tags=n,this._hash=h(ie(this.name+this.description),V(w(this.keyType)),V(Ft(this.tags)))}_hash;[P](){return this._hash}[R](e){return O0(e)&&this.name===e.name&&E(this.keyType,e.keyType)&&E(this.description,e.description)&&E0(this.tags,e.tags)}pipe(){return b(this,arguments)}}var O0=(e)=>v(e,Kw),Vw=(e,t)=>new du(e,Uw(t),$r(t?.description));var zw=(e,t,r)=>new du(e,jw(t),$r(r));var Gw=p(2,(e,t)=>t.length===0?e:new du(e.name,e.keyType,e.description,An(e.tags,t)));var Jw=Symbol.for("effect/MutableHashMap"),A0={[Jw]:Jw,[Symbol.iterator](){return new Cm(this)},toString(){return se(this.toJSON())},toJSON(){return{_id:"MutableHashMap",values:Array.from(this).map(re)}},[Y](){return this.toJSON()},pipe(){return b(this,arguments)}};class Cm{self;referentialIterator;bucketIterator;constructor(e){this.self=e,this.referentialIterator=e.referential[Symbol.iterator]()}next(){if(this.bucketIterator!==void 0)return this.bucketIterator.next();let e=this.referentialIterator.next();if(e.done)return this.bucketIterator=new Yw(this.self.buckets.values()),this.next();return e}[Symbol.iterator](){return new Cm(this.self)}}class Yw{backing;constructor(e){this.backing=e}currentBucket;next(){if(this.currentBucket===void 0){let t=this.backing.next();if(t.done)return t;this.currentBucket=t.value[Symbol.iterator]()}let e=this.currentBucket.next();if(e.done)return this.currentBucket=void 0,this.next();return e}}var Zw=()=>{let e=Object.create(A0);return e.referential=new Map,e.buckets=new Map,e.bucketsSize=0,e};var Jn=p(2,(e,t)=>{if(Es(t)===!1)return e.referential.has(t)?M(e.referential.get(t)):A();let r=t[P](),n=e.buckets.get(r);if(n===void 0)return A();return T0(e,n,t)});var T0=(e,t,r,n=!1)=>{for(let o=0,i=t.length;o<i;o++)if(r[R](t[o][0])){let s=t[o][1];if(n)t.splice(o,1),e.bucketsSize--;return M(s)}return A()},Wi=p(2,(e,t)=>de(Jn(e,t))),Ki=p(3,(e,t,r)=>{if(Es(t)===!1)return e.referential.set(t,r),e;let n=t[P](),o=e.buckets.get(n);if(o===void 0)return e.buckets.set(n,[[t,r]]),e.bucketsSize++,e;return I0(e,o,t),o.push([t,r]),e.bucketsSize++,e}),I0=(e,t,r)=>{for(let n=0,o=t.length;n<o;n++)if(r[R](t[n][0])){t.splice(n,1),e.bucketsSize--;return}};var k0="effect/MetricState",_a=Symbol.for(k0),Qw="effect/MetricState/Counter",Pm=Symbol.for(Qw),Xw="effect/MetricState/Frequency",Nm=Symbol.for(Xw),eE="effect/MetricState/Gauge",Fm=Symbol.for(eE),tE="effect/MetricState/Histogram",Mm=Symbol.for(tE),rE="effect/MetricState/Summary",Lm=Symbol.for(rE),wa={_A:(e)=>e};class nE{count;[_a]=wa;[Pm]=Pm;constructor(e){this.count=e}[P](){return h(w(Qw),V(w(this.count)),Z(this))}[R](e){return P0(e)&&this.count===e.count}pipe(){return b(this,arguments)}}var C0=Tn(E);class oE{occurrences;[_a]=wa;[Nm]=Nm;constructor(e){this.occurrences=e}_hash;[P](){return h(ie(Xw),V(Ft(fe(this.occurrences.entries()))),Z(this))}[R](e){return N0(e)&&C0(fe(this.occurrences.entries()),fe(e.occurrences.entries()))}pipe(){return b(this,arguments)}}class iE{value;[_a]=wa;[Fm]=Fm;constructor(e){this.value=e}[P](){return h(w(eE),V(w(this.value)),Z(this))}[R](e){return F0(e)&&this.value===e.value}pipe(){return b(this,arguments)}}class sE{buckets;count;min;max;sum;[_a]=wa;[Mm]=Mm;constructor(e,t,r,n,o){this.buckets=e,this.count=t,this.min=r,this.max=n,this.sum=o}[P](){return h(w(tE),V(w(this.buckets)),V(w(this.count)),V(w(this.min)),V(w(this.max)),V(w(this.sum)),Z(this))}[R](e){return M0(e)&&E(this.buckets,e.buckets)&&this.count===e.count&&this.min===e.min&&this.max===e.max&&this.sum===e.sum}pipe(){return b(this,arguments)}}class aE{error;quantiles;count;min;max;sum;[_a]=wa;[Lm]=Lm;constructor(e,t,r,n,o,i){this.error=e,this.quantiles=t,this.count=r,this.min=n,this.max=o,this.sum=i}[P](){return h(w(rE),V(w(this.error)),V(w(this.quantiles)),V(w(this.count)),V(w(this.min)),V(w(this.max)),V(w(this.sum)),Z(this))}[R](e){return L0(e)&&this.error===e.error&&E(this.quantiles,e.quantiles)&&this.count===e.count&&this.min===e.min&&this.max===e.max&&this.sum===e.sum}pipe(){return b(this,arguments)}}var cE=(e)=>new nE(e),lE=(e)=>new oE(e),uE=(e)=>new iE(e),pE=(e)=>new sE(e.buckets,e.count,e.min,e.max,e.sum),dE=(e)=>new aE(e.error,e.quantiles,e.count,e.min,e.max,e.sum);var P0=(e)=>v(e,Pm),N0=(e)=>v(e,Nm),F0=(e)=>v(e,Fm),M0=(e)=>v(e,Mm),L0=(e)=>v(e,Lm);var q0="effect/MetricHook",U0=Symbol.for(q0),j0={_In:(e)=>e,_Out:(e)=>e},Ea=(e)=>({[U0]:j0,pipe(){return b(this,arguments)},...e});var fE=BigInt(0),hE=(e)=>{let t=e.keyType.bigint?fE:0,r=e.keyType.incremental?e.keyType.bigint?(o)=>o>=fE:(o)=>o>=0:(o)=>!0,n=(o)=>{if(r(o))t=t+o};return Ea({get:()=>cE(t),update:n,modify:n})},gE=(e)=>{let t=new Map;for(let n of e.keyType.preregisteredWords)t.set(n,0);let r=(n)=>{let o=t.get(n)??0;t.set(n,o+1)};return Ea({get:()=>lE(t),update:r,modify:r})},yE=(e,t)=>{let r=t;return Ea({get:()=>uE(r),update:(n)=>{r=n},modify:(n)=>{r=r+n}})},xE=(e)=>{let t=e.keyType.boundaries.values,r=t.length,n=new Uint32Array(r+1),o=new Float64Array(r),i=0,s=0,{MAX_VALUE:a,MIN_VALUE:c}=Number;h(t,Wr(Rr),ir((d,f)=>{o[f]=d}));let l=(d)=>{let f=0,g=r;while(f!==g){let y=Math.floor(f+(g-f)/2),O=o[y];if(d<=O)g=y;else f=y;if(g===f+1)if(d<=o[f])g=f;else f=g}if(n[f]=n[f]+1,i=i+1,s=s+d,d<a)a=d;if(d>c)c=d},u=()=>{let d=bo(r),f=0;for(let g=0;g<r;g++){let y=o[g],O=n[g];f=f+O,d[g]=[y,f]}return d};return Ea({get:()=>pE({buckets:u(),count:i,min:a,max:c,sum:s}),update:l,modify:l})},SE=(e)=>{let{error:t,maxAge:r,maxSize:n,quantiles:o}=e.keyType,i=h(o,Wr(Rr)),s=bo(n),a=0,c=0,l=0,u=0,d=0,f=(y)=>{let O=[],m=0;while(m!==n-1){let x=s[m];if(x!=null){let[D,k]=x,H=zc(y-D);if(eS(H,qd)&&Xx(H,r))O.push(k)}m=m+1}return H0(t,i,Wr(O,Rr))},g=(y,O)=>{if(n>0){a=a+1;let m=a%n;s[m]=[O,y]}u=c===0?y:Math.min(u,y),d=c===0?y:Math.max(d,y),c=c+1,l=l+y};return Ea({get:()=>dE({error:t,quantiles:f(Date.now()),count:c,min:u,max:d,sum:l}),update:([y,O])=>g(y,O),modify:([y,O])=>g(y,O)})},H0=(e,t,r)=>{let n=r.length;if(!le(t))return Kr();let o=t[0],i=t.slice(1),s=mE(e,n,A(),0,o,r),a=tt(s);return i.forEach((c)=>{a.push(mE(e,n,s.value,s.consumed,c,s.rest))}),ir(a,(c)=>[c.quantile,c.value])},mE=(e,t,r,n,o,i)=>{let s=e,a=t,c=r,l=n,u=o,d=i,f=e,g=t,y=r,O=n,m=o,x=i;while(!0){if(!le(d))return{quantile:u,value:A(),consumed:l,rest:[]};if(u===1)return{quantile:u,value:M(td(d)),consumed:l+d.length,rest:[]};let D=Pe(d),k=jy(d,(L)=>L===D),H=u*a,T=s/2*H,I=l+k[0].length,C=Math.abs(I-H);if(I<H-T){f=s,g=a,y=Br(d),O=I,m=u,x=k[1],s=f,a=g,c=y,l=O,u=m,d=x;continue}if(I>H+T){let L=be(c)?M(D):c;return{quantile:u,value:L,consumed:l,rest:d}}switch(c._tag){case"None":{f=s,g=a,y=Br(d),O=I,m=u,x=k[1],s=f,a=g,c=y,l=O,u=m,d=x;continue}case"Some":{let L=Math.abs(H-c.value);if(C<L){f=s,g=a,y=Br(d),O=I,m=u,x=k[1],s=f,a=g,c=y,l=O,u=m,d=x;continue}return{quantile:u,value:M(c.value),consumed:l,rest:d}}}}throw Error("BUG: MetricHook.resolveQuantiles - please report an issue at https://github.com/Effect-TS/effect/issues")};var B0="effect/MetricPair",W0=Symbol.for(B0),K0={_Type:(e)=>e};var bE=(e,t)=>({[W0]:K0,metricKey:e,metricState:t,pipe(){return b(this,arguments)}});var z0="effect/MetricRegistry",_E=Symbol.for(z0);class wE{[_E]=_E;map=Zw();snapshot(){let e=[];for(let[t,r]of this.map)e.push(bE(t,r.get()));return e}get(e){let t=h(this.map,Jn(e),vt);if(t==null){if(Rm(e.keyType))return this.getCounter(e);if($w(e.keyType))return this.getGauge(e);if(Hw(e.keyType))return this.getFrequency(e);if(km(e.keyType))return this.getHistogram(e);if(Bw(e.keyType))return this.getSummary(e);throw Error("BUG: MetricRegistry.get - unknown MetricKeyType - please report an issue at https://github.com/Effect-TS/effect/issues")}else return t}getCounter(e){let t=h(this.map,Jn(e),vt);if(t==null){let r=hE(e);if(!h(this.map,Wi(e)))h(this.map,Ki(e,r));t=r}return t}getFrequency(e){let t=h(this.map,Jn(e),vt);if(t==null){let r=gE(e);if(!h(this.map,Wi(e)))h(this.map,Ki(e,r));t=r}return t}getGauge(e){let t=h(this.map,Jn(e),vt);if(t==null){let r=yE(e,e.keyType.bigint?BigInt(0):0);if(!h(this.map,Wi(e)))h(this.map,Ki(e,r));t=r}return t}getHistogram(e){let t=h(this.map,Jn(e),vt);if(t==null){let r=xE(e);if(!h(this.map,Wi(e)))h(this.map,Ki(e,r));t=r}return t}getSummary(e){let t=h(this.map,Jn(e),vt);if(t==null){let r=SE(e);if(!h(this.map,Wi(e)))h(this.map,Ki(e,r));t=r}return t}}var EE=()=>new wE;var J0="effect/Metric",Y0=Symbol.for(J0),Z0={_Type:(e)=>e,_In:(e)=>e,_Out:(e)=>e},OE=B(Symbol.for("effect/Metric/globalMetricRegistry"),()=>EE()),vE=function(e,t,r,n){let o=Object.assign((i)=>Sl(i,(s)=>X0(o,s)),{[Y0]:Z0,keyType:e,unsafeUpdate:t,unsafeValue:r,unsafeModify:n,register(){return this.unsafeValue([]),this},pipe(){return b(this,arguments)}});return o};var Oa=(e,t)=>AE(Vw(e,t));var AE=(e)=>{let t,r=new WeakMap,n=(o)=>{if(o.length===0){if(t!==void 0)return t;return t=OE.get(e),t}let i=r.get(o);if(i!==void 0)return i;return i=OE.get(Gw(e,o)),r.set(o,i),i};return vE(e.keyType,(o,i)=>n(i).update(o),(o)=>n(o).get(),(o,i)=>n(i).modify(o))};var TE=(e,t,r)=>AE(zw(e,t,r));var IE=p(3,(e,t,r)=>Q0(e,[yw(t,r)]));var Q0=p(2,(e,t)=>vE(e.keyType,(r,n)=>e.unsafeUpdate(r,An(t,n)),(r)=>e.unsafeValue(An(t,r)),(r,n)=>e.unsafeModify(r,An(t,n))));var X0=p(2,(e,t)=>Do(ua,(r)=>q(()=>e.unsafeUpdate(t,r))));var tN="effect/Request",rN=Symbol.for(tN),nN={_E:(e)=>e,_A:(e)=>e},Xj={...Rs,[rN]:nN};var RE=p(2,(e,t)=>Do(au,(r)=>q(()=>{if(r.has(e)){let n=r.get(e);if(!n.state.completed)n.state.completed=!0,Cl(n.result,t)}})));var oN="effect/Supervisor",fu=Symbol.for(oN),Dm={_T:(e)=>e};class mu{underlying;value0;[fu]=Dm;constructor(e,t){this.underlying=e,this.value0=t}get value(){return this.value0}onStart(e,t,r,n){this.underlying.onStart(e,t,r,n)}onEnd(e,t){this.underlying.onEnd(e,t)}onEffect(e,t){this.underlying.onEffect(e,t)}onSuspend(e){this.underlying.onSuspend(e)}onResume(e){this.underlying.onResume(e)}map(e){return new mu(this,h(this.value,ve(e)))}zip(e){return new hu(this,e)}}class hu{left;right;_tag="Zip";[fu]=Dm;constructor(e,t){this.left=e,this.right=t}get value(){return _l(this.left.value,this.right.value)}onStart(e,t,r,n){this.left.onStart(e,t,r,n),this.right.onStart(e,t,r,n)}onEnd(e,t){this.left.onEnd(e,t),this.right.onEnd(e,t)}onEffect(e,t){this.left.onEffect(e,t),this.right.onEffect(e,t)}onSuspend(e){this.left.onSuspend(e),this.right.onSuspend(e)}onResume(e){this.left.onResume(e),this.right.onResume(e)}map(e){return new mu(this,h(this.value,ve(e)))}zip(e){return new hu(this,e)}}var qm=(e)=>v(e,fu)&&_s(e,"Zip");class kE{effect;[fu]=Dm;constructor(e){this.effect=e}get value(){return this.effect}onStart(e,t,r,n){}onEnd(e,t){}onEffect(e,t){}onSuspend(e){}onResume(e){}map(e){return new mu(this,h(this.value,ve(e)))}zip(e){return new hu(this,e)}onRun(e,t){return e()}}var iN=(e)=>new kE(e),Ko=B("effect/Supervisor/none",()=>iN(Fe));var CE=qn;var PE="Empty",NE="AddSupervisor",FE="RemoveSupervisor",ME="AndThen",Vi={_tag:PE},gu=(e,t)=>({_tag:ME,first:e,second:t}),aN=(e,t)=>cN(t,Ne(e)),cN=(e,t)=>{let r=e,n=t;while(sr(n)){let o=ar(n);switch(o._tag){case PE:{n=cr(n);break}case NE:{r=r.zip(o.supervisor),n=cr(n);break}case FE:{r=jm(r,o.supervisor),n=cr(n);break}case ME:{n=rt(o.first)(rt(o.second)(cr(n)));break}}}return r},jm=(e,t)=>{if(E(e,t))return Ko;else if(qm(e))return jm(e.left,t).zip(jm(e.right,t));else return e},yu=(e)=>{if(E(e,Ko))return Or();else if(qm(e))return h(yu(e.left),Yr(yu(e.right)));else return Oo(e)},lN=(e,t)=>{if(E(e,t))return Vi;let r=yu(e),n=yu(t),o=h(n,Sd(r),Ao(Vi,(s,a)=>gu(s,{_tag:NE,supervisor:a}))),i=h(r,Sd(n),Ao(Vi,(s,a)=>gu(s,{_tag:FE,supervisor:a})));return gu(o,i)},LE=CE({empty:Vi,patch:aN,combine:gu,diff:lN});var SN=Oa("effect_fiber_started",{incremental:!0}),DE=Oa("effect_fiber_active"),bN=Oa("effect_fiber_successes",{incremental:!0}),_N=Oa("effect_fiber_failures",{incremental:!0}),wN=IE(TE("effect_fiber_lifetimes",Pw({start:0.5,factor:2,count:35})),"time_unit","milliseconds"),va="Continue",EN="Done",qE="Yield",ON={_E:(e)=>e,_A:(e)=>e},xu=(e)=>{throw Error(`BUG: FiberRuntime - ${jr(e)} - please report an issue at https://github.com/Effect-TS/effect/issues`)},sn=Symbol.for("effect/internal/fiberRuntime/YieldedOp"),an=B("effect/internal/fiberRuntime/yieldedOpChannel",()=>({currentOp:null})),Aa={[ai]:(e,t,r)=>ze(()=>t.effect_instruction_i1(r)),["OnStep"]:(e,t,r)=>xe(xe(r)),[ci]:(e,t,r)=>ze(()=>t.effect_instruction_i2(r)),[Ts]:(e,t,r)=>{if(e.patchRuntimeFlags(e.currentRuntimeFlags,t.patch),tn(e.currentRuntimeFlags)&&e.isInterrupted())return ue(e.getInterruptedCause());else return xe(r)},[li]:(e,t,r)=>{if(ze(()=>t.effect_instruction_i2(r)),ze(()=>t.effect_instruction_i0()))return e.pushStack(t),ze(()=>t.effect_instruction_i1());else return Fe},[ui]:(e,t,r)=>{while(!0){let n=ze(()=>t.effect_instruction_i0.next(r));if(n.done)return xe(n.value);let o=Np(n.value);if(!Li(o))return e.pushStack(t),o;else if(o._tag==="Failure")return o;r=o.value}}},vN={[bm]:(e,t,r,n)=>(e.processNewInterruptSignal(n.cause),tn(t)?ue(n.cause):r),[wm]:(e,t,r,n)=>{throw Error("It is illegal to have multiple concurrent run loops in a single fiber")},[_m]:(e,t,r,n)=>(n.onFiber(e,im(t)),r),[Em]:(e,t,r,n)=>W(aa(),()=>r)},AN=(e)=>Mo(HS(e),(t)=>Vo(BS(t),([r,n])=>{let o=new Map,i=[];for(let a of n){i.push(zr(a));for(let c of a)o.set(c.request,c)}let s=i.flat();return Wn(HN(r.runAll(i),s,()=>s.forEach((a)=>{a.listeners.interrupted=!0})),au,o)},!1,!1)),TN=Is();class Su extends Jf{[Om]=vm;[vw]=ON;_fiberRefs;_fiberId;_queue=[];_children=null;_observers=[];_running=!1;_stack=[];_asyncInterruptor=null;_asyncBlockingOn=null;_exitValue=null;_steps=[];_isYielding=!1;currentRuntimeFlags;currentOpCount=0;currentSupervisor;currentScheduler;currentTracer;currentSpan;currentContext;currentDefaultServices;constructor(e,t,r){super();if(this.currentRuntimeFlags=r,this._fiberId=e,this._fiberRefs=t,ff(r)){let n=this.getFiberRef(ua);SN.unsafeUpdate(1,n),DE.unsafeUpdate(1,n)}this.refreshRefCache()}commit(){return uu(this)}id(){return this._fiberId}resume(e){this.tell(Bo(e))}get status(){return this.ask((e,t)=>t)}get runtimeFlags(){return this.ask((e,t)=>{if(G_(t))return e.currentRuntimeFlags;return t.runtimeFlags})}scope(){return Ew(this)}get children(){return this.ask((e)=>Array.from(e.getChildren()))}getChildren(){if(this._children===null)this._children=new Set;return this._children}getInterruptedCause(){return this.getFiberRef(pa)}fiberRefs(){return this.ask((e)=>e.getFiberRefs())}ask(e){return me(()=>{let t=Ob(this._fiberId);return this.tell(Bi((r,n)=>{Cl(t,q(()=>e(r,n)))})),kl(t)})}tell(e){if(this._queue.push(e),!this._running)this._running=!0,this.drainQueueLaterOnExecutor()}get await(){return jn((e)=>{let t=(r)=>e(ne(r));if(this._exitValue!==null){t(this._exitValue);return}return this.tell(Bi((r,n)=>{if(r._exitValue!==null)t(this._exitValue);else r.addObserver(t)})),q(()=>this.tell(Bi((r,n)=>{r.removeObserver(t)})))},this.id())}get inheritAll(){return Ge((e,t)=>{let r=e.id(),n=e.getFiberRefs(),o=t.runtimeFlags,i=this.getFiberRefs(),s=tm(n,r,i);e.setFiberRefs(s);let a=e.getFiberRef(jE),c=h(Xs(o,a),yf(en),yf(al));return Nf(c)})}get poll(){return q(()=>$r(this._exitValue))}unsafePoll(){return this._exitValue}interruptAsFork(e){return q(()=>this.tell(cu(lr(e))))}unsafeInterruptAsFork(e){this.tell(cu(lr(e)))}addObserver(e){if(this._exitValue!==null)e(this._exitValue);else this._observers.push(e)}removeObserver(e){this._observers=this._observers.filter((t)=>t!==e)}getFiberRefs(){return this.setFiberRef(jE,this.currentRuntimeFlags),this._fiberRefs}unsafeDeleteFiberRef(e){this._fiberRefs=xa(this._fiberRefs,e)}getFiberRef(e){if(this._fiberRefs.locals.has(e))return this._fiberRefs.locals.get(e)[0][1];return e.initial}setFiberRef(e,t){this._fiberRefs=ji(this._fiberRefs,{fiberId:this._fiberId,fiberRef:e,value:t}),this.refreshRefCache()}refreshRefCache(){this.currentDefaultServices=this.getFiberRef(ya),this.currentTracer=this.currentDefaultServices.unsafeMap.get(ga.key),this.currentSupervisor=this.getFiberRef(jN),this.currentScheduler=this.getFiberRef(su),this.currentContext=this.getFiberRef(Uo),this.currentSpan=this.currentContext.unsafeMap.get(Kl.key)}setFiberRefs(e){this._fiberRefs=e,this.refreshRefCache()}addChild(e){this.getChildren().add(e)}removeChild(e){this.getChildren().delete(e)}transferChildren(e){let t=this._children;if(this._children=null,t!==null&&t.size>0){for(let r of t)if(r._exitValue===null)e.add(this.currentRuntimeFlags,r)}}drainQueueOnCurrentThread(){let e=!0;while(e){let t=va,r=globalThis[Gn];globalThis[Gn]=this;try{while(t===va)t=this._queue.length===0?EN:this.evaluateMessageWhileSuspended(this._queue.splice(0,1)[0])}finally{this._running=!1,globalThis[Gn]=r}if(this._queue.length>0&&!this._running)if(this._running=!0,t===qE)this.drainQueueLaterOnExecutor(),e=!1;else e=!0;else e=!1}}drainQueueLaterOnExecutor(){this.currentScheduler.scheduleTask(this.run,this.getFiberRef(Fi),this)}drainQueueWhileRunning(e,t){let r=t;while(this._queue.length>0){let n=this._queue.splice(0,1)[0];r=vN[n._tag](this,e,r,n)}return r}isInterrupted(){return!Hc(this.getFiberRef(pa))}addInterruptedCause(e){let t=this.getFiberRef(pa);this.setFiberRef(pa,nt(t,e))}processNewInterruptSignal(e){this.addInterruptedCause(e),this.sendInterruptSignalToAllChildren()}sendInterruptSignalToAllChildren(){if(this._children===null||this._children.size===0)return!1;let e=!1;for(let t of this._children)t.tell(cu(lr(this.id()))),e=!0;return e}interruptAllChildren(){if(this.sendInterruptSignalToAllChildren()){let e=this._children.values();this._children=null;let t=!1;return sa({while:()=>!t,body:()=>{let n=e.next();if(!n.done)return nn(n.value.await);else return q(()=>{t=!0})},step:()=>{}})}return null}reportExitValue(e){if(ff(this.currentRuntimeFlags)){let t=this.getFiberRef(ua),r=this.id().startTimeMillis,n=Date.now();switch(wN.unsafeUpdate(n-r,t),DE.unsafeUpdate(-1,t),e._tag){case Ot:{bN.unsafeUpdate(1,t);break}case Et:{_N.unsafeUpdate(1,t);break}}}if(e._tag==="Failure"){let t=this.getFiberRef(bb);if(!Oi(e.cause)&&t._tag==="Some")this.log("Fiber terminated with an unhandled error",e.cause,t)}}setExitValue(e){this._exitValue=e,this.reportExitValue(e);for(let t=this._observers.length-1;t>=0;t--)this._observers[t](e);this._observers=[]}getLoggers(){return this.getFiberRef(PN)}log(e,t,r){let n=de(r)?r.value:this.getFiberRef(qf),o=this.getFiberRef(IN);if(J_(o,n))return;let i=this.getFiberRef(gb),s=this.getFiberRef(hb),a=this.getLoggers(),c=this.getFiberRefs();if(Ds(a)>0){let l=Hs(this.getFiberRef(ya),ha),u=new Date(l.unsafeCurrentTimeMillis());cy(c,()=>{for(let d of a)d.log({fiberId:this.id(),logLevel:n,message:e,cause:t,context:c,spans:i,annotations:s,date:u})})}}evaluateMessageWhileSuspended(e){switch(e._tag){case Em:return qE;case bm:{if(this.processNewInterruptSignal(e.cause),this._asyncInterruptor!==null)this._asyncInterruptor(ue(e.cause)),this._asyncInterruptor=null;return va}case wm:return this._asyncInterruptor=null,this._asyncBlockingOn=null,this.evaluateEffect(e.effect),va;case _m:return e.onFiber(this,this._exitValue!==null?V_:z_(this.currentRuntimeFlags,this._asyncBlockingOn)),va;default:return xu(e)}}evaluateEffect(e){this.currentSupervisor.onResume(this);try{let t=tn(this.currentRuntimeFlags)&&this.isInterrupted()?ue(this.getInterruptedCause()):e;while(t!==null){let r=t,n=this.runLoop(r);if(n===sn){let o=an.currentOp;if(an.currentOp=null,o._op===pi)if(DS(this.currentRuntimeFlags))this.tell(Sw()),this.tell(Bo(Jt)),t=null;else t=Jt;else if(o._op===yo)t=null}else{this.currentRuntimeFlags=h(this.currentRuntimeFlags,uf(al));let o=this.interruptAllChildren();if(o!==null)t=W(o,()=>n);else{if(this._queue.length===0)this.setExitValue(n);else this.tell(Bo(n));t=null}}}}finally{this.currentSupervisor.onSuspend(this)}}start(e){if(!this._running){this._running=!0;let t=globalThis[Gn];globalThis[Gn]=this;try{this.evaluateEffect(e)}finally{if(this._running=!1,globalThis[Gn]=t,this._queue.length>0)this.drainQueueLaterOnExecutor()}}else this.tell(Bo(e))}startFork(e){this.tell(Bo(e))}patchRuntimeFlags(e,t){let r=ea(e,t);return globalThis[Gn]=this,this.currentRuntimeFlags=r,r}initiateAsync(e,t){let r=!1,n=(o)=>{if(!r)r=!0,this.tell(Bo(o))};if(tn(e))this._asyncInterruptor=n;try{t(n)}catch(o){n(ot(Lt(o)))}}pushStack(e){if(this._stack.push(e),e._op==="OnStep")this._steps.push({refs:this.getFiberRefs(),flags:this.currentRuntimeFlags})}popStack(){let e=this._stack.pop();if(e){if(e._op==="OnStep")this._steps.pop();return e}return}getNextSuccessCont(){let e=this.popStack();while(e){if(e._op!==As)return e;e=this.popStack()}}getNextFailCont(){let e=this.popStack();while(e){if(e._op!==ai&&e._op!==li&&e._op!==ui)return e;e=this.popStack()}}[uy](e){return q(()=>$s(this.currentContext,e))}["Left"](e){return Be(e.left)}["None"](e){return Be(new da)}["Right"](e){return xe(e.right)}["Some"](e){return xe(e.value)}["Micro"](e){return ta((t)=>{let r=t,n=uw(aw(e,this.currentContext));return n.addObserver((o)=>{if(o._tag==="Success")return r(xe(o.value));switch(o.cause._tag){case"Interrupt":return r(ue(lr(Vt)));case"Fail":return r(Be(o.cause.error));case"Die":return r(gl(o.cause.defect))}}),ta((o)=>{r=(i)=>{o(Fe)},n.unsafeInterrupt()})})}[xc](e){let t=ze(()=>e.effect_instruction_i0()),r=this.getNextSuccessCont();if(r!==void 0){if(!(r._op in Aa))xu(r);return Aa[r._op](this,r,t)}else return an.currentOp=xe(t),sn}[Ot](e){let t=e,r=this.getNextSuccessCont();if(r!==void 0){if(!(r._op in Aa))xu(r);return Aa[r._op](this,r,t.effect_instruction_i0)}else return an.currentOp=t,sn}[Et](e){let t=e.effect_instruction_i0,r=this.getNextFailCont();if(r!==void 0)switch(r._op){case As:case ci:if(!(tn(this.currentRuntimeFlags)&&this.isInterrupted()))return ze(()=>r.effect_instruction_i1(t));else return ue(Wc(t));case"OnStep":if(!(tn(this.currentRuntimeFlags)&&this.isInterrupted()))return xe(ue(t));else return ue(Wc(t));case Ts:if(this.patchRuntimeFlags(this.currentRuntimeFlags,r.patch),tn(this.currentRuntimeFlags)&&this.isInterrupted())return ue(nt(t,this.getInterruptedCause()));else return ue(t);default:xu(r)}else return an.currentOp=ue(t),sn}[Sc](e){return ze(()=>e.effect_instruction_i0(this,im(this.currentRuntimeFlags)))}["Blocked"](e){let t=this.getFiberRefs(),r=this.currentRuntimeFlags;if(this._steps.length>0){let n=[],o=this._steps[this._steps.length-1],i=this.popStack();while(i&&i._op!=="OnStep")n.push(i),i=this.popStack();this.setFiberRefs(o.refs),this.currentRuntimeFlags=o.flags;let s=M_(o.refs,t),a=Xs(o.flags,r);return xe(ml(e.effect_instruction_i0,Ge((c)=>{while(n.length>0)c.pushStack(n.pop());return c.setFiberRefs(L_(c.id(),c.getFiberRefs())(s)),c.currentRuntimeFlags=ea(a)(c.currentRuntimeFlags),e.effect_instruction_i1})))}return $n((n)=>W(Wm(Ef(e.effect_instruction_i0)),()=>n(e.effect_instruction_i1)))}["RunBlocked"](e){return AN(e.effect_instruction_i0)}[So](e){let t=e.effect_instruction_i0,r=this.currentRuntimeFlags,n=ea(r,t);if(tn(n)&&this.isInterrupted())return ue(this.getInterruptedCause());else if(this.patchRuntimeFlags(this.currentRuntimeFlags,t),e.effect_instruction_i1){let o=Xs(n,r);return this.pushStack(new Of(o,e)),ze(()=>e.effect_instruction_i1(r))}else return Jt}[ai](e){return this.pushStack(e),e.effect_instruction_i0}["OnStep"](e){return this.pushStack(e),e.effect_instruction_i0}[As](e){return this.pushStack(e),e.effect_instruction_i0}[ci](e){return this.pushStack(e),e.effect_instruction_i0}[yo](e){return this._asyncBlockingOn=e.effect_instruction_i1,this.initiateAsync(this.currentRuntimeFlags,e.effect_instruction_i0),an.currentOp=e,sn}[pi](e){return this._isYielding=!1,an.currentOp=e,sn}[li](e){let{effect_instruction_i0:t,effect_instruction_i1:r}=e;if(t())return this.pushStack(e),r();else return Jt}[ui](e){return Aa[ui](this,e,void 0)}[xo](e){return ze(()=>e.commit())}runLoop(e){let t=e;this.currentOpCount=0;while(!0){if((this.currentRuntimeFlags&LS)!==0)this.currentSupervisor.onEffect(this,t);if(this._queue.length>0)t=this.drainQueueWhileRunning(this.currentRuntimeFlags,t);if(!this._isYielding){this.currentOpCount+=1;let r=this.currentScheduler.shouldYield(this);if(r!==!1){this._isYielding=!0,this.currentOpCount=0;let n=t;t=W(aa({priority:r}),()=>n)}}try{if(t=this.currentTracer.context(()=>{if(TN!==t[Un]._V){let r=this.getFiberRef(_b);if(r._tag==="Some"){let n=t[Un]._V;this.log(`Executing an Effect versioned ${n} with a Runtime of version ${Is()}, you may want to dedupe the effect dependencies, you can use the language service plugin to detect this at compile time: https://github.com/Effect-TS/language-service`,Zr,r)}}return this[t._op](t)},this),t===sn){let r=an.currentOp;if(r._op===pi||r._op===yo)return sn;return an.currentOp=null,r._op===Ot||r._op===Et?r:ue(Lt(r))}}catch(r){if(t!==sn&&!v(t,"_op")||!(t._op in this))t=If(`Not a valid effect: ${jr(t)}`);else if(wb(r))t=ue(nt(Lt(r),lr(Vt)));else t=gl(r)}}}run=()=>{this.drainQueueOnCurrentThread()}}var IN=B("effect/FiberRef/currentMinimumLogLevel",()=>Je(Y_("Info"))),RN=(e)=>pu((t)=>{let r=E_(t.context,ya);Hs(r,Wl).unsafe.log(e.log(t))});var kN=B(Symbol.for("effect/Logger/defaultLogger"),()=>RN(Iw));var CN=B(Symbol.for("effect/Logger/tracerLogger"),()=>pu(({annotations:e,cause:t,context:r,fiberId:n,logLevel:o,message:i})=>{let s=Sm(Ln(Vn(r,Uo),Kl));if(s._tag==="None"||s.value._tag==="ExternalSpan")return;let a=$s(Vn(r,ya),ha),c={};for(let[l,u]of e)c[l]=u;if(c["effect.fiberId"]=uS(n),c["effect.logLevel"]=o.label,t!==null&&t._tag!=="Empty")c["effect.cause"]=ur(t,{renderErrorCause:!0});s.value.event(jr(Array.isArray(i)&&i.length===1?i[0]:i),a.unsafeCurrentTimeNanos(),c)}));var PN=B(Symbol.for("effect/FiberRef/currentLoggers"),()=>fb(Oo(kN,CN)));var HE=p((e)=>Rp(e[0]),(e,t,r)=>Ge((n)=>{let o=r?.batching===!0||r?.batching==="inherit"&&n.getFiberRef(Sb);if(r?.discard)return gm(r.concurrency,()=>zi(Vl,r?.concurrentFinalizers)((i)=>o?Vo(e,(s,a)=>i(t(s,a)),!0,!1,1):Mo(e,(s,a)=>i(t(s,a)))),()=>zi(zl,r?.concurrentFinalizers)((i)=>Vo(e,(s,a)=>i(t(s,a)),o,!1)),(i)=>zi(Gl(i),r?.concurrentFinalizers)((s)=>Vo(e,(a,c)=>s(t(a,c)),o,!1,i)));return gm(r?.concurrency,()=>zi(Vl,r?.concurrentFinalizers)((i)=>o?Hm(e,1,(s,a)=>i(t(s,a)),!0):Gt(e,(s,a)=>i(t(s,a)))),()=>zi(zl,r?.concurrentFinalizers)((i)=>$E(e,(s,a)=>i(t(s,a)),o)),(i)=>zi(Gl(i),r?.concurrentFinalizers)((s)=>Hm(e,i,(a,c)=>s(t(a,c)),o)))})),$E=(e,t,r)=>me(()=>{let n=fe(e),o=Array(n.length);return Bn(Vo(n,(s,a)=>W(t(s,a),(c)=>q(()=>o[a]=c)),r,!1),ne(o))}),Vo=(e,t,r,n,o)=>$n((i)=>Pf((s)=>Ge((a)=>{let c=Array.from(e).reverse(),l=c.length;if(l===0)return Fe;let u=0,d=!1,f=o?Math.min(c.length,o):c.length,g=new Set,y=[],O=()=>g.forEach((L)=>{L.currentScheduler.scheduleTask(()=>{L.unsafeInterruptAsFork(a.id())},0,L)}),m=[],x=[],D=[],k=()=>{let L=y.filter(({exit:ee})=>ee._tag==="Failure").sort((ee,X)=>ee.index<X.index?-1:ee.index===X.index?0:1).map(({exit:ee})=>ee);if(L.length===0)L.push(Jt);return L},H=(L,ee=!1)=>{let X=bl(s(L)),J=FN(X,a,a.currentRuntimeFlags,ba);return a.currentScheduler.scheduleTask(()=>{if(ee)J.unsafeInterruptAsFork(a.id());J.resume(X)},0,J),J},T=()=>{if(!n)l-=c.length,c=[];d=!0,O()},I=r?Cf:Hn,C=H(jn((L)=>{let ee=(J,he)=>{if(J._op==="Blocked")D.push(J);else if(y.push({index:he,exit:J}),J._op==="Failure"&&!d)T()},X=()=>{if(c.length>0){let J=c.pop(),he=u++,lt=()=>{let Re=c.pop();return he=u++,W(aa(),()=>W(I(i(t(Re,he))),Xe))},Xe=(Re)=>{if(c.length>0){if(ee(Re,he),c.length>0)return lt()}return ne(Re)},ut=W(I(i(t(J,he))),Xe),Me=H(ut);if(m.push(Me),g.add(Me),d)Me.currentScheduler.scheduleTask(()=>{Me.unsafeInterruptAsFork(a.id())},0,Me);Me.addObserver((Re)=>{let pt;if(Re._op==="Failure")pt=Re;else pt=Re.effect_instruction_i0;if(x.push(Me),g.delete(Me),ee(pt,he),y.length===l)L(ne(pe(Ho(k(),{parallel:!0}),()=>Jt)));else if(D.length+y.length===l){let Mr=k(),ss=D.map((io)=>io.effect_instruction_i0).reduce(Sf);L(ne(ml(ss,Vo([pe(Ho(Mr,{parallel:!0}),()=>Jt),...D.map((io)=>io.effect_instruction_i1)],(io)=>io,r,!0,o))))}else X()})}};for(let J=0;J<f;J++)X()}));return nn(Ni(oa(i(uu(C))),Rl({onFailure:(L)=>{T();let ee=D.length+1,X=Math.min(typeof o==="number"?o:D.length,D.length),J=Array.from(D);return jn((he)=>{let lt=[],Xe=0,ut=0,Me=(pt,Mr)=>(ss)=>{if(lt[pt]=ss,Xe++,Xe===ee)he(xe(ue(L)));if(J.length>0&&Mr)Re()},Re=()=>{H(J.pop(),!0).addObserver(Me(ut,!0)),ut++};C.addObserver(Me(ut,!1)),ut++;for(let pt=0;pt<X;pt++)Re()})},onSuccess:()=>Gt(x,(L)=>L.inheritAll)})))}))),Hm=(e,t,r,n)=>me(()=>{let o=fe(e),i=Array(o.length);return Bn(Vo(o,(a,c)=>ve(r(a,c),(l)=>i[c]=l),n,!1,t),ne(i))});var Wm=(e)=>MN(e,ba);var NN=(e,t,r,n=null)=>{let o=BE(e,t,r,n);return o.resume(e),o},FN=(e,t,r,n=null)=>BE(e,t,r,n),BE=(e,t,r,n=null)=>{let o=el(),i=t.getFiberRefs(),s=rm(i,o),a=new Su(o,s,r),c=Vn(s,Uo),l=a.currentSupervisor;return l.onStart(c,e,M(t),a),a.addObserver((d)=>l.onEnd(d,a)),(n!==null?n:h(t.getFiberRef(fl),pe(()=>t.scope()))).add(r,a),a},MN=(e,t)=>Ge((r,n)=>ne(NN(e,r,n.runtimeFlags,t)));var $m=(e)=>$o((t)=>Ae(Ln(t,Ta),{onNone:()=>e,onSome:(r)=>{switch(r.strategy._tag){case"Parallel":return e;case"Sequential":case"ParallelN":return W(Mi(r,zl),(n)=>Km(e,n))}}})),UE=(e)=>(t)=>$o((r)=>Ae(Ln(r,Ta),{onNone:()=>t,onSome:(n)=>{if(n.strategy._tag==="ParallelN"&&n.strategy.parallelism===e)return t;return W(Mi(n,Gl(e)),(o)=>Km(t,o))}}));var zi=(e,t)=>(r)=>$o((n)=>Ae(Ln(n,Ta),{onNone:()=>r(te),onSome:(o)=>{if(t===!0){let i=e._tag==="Parallel"?$m:e._tag==="Sequential"?Bm:UE(e.parallelism);switch(o.strategy._tag){case"Parallel":return i(r($m));case"Sequential":return i(r(Bm));case"ParallelN":return i(r(UE(o.strategy.parallelism)))}}else return r(te)}}));var Bm=(e)=>$o((t)=>Ae(Ln(t,Ta),{onNone:()=>e,onSome:(r)=>{switch(r.strategy._tag){case"Sequential":return e;case"Parallel":case"ParallelN":return W(Mi(r,Vl),(n)=>Km(e,n))}}}));var Ta=At("effect/Scope");var LN=(e,t)=>{if(e.state._tag==="Open")e.state.finalizers.set({},t)},DN={[vl]:vl,[Al]:Al,pipe(){return b(this,arguments)},fork(e){return q(()=>{let t=qN(e);if(this.state._tag==="Closed")return t.state=this.state,t;let r={},n=(o)=>t.close(o);return this.state.finalizers.set(r,n),LN(t,(o)=>q(()=>{if(this.state._tag==="Open")this.state.finalizers.delete(r)})),t})},close(e){return me(()=>{if(this.state._tag==="Closed")return Fe;let t=Array.from(this.state.finalizers.values()).reverse();if(this.state={_tag:"Closed",exit:e},t.length===0)return Fe;return Yf(this.strategy)?h(Gt(t,(r)=>Hn(r(e))),W((r)=>h(Ho(r),rr(fa),pe(()=>Jt)))):Zf(this.strategy)?h($E(t,(r)=>Hn(r(e)),!1),W((r)=>h(Ho(r,{parallel:!0}),rr(fa),pe(()=>Jt)))):h(Hm(t,this.strategy.parallelism,(r)=>Hn(r(e)),!1),W((r)=>h(Ho(r,{parallel:!0}),rr(fa),pe(()=>Jt))))})},addFinalizer(e){return me(()=>{if(this.state._tag==="Closed")return e(this.state.exit);return this.state.finalizers.set({},e),Fe})}},qN=(e=Ui)=>{let t=Object.create(DN);return t.strategy=e,t.state={_tag:"Open",finalizers:new Map},t};var Km=p(2,(e,t)=>Wf(e,Bs(Vx(Ta,t))));var UN=(e)=>qo(e,{differ:LE,fork:Vi});var jE=mb(qS),jN=UN(Ko);var WE=p(2,(e,t)=>$n((r)=>zt(r(e),{onFailure:(n)=>zt(t,{onFailure:(o)=>ot(nt(n,o)),onSuccess:()=>ot(n)}),onSuccess:(n)=>rn(t,n)}))),HN=(e,t,r)=>na((n)=>WE(W(Wm(yl(e)),(o)=>jn((i)=>{let s=t.map((l)=>l.listeners.count),a=()=>{if(s.every((l)=>l===0)){if(t.every((l)=>{if(l.result.state.current._tag==="Pending")return!0;else if(l.result.state.current._tag==="Done"&&Li(l.result.state.current.effect)&&l.result.state.current.effect._tag==="Failure"&&$c(l.result.state.current.effect.cause))return!0;else return!1}))c.forEach((l)=>l()),r?.(),i(ab(o))}};o.addObserver((l)=>{c.forEach((u)=>u()),i(l)});let c=t.map((l,u)=>{let d=(f)=>{s[u]=f,a()};return l.listeners.addObserver(d),()=>l.listeners.removeObserver(d)});return a(),q(()=>{c.forEach((l)=>l())})})),me(()=>{let o=t.flatMap((i)=>{if(!i.state.completed)return[i];return[]});return Mo(o,(i)=>RE(i.request,$f(n)))})));var VE=Uf;var zE=Mi;var zm=(e)=>function(){if(arguments.length===1){let t=arguments[0];return(r,...n)=>e(t,r,...n)}return e.apply(this,arguments)},GE=zm((e,t,r)=>{let n=el(),o=[[Uo,[[n,e.context]]]];if(r?.scheduler)o.push([su,[[n,r.scheduler]]]);let i=O_(e.fiberRefs,{entries:o,forkAs:n});if(r?.updateRefs)i=r.updateRefs(i,n);let s=new Su(n,i,e.runtimeFlags),a=t;if(r?.scope)a=W(zE(r.scope,Ui),(l)=>Bn(Tl(l,na((u)=>E(u,s.id())?Fe:la(s,u))),Ni(t,(u)=>VE(l,u))));let c=s.currentSupervisor;if(c!==Ko)c.onStart(e.context,a,A(),s),s.addObserver((l)=>c.onEnd(l,s));if(ba.add(e.runtimeFlags,s),r?.immediate===!1)s.resume(a);else s.start(a);return s});var KN=zm((e,t)=>{let r=JN(e)(t);if(r._tag==="Failure")throw zN(r.effect_instruction_i0);return r.effect_instruction_i0});class JE extends Error{fiber;_tag="AsyncFiberException";constructor(e){super(`Fiber #${e.id().id} cannot be resolved synchronously. This is caused by using runSync on an effect that performs async work`);this.fiber=e,this.name=this._tag,this.stack=this.message}}var VN=(e)=>{let t=Error.stackTraceLimit;Error.stackTraceLimit=0;let r=new JE(e);return Error.stackTraceLimit=t,r};var Vm=Symbol.for("effect/Runtime/FiberFailure"),bu=Symbol.for("effect/Runtime/FiberFailure/Cause");class YE extends Error{[Vm];[bu];constructor(e){let t=qs(e)[0];super(t?.message||"An error has occurred");if(this[Vm]=Vm,this[bu]=e,this.name=t?`(FiberFailure) ${t.name}`:"FiberFailure",t?.stack)this.stack=t.stack}toJSON(){return{_id:"FiberFailure",cause:this[bu].toJSON()}}toString(){return"(FiberFailure) "+ur(this[bu],{renderErrorCause:!0})}[Y](){return this.toString()}}var zN=(e)=>{let t=Error.stackTraceLimit;Error.stackTraceLimit=0;let r=new YE(e);return Error.stackTraceLimit=t,r};var GN=(e)=>{let t=e;switch(t._op){case"Failure":case"Success":return t;case"Left":return ma(t.left);case"Right":return xe(t.right);case"Some":return xe(t.value);case"None":return ma(new da)}},JN=zm((e,t)=>{let r=GN(t);if(r)return r;let n=new Sa,o=GE(e)(t,{scheduler:n});n.flush();let i=o.unsafePoll();if(i)return i;return Hf(hl(VN(o),Pl(o)))});class ZE{context;runtimeFlags;fiberRefs;constructor(e,t,r){this.context=e,this.runtimeFlags=t,this.fiberRefs=r}pipe(){return b(this,arguments)}}var YN=(e)=>new ZE(e.context,e.runtimeFlags,e.fiberRefs);var ZN=df(en,lf,cf),QE=YN({context:Mn(),runtimeFlags:ZN,fiberRefs:v_()});var XE=GE(QE);var eO=KN(QE);var tO=Ci;var Ia=HE;var Ra=me;var qt=Fe;var rO=ra;var _u=ve;var nO=Lo;var zo=Fo;var dr=W;var oO=XE;var iO=eO;var Gm=(e,t)=>{switch(t._tag){case"StringKeyword":case"TemplateLiteral":return Object.keys(e);case"SymbolKeyword":return Object.getOwnPropertySymbols(e);case"Refinement":return Gm(e,t.from)}},ka=(e)=>{let t=!1,r;return()=>{if(t)return r;return r=e(),t=!0,r}},Jm=(e)=>Array.isArray(e),aO=(e)=>!Array.isArray(e),sO=(e)=>`[${vs(e)}]`,wu=(e)=>Jm(e)?e.map(sO).join(""):sO(e);var Yn=(e,t,r,n)=>{let o=e;if(r&&le(r))o+=`
34
- at path: ${wu(r)}`;if(t!==void 0)o+=`
35
- details: ${t}`;if(n)o+=`
36
- schema (${n._tag}): ${n}`;return o},cO=(e)=>Yn("Invalid Argument",e);var lO=(e)=>Yn("Unsupported key schema",void 0,void 0,e),uO=(e)=>Yn("Unsupported literal",`literal value: ${_r(e)}`),Ym=(e)=>Yn("Duplicate index signature",`${e} index signature`),pO=Yn("Unsupported index signature parameter","An index signature parameter type must be `string`, `symbol`, a template literal type or a refinement of the previous types"),dO=Yn("Invalid element","A required element cannot follow an optional element. ts(1257)"),Zm=(e)=>Yn("Duplicate property signature transformation",`Duplicate key ${_r(e)}`);var Qm=(e)=>Yn("Duplicate property signature",`Duplicate key ${_r(e)}`);var mO=Symbol.for("effect/SchemaId/DateFromSelf"),hO=Symbol.for("effect/SchemaId/GreaterThan"),gO=Symbol.for("effect/SchemaId/GreaterThanOrEqualTo");var yO=Symbol.for("effect/SchemaId/Int");var xO=Symbol.for("effect/SchemaId/MinLength");var SO=Symbol.for("effect/SchemaId/MinItems");var _O=Symbol.for("effect/annotation/TypeConstructor"),th=Symbol.for("effect/annotation/Brand"),wO=Symbol.for("effect/annotation/SchemaId"),rh=Symbol.for("effect/annotation/Message"),Ou=Symbol.for("effect/annotation/MissingMessage"),vu=Symbol.for("effect/annotation/Identifier"),Tt=Symbol.for("effect/annotation/Title"),Au=Symbol.for("effect/annotation/AutoTitle"),cn=Symbol.for("effect/annotation/Description"),nh=Symbol.for("effect/annotation/Examples"),oh=Symbol.for("effect/annotation/Default"),ih=Symbol.for("effect/annotation/JSONSchema"),sh=Symbol.for("effect/annotation/Arbitrary"),ah=Symbol.for("effect/annotation/Pretty"),ch=Symbol.for("effect/annotation/Equivalence"),EO=Symbol.for("effect/annotation/Documentation"),lh=Symbol.for("effect/annotation/Concurrency"),uh=Symbol.for("effect/annotation/Batching"),ph=Symbol.for("effect/annotation/ParseIssueTitle"),dh=Symbol.for("effect/annotation/ParseOptions"),fh=Symbol.for("effect/annotation/DecodingFallback"),mh=Symbol.for("effect/annotation/Surrogate"),hh=Symbol.for("effect/annotation/StableFilter"),it=p(2,(e,t)=>Object.prototype.hasOwnProperty.call(e.annotations,t)?M(e.annotations[t]):A());var gh=it(th);var OO=it(rh),vO=it(Ou),yh=it(Tt),xh=it(Au),Ca=it(vu),Sh=it(cn);var AO=it(lh),TO=it(uh),IO=it(ph),RO=it(dh),kO=it(fh),bh=it(mh),tF=it(hh),_h=(e)=>Ny(tF(e),(t)=>t===!0),wh=Symbol.for("effect/annotation/JSONIdentifier"),rF=it(wh),nF=(e)=>tr(rF(e),()=>Ca(e));class Gi{typeParameters;decodeUnknown;encodeUnknown;annotations;_tag="Declaration";constructor(e,t,r,n={}){this.typeParameters=e,this.decodeUnknown=t,this.encodeUnknown=r,this.annotations=n}toString(){return pe(Cr(this),()=>"<declaration schema>")}toJSON(){return{_tag:this._tag,typeParameters:this.typeParameters.map((e)=>e.toJSON()),annotations:Ee(this.annotations)}}}var Pa=(e)=>(t)=>t._tag===e;class Go{literal;annotations;_tag="Literal";constructor(e,t={}){this.literal=e,this.annotations=t}toString(){return pe(Cr(this),()=>_r(this.literal))}toJSON(){return{_tag:this._tag,literal:_n(this.literal)?String(this.literal):this.literal,annotations:Ee(this.annotations)}}}var Tu=Pa("Literal"),CO=new Go(null);class Iu{symbol;annotations;_tag="UniqueSymbol";constructor(e,t={}){this.symbol=e,this.annotations=t}toString(){return pe(Cr(this),()=>_r(this.symbol))}toJSON(){return{_tag:this._tag,symbol:String(this.symbol),annotations:Ee(this.annotations)}}}class PO{annotations;_tag="UndefinedKeyword";constructor(e={}){this.annotations=e}toString(){return fr(this)}toJSON(){return{_tag:this._tag,annotations:Ee(this.annotations)}}}var Ru=new PO({[Tt]:"undefined"});class NO{annotations;_tag="VoidKeyword";constructor(e={}){this.annotations=e}toString(){return fr(this)}toJSON(){return{_tag:this._tag,annotations:Ee(this.annotations)}}}var oF=new NO({[Tt]:"void"});class FO{annotations;_tag="NeverKeyword";constructor(e={}){this.annotations=e}toString(){return fr(this)}toJSON(){return{_tag:this._tag,annotations:Ee(this.annotations)}}}var ku=new FO({[Tt]:"never"});class MO{annotations;_tag="UnknownKeyword";constructor(e={}){this.annotations=e}toString(){return fr(this)}toJSON(){return{_tag:this._tag,annotations:Ee(this.annotations)}}}var LO=new MO({[Tt]:"unknown"});class DO{annotations;_tag="AnyKeyword";constructor(e={}){this.annotations=e}toString(){return fr(this)}toJSON(){return{_tag:this._tag,annotations:Ee(this.annotations)}}}var qO=new DO({[Tt]:"any"});class UO{annotations;_tag="StringKeyword";constructor(e={}){this.annotations=e}toString(){return fr(this)}toJSON(){return{_tag:this._tag,annotations:Ee(this.annotations)}}}var jO=new UO({[Tt]:"string",[cn]:"a string"}),Cu=Pa("StringKeyword");class HO{annotations;_tag="NumberKeyword";constructor(e={}){this.annotations=e}toString(){return fr(this)}toJSON(){return{_tag:this._tag,annotations:Ee(this.annotations)}}}var $O=new HO({[Tt]:"number",[cn]:"a number"});class BO{annotations;_tag="BooleanKeyword";constructor(e={}){this.annotations=e}toString(){return fr(this)}toJSON(){return{_tag:this._tag,annotations:Ee(this.annotations)}}}var WO=new BO({[Tt]:"boolean",[cn]:"a boolean"});class KO{annotations;_tag="BigIntKeyword";constructor(e={}){this.annotations=e}toString(){return fr(this)}toJSON(){return{_tag:this._tag,annotations:Ee(this.annotations)}}}var iF=new KO({[Tt]:"bigint",[cn]:"a bigint"});class VO{annotations;_tag="SymbolKeyword";constructor(e={}){this.annotations=e}toString(){return fr(this)}toJSON(){return{_tag:this._tag,annotations:Ee(this.annotations)}}}var sF=new VO({[Tt]:"symbol",[cn]:"a symbol"}),zO=Pa("SymbolKeyword");class GO{annotations;_tag="ObjectKeyword";constructor(e={}){this.annotations=e}toString(){return fr(this)}toJSON(){return{_tag:this._tag,annotations:Ee(this.annotations)}}}var aF=new GO({[Tt]:"object",[cn]:"an object in the TypeScript meaning, i.e. the `object` type"});class Ji{type;annotations;constructor(e,t={}){this.type=e,this.annotations=t}toJSON(){return{type:this.type.toJSON(),annotations:Ee(this.annotations)}}toString(){return String(this.type)}}class Zn extends Ji{isOptional;constructor(e,t,r={}){super(e,r);this.isOptional=t}toJSON(){return{type:this.type.toJSON(),isOptional:this.isOptional,annotations:Ee(this.annotations)}}toString(){return String(this.type)+(this.isOptional?"?":"")}}var JO=(e)=>e.map((t)=>t.type);class Na{elements;rest;isReadonly;annotations;_tag="TupleType";constructor(e,t,r,n={}){this.elements=e,this.rest=t,this.isReadonly=r,this.annotations=n;let o=!1,i=!1;for(let s of e)if(s.isOptional)o=!0;else if(o){i=!0;break}if(i||o&&t.length>1)throw Error(dO)}toString(){return pe(Cr(this),()=>cF(this))}toJSON(){return{_tag:this._tag,elements:this.elements.map((e)=>e.toJSON()),rest:this.rest.map((e)=>e.toJSON()),isReadonly:this.isReadonly,annotations:Ee(this.annotations)}}}var cF=(e)=>{let t=e.elements.map(String).join(", ");return My(e.rest,{onEmpty:()=>`readonly [${t}]`,onNonEmpty:(r,n)=>{let o=String(r),i=o.includes(" | ")?`(${o})`:o;if(n.length>0){let s=n.map(String).join(", ");if(e.elements.length>0)return`readonly [${t}, ...${i}[], ${s}]`;else return`readonly [...${i}[], ${s}]`}else if(e.elements.length>0)return`readonly [${t}, ...${i}[]]`;else return`ReadonlyArray<${o}>`}})};class Ue extends Zn{name;isReadonly;constructor(e,t,r,n,o){super(t,r,o);this.name=e,this.isReadonly=n}toString(){return(this.isReadonly?"readonly ":"")+String(this.name)+(this.isOptional?"?":"")+": "+this.type}toJSON(){return{name:String(this.name),type:this.type.toJSON(),isOptional:this.isOptional,isReadonly:this.isReadonly,annotations:Ee(this.annotations)}}}var YO=(e)=>{switch(e._tag){case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":return!0;case"Refinement":return YO(e.from)}return!1};class Yi{type;isReadonly;parameter;constructor(e,t,r){if(this.type=t,this.isReadonly=r,YO(e))this.parameter=e;else throw Error(pO)}toString(){return(this.isReadonly?"readonly ":"")+`[x: ${this.parameter}]: ${this.type}`}toJSON(){return{parameter:this.parameter.toJSON(),type:this.type.toJSON(),isReadonly:this.isReadonly}}}class Pr{annotations;_tag="TypeLiteral";propertySignatures;indexSignatures;constructor(e,t,r={}){this.annotations=r;let n={};for(let i=0;i<e.length;i++){let s=e[i].name;if(Object.prototype.hasOwnProperty.call(n,s))throw Error(Qm(s));n[s]=null}let o={string:!1,symbol:!1};for(let i=0;i<t.length;i++){let s=Rh(t[i].parameter);if(Cu(s)){if(o.string)throw Error(Ym("string"));o.string=!0}else if(zO(s)){if(o.symbol)throw Error(Ym("symbol"));o.symbol=!0}}this.propertySignatures=e,this.indexSignatures=t}toString(){return pe(Cr(this),()=>lF(this))}toJSON(){return{_tag:this._tag,propertySignatures:this.propertySignatures.map((e)=>e.toJSON()),indexSignatures:this.indexSignatures.map((e)=>e.toJSON()),annotations:Ee(this.annotations)}}}var bO=(e)=>e.map(String).join("; "),lF=(e)=>{if(e.propertySignatures.length>0){let t=e.propertySignatures.map(String).join("; ");if(e.indexSignatures.length>0)return`{ ${t}; ${bO(e.indexSignatures)} }`;else return`{ ${t} }`}else if(e.indexSignatures.length>0)return`{ ${bO(e.indexSignatures)} }`;else return"{}"};var uF=Wr(Ec(Rr,(e)=>{switch(e._tag){case"AnyKeyword":return 0;case"UnknownKeyword":return 1;case"ObjectKeyword":return 2;case"StringKeyword":case"NumberKeyword":case"BooleanKeyword":case"BigIntKeyword":case"SymbolKeyword":return 3}return 4})),pF={string:"StringKeyword",number:"NumberKeyword",boolean:"BooleanKeyword",bigint:"BigIntKeyword"},ZO=(e)=>Ps(e,(t)=>Eh(t)?ZO(t.types):[t]),dF=(e)=>{let t=uF(e),r=[],n={},o=[];for(let i of t)switch(i._tag){case"NeverKeyword":break;case"AnyKeyword":return[qO];case"UnknownKeyword":return[LO];case"ObjectKeyword":case"UndefinedKeyword":case"VoidKeyword":case"StringKeyword":case"NumberKeyword":case"BooleanKeyword":case"BigIntKeyword":case"SymbolKeyword":{if(!n[i._tag])n[i._tag]=i,r.push(i);break}case"Literal":{let s=typeof i.literal;switch(s){case"string":case"number":case"bigint":case"boolean":{let a=pF[s];if(!n[a]&&!o.includes(i.literal))o.push(i.literal),r.push(i);break}case"object":{if(!o.includes(i.literal))o.push(i.literal),r.push(i);break}}break}case"UniqueSymbol":{if(!n.SymbolKeyword&&!o.includes(i.symbol))o.push(i.symbol),r.push(i);break}case"TupleType":{if(!n.ObjectKeyword)r.push(i);break}case"TypeLiteral":{if(i.propertySignatures.length===0&&i.indexSignatures.length===0){if(!n["{}"])n["{}"]=i,r.push(i)}else if(!n.ObjectKeyword)r.push(i);break}default:r.push(i)}return r};class ht{types;annotations;static make=(e,t)=>Pu(e)?new ht(e,t):e.length===1?e[0]:ku;static unify=(e,t)=>ht.make(dF(ZO(e)),t);_tag="Union";constructor(e,t={}){this.types=e,this.annotations=t}toString(){return pe(Cr(this),()=>this.types.map(String).join(" | "))}toJSON(){return{_tag:this._tag,types:this.types.map((e)=>e.toJSON()),annotations:Ee(this.annotations)}}}var QO=(e,t)=>e.map(t),Pu=(e)=>e.length>1,Eh=Pa("Union"),Xm=B(Symbol.for("effect/Schema/AST/toJSONMemoMap"),()=>new WeakMap);class Nu{f;annotations;_tag="Suspend";constructor(e,t={}){this.f=e,this.annotations=t,this.f=ka(e)}toString(){return Cr(this).pipe(tr(()=>nr(ky(this.f)(),(e)=>Cr(e))),pe(()=>"<suspended schema>"))}toJSON(){let e=this.f(),t=Xm.get(e);if(t)return t;return Xm.set(e,{_tag:this._tag}),t={_tag:this._tag,ast:e.toJSON(),annotations:Ee(this.annotations)},Xm.set(e,t),t}}class Fa{from;filter;annotations;_tag="Refinement";constructor(e,t,r={}){this.from=e,this.filter=t,this.annotations=r}toString(){return Ca(this).pipe(pe(()=>Ae(rv(this),{onNone:()=>`{ ${this.from} | filter }`,onSome:(e)=>Ma(this.from)?String(this.from)+" & "+e:e})))}toJSON(){return{_tag:this._tag,from:this.from.toJSON(),annotations:Ee(this.annotations)}}}var Ma=Pa("Refinement"),Fu={};class Oh{from;to;transformation;annotations;_tag="Transformation";constructor(e,t,r,n={}){this.from=e,this.to=t,this.transformation=r,this.annotations=n}toString(){return pe(Cr(this),()=>`(${String(this.from)} <-> ${String(this.to)})`)}toJSON(){return{_tag:this._tag,from:this.from.toJSON(),to:this.to.toJSON(),annotations:Ee(this.annotations)}}}class vh{from;to;decode;encode;constructor(e,t,r,n){this.from=e,this.to=t,this.decode=r,this.encode=n}}class Ah{propertySignatureTransformations;_tag="TypeLiteralTransformation";constructor(e){this.propertySignatureTransformations=e;let t={},r={};for(let n of e){let o=n.from;if(t[o])throw Error(Zm(o));t[o]=!0;let i=n.to;if(r[i])throw Error(Zm(i));r[i]=!0}}}var La=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),n={...e.annotations};delete n[vu];let o={...n,...t},i=bh(e);if(de(i))o[mh]=La(i.value,t);return r.annotations.value=o,Object.create(Object.getPrototypeOf(e),r)};var fF="[\\s\\S]*?",mF="[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?",XO=(e,t)=>{switch(e._tag){case"Literal":return qi(String(e.literal));case"StringKeyword":return fF;case"NumberKeyword":return mF;case"TemplateLiteral":return ev(e,t,!1);case"Union":return e.types.map((r)=>XO(r,t)).join("|")}},hF=(e,t,r,n)=>{if(Eh(e)){if(r&&!n)return`(?:${t})`}else if(!r||!n)return t;return`(${t})`},ev=(e,t,r)=>{let n="";if(e.head!==""){let o=qi(e.head);n+=t&&r?`(${o})`:o}for(let o of e.spans){let i=XO(o.type,t);if(n+=hF(o.type,i,t,r),o.literal!==""){let s=qi(o.literal);n+=t&&r?`(${s})`:s}}return n},tv=(e)=>new RegExp(`^${ev(e,!1,!0)}$`);var Th=(e,t)=>{let r=[],n=[],o=(i)=>{switch(i._tag){case"NeverKeyword":break;case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":case"Refinement":n.push(new Yi(i,t,!0));break;case"Literal":if(Ve(i.literal)||Nt(i.literal))r.push(new Ue(i.literal,t,!1,!0));else throw Error(uO(i.literal));break;case"Enums":{for(let[s,a]of i.enums)r.push(new Ue(a,t,!1,!0));break}case"UniqueSymbol":r.push(new Ue(i.symbol,t,!1,!0));break;case"Union":i.types.forEach(o);break;default:throw Error(lO(i))}};return o(e),{propertySignatures:r,indexSignatures:n}};var Ih=(e)=>(t)=>{let r=void 0;for(let n of e)if(Object.prototype.hasOwnProperty.call(t.annotations,n)){if(r===void 0)r={};r[n]=t.annotations[n]}return r};var gF=Ih([nh,oh,ih,sh,ah,ch]),qe=(e)=>{switch(e._tag){case"Declaration":{let t=Yt(e.typeParameters,qe);return t===e.typeParameters?e:new Gi(t,e.decodeUnknown,e.encodeUnknown,e.annotations)}case"TupleType":{let t=Yt(e.elements,(o)=>{let i=qe(o.type);return i===o.type?o:new Zn(i,o.isOptional)}),r=JO(e.rest),n=Yt(r,qe);return t===e.elements&&n===r?e:new Na(t,n.map((o)=>new Ji(o)),e.isReadonly,e.annotations)}case"TypeLiteral":{let t=Yt(e.propertySignatures,(n)=>{let o=qe(n.type);return o===n.type?n:new Ue(n.name,o,n.isOptional,n.isReadonly)}),r=Yt(e.indexSignatures,(n)=>{let o=qe(n.type);return o===n.type?n:new Yi(n.parameter,o,n.isReadonly)});return t===e.propertySignatures&&r===e.indexSignatures?e:new Pr(t,r,e.annotations)}case"Union":{let t=Yt(e.types,qe);return t===e.types?e:ht.make(t,e.annotations)}case"Suspend":return new Nu(()=>qe(e.f()),e.annotations);case"Refinement":{let t=qe(e.from);return t===e.from?e:new Fa(t,e.filter,e.annotations)}case"Transformation":{let t=gF(e);return qe(t!==void 0?La(e.to,t):e.to)}}return e};function Yt(e,t){let r=!1,n=bo(e.length);for(let o=0;o<e.length;o++){let i=e[o],s=t(i);if(s!==i)r=!0;n[o]=s}return r?n:e}var eh=(e)=>{switch(e._tag){case"Transformation":return e.from;case"Refinement":return eh(e.from);case"Suspend":return eh(e.f())}},kr=(e,t)=>{switch(e._tag){case"Declaration":{let r=Yt(e.typeParameters,(n)=>kr(n,t));return r===e.typeParameters?e:new Gi(r,e.decodeUnknown,e.encodeUnknown)}case"TupleType":{let r=Yt(e.elements,(i)=>{let s=kr(i.type,t);return s===i.type?i:new Zn(s,i.isOptional)}),n=JO(e.rest),o=Yt(n,(i)=>kr(i,t));return r===e.elements&&o===n?e:new Na(r,o.map((i)=>new Ji(i)),e.isReadonly)}case"TypeLiteral":{let r=Yt(e.propertySignatures,(o)=>{let i=kr(o.type,t);return i===o.type?o:new Ue(o.name,i,o.isOptional,o.isReadonly)}),n=Yt(e.indexSignatures,(o)=>{let i=kr(o.type,t);return i===o.type?o:new Yi(o.parameter,i,o.isReadonly)});return r===e.propertySignatures&&n===e.indexSignatures?e:new Pr(r,n)}case"Union":{let r=Yt(e.types,(n)=>kr(n,t));return r===e.types?e:ht.make(r)}case"Suspend":{let r=void 0,n=nF(e);if(de(n)){let o=t?"Bound":"";r={[wh]:`${n.value}Encoded${o}`}}return new Nu(()=>kr(e.f(),t),r)}case"Refinement":{let r=kr(e.from,t);if(t){if(r===e.from)return e;if(eh(e.from)===void 0&&_h(e))return new Fa(r,e.filter,e.annotations);return r}else return r}case"Transformation":return kr(e.from,t)}return e},Mu=(e)=>kr(e,!1);var Ee=(e)=>{let t={};for(let r of Object.getOwnPropertySymbols(e))t[String(r)]=e[r];return t},Rh=(e)=>{switch(e._tag){case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":return e;case"Refinement":return Rh(e.from)}};var fr=(e)=>pe(Cr(e),()=>e._tag);function yF(e){return Ae(gh(e),{onNone:()=>"",onSome:(t)=>t.map((r)=>` & Brand<${_r(r)}>`).join("")})}var rv=(e)=>yh(e).pipe(tr(()=>Sh(e)),tr(()=>xh(e)),rr((t)=>t+yF(e))),Cr=(e)=>tr(Ca(e),()=>rv(e));class je{path;actual;issue;_tag="Pointer";constructor(e,t,r){this.path=e,this.actual=t,this.issue=r}}class Ph{actual;message;_tag="Unexpected";constructor(e,t){this.actual=e,this.message=t}}class Zi{ast;message;_tag="Missing";actual=void 0;constructor(e,t){this.ast=e,this.message=t}}class Oe{ast;actual;issues;output;_tag="Composite";constructor(e,t,r,n){this.ast=e,this.actual=t,this.issues=r,this.output=n}}class Du{ast;actual;kind;issue;_tag="Refinement";constructor(e,t,r,n){this.ast=e,this.actual=t,this.kind=r,this.issue=n}}class qu{ast;actual;kind;issue;_tag="Transformation";constructor(e,t,r,n){this.ast=e,this.actual=t,this.kind=r,this.issue=n}}class Zt{ast;actual;message;_tag="Type";constructor(e,t,r){this.ast=e,this.actual=t,this.message=r}}class Nh{ast;actual;message;_tag="Forbidden";constructor(e,t,r){this.ast=e,this.actual=t,this.message=r}}var ov=Symbol.for("effect/Schema/ParseErrorTypeId");class av extends d_("ParseError"){[ov]=ov;get message(){return this.toString()}toString(){return Ua.formatIssueSync(this.issue)}toJSON(){return{_id:"ParseError",message:this.toString()}}[Y](){return this.toJSON()}}var Mh=(e)=>new av({issue:e}),cv=G,lv=K;var Rt=Kp,ln=p(2,(e,t)=>Rt(e)?Cs(e,{onLeft:K,onRight:t}):dr(e,t)),hr=p(2,(e,t)=>Rt(e)?Oy(e,t):_u(e,t)),Uu=p(2,(e,t)=>Rt(e)?wc(e,t):nO(e,t));var uv=p(2,(e,t)=>Rt(e)?Cs(e,{onLeft:t,onRight:G}):rO(e,t)),pv=(e,t)=>{if(t===void 0||Nt(t))return e;if(e===void 0)return t;return{...e,...t}},dv=(e,t,r)=>{let n=st(e,t);return(o,i)=>n(o,pv(r,i))},xF=(e,t,r)=>{let n=dv(e,t,r);return(o,i)=>Vp(n(o,i),Mh)};var fv=(e,t)=>dv(e.ast,!0,t);var ju=(e,t)=>xF(qe(e.ast),!0,t);var SF=B(Symbol.for("effect/ParseResult/decodeMemoMap"),()=>new WeakMap),bF=B(Symbol.for("effect/ParseResult/encodeMemoMap"),()=>new WeakMap),st=(e,t)=>{let r=t?SF:bF,n=r.get(e);if(n)return n;let o=_F(e,t),i=RO(e),s=de(i)?(l,u)=>o(l,pv(u,i.value)):o,a=kO(e),c=t&&de(a)?(l,u)=>qa(uv(s(l,u),a.value),e,l,u):s;return r.set(e,c),c},kh=(e)=>vt(AO(e)),Ch=(e)=>vt(TO(e)),_F=(e,t)=>{switch(e._tag){case"Refinement":if(t){let r=st(e.from,!0);return(n,o)=>{o=o??Fu;let i=o?.errors==="all",s=ln(uv(r(n,o),(a)=>{let c=new Du(e,n,"From",a);if(i&&_h(e)&&xv(a))return Ae(e.filter(n,o,e),{onNone:()=>K(c),onSome:(l)=>K(new Oe(e,n,[c,new Du(e,n,"Predicate",l)]))});return K(c)}),(a)=>Ae(e.filter(a,o,e),{onNone:()=>G(a),onSome:(c)=>K(new Du(e,n,"Predicate",c))}));return qa(s,e,n,o)}}else{let r=st(qe(e),!0),n=st(hv(e.from),!1);return(o,i)=>qa(ln(r(o,i),(s)=>n(s,i)),e,o,i)}case"Transformation":{let r=EF(e.transformation,t),n=t?st(e.from,!0):st(e.to,!1),o=t?st(e.to,!0):st(e.from,!1);return(i,s)=>qa(ln(Uu(n(i,s),(a)=>new qu(e,i,t?"Encoded":"Type",a)),(a)=>ln(Uu(r(a,s??Fu,e,i),(c)=>new qu(e,i,"Transformation",c)),(c)=>Uu(o(c,s),(l)=>new qu(e,i,t?"Type":"Encoded",l)))),e,i,s)}case"Declaration":{let r=t?e.decodeUnknown(...e.typeParameters):e.encodeUnknown(...e.typeParameters);return(n,o)=>qa(r(n,o??Fu,e),e,n,o)}case"Literal":return It(e,(r)=>r===e.literal);case"UniqueSymbol":return It(e,(r)=>r===e.symbol);case"UndefinedKeyword":return It(e,ty);case"NeverKeyword":return It(e,ry);case"UnknownKeyword":case"AnyKeyword":case"VoidKeyword":return G;case"StringKeyword":return It(e,Ve);case"NumberKeyword":return It(e,Nt);case"BooleanKeyword":return It(e,uo);case"BigIntKeyword":return It(e,_n);case"SymbolKeyword":return It(e,po);case"ObjectKeyword":return It(e,mt);case"Enums":return It(e,(r)=>e.enums.some(([n,o])=>o===r));case"TemplateLiteral":{if(e.spans.every((n)=>Cu(n.type)))return It(e,(n)=>{if(!Ve(n)||!n.startsWith(e.head))return!1;let o=e.head.length;for(let s=0;s<e.spans.length-1;s++){let a=e.spans[s].literal,c=n.indexOf(a,o);if(c===-1)return!1;o=c+a.length}let i=e.spans[e.spans.length-1].literal;return n.endsWith(i)&&n.length-i.length>=o});let r=tv(e);return It(e,(n)=>Ve(n)&&r.test(n))}case"TupleType":{let r=e.elements.map((l)=>st(l.type,t)),n=e.rest.map((l)=>st(l.type,t)),o=e.elements.filter((l)=>!l.isOptional);if(e.rest.length>0)o=o.concat(e.rest.slice(1));let i=o.length,s=e.elements.length>0?e.elements.map((l,u)=>u).join(" | "):"never",a=kh(e),c=Ch(e);return(l,u)=>{if(!Xp(l))return K(new Zt(e,l));let d=u?.errors==="all",f=[],g=0,y=[],O=l.length;for(let k=O;k<=i-1;k++){let H=new je(k,l,new Zi(o[k-O]));if(d){f.push([g++,H]);continue}else return K(new Oe(e,l,H,y))}if(e.rest.length===0)for(let k=e.elements.length;k<=O-1;k++){let H=new je(k,l,new Ph(l[k],`is unexpected, expected: ${s}`));if(d){f.push([g++,H]);continue}else return K(new Oe(e,l,H,y))}let m=0,x=void 0;for(;m<r.length;m++)if(O<m+1){if(e.elements[m].isOptional)continue}else{let k=r[m],H=k(l[m],u);if(Rt(H)){if(ge(H)){let T=new je(m,l,H.left);if(d){f.push([g++,T]);continue}else return K(new Oe(e,l,T,mr(y)))}y.push([g++,H.right])}else{let T=g++,I=m;if(!x)x=[];x.push(({es:C,output:L})=>dr(zo(H),(ee)=>{if(ge(ee)){let X=new je(I,l,ee.left);if(d)return C.push([T,X]),qt;else return K(new Oe(e,l,X,mr(L)))}return L.push([T,ee.right]),qt}))}}if(le(n)){let[k,...H]=n;for(;m<O-H.length;m++){let T=k(l[m],u);if(Rt(T))if(ge(T)){let I=new je(m,l,T.left);if(d){f.push([g++,I]);continue}else return K(new Oe(e,l,I,mr(y)))}else y.push([g++,T.right]);else{let I=g++,C=m;if(!x)x=[];x.push(({es:L,output:ee})=>dr(zo(T),(X)=>{if(ge(X)){let J=new je(C,l,X.left);if(d)return L.push([I,J]),qt;else return K(new Oe(e,l,J,mr(ee)))}else return ee.push([I,X.right]),qt}))}}for(let T=0;T<H.length;T++){let I=m+T;if(O<I+1)continue;else{let C=H[T](l[I],u);if(Rt(C)){if(ge(C)){let L=new je(I,l,C.left);if(d){f.push([g++,L]);continue}else return K(new Oe(e,l,L,mr(y)))}y.push([g++,C.right])}else{let L=g++;if(!x)x=[];x.push(({es:ee,output:X})=>dr(zo(C),(J)=>{if(ge(J)){let he=new je(I,l,J.left);if(d)return ee.push([L,he]),qt;else return K(new Oe(e,l,he,mr(X)))}return X.push([L,J.right]),qt}))}}}}let D=({es:k,output:H})=>vn(k)?K(new Oe(e,l,mr(k),mr(H))):G(mr(H));if(x&&x.length>0){let k=x;return Ra(()=>{let H={es:fi(f),output:fi(y)};return dr(Ia(k,(T)=>T(H),{concurrency:a,batching:c,discard:!0}),()=>D(H))})}return D({output:y,es:f})}}case"TypeLiteral":{if(e.propertySignatures.length===0&&e.indexSignatures.length===0)return It(e,ny);let r=[],n={},o=[];for(let u of e.propertySignatures)r.push([st(u.type,t),u]),n[u.name]=null,o.push(u.name);let i=e.indexSignatures.map((u)=>[st(u.parameter,t),st(u.type,t),u.parameter]),s=ht.make(e.indexSignatures.map((u)=>u.parameter).concat(o.map((u)=>po(u)?new Iu(u):new Go(u)))),a=st(s,t),c=kh(e),l=Ch(e);return(u,d)=>{if(!kp(u))return K(new Zt(e,u));let f=d?.errors==="all",g=[],y=0,O=d?.onExcessProperty==="error",m=d?.onExcessProperty==="preserve",x={},D;if(O||m){D=Reflect.ownKeys(u);for(let I of D){let C=a(I,d);if(Rt(C)&&ge(C))if(O){let L=new je(I,u,new Ph(u[I],`is unexpected, expected: ${String(s)}`));if(f){g.push([y++,L]);continue}else return K(new Oe(e,u,L,x))}else x[I]=u[I]}}let k=void 0,H=d?.exact===!0;for(let I=0;I<r.length;I++){let C=r[I][1],L=C.name,ee=Object.prototype.hasOwnProperty.call(u,L);if(!ee){if(C.isOptional)continue;else if(H){let he=new je(L,u,new Zi(C));if(f){g.push([y++,he]);continue}else return K(new Oe(e,u,he,x))}}let X=r[I][0],J=X(u[L],d);if(Rt(J)){if(ge(J)){let he=new je(L,u,ee?J.left:new Zi(C));if(f){g.push([y++,he]);continue}else return K(new Oe(e,u,he,x))}x[L]=J.right}else{let he=y++,lt=L;if(!k)k=[];k.push(({es:Xe,output:ut})=>dr(zo(J),(Me)=>{if(ge(Me)){let Re=new je(lt,u,ee?Me.left:new Zi(C));if(f)return Xe.push([he,Re]),qt;else return K(new Oe(e,u,Re,ut))}return ut[lt]=Me.right,qt}))}}for(let I=0;I<i.length;I++){let C=i[I],L=C[0],ee=C[1],X=Gm(u,C[2]);for(let J of X){let he=L(J,d);if(Rt(he)&&He(he)){let lt=ee(u[J],d);if(Rt(lt)){if(ge(lt)){let Xe=new je(J,u,lt.left);if(f){g.push([y++,Xe]);continue}else return K(new Oe(e,u,Xe,x))}else if(!Object.prototype.hasOwnProperty.call(n,J))x[J]=lt.right}else{let Xe=y++,ut=J;if(!k)k=[];k.push(({es:Me,output:Re})=>dr(zo(lt),(pt)=>{if(ge(pt)){let Mr=new je(ut,u,pt.left);if(f)return Me.push([Xe,Mr]),qt;else return K(new Oe(e,u,Mr,Re))}else{if(!Object.prototype.hasOwnProperty.call(n,J))Re[J]=pt.right;return qt}}))}}}}let T=({es:I,output:C})=>{if(vn(I))return K(new Oe(e,u,mr(I),C));if(d?.propertyOrder==="original"){let L=D||Reflect.ownKeys(u);for(let X of o)if(L.indexOf(X)===-1)L.push(X);let ee={};for(let X of L)if(Object.prototype.hasOwnProperty.call(C,X))ee[X]=C[X];return G(ee)}return G(C)};if(k&&k.length>0){let I=k;return Ra(()=>{let C={es:fi(g),output:Object.assign({},x)};return dr(Ia(I,(L)=>L(C),{concurrency:c,batching:l,discard:!0}),()=>T(C))})}return T({es:g,output:x})}}case"Union":{let r=mv(e.types,t),n=Reflect.ownKeys(r.keys),o=n.length,i=e.types.length,s=new Map;for(let l=0;l<i;l++)s.set(e.types[l],st(e.types[l],t));let a=kh(e)??1,c=Ch(e);return(l,u)=>{let d=[],f=0,g=[];if(o>0)if(bs(l))for(let m=0;m<o;m++){let x=n[m],D=r.keys[x].buckets;if(Object.prototype.hasOwnProperty.call(l,x)){let k=String(l[x]);if(Object.prototype.hasOwnProperty.call(D,k))g=g.concat(D[k]);else{let{candidates:H,literals:T}=r.keys[x],I=ht.make(T),C=H.length===i?new Pr([new Ue(x,I,!1,!0)],[]):ht.make(H);d.push([f++,new Oe(C,l,new je(x,l,new Zt(I,l[x])))])}}else{let{candidates:k,literals:H}=r.keys[x],T=new Ue(x,ht.make(H),!1,!0),I=k.length===i?new Pr([T],[]):ht.make(k);d.push([f++,new Oe(I,l,new je(x,l,new Zi(T)))])}}else{let m=r.candidates.length===i?e:ht.make(r.candidates);d.push([f++,new Zt(m,l)])}if(r.otherwise.length>0)g=g.concat(r.otherwise);let y=void 0;for(let m=0;m<g.length;m++){let x=g[m],D=s.get(x)(l,u);if(Rt(D)&&(!y||y.length===0))if(He(D))return D;else d.push([f++,D.left]);else{let k=f++;if(!y)y=[];y.push((H)=>Ra(()=>{if("finalResult"in H)return qt;else return dr(zo(D),(T)=>{if(He(T))H.finalResult=T;else H.es.push([k,T.left]);return qt})}))}}let O=(m)=>vn(m)?m.length===1&&m[0][1]._tag==="Type"?K(m[0][1]):K(new Oe(e,l,mr(m))):K(new Zt(e,l));if(y&&y.length>0){let m=y;return Ra(()=>{let x={es:fi(d)};return dr(Ia(m,(D)=>D(x),{concurrency:a,batching:c,discard:!0}),()=>{if("finalResult"in x)return x.finalResult;return O(x.es)})})}return O(d)}}case"Suspend":{let r=ka(()=>st(e.f(),t));return(n,o)=>r()(n,o)}}},It=(e,t)=>(r)=>t(r)?G(r):K(new Zt(e,r)),Da=(e,t)=>{switch(e._tag){case"Declaration":{let r=bh(e);if(de(r))return Da(r.value,t);break}case"TypeLiteral":{let r=[];for(let n=0;n<e.propertySignatures.length;n++){let o=e.propertySignatures[n],i=t?Mu(o.type):qe(o.type);if(Tu(i)&&!o.isOptional)r.push([o.name,i])}return r}case"TupleType":{let r=[];for(let n=0;n<e.elements.length;n++){let o=e.elements[n],i=t?Mu(o.type):qe(o.type);if(Tu(i)&&!o.isOptional)r.push([n,i])}return r}case"Refinement":return Da(e.from,t);case"Suspend":return Da(e.f(),t);case"Transformation":return Da(t?e.from:e.to,t)}return[]},mv=(e,t)=>{let r={},n=[],o=[];for(let i=0;i<e.length;i++){let s=e[i],a=Da(s,t);if(a.length>0){o.push(s);for(let c=0;c<a.length;c++){let[l,u]=a[c],d=String(u.literal);r[l]=r[l]||{buckets:{},literals:[],candidates:[]};let f=r[l].buckets;if(Object.prototype.hasOwnProperty.call(f,d)){if(c<a.length-1)continue;f[d].push(s),r[l].literals.push(u),r[l].candidates.push(s)}else{f[d]=[s],r[l].literals.push(u),r[l].candidates.push(s);break}}}else n.push(s)}return{keys:r,otherwise:n,candidates:o}},hv=(e)=>Ma(e)?hv(e.from):e,qa=(e,t,r,n)=>{if(n?.isEffectAllowed===!0)return e;if(Rt(e))return e;let o=new Sa,i=oO(e,{scheduler:o});o.flush();let s=i.unsafePoll();if(s){if(xw(s))return G(s.value);let a=s.cause;if(Ab(a))return K(a.error);return K(new Nh(t,r,Tb(a)))}return K(new Nh(t,r,"cannot be be resolved synchronously, this is caused by using runSync on an effect that performs async work"))},wF=([e],[t])=>e>t?1:e<t?-1:0;function mr(e){return e.sort(wF).map((t)=>t[1])}var EF=(e,t)=>{switch(e._tag){case"FinalTransformation":return t?e.decode:e.encode;case"ComposeTransformation":return G;case"TypeLiteralTransformation":return(r)=>{let n=G(r);for(let o of e.propertySignatureTransformations){let[i,s]=t?[o.from,o.to]:[o.to,o.from],a=t?o.decode:o.encode;n=hr(n,(l)=>{let u=a(Object.prototype.hasOwnProperty.call(l,i)?M(l[i]):A());if(delete l[i],de(u))l[s]=u.value;return l})}return n}}},gt=(e,t=[])=>({value:e,forest:t}),Ua={formatIssue:(e)=>hr(Qi(e),OF),formatIssueSync:(e)=>{let t=Ua.formatIssue(e);return Rt(t)?Ay(t):iO(t)},formatError:(e)=>Ua.formatIssue(e.issue),formatErrorSync:(e)=>Ua.formatIssueSync(e.issue)},OF=(e)=>e.value+gv(`
37
- `,e.forest),gv=(e,t)=>{let r="",n=t.length,o;for(let i=0;i<n;i++){o=t[i];let s=i===n-1;r+=e+(s?"\u2514":"\u251C")+"\u2500 "+o.value,r+=gv(e+(n>1&&!s?"\u2502 ":" "),o.forest)}return r},vF=(e)=>{switch(e){case"Encoded":return"Encoded side transformation failure";case"Transformation":return"Transformation process failure";case"Type":return"Type side transformation failure"}},AF=(e)=>{switch(e){case"From":return"From side refinement failure";case"Predicate":return"Predicate refinement failure"}},yv=(e)=>("ast"in e)?M(e.ast):A(),Fh=G(void 0),TF=(e)=>yv(e).pipe(nr(OO),Ae({onNone:()=>Fh,onSome:(t)=>{let r=t(e);if(Ve(r))return G({message:r,override:!1});if(tO(r))return _u(r,(n)=>({message:n,override:!1}));if(Ve(r.message))return G({message:r.message,override:r.override});return _u(r.message,(n)=>({message:n,override:r.override}))}})),Lh=(e)=>(t)=>t._tag===e,xv=Lh("Composite"),iv=Lh("Refinement"),sv=Lh("Transformation"),ja=(e)=>ln(TF(e),(t)=>{if(t!==void 0)return!t.override&&(xv(e)||iv(e)&&e.kind==="From"||sv(e)&&e.kind!=="Transformation")?sv(e)||iv(e)?ja(e.issue):Fh:G(t.message);return Fh}),Sv=(e)=>yv(e).pipe(nr(IO),Cy((t)=>t(e)),vt);function IF(e){return Sh(e).pipe(tr(()=>yh(e)),tr(()=>xh(e)),tr(()=>Ca(e)),pe(()=>`{ ${e.from} | filter }`))}function RF(e){if(e.message!==void 0)return e.message;return`Expected ${Ma(e.ast)?IF(e.ast):String(e.ast)}, actual ${_r(e.actual)}`}var kF=(e)=>hr(ja(e),(t)=>t??Sv(e)??RF(e)),Lu=(e)=>Sv(e)??String(e.ast),CF=(e)=>e.message??"is forbidden",PF=(e)=>e.message??"is unexpected",NF=(e)=>{let t=vO(e.ast);if(de(t)){let r=t.value();return Ve(r)?G(r):r}return G(e.message??"is missing")},Qi=(e)=>{switch(e._tag){case"Type":return hr(kF(e),gt);case"Forbidden":return G(gt(Lu(e),[gt(CF(e))]));case"Unexpected":return G(gt(PF(e)));case"Missing":return hr(NF(e),gt);case"Transformation":return ln(ja(e),(t)=>{if(t!==void 0)return G(gt(t));return hr(Qi(e.issue),(r)=>gt(Lu(e),[gt(vF(e.kind),[r])]))});case"Refinement":return ln(ja(e),(t)=>{if(t!==void 0)return G(gt(t));return hr(Qi(e.issue),(r)=>gt(Lu(e),[gt(AF(e.kind),[r])]))});case"Pointer":return hr(Qi(e.issue),(t)=>gt(wu(e.path),[t]));case"Composite":return ln(ja(e),(t)=>{if(t!==void 0)return G(gt(t));let r=Lu(e);return Jm(e.issues)?hr(Ia(e.issues,Qi),(n)=>gt(r,n)):hr(Qi(e.issues),(n)=>gt(r,[n]))})}};var bv=p((e)=>mt(e[0]),(e,...t)=>{let r={};for(let n of t)if(n in e)r[n]=e[n];return r}),_v=p((e)=>mt(e[0]),(e,...t)=>{let r={...e};for(let n of t)delete r[n];return r});var Ha=Symbol.for("effect/Schema");function at(e){return class{[Ha]=wv;static ast=e;static annotations(r){return at(un(this.ast,r))}static pipe(){return b(this,arguments)}static toString(){return String(e)}static Type;static Encoded;static Context;static[Ha]=wv}}var wv={_A:(e)=>e,_I:(e)=>e,_R:(e)=>e};var Ev={typeConstructor:_O,schemaId:wO,message:rh,missingMessage:Ou,identifier:vu,title:Tt,description:cn,examples:nh,default:oh,documentation:EO,jsonSchema:ih,arbitrary:sh,pretty:ah,equivalence:ch,concurrency:lh,batching:uh,parseIssueTitle:ph,parseOptions:dh,decodingFallback:fh},Jo=(e)=>{if(!e)return{};let t={...e};for(let r in Ev)if(r in e){let n=Ev[r];t[n]=e[r],delete t[r]}return t},un=(e,t)=>La(e,Jo(t));var Qn=(e,t)=>{let r=fv(e,t);return(n,o)=>wc(r(n,o),Mh)};var Ov=(e)=>v(e,Ha)&&mt(e[Ha]);function LF(e){return Pu(e)?ht.make(QO(e,(t)=>new Go(t))):new Go(e[0])}function Rv(e,t=LF(e)){return class extends at(t){static annotations(n){return Rv(this.literals,un(this.ast,n))}static literals=[...e]}}function F(...e){return le(e)?Rv(e):Uh}var DF=(e,t,r)=>qh(e,new Gi(e.map((n)=>n.ast),(...n)=>t.decode(...n.map(at)),(...n)=>t.encode(...n.map(at)),Jo(r))),qF=(e,t)=>{let r=()=>(o,i,s)=>e(o)?cv(o):lv(new Zt(s,o));return qh([],new Gi([],r,r,Jo(t)))};function qh(e,t){return class extends at(t){static annotations(n){return qh(this.typeParameters,un(this.ast,n))}static typeParameters=[...e]}}var Ut=function(){if(Array.isArray(arguments[0])){let r=arguments[0],n=arguments[1],o=arguments[2];return DF(r,n,o)}let e=arguments[0],t=arguments[1];return qF(e,t)};class kv extends at(Ru){}class pn extends at(CO){}class Uh extends at(ku){}class Q extends at(jO){}class Hu extends at($O){}class ye extends at(WO){}var UF=(e)=>ht.make(e.map((t)=>t.ast));function Cv(e,t=UF(e)){return class extends at(t){static annotations(n){return Cv(this.members,un(this.ast,n))}static members=[...e]}}function Ke(...e){return Pu(e)?Cv(e):le(e)?e[0]:Uh}var jF=(e)=>Ke(e,kv);var HF=(e,t)=>new Na(e.map((r)=>Ov(r)?new Zn(r.ast,!1):r.ast),t.map((r)=>Ov(r)?new Ji(r.ast):r.ast),!0);function Pv(e,t,r=HF(e,t)){return class extends at(r){static annotations(o){return Pv(this.elements,this.rest,un(this.ast,o))}static elements=[...e];static rest=[...t]}}function Nv(e,t){return class extends Pv([],[e],t){static annotations(n){return Nv(this.value,un(this.ast,n))}static value=e}}var z=(e)=>Nv(e);var Dh=(e)=>e?'"?:"':'":"';class jh extends Zn{isReadonly;defaultValue;_tag="PropertySignatureDeclaration";constructor(e,t,r,n,o){super(e,t,n);this.isReadonly=r,this.defaultValue=o}toString(){let e=Dh(this.isOptional),t=String(this.type);return`PropertySignature<${e}, ${t}, never, ${e}, ${t}>`}}class Fv extends Zn{isReadonly;defaultValue;constructor(e,t,r,n,o){super(e,t,n);this.isReadonly=r,this.defaultValue=o}}var $F=(e)=>{if(e===void 0)return"never";if(Ve(e))return JSON.stringify(e);return String(e)};class Mv{from;to;decode;encode;_tag="PropertySignatureTransformation";constructor(e,t,r,n){this.from=e,this.to=t,this.decode=r,this.encode=n}toString(){return`PropertySignature<${Dh(this.to.isOptional)}, ${this.to.type}, ${$F(this.from.fromKey)}, ${Dh(this.from.isOptional)}, ${this.from.type}>`}}var Lv=(e,t)=>{switch(e._tag){case"PropertySignatureDeclaration":return new jh(e.type,e.isOptional,e.isReadonly,{...e.annotations,...t},e.defaultValue);case"PropertySignatureTransformation":return new Mv(e.from,new Fv(e.to.type,e.to.isOptional,e.to.isReadonly,{...e.to.annotations,...t},e.to.defaultValue),e.decode,e.encode)}},Dv=Symbol.for("effect/PropertySignature"),qv=(e)=>v(e,Dv);class Hh{ast;[Ha];[Dv]=null;_TypeToken;_Key;_EncodedToken;_HasDefault;constructor(e){this.ast=e}pipe(){return b(this,arguments)}annotations(e){return new Hh(Lv(this.ast,Jo(e)))}toString(){return String(this.ast)}}class $h extends Hh{from;constructor(e,t){super(e);this.from=t}annotations(e){return new $h(Lv(this.ast,Jo(e)),this.from)}}var N=(e)=>{let t=e.ast===Ru||e.ast===ku?Ru:jF(e).ast;return new $h(new jh(t,!0,!0,{},void 0),e)};var BF=Ih([Ou]),WF=(e,t)=>{let r=Reflect.ownKeys(e),n=[];if(r.length>0){let i=[],s=[],a=[];for(let c=0;c<r.length;c++){let l=r[c],u=e[l];if(qv(u)){let d=u.ast;switch(d._tag){case"PropertySignatureDeclaration":{let{type:f,isOptional:g,annotations:y}=d;i.push(new Ue(l,f,g,!0,BF(d))),s.push(new Ue(l,qe(f),g,!0,y)),n.push(new Ue(l,f,g,!0,y));break}case"PropertySignatureTransformation":{let f=d.from.fromKey??l;i.push(new Ue(f,d.from.type,d.from.isOptional,!0,d.from.annotations)),s.push(new Ue(l,d.to.type,d.to.isOptional,!0,d.to.annotations)),a.push(new vh(f,l,d.decode,d.encode));break}}}else i.push(new Ue(l,u.ast,!1,!0)),s.push(new Ue(l,qe(u.ast),!1,!0)),n.push(new Ue(l,u.ast,!1,!0))}if(le(a)){let c=[],l=[];for(let u of t){let{indexSignatures:d,propertySignatures:f}=Th(u.key.ast,u.value.ast);f.forEach((g)=>{i.push(g),s.push(new Ue(g.name,qe(g.type),g.isOptional,g.isReadonly,g.annotations))}),d.forEach((g)=>{c.push(g),l.push(new Yi(g.parameter,qe(g.type),g.isReadonly))})}return new Oh(new Pr(i,c,{[Au]:"Struct (Encoded side)"}),new Pr(s,l,{[Au]:"Struct (Type side)"}),new Ah(a))}}let o=[];for(let i of t){let{indexSignatures:s,propertySignatures:a}=Th(i.key.ast,i.value.ast);a.forEach((c)=>n.push(c)),s.forEach((c)=>o.push(c))}return new Pr(n,o)},KF=(e,t)=>{let r=Reflect.ownKeys(e);for(let n of r){let o=e[n];if(t[n]===void 0&&qv(o)){let i=o.ast,s=i._tag==="PropertySignatureDeclaration"?i.defaultValue:i.to.defaultValue;if(s!==void 0)t[n]=s()}}return t};function Uv(e,t,r=WF(e,t)){return class extends at(r){static annotations(o){return Uv(this.fields,this.records,un(this.ast,o))}static fields={...e};static records=[...t];static make=(o,i)=>{let s=KF(e,{...o});return Bh(i)?s:ju(this)(s)};static pick(...o){return U(bv(e,...o))}static omit(...o){return U(_v(e,...o))}}}function U(e,...t){return Uv(e,t)}function jv(e,t){return class extends at(t){static annotations(n){return jv(this.from,un(this.ast,n))}static make=(n,o)=>Bh(o)?n:ju(this)(n);static from=e}}var $a=(e,t)=>(r)=>{let n=Ae(gh(r.ast),{onNone:()=>[e],onSome:(i)=>[...i,e]}),o=La(r.ast,Jo({[th]:n,...t}));return jv(r,o)};var VF=Symbol.for("effect/SchemaId/Refine");function Hv(e,t,r){return class extends at(r){static annotations(o){return Hv(this.from,this.filter,un(this.ast,o))}static[VF]=e;static from=e;static filter=t;static make=(o,i)=>Bh(i)?o:ju(this)(o)}}var vv=(e,t,r)=>{if(uo(e))return e?A():M(new Zt(t,r));if(Ve(e))return M(new Zt(t,r,e));if(e!==void 0){if("_tag"in e)return M(e);let n=new Zt(t,r,e.message);return M(le(e.path)?new je(e.path,r,n):n)}return A()},zF=(e,t,r)=>{if(aO(e))return vv(e,t,r);if(le(e)){let n=vc(e,(o)=>vv(o,t,r));if(le(n))return M(n.length===1?n[0]:new Oe(t,r,n))}return A()};function jt(e,t){return(r)=>{function n(i,s,a){return zF(e(i,s,a),a,i)}let o=new Fa(r.ast,n,Jo(t));return Hv(r,n,o)}}var GF=xO,$v=(e,t)=>(r)=>r.pipe(jt((n)=>n.length>=e,{schemaId:GF,title:`minLength(${e})`,description:`a string at least ${e} character(s) long`,jsonSchema:{minLength:e},...t}));var Av=Symbol.for("effect/SchemaId/Pattern"),Ht=(e,t)=>(r)=>{let n=e.source;return r.pipe(jt((o)=>(e.lastIndex=0,e.test(o)),{schemaId:Av,[Av]:{regex:e},description:`a string matching the pattern ${n}`,jsonSchema:{pattern:n},...t}))};var JF=Symbol.for("effect/SchemaId/UUID"),Tv=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/i;class YF extends Q.pipe(Ht(Tv,{schemaId:JF,identifier:"UUID",jsonSchema:{format:"uuid",pattern:Tv.source},description:"a Universally Unique Identifier",arbitrary:()=>(e)=>e.uuid()})){}var ZF=hO,Bv=(e,t)=>(r)=>r.pipe(jt((n)=>n>e,{schemaId:ZF,title:`greaterThan(${e})`,description:e===0?"a positive number":`a number greater than ${e}`,jsonSchema:{exclusiveMinimum:e},...t})),QF=gO,Wv=(e,t)=>(r)=>r.pipe(jt((n)=>n>=e,{schemaId:QF,title:`greaterThanOrEqualTo(${e})`,description:e===0?"a non-negative number":`a number greater than or equal to ${e}`,jsonSchema:{minimum:e},...t}));var XF=yO,eM=(e)=>(t)=>t.pipe(jt((r)=>Number.isSafeInteger(r),{schemaId:XF,title:"int",description:"an integer",jsonSchema:{type:"integer"},...e}));class $u extends Hu.pipe(eM({identifier:"Int"})){}var tM=SO,Nr=(e,t)=>(r)=>{let n=Math.floor(e);if(n<1)throw Error(cO(`Expected an integer greater than or equal to 1, actual ${e}`));return r.pipe(jt((o)=>o.length>=n,{schemaId:tM,title:`minItems(${n})`,description:`an array of at least ${n} item(s)`,jsonSchema:{minItems:n},[hh]:!0,...t}))};var Iv=mO;class rM extends Ut(dc,{typeConstructor:{_tag:"Date"},identifier:"DateFromSelf",schemaId:Iv,[Iv]:{noInvalidDate:!1},description:"a potentially invalid Date instance",pretty:()=>(e)=>`new Date(${JSON.stringify(e)})`,arbitrary:()=>(e)=>e.date({noInvalidDate:!1}),equivalence:()=>Xg}){}function Bh(e){return uo(e)?e:e?.disableValidation??!1}var nM={onExcessProperty:"error"};function gr(e,t){return Qn(e,nM)(t)}var Vv=/^0\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-(?:0|[1-9]\d*))?$/u,Wh=Q.pipe(Ht(Vv));function oM(e){let t=Qn(Wh)(e);return He(t)?t.right:void 0}function zv(e){return oM(e)!==void 0}function Gv(e){return zv(e)&&!e.includes("-")}var iM=Q.pipe(jt(Gv));function Kv(e){if(e===void 0||e.length===0||e[0]==="0")return!1;for(let t of e)if(t<"0"||t>"9")return!1;return!0}function sM(e){let[t,r,n]=e.split("-");if(t===void 0||r===void 0||n!==void 0)return!1;if(!Gv(t))return!1;let[o,i,s,a]=r.split(".");return o==="dev"&&a===void 0&&Kv(i)&&Kv(s)}var Jv=Q.pipe(jt(sM)),aM=Ke(Wh,Jv);var Vh=F("browser_use","computer_use","frontend","security","sites"),cM=F("browser_use","computer_use","sites"),lM=F("installed","disabled","missing","uncertain"),uM=F("healthy","missing","disabled","uncertain"),pM=Object.freeze(["openai-curated","openai-curated-remote"]),dM=Object.freeze(["build-web-apps","codex-security"]),fM=Object.freeze(["browser","computer-use","sites"]);var fn=Object.freeze({coding:!0,computer_use:!1,browser_use:!0,sites:!0,frontend:!0,security:!0}),Xn=Object.freeze({frontend:Object.freeze([{skillId:"build-web-apps:frontend-app-builder",appliesWhen:"a new visually-driven UI or meaningful redesign"},{skillId:"build-web-apps:frontend-testing-debugging",appliesWhen:"a rendered UI or interaction defect"},{skillId:"build-web-apps:react-best-practices",appliesWhen:"a relevant React or Next implementation or review"}]),security:Object.freeze([]),computer_use:Object.freeze([]),browser_use:Object.freeze([]),sites:Object.freeze([])}),mM=Xn.frontend,hM={frontend:{name:"frontend",pluginIds:["build-web-apps@openai-curated"],defaultSelected:fn.frontend,semanticSkillIds:Object.freeze(Xn.frontend.map(({skillId:e})=>e)),applicability:Xn.frontend,ownership:"shared-preserve"},security:{name:"security",pluginIds:["codex-security@openai-curated"],defaultSelected:fn.security,semanticSkillIds:["codex-security:security-scan","codex-security:security-diff-scan","codex-security:threat-model"],applicability:Xn.security,ownership:"shared-preserve"},computer_use:{name:"computer_use",pluginIds:["computer-use@openai-bundled"],defaultSelected:fn.computer_use,migrationKey:"computer_use",semanticSkillIds:["computer-use:computer-use"],applicability:Xn.computer_use,ownership:"shared-preserve"},browser_use:{name:"browser_use",pluginIds:[],defaultSelected:fn.browser_use,migrationKey:"browser_use",semanticSkillIds:[],applicability:Xn.browser_use,ownership:"shared-preserve"},sites:{name:"sites",pluginIds:["sites@openai-bundled"],defaultSelected:fn.sites,migrationKey:"sites",semanticSkillIds:[],applicability:Xn.sites,ownership:"shared-preserve"}},Kh=Object.freeze(hM),gM=Object.freeze(["browser_use","computer_use","sites"]),yM=Object.freeze(["frontend","security"]),xM=Object.freeze([...Kh.frontend.pluginIds,...Kh.security.pluginIds]),SM=Object.freeze(["writing-instructions","babysit-ci","dev-server","visual-loop"]),bM=Object.freeze({browser_use:fn.browser_use,computer_use:fn.computer_use,sites:fn.sites});var Qv=F("local.repository.edit","local.repository.check","local.repository.lint","local.repository.format","local.repository.commit","external.read","specialist.dispatch","vcs.server.mutation","vcs.server.ci-trigger","unknown.effect"),_M=U({identifier:Qv,label:Q,requiresRootApproval:ye});function Fr(e){return U({identifier:F(e),label:Q,requiresRootApproval:ye})}var wM=U({localRepositoryEdit:Fr("local.repository.edit"),localRepositoryCheck:Fr("local.repository.check"),localRepositoryLint:Fr("local.repository.lint"),localRepositoryFormat:Fr("local.repository.format"),localRepositoryCommit:Fr("local.repository.commit"),externalRead:Fr("external.read"),specialistDispatch:Fr("specialist.dispatch"),versionControlServerMutation:Fr("vcs.server.mutation"),versionControlServerCiTrigger:Fr("vcs.server.ci-trigger"),unknownEffect:Fr("unknown.effect")}),zh={localRepositoryEdit:{identifier:"local.repository.edit",label:"local repository edit",requiresRootApproval:!1},localRepositoryCheck:{identifier:"local.repository.check",label:"local repository check",requiresRootApproval:!1},localRepositoryLint:{identifier:"local.repository.lint",label:"local repository lint",requiresRootApproval:!1},localRepositoryFormat:{identifier:"local.repository.format",label:"local repository format",requiresRootApproval:!1},localRepositoryCommit:{identifier:"local.repository.commit",label:"local repository commit",requiresRootApproval:!1},externalRead:{identifier:"external.read",label:"external read",requiresRootApproval:!1},specialistDispatch:{identifier:"specialist.dispatch",label:"specialist dispatch",requiresRootApproval:!1},versionControlServerMutation:{identifier:"vcs.server.mutation",label:"version-control-server mutation",requiresRootApproval:!0},versionControlServerCiTrigger:{identifier:"vcs.server.ci-trigger",label:"version-control-server CI triggering",requiresRootApproval:!0},unknownEffect:{identifier:"unknown.effect",label:"unclassified effect",requiresRootApproval:!0}};br(zh);var EM=F("never","root"),Xv=Object.values(zh);function Yv(e){let t=e.map((n)=>n.label),r=t.at(-1);if(r===void 0)return"";if(t.length===1)return r;return`${t.slice(0,-1).join(", ")}, and ${r}`}function Zv(e){return e.length===0?e:`${e[0]?.toUpperCase()??""}${e.slice(1)}`}var OM=Xv.filter((e)=>!e.requiresRootApproval),vM=Xv.filter((e)=>e.requiresRootApproval),AM=Object.freeze({noRootApproval:`${Zv(Yv(OM))} actions do not require Root approval.`,rootApproval:`${Zv(Yv(vM))} require Root approval.`});var yr=Q.pipe(Ht(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),Gh=Q.pipe(Ht(/^[0-9a-f]{64}$/u)),YW=yr.pipe($a("RunId")),ZW=yr.pipe($a("ProjectId")),QW=yr.pipe($a("TrustId")),XW=Gh.pipe($a("Sha256Digest"));var TM=U({run_id:yr,objective_lineage:yr,parent_run_id:N(Ke(yr,pn))}),IM=U({project_id:yr,trust_id:yr,trust_digest:Gh}),RM=U({project_id:yr,project_digest:Gh}),kM=Q.pipe(Ht(/^state-[0-9]+\.[0-9]+$/u));var Ku=F("low","default","high"),nA=F("go","Go","plus-low","plus","plus-high","pro-5x","pro-20x"),CM=Ke(Ku,nA);var oA=F("standard","fast","fast-all"),PM=F("low","medium","high","xhigh","max"),iA="Satisfy the complete requested outcome correctly, elegantly, and mergeably; never weaken or reinterpret it to shrink the patch. Then make the smallest coherent patch within the authorized boundary. Prefer simple, cohesive, idiomatic solutions with appropriate abstraction and minimal accidental complexity. Avoid unrelated code, prose, configuration, documentation, instructions, tests, restructuring, formatting churn, files, and operations. Preserve unrelated work; return material scope expansion to Root.",Bu="Treat unnecessary text, headings, subheadings, typography hierarchy, cards, pills, badges, decorative containers, labels, microcopy, repeated information, and grouping without information or interaction value as design defects. Use these primitives when they materially improve hierarchy, comprehension, composition, interaction, or content. Every visible item must be necessary or usefully complementary to the content and design.",mn="Do not modify repository source or the implementation under validation; observation, analysis, and proof artifacts only.";var NM=F("none"),sA=Object.freeze(["implementation","review","validation","integration","vcs"]),FM=F("read-only","workspace-write"),hn=[{role:"Explorer",tasks:[{name:"map",description:"Bounded repository structure mapping specialist.",instruction:`Map the assigned repository area: locate its relevant packages, entry points, ownership boundaries, and nearby tests or docs. Return a compact path map and identify where a follow-up lookup or trace should start; do not trace runtime behavior or resolve an unrelated fact. ${mn}`,permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{name:"lookup",description:"Repository fact lookup specialist.",instruction:`Find the specific requested repository fact and cite its exact path or symbol; keep the search narrower than a structure map or execution trace. ${mn}`,permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{name:"trace",description:"Repository execution and reference tracing specialist.",instruction:`Follow the assigned execution or reference path across callers, boundaries, and tests; explain the evidence-backed flow and stop at the assigned boundary. ${mn}`,permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}}],capability:"repository-read",authority:"Read only the delegated Assignment repository scope; Git/VCS writes, Intent lifecycle, and material decisions remain Root-only.",evidence:"Return exact paths, symbols, callers, tests, and constraints.",completion:"Account for every in-scope caller and constraint.",permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{role:"Librarian",tasks:[{name:"lookup",description:"Authoritative external fact lookup specialist.",instruction:`Answer the specific external fact with its current authoritative source. ${mn}`,permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{name:"research",description:"Current authoritative-source research specialist.",instruction:`Compare and synthesize the assigned current sources with citations, noting conflicts and uncertainty. ${mn}`,permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}}],capability:"current-research",authority:"Research only the delegated Assignment current sources without repository mutation; Git/VCS writes, Intent lifecycle, and material decisions remain Root-only.",evidence:"Return sourced facts, dates, and explicit uncertainty.",completion:"Resolve the assigned external fact or report the exact evidence gap.",permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{role:"Worker",tasks:[{name:"mechanical",description:"Deterministic bounded-edit specialist.",instruction:"Apply the exact already-decided transformation within the assigned files and verify it.",permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}},{name:"implementation",description:"Bounded behavior implementation specialist.",instruction:"Design and implement the assigned behavior within its bounded seam, then verify the changed behavior.",permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}},{name:"visual",description:"Rendered visual implementation and interaction specialist.",instruction:`Produce mergeable visual implementation within the Assignment, including frontend, 3D, browser-driven UI, and interactive visualization. Inspect the actual rendered and interacted-with result against acceptance criteria and references; iterate on material discrepancies in visual quality, UI, UX, accessibility, responsiveness, interaction, task adherence, and reference adherence. Use the projected skills appropriate to this visual work. Return changed paths and observable rendered/interaction evidence for independent Reviewer.visual review. ${Bu}`,permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}},{name:"integration",description:"Decided seam integration specialist.",instruction:"Connect already-decided component seams, resolve interface mismatches within the assigned boundary, and verify their combined behavior.",permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}},{name:"operations",description:"Exact-ref or SHA terminal operations observer.",instruction:`Use babysit-ci to observe the assigned CI or release gate for the Root-supplied exact ref or SHA until terminal; report the matching result and failure evidence. ${mn}`,permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{name:"validation",description:"Independent local behavioral validation specialist.",instruction:`Independently exercise the assigned local behavior with the smallest relevant checks, classify failures, and report reproducible evidence; generated proof state is allowed, but do not repair the implementation or substitute for code review. ${mn}`,permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!1}},{name:"debugging",description:"Reproducible bounded defect-repair specialist.",instruction:"Use the debugging skill to repair the assigned defect within its bounded seam.",permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}}],capability:"task-scoped-assignment",authority:"Concrete task permissions govern observation, proof writes, or source repair within the delegated Assignment; no role-level source-mutation authority is granted. Intent lifecycle, Git/VCS writes, and material choices remain Root-only.",evidence:"Return changed files, verification results, and remaining risk.",completion:"Finish the delegated Assignment with proportional proof or an exact blocker and return a compact structured outcome.",permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{role:"Reviewer",tasks:[{name:"code",description:"Adversarial implemented-code review specialist.",instruction:"Review and repair the implemented code to a fixed point. Batch relevant evidence, then follow up on concrete uncertainty. Check correctness, safety, compatibility, test quality, generated-artifact hygiene, and the canonical patch-quality rule.",permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}},{name:"visual",description:"Independent rendered visual, UI, UX, and interaction review specialist.",instruction:`Independently inspect the implementation and actual rendered/interacted-with result against acceptance criteria and references. Review visual quality, UI, UX, accessibility, responsiveness, interactions, task adherence, and reference adherence. Do not implement repairs. Return concrete reproducible discrepancies or sufficient acceptance evidence to Root for its final independent visual pass. ${Bu} ${mn}`,permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!1}},{name:"artifact",description:"Adversarial produced-artifact review specialist.",instruction:"Inspect the assigned produced artifact against its requested content, usability, and delivery constraints; repair concrete defects within the artifact boundary and repeat inspection until no actionable findings remain.",permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}}],capability:"task-scoped-review",authority:"Concrete task permissions govern observational review or bounded repair within the delegated Assignment; no role-level source-mutation authority is granted. Intent lifecycle, Git/VCS writes, and material choices remain Root-only.",evidence:"Return findings, repaired paths, verification, and residual risk.",completion:"Reach a fixed point or report each reproducible blocker as a compact structured outcome.",permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}}];br(hn);var aA=new Map(hn.map((e)=>[e.role,e])),MM=new Set(hn.map((e)=>e.role)),Jh=hn.flatMap((e)=>e.tasks.map((t)=>`${e.role}:${t.name}`)),LM=new Set(Jh),cA=Jh.map((e)=>e.replace(":",".")),lA=new Set(cA);function uA(e){return typeof e==="string"&&MM.has(e)}function DM(e){if(typeof e!=="object"||e===null||!("role"in e)||!("task"in e))return!1;let{role:t,task:r}=e;if(!uA(t)||typeof r!=="string")return!1;return aA.get(t)?.tasks.some((n)=>n.name===r)===!0}function Vu(e,t){return typeof t==="string"&&aA.get(e)?.tasks.some((r)=>r.name===t)===!0}function pA(e){return typeof e==="string"&&LM.has(e)}var Yh=Ut(uA),qM=Ut((e)=>Vu("Explorer",e)),UM=Ut((e)=>Vu("Librarian",e)),jM=Ut((e)=>Vu("Worker",e)),HM=Ut((e)=>Vu("Reviewer",e)),Ba=Ut(DM),Wa=Object.freeze(Jh.filter((e)=>pA(e))),dA=Ut(pA),fA=Object.freeze(cA.filter((e)=>lA.has(e))),$M=Ut((e)=>typeof e==="string"&&lA.has(e)),mA=Object.freeze(["worker","explorer","reviewer","librarian"]);var hA=U({profile:Ku,service_tier:N(oA)}),Wu=Object.freeze(["user_interaction","intent","material_decisions","orchestration_lifecycle","integration_acceptance","completion","git_vcs","external_effects","visual_judgment","dev_server"]),BM=F(...Wu),WM=F("delegated","root_direct","unavailable"),KM=F(...Wu),Zh=F("used","no_coverage","unavailable","auth_or_quota_failure","source_conflict"),gA=Object.freeze({rule:"Prove success with the smallest meaningful validation proportionate to changed behavior, scope, risk, uncertainty, and acceptance criteria; preserve required repository gates. Reuse already-conclusive evidence. Do not manufacture proof work, add redundant tests, or test unrelated surfaces merely to increase confidence. Broaden or repeat validation only after relevant changes, failures, elevated risk, or unresolved material concerns. Avoid tests that mirror implementation for reversible low-impact changes.",avoidImplementationMirrorTestsForLowImpactReversibleChanges:!0,broadenOrRepeatOnlyAfter:Object.freeze(["source_change","proof_failure","unresolved_material_concern","change_breadth_or_risk"]),mandatoryRepositoryGatesRemainRequired:!0,reviewerCodeRemainsRequired:!0}),VM=Object.freeze({requiredFor:Object.freeze(["library","framework","sdk","api","cli","cloud_service"]),resolveIdentityBeforeQuery:!0,queryNarrowly:!0,evidenceStates:Object.freeze(["used","no_coverage","unavailable","auth_or_quota_failure","source_conflict"]),webFallbackEvidenceStates:Object.freeze(["no_coverage","unavailable","auth_or_quota_failure"]),missingRequiredVersionAllowsFallback:!0,successfulEvidenceAloneAllowsFallback:!1,checkFirstPartyDocsBeforeFallbackForConflict:!0,unresolvedConflictAfterFirstPartyAllowsFallback:!0,materialDecisionsRemainRootOwned:!0}),zM=/\b(?:libraries?|frameworks?|sdks?|apis?|clis?|cloud[ _-]?services?|packages?|dependencies?|technical|documentation|docs?|context7)\b/iu,GM=/\b(?:historical|history|legacy|archived?|past)\b/iu;function Qh(e){if(e.role!=="Librarian"||e.task!=="lookup"&&e.task!=="research")return!1;let t=[e.objective,...e.scope,...e.constraints,...e.exclusions,...e.dependencies,...e.acceptanceCriteria].join(" ");return zM.test(t)&&!GM.test(t)}var JM=Object.freeze({repositoryAndUserRequirementsPrecedePluginDefaults:!0,specialistsOwnImplementationAndInteractionProof:!0,specialistVisualImplementationInstruction:"Assign material rendered implementation to Worker.visual, independent rendered review to Reviewer.visual, then perform Root's independent visual pass. Root remains final visual authority and actively looks for issues both specialists missed. Dispatch only bounded repairs for material discrepancies, repeat only affected review and judgment, and reuse unaffected evidence.",rootOwnsVisualJudgment:!0,designJudgment:Bu,rootOwnsSharedDevServer:!0,rootAcceptsTerminalVisualEvidence:!0,sourceChangesInvalidateRenderEvidence:!0,specialistReportsIncludeObservableRenderedEvidence:!0,logicOnlyChangesRequireVisualAcceptance:!1,fixedPoint:Object.freeze(["worker_visual_implements_and_inspects","reviewer_visual_independently_reviews","root_independently_judges","root_assigns_bounded_visual_repair","repeat_affected_review_and_judgment"])}),YM=Object.freeze({interactiveCapabilitiesRemainSpecialistOwned:!0,rootMayInspectForVisualJudgment:!0,credentialEntryAndSubmissionRemainUserOwned:!0,specialistsMustNeverHandleCredentials:!0,missingAuthorizedPathIsCapabilityBlocker:!0}),ZM=Object.freeze({threatModelForMaterialTrustBoundaryChanges:!0,securityDiffScanRequiredForSecuritySensitiveDiffs:!0,fullScanOnlyForAuditNewExposedSurfaceOrSystemicConcern:!0,validateSupportedFindingsBeforeBlocking:!0,introducedOrWorsenedValidatedVulnerabilityBlocksVcs:!0,preExistingUnrelatedFindingsDoNotExpandScope:!0,securityEditsInvalidateCodeReview:!0,securitySensitiveCodeReviewEditsInvalidateSecurityReview:!0,materialDecisionsRemainRootOwned:!0}),QM=Object.freeze({requiresDelegation:!0,explicitUserDirectExecutionOverridesDelegation:!0,assignmentStartAndDispatchPrecedeDelegableExecution:!0,trivialWorkRequiresDelegation:!0,preparatoryAndExploratoryWorkRequiresDelegation:!0,genericDirectWorkFallback:!1,concreteSpecialistDispatchRequired:!0,registeredSpecialistAgentTypes:fA,roleFamiliesAreLabelsOnly:!0,forbiddenGenericAgentTypes:mA,missingConcreteRouteIsBlocker:!0,delegableActions:Object.freeze(["repository_discovery","file_source_test_doc_inspection","fact_finding","research","implementation","debugging","testing","validation","frontend_work","security_work","browser_use","computer_use","review","ci_release_observation"]),directExecutionExceptions:Wu,rootOwnedAuthority:Wu,requestUserInputGates:Object.freeze(["missing_authorization_for_consequential_effect","ambiguity_or_missing_material_input"]),surgicalMutationRule:iA,phaseOrder:sA,phaseGates:Object.freeze({implementedScopeStableBeforeReview:!0,reviewerCodeAndWorkerValidationMayOverlapOnNonConflictingScopes:!0,currentValidationBeforeRootIntegration:!0,rootIntegrationBeforeVcs:!0}),initialDispatch:Object.freeze({independentAssignments:!0,substantiveIndependentConcurrency:!0,routinePostdispatchSteering:!1,collectiveWaits:!0,evidenceReusedAcrossPhases:!0}),atomicLifecycleTransitions:Object.freeze({relatedAssignmentAndIntentWrites:!0,oneLockOneCommit:!0,staleRevisionChecksRetained:!0,repositoryDriftChecksRetained:!0}),supersession:Object.freeze({explicitOnly:!0,unfinishedPredecessorOnly:!0,validatedRelatedReplacement:!0,reasonAndProvenanceRequired:!0,supersededExcludedFromCompletionBlockers:!0}),specialistTerminalResultPersistence:Object.freeze({ownActiveInvocationCapabilityRequired:!0,ownAssignmentOnly:!0,terminalOutcomeOnly:!0,rootOwnedIntentLifecycle:!0,rootOwnedAcceptanceReviewAndCiGates:!0,rootOwnedVcsAndExternalEffects:!0,sharedRuntimeCallerIdentityUnavailable:!0,legacyResultCompatibilityPreserved:!0}),normalSpawnForkTurns:"none",normalSpawnRequiresExplicitForkTurns:!0,normalSpawnUsesConcreteRegisteredAgentType:!0,semanticStateBoundary:"Use holycodex-agent semantic operations for Intent and Assignment state. Do not edit TOON state. Resume the current Intent or create one for new work; record verification, acceptance, and readiness, and complete only when holycodex-agent confirms every completion predicate. There is no HolyCodex planning workflow or automatic Plan approval gate; preserve existing Plan state when resuming work that uses it.",routeConfigurationBeforeDispatch:"Use the active profile's registered Role.task configuration, including model, effort, tier, permissions, shell, and capabilities. Verify the registration once per configuration generation; recheck after configuration changes or when resuming an unverified thread. Pass fields required by the dispatch tool; registered settings need not be copied into Assignment prose. Never inherit Root settings, substitute a generic route, or override the selected route. Report a missing or incompatible route before dispatch.",assignmentInvocationLifecycle:"Before each specialist spawn, persist the bounded Assignment and call holycodex-agent assignment start. Keep the returned active_invocation_id and capability in Root; give the specialist only the bounded Assignment, never the capability. After a terminal report, record the result with that invocation ID and capability. Recover an interrupted invocation only after confirming it stopped, using the matching Root-held capability; never share that capability.",assignmentContextIsTaskSpecificOnly:!0,configuredRouteModelAndEffortPreserved:!0,normalProgressMessages:!1,normalHeartbeatMessages:!1,normalIntermediateEvidence:!1,userUpdatesUsefulOrImportantOnly:!0,routinePerToolOrSubagentNarrationForbidden:!0,routineStatusOnlyChatterForbidden:!0,fixedCadenceUserUpdatesForbidden:!0,materialUserUpdateKinds:Object.freeze(["significant_findings_or_decisions","consequential_blockers_or_input_needs","release_milestones"]),outOfBoundaryRequiresNewAssignment:!0,routineWaitTool:"collaboration.wait_agent",routineWaitMaximumTimeoutMs:600000,routineWaitUsesMaximumRuntimeTimeout:!0,earlySpecialistCompletionWakesWait:!0,collectiveMailboxIncludesRelevantAgents:!0,idleTimeoutRepeatsMaximumWait:!0,shortRoutineWaitsForbidden:!0,longestPracticalEventWait:!0,busyPollingForbidden:!0,statusOnlyCoordinationLoopsForbidden:!0,batchIndependentLifecycleActions:!0,releaseLeavesAfterAcceptedOutcome:!0,specialistOutcomes:Object.freeze(["completed","blocked","needs_root_input","failed"]),evidenceFirstConciseStructuredReports:!0,specialistReportFields:Object.freeze(["changed paths","checks","observable evidence","blockers","Root decisions needed","remaining risk"]),rootLargeReadsOnlyFor:Object.freeze(["material decisions","conflicts","failures","findings"]),stableFactsReused:!0,duplicatePolicyForbidden:!0,stableBoundedComponentScopesAreCanonical:!0,lifecycleWorkerOwnsDeterministicApi:!0,materialDecisionsRemainRootOwned:!0,lifecycleRemainsRootOwned:!0,integrationAndCompletionRemainRootOwned:!0,routineSafeReversibleInScopeDecisionsProceedAutonomously:!0,userInstructionsOverrideSkillGuidelinesExceptHardInvariants:!0,authorizedWorkContinuesThroughRequestedTerminalState:!0,testingPolicy:gA,codeReviewRequiredForImplementation:!0,codeReviewRequiredBeforeVcs:!0,externalVerificationMustBeTerminal:!0,postVcsFlow:"discover_topology_observe_repair_repeat"});function ct(e,t){return new _t("invalid_canonical_value",`Cannot canonicalize ${e}: ${t}.`,{path:e,reason:t})}function Xh(e,t,r){if(e===null)return"null";switch(typeof e){case"string":{let n=JSON.stringify(e);if(n===void 0)throw ct(t,"invalid string");return n}case"boolean":return e?"true":"false";case"number":{if(!Number.isFinite(e))throw ct(t,"non-finite number");let n=JSON.stringify(e);if(n===void 0)throw ct(t,"invalid number");return n}case"undefined":throw ct(t,"undefined is not JSON");case"bigint":throw ct(t,"bigint is not JSON");case"function":throw ct(t,"function is not JSON");case"symbol":throw ct(t,"symbol is not JSON");case"object":break}if(r.has(e))throw ct(t,"cyclic value");r.add(e);try{if(Array.isArray(e)){for(let a of Object.getOwnPropertySymbols(e))throw ct(t,`symbol property ${String(a)}`);let i=e,s=[];for(let a=0;a<i.length;a+=1){let c=Object.getOwnPropertyDescriptor(i,String(a));if(!c||!c.enumerable||!("value"in c))throw ct(`${t}[${a}]`,"sparse or accessor array item");s.push(Xh(c.value,`${t}[${a}]`,r))}for(let a of Object.getOwnPropertyNames(i)){if(a==="length")continue;let c=Number(a);if(!Number.isInteger(c)||c<0||c>=i.length||String(c)!==a)throw ct(t,`non-index array property ${a}`);let l=Object.getOwnPropertyDescriptor(i,a);if(!l||!l.enumerable||!("value"in l))throw ct(`${t}[${c}]`,"non-enumerable or accessor array item")}return`[${s.join(",")}]`}let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw ct(t,"only plain objects are supported");for(let i of Object.getOwnPropertySymbols(e))throw ct(t,`symbol property ${String(i)}`);for(let i of Object.getOwnPropertyNames(e)){let s=Object.getOwnPropertyDescriptor(e,i);if(!s||!s.enumerable||!("value"in s))throw ct(`${t}.${i}`,"non-enumerable or accessor property")}let o=[];for(let i of Object.keys(e).sort()){let s=Object.getOwnPropertyDescriptor(e,i);if(!s||!("value"in s))throw ct(`${t}.${i}`,"accessor property");o.push(`${JSON.stringify(i)}:${Xh(s.value,`${t}.${i}`,r)}`)}return`{${o.join(",")}}`}finally{r.delete(e)}}function eg(e){return Xh(e,"$",new Set)}var yA=F("blocked","completed","failed","partial"),xA=Ke(F("high","max","xhigh"),pn);function SA(e){try{return eg(e)!==void 0}catch{return!1}}var bA=Ut((e)=>SA(e)),eL=Ut((e)=>hp(e)&&!Array.isArray(e)&&SA(e)),tL=U({blocked:ye,changed_files:z(Q),confidence:Hu,context_owner:Ke(Q,pn),material_findings:z(Q),needs_more_context:ye,needs_root_decision:ye,needs_verification:ye,relevant_files:z(Q),remaining_risk:z(Q),reuse_recommended:ye,status:yA,suggested_followup:Ke(Q,pn),suggested_luna_effort:xA,suggested_specialist:Ke(Yh,pn),verification:z(Q),verification_passed:ye}),tg="holycodex-specialist-outcome-2",Ye=Q.pipe($v(1)),Xi=U({state:Zh,evidence:z(Ye).pipe(Nr(1)),library:N(Ye),version:N(Ye)}),Ka={protocol_version:F(tg),route:Ba,evidence:z(Ye),context7:N(Xi)},rL=U(Ka),nL=U({...Ka,status:F("completed"),summary:Ye}),oL=U({...Ka,status:F("blocked"),reason:Ye,needs_root_decision:ye}),iL=U({...Ka,status:F("partial"),summary:Ye,completed:z(Ye),remaining:z(Ye),needs_root_decision:ye}),sL=U({...Ka,status:F("failed"),error:Ye}),aL=Ke(nL,oL,iL,sL),zu={protocol_version:F(tg),capability:Vh,route:Ke(Ba,pn),evidence:z(Ye),context7:N(Xi),data:bA},cL=U({...zu,status:F("completed"),summary:Ye}),lL=U({...zu,status:F("blocked"),reason:Ye,needs_root_decision:ye}),uL=U({...zu,status:F("partial"),summary:Ye,completed:z(Ye),remaining:z(Ye),needs_root_decision:ye}),pL=U({...zu,status:F("failed"),error:Ye}),dL=Ke(cL,lL,uL,pL);var _A=z(Q),wA=Q.pipe(Ht(/^[a-z][a-z0-9-]*(?: [a-z][a-z0-9-]*)*$/u)),EA=F(mp),fL=U({code:yr,message:Q,details:eL}),OA=U({schema_version:EA,ok:F(!0),command:wA,data:bA,warnings:_A}),vA=U({schema_version:EA,ok:F(!1),command:wA,error:fL,warnings:_A}),mL=Ke(OA,vA);var Gu="gpt-6.1-sol",Va="gpt-6-luna";function hL(e,t,r){return{key:`${e}:${t}`,role:e,task:t,model:Va,effort:r}}var gL=new Set(Wa),ng=[{profile:"low",rationale:"Cheapest practical configuration without dropping Luna below its useful agentic threshold.",efforts:{"Explorer:map":"medium","Explorer:lookup":"medium","Explorer:trace":"high","Librarian:lookup":"medium","Librarian:research":"high","Worker:mechanical":"medium","Worker:implementation":"high","Worker:integration":"high","Worker:operations":"medium","Worker:validation":"medium","Worker:debugging":"high","Worker:visual":"high","Reviewer:code":"high","Reviewer:artifact":"high","Reviewer:visual":"high"}},{profile:"default",rationale:"Best general whole-task cost/performance: Sol medium orchestration and Luna medium/high execution.",efforts:{"Explorer:map":"medium","Explorer:lookup":"medium","Explorer:trace":"high","Librarian:lookup":"medium","Librarian:research":"high","Worker:mechanical":"medium","Worker:implementation":"high","Worker:integration":"high","Worker:operations":"medium","Worker:validation":"high","Worker:debugging":"high","Worker:visual":"high","Reviewer:code":"high","Reviewer:artifact":"high","Reviewer:visual":"high"}},{profile:"high",rationale:"Highest practical reliability without indiscriminate reasoning waste; reserve Luna max for difficult long-horizon work.",efforts:{"Explorer:map":"high","Explorer:lookup":"medium","Explorer:trace":"high","Librarian:lookup":"high","Librarian:research":"max","Worker:mechanical":"high","Worker:implementation":"max","Worker:integration":"max","Worker:operations":"high","Worker:validation":"high","Worker:debugging":"max","Worker:visual":"max","Reviewer:code":"high","Reviewer:artifact":"max","Reviewer:visual":"high"}}];br(ng);var yL=new Map(ng.map((e)=>[e.profile,e]));function xL(e){let t=yL.get(e);if(t===void 0)throw new _t("catalog_invalid","A profile has no route effort policy.",{profile:e});return hn.flatMap((r)=>r.tasks.map((n)=>{let o=`${r.role}:${n.name}`,i=t.efforts[o];if(i===void 0)throw new _t("catalog_invalid","A route effort policy is incomplete.",{profile:e,route:o});return hL(r.role,n.name,i)}))}function rg(e){return{name:e.name,root:{model:e.rootModel,effort:e.rootEffort},specialistModel:Va,defaultServiceTier:"standard",routes:xL(e.name)}}var og=[rg({name:"low",rootModel:Gu,rootEffort:"low"}),rg({name:"default",rootModel:Gu,rootEffort:"medium"}),rg({name:"high",rootModel:Gu,rootEffort:"medium"})];function SL(e){let t=["low","default","high"];if(e.length!==t.length)throw new _t("catalog_invalid","The profile catalog has an invalid size.");for(let r=0;r<t.length;r+=1){let n=e[r],o=t[r];if(!n||n.name!==o)throw new _t("catalog_invalid","The profile catalog order is invalid.",{index:r});let i=Gu,s=o==="low"?"low":"medium";if(n.root.model!==i||n.root.effort!==s||n.specialistModel!==Va)throw new _t("catalog_invalid","A profile has an invalid model route.",{profile:n.name});if(n.routes.length!==Wa.length)throw new _t("catalog_invalid","A profile is incomplete.",{profile:n.name});let a=new Set;for(let c of n.routes){if(a.has(c.key)||!gL.has(c.key)||c.model!==Va||`${c.role}:${c.task}`!==c.key)throw new _t("catalog_invalid","A profile contains an invalid route.",{profile:n.name});a.add(c.key)}if(a.size!==Wa.length)throw new _t("catalog_invalid","A profile is missing a specialist route.",{profile:n.name})}}SL(og);br(og);var AA=og,bL=new Map,_L=new Map;for(let e of AA){bL.set(e.name,e);let t=new Map;for(let r of e.routes)t.set(r.key,r);_L.set(e.name,t)}import{execFile as wL}from"child_process";import{createHash as EL,randomBytes as OL}from"crypto";import{lstat as Qt,mkdir as rs,open as tp,readFile as dg,readdir as xn,realpath as vL,rename as AL,rm as Xo,stat as TL}from"fs/promises";import{basename as ig,dirname as ei,isAbsolute as IL,join as _,relative as pg,resolve as ns}from"path";import{promisify as RL}from"util";var rp="holycodex-intent-1",fg="holycodex-plan-1",mg="holycodex-assignment-1",to="toon-4",j=Q.pipe(jt((e)=>e.trim().length>0)),Ze=Q.pipe(Ht(/^[a-z0-9][a-z0-9-]{0,95}$/u)),np=Q.pipe(Ht(/^[a-f0-9]{64}$/u)),MA=Q.pipe(Ht(/^[a-f0-9]{40}$/u)),os=$u.pipe(Wv(1)),Xt=Q.pipe(jt((e)=>!Number.isNaN(Date.parse(e)))),Ie=z(j),kL=U({pid:$u.pipe(Bv(0)),token:j}),CL=120000,PL=4294967295,op=U({role:F("Explorer","Librarian","Worker","Reviewer"),task:j}).pipe(jt((e)=>hn.some((t)=>t.role===e.role&&t.tasks.some((r)=>r.name===e.task)))),ri=U({kind:F("changed_path","check","repository_fact","ci","behavior","uncertainty"),value:j,result:N(F("passed","failed","observed","unknown"))}),hg=U({root:j,git_common_dir:j,initial_head:j,expected_head:j,expected_changes:Ie,expected_status_digest:np,integrated_commit:N(MA),updated_at:Xt}),is=F("scoping","ready","executing","verifying","reviewing","blocked","needs_root_input","complete","abandoned"),NL=F("scoping","ready","executing","verifying","reviewing"),TA=U({required:ye,status:F("not_required","missing","passed","failed","accepted","rejected"),evidence:z(ri)}),ti=U({schema_version:F(rp),toon_compatibility:F(to),id:Ze,slug:Ze,title:j,goal:j,acceptance_criteria:Ie,state:is,revision:os,plan_required:ye,active_plan_revision:N(os),active_plan_digest:N(np),blockers:Ie,resume_state:N(NL),verification:TA,review:TA,acceptance_met:ye,root_readiness:ye,evidence:z(ri),baseline:hg,created_at:Xt,updated_at:Xt}),Ja=U({schema_version:F(fg),toon_compatibility:F(to),intent_id:Ze,revision:os,predecessor_digest:N(np),approach:j,scope:Ie,exclusions:Ie,assignments:Ie,dependencies:Ie,architecture:Ie,risks:Ie,assumptions:Ie,open_questions:Ie,verification:Ie,recovery:Ie,updated_at:Xt}),gg=F("completed","blocked","needs_root_input","failed"),LA=F("pending","executing","completed","blocked","needs_root_input","failed","superseded"),yg=U({id:Ze,outcome:gg,started_at:Xt,finished_at:Xt,summary:j,evidence:z(ri),context7:N(Xi),blocker:N(j),remaining_risk:Ie}),oo=np,xg={schema_version:F(mg),toon_compatibility:F(to),intent_id:Ze,id:Ze,objective:j,owner:Ke(op,U({role:F("Reviewer"),task:F("plan")})),scope:Ie,constraints:Ie,exclusions:Ie,dependencies:Ie,acceptance_criteria:Ie,status:LA,revision:os,invocations:z(yg),active_invocation_id:N(j),active_started_at:N(Xt),supersedes:N(Ze),superseded_by:N(Ze),supersession_reason:N(j),supersession_provenance:N(j),evidence:z(ri),blocker:N(j),remaining_risk:Ie,created_at:Xt,updated_at:Xt},Sg=U(xg),DA=U({...xg,capability:oo}),Ya=U({...xg,active_invocation_capability_verifier:N(oo),active_invocation_capability:N(oo)}),Ju=".holycodex-transaction.toon",qA="holycodex-work-state-transaction-1",IA=U({schema_version:F(qA),state:F("prepared","committed"),files:z(U({path:j,previous:Q,next:Q})).pipe(Nr(1))}),UA=U({schema_version:F("holycodex-intent-0"),id:Ze,slug:Ze,title:j,goal:j,acceptance_criteria:Ie,state:is,revision:os,baseline:hg,created_at:Xt,updated_at:Xt});class S extends Error{code;details;constructor(e,t,r={}){super(t);this.name="IntentStoreError",this.code=e,this.details=r}}var ip=U({title:j,goal:j,acceptanceCriteria:z(j).pipe(Nr(1)),planRequired:N(ye),verificationRequired:N(ye),reviewRequired:N(ye)}),jA=U({approach:j,scope:N(z(j)),exclusions:N(z(j)),assignments:N(z(j)),dependencies:N(z(j)),architecture:N(z(j)),risks:N(z(j)),assumptions:N(z(j)),openQuestions:N(z(j)),verification:N(z(j)),recovery:N(z(j))}),sp=U({id:N(j),objective:j,owner:op,scope:z(j).pipe(Nr(1)),constraints:N(z(j)),exclusions:N(z(j)),dependencies:N(z(j)),acceptanceCriteria:z(j).pipe(Nr(1))}),ap=U({scope:z(j).pipe(Nr(1))}),cp=U({scope:N(z(j).pipe(Nr(1)))}),lp=U({replacementId:Ze,replacementRevision:N(os),reason:j,provenance:j}),up=U({commit:MA}),Xa=U({invocationId:N(j),capability:N(oo),outcome:gg,startedAt:N(j),summary:j,scope:N(z(j).pipe(Nr(1))),evidence:N(z(ri)),context7:N(Xi),blocker:N(j),remainingRisk:N(z(j))}),FL=U({invocationId:j,startedAt:Xt,capability:oo,interruptionReason:j}),pp=U({evidence:N(z(ri)),verification:N(F("passed","failed")),review:N(F("accepted","rejected")),acceptanceMet:N(ye),rootReadiness:N(ye),clearBlockers:N(ye)}),ec=RL(wL);class dp{repositoryRoot;stateRoot;#e;async diagnose(e){await this.#a();let t=await xn(this.stateRoot).catch((m)=>{if(oe(m,"ENOENT"))throw new S("not_found","Intent was not found.",{reference:e});throw Se(m)}),r=[];for(let m of t.sort()){let x=_(this.stateRoot,m);if(!await Ga(x)||!await ts(_(x,"intent.toon")))continue;let D;try{D=await WL(_(x,"intent.toon"))}catch(k){if(Za(k)){if(m===e||k.code!=="not_found"&&await KL(_(x,"intent.toon"),e))throw k;continue}throw k}if([D.id,D.slug,m].includes(e))r.push({directory:x,intent:D})}if(r.length!==1)throw new S(r.length?"current_ambiguous":"not_found",r.length?"Intent reference is ambiguous.":"Intent was not found.",{reference:e});let{directory:n,intent:o}=r[0],i=[],s=(m,x,D)=>{i.push({code:m,subject:x,repair:D})},a=_(n,Ju);try{let m=await Qt(a);if(m.isSymbolicLink()||!m.isFile())s("transaction_journal_invalid","intent","Restore the transaction journal as a regular repository-local file.");else s("pending_transaction","intent","Recover the interrupted work-state transaction before relying on this diagnosis.")}catch(m){if(!oe(m,"ENOENT")&&!oe(m,"ENOTDIR"))throw Se(m)}let c=_(n,"plan.toon"),l,u=!1;try{l=await BL(c,Ja)}catch(m){if(!Za(m))throw m;u=!0,s("plan_unreadable","plan","Repair the canonical Plan record before continuing.")}if(l!==void 0){let m=xr(`${et(l)}
38
- `);if(l.intent_id!==o.id||o.active_plan_revision!==l.revision||o.active_plan_digest!==m)s("plan_provenance_mismatch","plan","Reconcile the canonical Plan and Intent provenance.")}else if(!u&&(o.active_plan_revision!==void 0||o.active_plan_digest!==void 0))s("stale_plan_reference","intent","Restore or reconcile the referenced Plan.");let d=_(n,"assignments"),f=[];try{if(await lg(d,!0))f=(await xn(d)).filter((m)=>m.endsWith(".toon")).sort()}catch(m){if(!Za(m))throw m;s("assignment_directory_invalid","assignments","Restore the Assignments directory as a real repository-local directory.")}let g=[];for(let m of f){let x;try{x=await Qo(_(d,m),Ya)}catch(D){if(!Za(D))throw D;s("assignment_unreadable",m,"Repair this Assignment record before continuing.");continue}if(x.intent_id!==o.id||m!==`${x.id}.toon`){s("assignment_identity_mismatch",m,"Reconcile the Assignment identity and path.");continue}g.push(x)}let y=new Map(g.map((m)=>[m.id,m]));for(let m of g){let x=`assignment:${m.id}`,D=m.active_invocation_id,k=D!==void 0,H=k||m.active_started_at!==void 0||m.active_invocation_capability!==void 0||m.active_invocation_capability_verifier!==void 0;if(m.status==="executing"&&!k)s("missing_active_invocation",x,"Reconcile the executing Assignment's invocation.");if(m.status!=="executing"&&H)s("orphaned_active_invocation",x,"Reconcile the active invocation and Assignment status.");if(k&&m.active_started_at===void 0)s("missing_invocation_start",x,"Reconcile the active invocation start time.");let T=new Set;for(let C of m.invocations){if(T.has(C.id))s("duplicate_invocation_id",x,"Reconcile duplicate invocation records.");T.add(C.id)}if(D!==void 0&&T.has(D))s("active_invocation_reused",x,"Reconcile the active invocation identity.");if(m.status==="superseded"&&m.superseded_by===void 0)s("missing_replacement",x,"Record or reconcile the replacement Assignment.");if(m.superseded_by!==void 0){let C=y.get(m.superseded_by);if(m.superseded_by===m.id||C?.supersedes!==m.id||m.status!=="superseded")s("stale_supersession",x,"Reconcile both ends of the supersession relation.");else if(m.supersession_reason===void 0||m.supersession_provenance===void 0||C.supersession_reason===void 0||C.supersession_provenance===void 0)s("supersession_metadata_missing",x,"Record the reason and provenance on both Assignments.");else if(m.supersession_reason!==C.supersession_reason||m.supersession_provenance!==C.supersession_provenance)s("supersession_metadata_mismatch",x,"Reconcile the reason and provenance on both Assignments.")}if(m.supersedes!==void 0&&(m.supersedes===m.id||y.get(m.supersedes)?.superseded_by!==m.id))s("stale_predecessor",x,"Reconcile the predecessor Assignment reference.");for(let C of m.dependencies)if(C===m.id)s("self_dependency",x,"Remove the Assignment's dependency on itself.");else if(C.startsWith("assignment-")&&!y.has(C))s("stale_dependency",x,`Reconcile missing dependency ${C}.`);else if(y.get(C)?.status==="superseded")s("superseded_dependency",x,`Reconcile dependency ${C} with its replacement Assignment.`);let I=m.invocations.at(-1);if(m.status==="completed"){if(I?.outcome!=="completed"||I.evidence.length===0&&I.context7===void 0)s("completion_evidence_missing",x,"Reconcile the completed invocation result and its evidence.")}else if(["blocked","needs_root_input","failed"].includes(m.status)&&I?.outcome!==m.status)s("assignment_result_mismatch",x,"Reconcile the status with its latest result.");if(["blocked","needs_root_input"].includes(m.status)&&m.blocker===void 0)s("assignment_blocker_missing",x,"Record the Assignment's current blocker.");if(m.status==="pending"&&m.invocations.length>0)s("pending_assignment_has_history",x,"Reconcile pending status with its results.");if(!["completed","superseded"].includes(m.status))s("assignment_unresolved",x,o.state==="abandoned"?"Treat as intentionally unfinished; create a new Intent if work resumes.":"Resume, repair, or explicitly supersede this Assignment.")}if(l!==void 0){for(let m of l.assignments)if(m.startsWith("assignment-")&&!y.has(m))s("stale_plan_assignment","plan",`Reconcile missing Assignment ${m}.`);else if(y.get(m)?.status==="superseded")s("superseded_plan_assignment","plan",`Reconcile Plan reference ${m} with its replacement Assignment.`)}let O=VL(g);for(let m of O)s("dependency_cycle",`assignment:${m}`,"Remove the cyclic Assignment dependency before continuing.");if(o.state==="complete"&&g.some((m)=>!["completed","superseded"].includes(m.status)))s("terminal_intent_with_unresolved_work","intent","Reconcile terminal state and unfinished Assignments.");if(o.state==="complete"&&g.length===0)s("assignment_required","intent","Reconcile the required Assignment record.");if(["complete","abandoned"].includes(o.state)&&o.blockers.length>0)s("terminal_intent_with_blockers","intent","Reconcile terminal state and blockers.");if(["blocked","needs_root_input"].includes(o.state)){if(o.blockers.length===0)s("blocked_without_reason","intent","Record the blocker or resume the previous state.");if(o.resume_state===void 0)s("resume_state_missing","intent","Record the state to resume after the blocker clears.")}else if(o.resume_state!==void 0)s("stale_resume_state","intent","Clear the stale blocked-state resume target.");if(o.state==="complete"){if(o.verification.required&&(o.verification.status!=="passed"||!kA(o.verification.evidence)))s("verification_evidence_missing","intent","Reconcile required verification evidence.");if(o.review.required&&(o.review.status!=="accepted"||o.review.evidence.length===0))s("review_evidence_missing","intent","Reconcile required review evidence.");if(!o.acceptance_met||!o.root_readiness||o.evidence.length===0)s("completion_evidence_missing","intent","Reconcile acceptance and Root readiness evidence.")}try{await this.#o(o,g.filter((m)=>m.status==="executing").flatMap((m)=>m.scope))}catch(m){if(!(m instanceof S)||m.code!=="repository_drift")throw m;s("repository_drift","repository","Reconcile the recorded baseline with the current repository state.")}return i.sort((m,x)=>cg(m.subject,x.subject)||cg(m.code,x.code)||cg(m.repair,x.repair)),{intent_id:o.id,issues:i}}#s;constructor(e,t={}){this.repositoryRoot=ns(e),this.stateRoot=_(this.repositoryRoot,".holycodex"),this.#e=t.now??(()=>new Date),this.#s=t.repositorySnapshot??(()=>HA(this.repositoryRoot))}async recover(){if(await this.#a(),!await Zu(this.stateRoot))return[];return await Zo(_(this.stateRoot,".intent-store"),async()=>{let e=await this.#l(this.stateRoot),t=await this.#h();return[...e,...t].sort()})}async#l(e,t=!1){let r;try{r=t?await xn(e,{recursive:!0}):await xn(e)}catch(o){if(oe(o,"ENOENT"))return[];throw Se(o)}let n=[];for(let o of r){let i=ig(o);if(!i.startsWith(".holycodex-write-")||!i.endsWith(".tmp"))continue;let s=_(e,o);await no(s),await Xo(s,{force:!0}),n.push(pg(this.stateRoot,s).replaceAll("\\","/"))}return n.sort()}async#h(){let e;try{e=await xn(this.stateRoot)}catch(r){if(oe(r,"ENOENT"))return[];throw Se(r)}let t=[];for(let r of e){if(r===".intent-store")continue;let n=_(this.stateRoot,r);if(!await Ga(n))continue;await Zo(_(n,".intent-store"),async()=>{t.push(...await this.#u(n))})}return t.sort()}async#u(e){let t=[],r=_(e,Ju);if(await this.#d(e))t.push(pg(this.stateRoot,r).replaceAll("\\","/"));return t.push(...await this.#l(e,!0)),t}async#d(e){let t=_(e,Ju);await no(t);let r;try{r=await Qt(t)}catch(l){if(oe(l,"ENOENT"))return!1;throw Se(l)}if(r.isSymbolicLink()||!r.isFile())throw new S("schema_invalid","The work-state transaction journal must be a regular file.",{path:t});let n=await Qo(t,IA),o=n.files.filter((l)=>ro(l.path)==="intent.toon"),i=n.files.filter((l)=>{let u=ro(l.path);return u!==void 0&&/^assignments\/[a-z0-9][a-z0-9-]{0,95}\.toon$/u.test(u)});if(n.files.length<2||o.length!==1||i.length<1||o.length+i.length!==n.files.length)throw new S("schema_invalid","The work-state transaction must pair one or more Assignments with their Intent.",{path:t});let s=new Set,a=n.files.map((l)=>{let u=ro(l.path);if(u===void 0)throw new S("schema_invalid","The work-state transaction contains an invalid target path.",{path:t,target:l.path});let d=NA(e,l.path);if(s.has(d))throw new S("schema_invalid","The work-state transaction has duplicate targets.",{path:t,target:l.path});s.add(d);let f=n.state==="committed"?l.next:l.previous,g=u==="intent.toon"?FA(f,ti,d):FA(f,Ya,d);return{canonical:u,target:d,contents:f,record:g}}),c=a.find((l)=>l.canonical==="intent.toon")?.record?.id;if(c===void 0)throw new S("schema_invalid","The work-state transaction has no Intent.",{path:t});for(let l of a)if(await no(l.target),l.canonical!=="intent.toon"){let u=l.canonical.slice(12,-5);ug(l.record,c,u,l.target)}for(let l of a)await Qa(l.target,l.contents);return await Xo(t,{force:!0}),await ep(e),!0}async#a(){try{let e=await Qt(this.stateRoot);if(e.isSymbolicLink()||!e.isDirectory())throw new S("schema_invalid","Repository-local work state must be a real directory.",{path:this.stateRoot})}catch(e){if(oe(e,"ENOENT"))return;throw Se(e)}}async createIntent(e){let t=ae(ip,e);if(!t.title.trim()||!t.goal.trim()||t.acceptanceCriteria.length===0)throw xt("Intent title, goal, and acceptance criteria are required.");return await this.recover(),await rs(this.stateRoot,{recursive:!0}),await Zo(_(this.stateRoot,".intent-store"),async()=>{let r=await this.#s(),n=UL(t.title),o=xr([r.root,t.title.trim(),t.goal.trim()].join("\x00")).slice(0,10),i=`${n}-${o}`,s=1;while(await Zu(_(this.stateRoot,i)))s+=1,i=`${n}-${o}-${String(s).padStart(2,"0")}`;let a=`intent-${o}${s===1?"":`-${String(s).padStart(2,"0")}`}`,c=this.#e().toISOString(),l=ae(ti,{schema_version:rp,toon_compatibility:to,id:a,slug:n,title:t.title.trim(),goal:t.goal.trim(),acceptance_criteria:[...t.acceptanceCriteria],state:"scoping",revision:1,plan_required:t.planRequired??!1,blockers:[],verification:Qu(t.verificationRequired??!0),review:Qu(t.reviewRequired??!0),acceptance_met:!1,root_readiness:!1,evidence:[],baseline:sg(r,c),created_at:c,updated_at:c}),u=_(this.stateRoot,i);return await rs(_(u,"assignments"),{recursive:!0}),await yt(_(u,"intent.toon"),l),await Qa(_(this.stateRoot,"current"),`${i}
39
- `),l})}async listIntents(){if(await this.#a(),!await Zu(this.stateRoot))return[];return await Zo(_(this.stateRoot,".intent-store"),async()=>{await this.#l(this.stateRoot);let e;try{e=await xn(this.stateRoot)}catch(r){if(oe(r,"ENOENT"))return[];throw Se(r)}let t=[];for(let r of e.sort()){if(r===".intent-store")continue;let n=_(this.stateRoot,r);if(!await Ga(n))continue;await Zo(_(n,".intent-store"),async()=>{await this.#u(n);let o=_(n,"intent.toon");if(await ts(o))t.push(await this.#t(o))})}return t.sort((r,n)=>r.id.localeCompare(n.id))})}async readIntent(e){let t=await this.#r(e);return await this.#n(t,async()=>this.#t(_(t,"intent.toon")))}async currentIntent(){await this.#a(),await this.recover();let e=_(this.stateRoot,"current"),t=await Qt(e).catch((o)=>{if(oe(o,"ENOENT"))return;throw Se(o)});if(t?.isSymbolicLink()||t&&!t.isFile())throw new S("schema_invalid","The current Intent pointer must be a regular file.");let r=t?(await dg(e,"utf8")).trim():"";if(t&&!r)throw new S("schema_invalid","The current Intent pointer must select a work-state directory.");if(r){let o=ns(this.stateRoot,r);if(!VA(this.stateRoot,o))throw new S("schema_invalid","The current Intent pointer escapes repository-local state.",{directory:r});if(!await Ga(o))throw new S("schema_invalid","The current Intent pointer does not select a work-state directory.",{directory:r});return await this.#n(o,async()=>this.#t(_(o,"intent.toon")))}let n=(await this.listIntents()).filter((o)=>o.state!=="complete"&&o.state!=="abandoned");if(n.length===1)return n[0];throw new S(n.length?"current_ambiguous":"not_found",n.length?"Multiple active Intents require explicit selection.":"No current Intent exists.",{intent_ids:n.map((o)=>o.id)})}async selectCurrent(e){let t=await this.#r(e),r=await this.#t(_(t,"intent.toon"));return await Zo(_(this.stateRoot,".intent-store"),async()=>Qa(_(this.stateRoot,"current"),`${ig(t)}
40
- `)),r}async transitionIntent(e,t,r,n){let o=ae(is,t),i=n===void 0?void 0:ae(j,n);if(!Number.isSafeInteger(r)||r<1)throw xt("Intent revision must be a positive integer.");let s=await this.#r(e);return await this.#n(s,async()=>{let a=await this.#t(_(s,"intent.toon"));if(kt(a.revision,r),o==="complete")throw new S("invalid_transition","Use the predicate-checked complete operation.");if(o==="abandoned")return await this.#m(s,a);return await this.#g(s,a,o,i)})}async completeIntent(e,t){let r=await this.#r(e);return await this.#n(r,async()=>{let n=await this.#t(_(r,"intent.toon"));if(kt(n.revision,t),yn(n),await this.#o(n),n.active_plan_revision!==void 0)await this.readPlan(e);let o=await this.#c(r,n),i=[];if(n.state!=="reviewing")i.push("intent_not_reviewing");if(n.blockers.length)i.push("global_blockers_unresolved");if(o.length===0)i.push("assignment_required");if(o.some((a)=>a.status!=="completed"&&a.status!=="superseded"))i.push("assignments_unresolved");if(n.verification.required&&n.verification.status!=="passed")i.push("verification_unresolved");if(n.review.required&&n.review.status!=="accepted")i.push("review_unresolved");if(!n.acceptance_met)i.push("acceptance_criteria_unmet");if(!n.root_readiness)i.push("root_readiness_missing");if(i.length)return{completed:!1,reasons:i};let s=gn(n,this.#e,{state:"complete"});return await yt(_(r,"intent.toon"),s),s})}async abandonIntent(e,t){let r=await this.#r(e);return await this.#n(r,async()=>{let n=await this.#t(_(r,"intent.toon"));return kt(n.revision,t),await this.#m(r,n)})}async recordIntentEvidence(e,t,r){let n=ae(pp,r),o=await this.#r(e);return await this.#n(o,async()=>{let i=await this.#t(_(o,"intent.toon"));if(kt(i.revision,t),yn(i),n.verification!==void 0||n.review!==void 0)await this.#o(i);if(n.verification!==void 0&&i.state!=="verifying")throw new S("invalid_transition","Verification evidence is only accepted while the Intent is verifying.",{state:i.state});let s=[...i.verification.evidence,...n.evidence??[]];if(n.verification==="passed"&&!kA(s))throw new S("invalid_input","Verification cannot pass without meaningful successful check or behavioral evidence.",{required_evidence:["check","behavior","ci"]});if(n.review!==void 0&&i.state!=="reviewing")throw new S("invalid_transition","Review evidence is only accepted while the Intent is reviewing.",{state:i.state});let a=[...i.evidence,...n.evidence??[]],c=n.verification===void 0?i.verification:{...i.verification,status:n.verification,evidence:[...i.verification.evidence,...n.evidence??[]]},l=n.review===void 0?i.review:{...i.review,status:n.review,evidence:[...i.review.evidence,...n.evidence??[]]},u=n.review==="rejected"&&i.state==="reviewing"?"executing":i.state,d=gn(i,this.#e,{state:u,evidence:a,verification:c,review:l,...n.acceptanceMet===void 0?{}:{acceptance_met:n.acceptanceMet},...n.rootReadiness===void 0?{}:{root_readiness:n.rootReadiness},...n.clearBlockers?{blockers:[]}:{}});return await yt(_(o,"intent.toon"),d),d})}async recordVcsIntegration(e,t,r){let n=ae(up,r),o=await this.#r(e);return await this.#n(o,async()=>{let i=await this.#t(_(o,"intent.toon"));if(kt(i.revision,t),yn(i),i.state!=="reviewing")throw new S("invalid_transition","VCS integration is only accepted after review while the Intent is reviewing.",{state:i.state});if(i.review.required&&i.review.status!=="accepted")throw new S("not_ready","VCS integration requires accepted review evidence.",{review_status:i.review.status});let s=await this.#s();if(s.root!==i.baseline.root||s.gitCommonDir!==i.baseline.git_common_dir)throw new S("repository_drift","VCS integration repository identity does not match the Intent baseline.",{expected_root:i.baseline.root,actual_root:s.root});if(s.head!==n.commit)throw new S("repository_drift","VCS integration requires the requested commit to be the current HEAD.",{expected_head:n.commit,actual_head:s.head});if(s.changedPaths.length)throw new S("repository_drift","VCS integration requires a clean worktree.",{changed_paths:[...s.changedPaths].sort()});let a=await ML(this.repositoryRoot,n.commit);if(a.parents[0]!==i.baseline.expected_head)throw new S("repository_drift","VCS integration commit parent does not match the recorded baseline HEAD.",{expected_parent:i.baseline.expected_head,actual_parents:a.parents});let c=await LL(this.repositoryRoot,i.baseline.expected_head,n.commit),l=[...new Set(ag(i.baseline.expected_changes,c))].sort();if(c.join("\x00")!==l.join("\x00"))throw new S("repository_drift","VCS integration commit tree does not match the recorded expected change set.",{expected_changes:l,actual_changes:c});let u=this.#e().toISOString(),d={kind:"repository_fact",value:`Root VCS integration recorded at ${n.commit}; ${String(c.length)} expected path(s) committed.`,result:"observed"},f=gn(i,this.#e,{baseline:sg(s,u,i.baseline.initial_head,n.commit),evidence:[...i.evidence,d]});return await yt(_(o,"intent.toon"),f),f})}async readPlan(e){let t=await this.#r(e),r=_(t,"plan.toon");if(!await ts(r))return;let n=await Qo(r,Ja),o=await this.#t(_(t,"intent.toon")),i=xr(`${et(n)}
41
- `);if(n.intent_id!==o.id||o.active_plan_revision!==n.revision||o.active_plan_digest!==i)throw new S("schema_invalid","Canonical Plan provenance does not match its Intent.",{intent_id:o.id,plan_revision:n.revision});return n}async revisePlan(e,t,r,n){let o=ae(jA,t);if(!o.approach.trim())throw xt("Plan approach is required.");let i=await this.#r(e);return await this.#n(i,async()=>{let s=await this.#t(_(i,"intent.toon"));kt(s.revision,r),yn(s),await this.#o(s);let a=_(i,"plan.toon"),c=await ts(a)?await Qo(a,Ja):void 0;if(c===void 0&&n!==void 0)kt(0,n);if(c!==void 0)kt(c.revision,n);let l,u;if(c){let y=`${et(c)}
42
- `;u=xr(y),l=await ZL(i),await zL(l,y)}let d=ae(Ja,{schema_version:fg,toon_compatibility:to,intent_id:s.id,revision:(c?.revision??0)+1,...u?{predecessor_digest:u}:{},approach:o.approach.trim(),scope:[...o.scope??[]],exclusions:[...o.exclusions??[]],assignments:[...o.assignments??[]],dependencies:[...o.dependencies??[]],architecture:[...o.architecture??[]],risks:[...o.risks??[]],assumptions:[...o.assumptions??[]],open_questions:[...o.openQuestions??[]],verification:[...o.verification??[]],recovery:[...o.recovery??[]],updated_at:this.#e().toISOString()});await yt(a,d);let f=xr(`${et(d)}
43
- `),g=gn(s,this.#e,{active_plan_revision:d.revision,active_plan_digest:f,verification:es(s.verification),review:es(s.review),acceptance_met:!1,root_readiness:!1});return await yt(_(i,"intent.toon"),g),{intent:g,plan:d,...l?{archived:ig(l)}:{}}})}async createAssignment(e,t,r){let n=ae(sp,t);if(!n.objective.trim()||n.scope.length===0||n.acceptanceCriteria.length===0)throw xt("Assignment objective, scope, and acceptance criteria are required.");let o=Xu(n.scope),i=await this.#r(e);return await this.#n(i,async()=>{let s=await this.#t(_(i,"intent.toon"));if(kt(s.revision,r),yn(s),await this.#o(s,o),n.owner.role==="Worker"&&n.owner.task==="operations"&&s.baseline.integrated_commit!==s.baseline.expected_head)throw new S("not_ready","Worker.operations requires a successfully integrated exact commit.",{expected_head:s.baseline.expected_head});let a=n.id??`assignment-${xr([s.id,n.objective,...o].join("\x00")).slice(0,10)}`;if(!/^[a-z0-9][a-z0-9-]{0,95}$/u.test(a))throw xt("Assignment id is invalid.");let c=_(i,"assignments",`${a}.toon`);if(await Zu(c))throw new S("already_exists","Assignment already exists.",{id:a});let l=this.#e().toISOString(),u=ae(Sg,{schema_version:mg,toon_compatibility:to,intent_id:s.id,id:a,objective:n.objective.trim(),owner:n.owner,scope:o,constraints:[...n.constraints??[]],exclusions:[...n.exclusions??[]],dependencies:[...n.dependencies??[]],acceptance_criteria:[...n.acceptanceCriteria],status:"pending",revision:1,invocations:[],evidence:[],remaining_risk:[],created_at:l,updated_at:l});return await rs(ei(c),{recursive:!0}),await yt(c,u),u})}async reviseAssignmentScope(e,t,r,n){let o=ae(ap,r),i=Xu(o.scope),s=ae(Ze,t),a=await this.#r(e);return await this.#n(a,async()=>{let c=await this.#t(_(a,"intent.toon"));yn(c);let l=await this.#i(a,c,s);if(kt(l.revision,n),l.status==="completed"||l.status==="superseded")throw new S("invalid_transition","A completed or superseded Assignment cannot have its scope revised.");let u=za(l,this.#e,{scope:i});return await yt(_(a,"assignments",`${s}.toon`),u),Yo(u)})}async supersedeAssignment(e,t,r,n){let o=ae(lp,n),i=ae(Ze,t),s=await this.#r(e);return await this.#n(s,async()=>{let a=await this.#t(_(s,"intent.toon"));if(yn(a),a.acceptance_met||a.root_readiness||a.review.status==="accepted")throw new S("invalid_transition","Accepted Intent evidence cannot be superseded.",{intent_id:a.id});let c=await this.#i(s,a,i);kt(c.revision,r);let l=await this.#i(s,a,o.replacementId);if(o.replacementRevision!==void 0)kt(l.revision,o.replacementRevision);if(l.id===c.id)throw xt("An Assignment cannot supersede itself.");if(c.status==="completed"||c.status==="superseded")throw new S("invalid_transition","Only unfinished, non-superseded Assignments may be replaced.",{assignment_id:c.id,status:c.status});if(c.status==="executing")throw new S("invalid_transition","An executing Assignment must record its active invocation before supersession.",{assignment_id:c.id});if(c.superseded_by!==void 0)throw new S("invalid_transition","An Assignment with an existing replacement cannot be superseded again.",{assignment_id:c.id,replacement_id:c.superseded_by});if(l.status==="completed"||l.status==="executing"||l.status==="superseded")throw new S("invalid_transition","A supersession replacement must be unfinished and inactive.",{assignment_id:l.id,status:l.status});if(l.supersedes!==void 0||l.superseded_by!==void 0)throw new S("invalid_transition","An Assignment already participating in a supersession cannot be reused.",{assignment_id:l.id});if(!c.scope.some((O)=>l.scope.some((m)=>eo(O,m)||eo(m,O))))throw xt("A supersession replacement must overlap the predecessor bounded scope.");let d=await this.#c(s,a);await this.#o(a,[...c.scope,...l.scope,...d.filter((O)=>O.status==="executing").flatMap((O)=>O.scope)]);let f=za(c,this.#e,{status:"superseded",blocker:void 0,active_invocation_id:void 0,active_started_at:void 0,active_invocation_capability_verifier:void 0,active_invocation_capability:void 0,superseded_by:l.id,supersession_reason:o.reason.trim(),supersession_provenance:o.provenance.trim()}),g=za(l,this.#e,{supersedes:c.id,supersession_reason:o.reason.trim(),supersession_provenance:o.provenance.trim()}),y=gn(a,this.#e,{state:a.blockers.length===0&&["blocked","needs_root_input","verifying","reviewing"].includes(a.state)?"executing":a.state,blockers:[...a.blockers],...a.blockers.length===0?{resume_state:void 0}:{},verification:es(a.verification),review:es(a.review),acceptance_met:!1,root_readiness:!1,evidence:[...a.evidence,{kind:"behavior",value:`Assignment ${c.id} superseded by ${l.id}: ${o.reason.trim()} (${o.provenance.trim()})`,result:"observed"}]});return await this.#f(s,[{path:`assignments/${c.id}.toon`,previous:`${et(c)}
44
- `,next:`${et(f)}
45
- `},{path:`assignments/${l.id}.toon`,previous:`${et(l)}
46
- `,next:`${et(g)}
47
- `},{path:"intent.toon",previous:`${et(a)}
48
- `,next:`${et(y)}
49
- `}]),{assignment:Yo(f),replacement:Yo(g),intent:y}})}async readAssignment(e,t){let r=ae(Ze,t),n=await this.#r(e);return await this.#n(n,async()=>{let o=await this.#t(_(n,"intent.toon"));return Yo(await this.#i(n,o,r))})}async isLegacyExecutingAssignment(e,t){let r=ae(Ze,t),n=await this.#r(e);return await this.#n(n,async()=>{let o=await this.#t(_(n,"intent.toon")),i=await this.#i(n,o,r);return i.status==="executing"&&i.active_invocation_capability_verifier===void 0&&i.active_invocation_capability===void 0})}async#i(e,t,r){let n=_(e,"assignments");await lg(n,!0);let o=_(n,`${r}.toon`);if(!await ts(o))throw new S("not_found","Assignment was not found.",{assignment_id:r});let i=await Qo(o,Ya);return ug(i,t.id,r,o),i}async listAssignments(e){let t=await this.#r(e);return await this.#n(t,async()=>(await this.#c(t,await this.#t(_(t,"intent.toon")))).map(Yo))}async#c(e,t){let r=_(e,"assignments");if(!await lg(r,!0))return[];let n;try{n=await xn(r)}catch(i){if(oe(i,"ENOENT"))return[];throw Se(i)}return await Promise.all(n.filter((i)=>i.endsWith(".toon")).sort().map(async(i)=>{let s=_(r,i),a=await Qo(s,Ya),c=i.slice(0,-5);return ug(a,t.id,c,s),a}))}async startAssignment(e,t,r,n={}){let o=ae(cp,n),i=ae(Ze,t),s=await this.#r(e);return await this.#n(s,async()=>{let a=await this.#t(_(s,"intent.toon"));yn(a);let c=await this.#i(s,a,i);if(kt(c.revision,r),!He(Qn(op)(c.owner)))throw xt("This Assignment owner is retired; supersede it with a current route.");let l=PA(c.scope,o.scope);if(await this.#o(a,l),c.status==="completed")throw new S("invalid_transition","A completed Assignment cannot be restarted.");if(c.status==="superseded")throw new S("invalid_transition","A superseded Assignment cannot be restarted.",{assignment_id:c.id});if(c.status==="executing")throw new S("invalid_transition","Assignment is already executing; record its active invocation result first.",{assignment_id:c.id,...c.active_invocation_id?{invocation_id:c.active_invocation_id}:{}});let u=this.#e().toISOString(),d=CA(c),f=qL(),g=za(c,this.#e,{status:"executing",scope:l,blocker:void 0,active_invocation_id:d,active_started_at:u,active_invocation_capability_verifier:xr(f),active_invocation_capability:void 0});return await yt(_(s,"assignments",`${i}.toon`),g),ae(DA,{...Yo(g),capability:f})})}async recordAssignmentResult(e,t,r,n){return await this.#p(e,t,r,n,!1)}async recordSpecialistAssignmentResult(e,t,r,n){if(ae(Xa,n).capability===void 0)throw xt("Specialist Assignment results require an active invocation capability.");return await this.#p(e,t,r,n,!0)}async recoverInterruptedAssignment(e,t,r,n){let o=ae(FL,n),i=o.interruptionReason.trim(),s={kind:"behavior",value:`Interrupted invocation ${o.invocationId} started at ${o.startedAt} recovered as failed: ${i}`,result:"failed"};return await this.#p(e,t,r,{invocationId:o.invocationId,capability:o.capability,outcome:"failed",startedAt:o.startedAt,summary:`Interrupted invocation recovered as failed: ${i}`,evidence:[s]},!0,{invocationId:o.invocationId,startedAt:o.startedAt})}async#p(e,t,r,n,o,i){let s=ae(Xa,n),a=ae(Ze,t),c=await this.#r(e);return await this.#n(c,async()=>{let l=await this.#t(_(c,"intent.toon"));if(yn(l),i!==void 0&&e!==l.id)throw xt("Interruption recovery requires the exact Intent ID reference.");let u=await this.#i(c,l,a);if(kt(u.revision,r),u.status!=="executing")throw new S("invalid_transition",`Assignment result requires an executing Assignment; current status is ${u.status}.`,{assignment_id:u.id,status:u.status});if(i===void 0&&!o&&s.capability===void 0&&(u.active_invocation_capability_verifier!==void 0||u.active_invocation_capability!==void 0))throw new S("invalid_transition","This Assignment invocation requires its active capability to record a result.",{assignment_id:u.id});if(i!==void 0){if(u.active_invocation_id!==i.invocationId||u.active_started_at!==i.startedAt)throw new S("invalid_transition","Interruption recovery does not match the active invocation identity and start time.",{assignment_id:u.id,expected_invocation_id:u.active_invocation_id,expected_started_at:u.active_started_at})}if(u.active_invocation_id!==void 0&&s.invocationId!==void 0&&u.active_invocation_id!==s.invocationId)throw new S("invalid_transition","Assignment result does not match the active invocation.",{assignment_id:u.id,expected_invocation_id:u.active_invocation_id,actual_invocation_id:s.invocationId});if(o&&(u.active_invocation_id===void 0||s.invocationId===void 0))throw new S("invalid_transition",i===void 0?"Specialist Assignment results require the active invocation identity.":"Interruption recovery requires the active invocation identity.",{assignment_id:u.id});if(o&&u.active_invocation_capability_verifier===void 0&&u.active_invocation_capability===void 0)throw new S("invalid_transition",i===void 0?"The active Assignment invocation has no capability to authorize a specialist result.":"The active Assignment invocation has no capability to authorize interruption recovery.",{assignment_id:u.id});if(s.capability!==void 0&&(u.active_invocation_capability_verifier!==void 0?xr(s.capability)!==u.active_invocation_capability_verifier:u.active_invocation_capability!==s.capability))throw new S("invalid_transition","Assignment result capability does not match the active invocation.",{assignment_id:u.id});if((s.outcome==="blocked"||s.outcome==="needs_root_input")&&!s.blocker?.trim())throw xt("Blocked results require a local blocker.");if(i===void 0&&Qh({role:u.owner.role,task:u.owner.task,objective:u.objective,scope:u.scope,constraints:u.constraints,exclusions:u.exclusions,dependencies:u.dependencies,acceptanceCriteria:u.acceptance_criteria})&&s.context7===void 0)throw new S("invalid_input","This Librarian Assignment result requires typed Context7 evidence.",{assignment_id:u.id,required_evidence:"context7"});let d=PA(u.scope,s.scope),f=await this.#s(),g=ag(l.baseline.expected_changes,f.changedPaths),y=[...s.evidence??[]],O=new Set(y.filter((_e)=>_e.kind==="changed_path").map((_e)=>_e.value)),m=[...O].filter((_e)=>!d.some((as)=>eo(_e,as)));if(m.length)throw new S("repository_drift","Assignment evidence declares paths outside its bounded scope.",{assignment_id:u.id,out_of_scope_paths:m.sort()});let D=(await this.#c(c,l)).filter((_e)=>_e.id!==u.id&&_e.status==="executing"),k=f.changedPaths.filter((_e)=>D.some((as)=>as.scope.some((YA)=>eo(_e,YA)))),H=new Set(k),T=new Set([...g,...O,...k]),I=f.changedPaths.filter((_e)=>!T.has(_e)),C=new Set(g),L=f.changedPaths.filter((_e)=>d.some((as)=>eo(_e,as))&&!C.has(_e)&&!O.has(_e)&&!H.has(_e)),ee=f.root!==l.baseline.root||f.gitCommonDir!==l.baseline.git_common_dir,X=RA(f.statusDigest)!==l.baseline.expected_status_digest,J=f.head!==l.baseline.expected_head||X||[...new Set(g)].sort().join("\x00")!==[...new Set(f.changedPaths)].sort().join("\x00"),he=[...O].some((_e)=>f.changedPaths.includes(_e)),lt=k.length>0;if(i===void 0&&(ee||I.length||L.length||X&&!he&&!lt||f.head!==l.baseline.expected_head&&!he&&!lt))throw new S("repository_drift","Repository state changed outside the recorded Assignment result.",{expected_head:l.baseline.expected_head,actual_head:f.head,unexpected_paths:[...new Set([...I,...L])].sort(),concurrent_assignments:D.map((_e)=>_e.id).sort()});let Xe=this.#e().toISOString(),ut=u.active_invocation_id??s.invocationId??CA(u);if(u.invocations.some((_e)=>_e.id===ut))throw new S("already_exists","Assignment invocation already exists.",{invocation_id:ut});let Me=ae(yg,{id:ut,outcome:s.outcome,started_at:u.active_started_at??s.startedAt??Xe,finished_at:Xe,summary:s.summary,evidence:y,...s.context7===void 0?{}:{context7:s.context7},...s.blocker?{blocker:s.blocker}:{},remaining_risk:[...s.remainingRisk??[]]}),Re=za(u,this.#e,{status:s.outcome,scope:d,invocations:[...u.invocations,Me],active_invocation_id:void 0,active_started_at:void 0,active_invocation_capability_verifier:void 0,active_invocation_capability:void 0,evidence:[...u.evidence,...y],blocker:s.blocker,remaining_risk:[...s.remainingRisk??[]]}),pt=u.owner.role==="Worker"&&u.owner.task==="operations",Mr=l.baseline.integrated_commit!==void 0&&l.baseline.integrated_commit===l.baseline.expected_head&&f.head===l.baseline.expected_head&&f.changedPaths.length===0,ss=pt&&s.outcome==="failed",io=pt&&s.outcome==="completed"&&Mr&&l.state==="reviewing"&&(!l.verification.required||l.verification.status==="passed")&&(!l.review.required||l.review.status==="accepted"),JA=J||s.outcome==="failed",Eg=gn(l,this.#e,{baseline:i===void 0?sg(f,Xe,l.baseline.initial_head,Mr?l.baseline.integrated_commit:void 0):l.baseline,...io||!JA?{}:{state:ss?"executing":l.state,verification:es(l.verification),review:es(l.review),acceptance_met:!1,root_readiness:!1}});return await this.#y(c,a,u,Re,l,Eg),{assignment:Yo(Re),intent:Eg}})}async#g(e,t,r,n){let o=t.state;if(r==="blocked"||r==="needs_root_input"){if(["complete","abandoned","blocked","needs_root_input"].includes(o))throw Yu(o,r);if(!n?.trim())throw xt("A blocker or required input is required.");let s=gn(t,this.#e,{state:r,blockers:[n.trim()],resume_state:o});return await yt(_(e,"intent.toon"),s),s}if(o==="blocked"||o==="needs_root_input"){if(r!==t.resume_state||t.blockers.length)throw Yu(o,r)}else if(!{scoping:["ready"],ready:["executing"],executing:["verifying"],verifying:["reviewing","executing"],reviewing:["executing"]}[o]?.includes(r))throw Yu(o,r);if(r==="ready"){let s=[];if(!t.goal.trim())s.push("goal_missing");if(!t.acceptance_criteria.length)s.push("acceptance_criteria_missing");if((t.active_plan_revision===void 0?void 0:await this.readPlan(t.id))?.open_questions.length)s.push("material_open_questions");if(s.length)throw new S("not_ready","Intent readiness predicates failed.",{reasons:s})}if(r==="executing"&&o==="ready")await this.#o(t);if(r==="reviewing"&&t.verification.required&&t.verification.status!=="passed")throw new S("invalid_transition","Verification must pass before review.");if(r==="reviewing")await this.#o(t);let i=gn(t,this.#e,{state:r,resume_state:void 0});return await yt(_(e,"intent.toon"),i),i}async#n(e,t){return await Zo(_(e,".intent-store"),async()=>(await this.#u(e),await t()))}async#y(e,t,r,n,o,i){await this.#f(e,[{path:`assignments/${t}.toon`,previous:`${et(r)}
50
- `,next:`${et(n)}
51
- `},{path:"intent.toon",previous:`${et(o)}
52
- `,next:`${et(i)}
53
- `}])}async#f(e,t){let r=_(e,Ju),n=ae(IA,{schema_version:qA,state:"prepared",files:t.map((i)=>({...i}))}),o=n.files.map((i)=>NA(e,i.path));await yt(r,n);try{for(let[i,s]of o.entries())await Qa(s,n.files[i].next);await yt(r,{...n,state:"committed"})}catch(i){try{await this.#d(e)}catch(s){throw Se(s)}throw i}await Xo(r,{force:!0}),await ep(e)}async#m(e,t){if(t.state==="complete"||t.state==="abandoned")throw Yu(t.state,"abandoned");let r=gn(t,this.#e,{state:"abandoned",blockers:[]});return await yt(_(e,"intent.toon"),r),r}async#o(e,t){let r=await this.#s(),n=[...ag(e.baseline.expected_changes,r.changedPaths)].sort(),o=[...r.changedPaths].sort(),i=new Set(t===void 0?[]:o.filter((a)=>t.some((c)=>eo(a,c)))),s=[...new Set([...n,...i])].sort();if(r.root!==e.baseline.root||r.gitCommonDir!==e.baseline.git_common_dir||r.head!==e.baseline.expected_head||s.join("\x00")!==o.join("\x00")||RA(r.statusDigest)!==e.baseline.expected_status_digest&&i.size===0)throw new S("repository_drift","Repository baseline no longer matches recorded assumptions.",{expected_head:e.baseline.expected_head,actual_head:r.head,expected_changes:s,actual_changes:o})}async#r(e){await this.#a();let t;try{t=await xn(this.stateRoot)}catch(n){if(oe(n,"ENOENT"))throw new S("not_found","Intent was not found.",{reference:e});throw Se(n)}let r=[];for(let n of t.sort()){let o=_(this.stateRoot,n);if(!await Ga(o))continue;let i=_(o,"intent.toon");if(!await ts(i))continue;let s=await this.#t(i);if(s.id===e||s.slug===e||n===e)r.push(o)}if(r.length===1)return r[0];if(r.length>1)throw new S("current_ambiguous","Intent reference is ambiguous.",{reference:e});throw new S("not_found","Intent was not found.",{reference:e})}async#t(e){let t=await fp(e),r=gr(ti,t);if(He(r))return r.right;let n=gr(UA,t);if(ge(n))throw new S("schema_invalid","Persisted Intent failed schema validation.",{path:e,error:String(r.left)});let o=$A(n.right);return await yt(e,o),o}}async function HA(e){let t=await vL(e),r=async(...l)=>{try{return(await ec("git",["-C",t,...l],{encoding:"utf8"})).stdout.trimEnd()}catch(u){throw new S("io_failure","Repository identity requires an accessible Git worktree.",{message:u instanceof Error?u.message:String(u)})}},n=await r("rev-parse","--git-common-dir"),o=await DL(t,"rev-parse","--verify","HEAD")??"unborn",i=await r("status","--porcelain=v1","-z","--untracked-files=all"),s=await r("status","--porcelain=v1","--untracked-files=all"),a=i.split("\x00"),c=[];for(let l=0;l<a.length;l+=1){let u=a[l];if(!u)continue;if(c.push(u.slice(3)),u.slice(0,2).includes("R")||u.slice(0,2).includes("C"))l+=1}return c.sort(),{root:t,gitCommonDir:ns(t,n),head:o,changedPaths:c,statusDigest:xr(s)}}async function ML(e,t){try{let r=(await ec("git",["-C",e,"show","-s","--format=%H%n%P",t],{encoding:"utf8"})).stdout.trim(),[n,o=""]=r.split(`
54
- `);if(n!==t)throw Error(`Resolved commit ${n??""} does not match requested ${t}.`);return{hash:n,parents:o?o.split(/\s+/u):[]}}catch(r){throw new S("repository_drift","VCS integration commit could not be inspected.",{commit:t,message:r instanceof Error?r.message:String(r)})}}async function LL(e,t,r){try{return(await ec("git",["-C",e,"diff","--name-only","-z","--no-ext-diff",t,r],{encoding:"utf8"})).stdout.split("\x00").filter(Boolean).sort()}catch(n){throw new S("repository_drift","VCS integration commit tree could not be inspected.",{parent:t,commit:r,message:n instanceof Error?n.message:String(n)})}}async function DL(e,...t){try{return(await ec("git",["-C",e,...t],{encoding:"utf8"})).stdout.trim()}catch{return}}function $A(e){return ae(ti,{...e,schema_version:rp,toon_compatibility:to,plan_required:!1,blockers:[],verification:Qu(!0),review:Qu(!0),acceptance_met:!1,root_readiness:!1,evidence:[]})}function Qu(e){return{required:e,status:e?"missing":"not_required",evidence:[]}}function es(e){return{...e,status:e.required?"missing":"not_required"}}function sg(e,t,r=e.head,n){return{root:e.root,git_common_dir:e.gitCommonDir,initial_head:r,expected_head:e.head,expected_changes:[...e.changedPaths].sort(),expected_status_digest:/^[a-f0-9]{64}$/u.test(e.statusDigest)?e.statusDigest:xr(e.statusDigest),...n===void 0?{}:{integrated_commit:n},updated_at:t}}function RA(e){return/^[a-f0-9]{64}$/u.test(e)?e:xr(e)}function kA(e){return e.some((t)=>["check","behavior","ci"].includes(t.kind)&&["passed","observed"].includes(t.result??""))}function qL(){return OL(32).toString("hex")}function CA(e){let t=e.invocations.length+1,r=`invocation-${String(t).padStart(3,"0")}`;while(e.invocations.some((n)=>n.id===r))t+=1,r=`invocation-${String(t).padStart(3,"0")}`;return r}function gn(e,t,r){return ae(ti,BA({...e,...r,revision:e.revision+1,updated_at:t().toISOString()}))}function za(e,t,r){return ae(Ya,BA({...e,...r,revision:e.revision+1,updated_at:t().toISOString()}))}function Yo(e){let{active_invocation_capability_verifier:t,active_invocation_capability:r,...n}=e;return ae(Sg,n)}function BA(e){let t={...e};for(let[r,n]of Object.entries(t))if(n===void 0)delete t[r];return t}function UL(e){return e.normalize("NFKD").toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-|-$/gu,"").slice(0,48).replace(/-$/u,"")||"intent"}function Xu(e){let t=e.map((r)=>{let n=ro(r);if(n===void 0)throw xt("Assignment scope must contain canonical repository-relative paths.");return n});return[...new Set(t)].sort()}function PA(e,t){let r=Xu(e);if(t===void 0)return r;let n=Xu(t);if(r.some((i)=>!n.includes(i)))throw xt("Assignment scope expansion must preserve the existing scope.");if(n.filter((i)=>!r.some((s)=>jL(i,s))).length)throw xt("Assignment scope expansion exceeds the declared component authority.");return n}function jL(e,t){if(eo(e,t))return!0;let r=ro(t);if(r===void 0||r===".")return!1;let n=r.split("/"),o=n.at(-1);if(o===void 0||!o.includes("."))return!1;let i=n.slice(0,-1).join("/")||".";return e!==i&&eo(e,i)}function eo(e,t){let r=ro(e),n=ro(t);if(r===void 0||n===void 0)return!1;return n==="."||r===n||r.startsWith(`${n}/`)}function ro(e){let t=e.replaceAll("\\","/");if(!t||t.startsWith("/")||/^[a-z]:/iu.test(t))return;let r=t.split("/");if(r.some((o)=>o===".."))return;let n=r.filter((o)=>o!==""&&o!==".");return n.length===0?".":n.join("/")}function NA(e,t){let r=ro(t);if(r===void 0||r!=="intent.toon"&&!/^assignments\/[a-z0-9][a-z0-9-]{0,95}\.toon$/u.test(r))throw new S("schema_invalid","The work-state transaction target is outside the supported Intent records.",{path:t});let n=ns(e,r);if(!VA(ns(e),n))throw new S("schema_invalid","The work-state transaction target escapes the Intent directory.",{path:t});return n}function ag(e,t){let r=new Set(t);return e.map((n)=>{if(r.has(n))return n;let o=$L(n);return o!==void 0&&r.has(o)?o:n})}var HL={a:7,b:8,t:9,n:10,v:11,f:12,r:13,"\\":92,'"':34};function $L(e){if(e.length<2||e[0]!=='"'||e[e.length-1]!=='"')return;let t=[],r=new TextEncoder,n=e.slice(1,-1);for(let o=0;o<n.length;){let i=n.codePointAt(o);if(i===void 0)return;if(i!==92){if(i===34||i<32||i===127)return;let l=String.fromCodePoint(i);t.push(...r.encode(l)),o+=l.length;continue}let s=n[o+1];if(s===void 0)return;let a=HL[s];if(a!==void 0){t.push(a),o+=2;continue}if(s<"0"||s>"7")return;let c=o+2;while(c<n.length&&c<o+4&&n[c]>="0"&&n[c]<="7")c+=1;t.push(Number.parseInt(n.slice(o+1,c),8)),o=c}try{return new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(Uint8Array.from(t))}catch{return}}function xr(e){return EL("sha256").update(e).digest("hex")}function kt(e,t){if(t===void 0||e!==t)throw new S("stale_write","Persisted revision changed before mutation.",{expected_revision:t,actual_revision:e})}function xt(e){return new S("invalid_input",e)}function yn(e){if(e.state==="complete"||e.state==="abandoned")throw new S("invalid_transition","Terminal Intents cannot be mutated.",{state:e.state})}function Yu(e,t){return new S("invalid_transition",`Intent cannot transition from ${e} to ${t}.`,{source:e,target:t})}function ae(e,t){let r=gr(e,t);if(ge(r))throw new S("schema_invalid","Value failed Effect Schema validation.",{error:String(r.left)});return r.right}async function fp(e){let t;try{let r=await Qt(e);if(r.isSymbolicLink()||!r.isFile())throw new S("schema_invalid","Persistent work state must be a regular file.",{path:e});t=await dg(e,"utf8")}catch(r){if(oe(r,"ENOENT"))throw new S("not_found","Persistent work state was not found.",{path:e});throw Se(r)}return WA(t,e)}async function Qo(e,t){return ae(t,await fp(e))}async function BL(e,t){let r;try{r=await Qt(e)}catch(n){if(oe(n,"ENOENT")||oe(n,"ENOTDIR"))return;throw Se(n)}if(r.isSymbolicLink()||!r.isFile())throw new S("schema_invalid","Persistent work state must be a regular file.",{path:e});return await Qo(e,t)}async function WL(e){let t=await fp(e),r=gr(ti,t);if(He(r))return r.right;let n=gr(UA,t);if(ge(n))throw new S("schema_invalid","Persisted Intent failed schema validation.",{path:e,error:String(r.left)});return $A(n.right)}async function KL(e,t){let r;try{r=await fp(e)}catch(o){if(Za(o))return!1;throw o}if(typeof r!=="object"||r===null||Array.isArray(r))return!1;let n=r;return n.id===t||n.slug===t}function Za(e){return e instanceof S&&["malformed_toon","schema_invalid","not_found"].includes(e.code)}function VL(e){let t=new Map(e.map((s)=>[s.id,s])),r=new Set,n=[],o=new Set,i=(s)=>{let a=n.indexOf(s);if(a>=0){for(let c of n.slice(a))o.add(c);return}if(r.has(s))return;n.push(s);for(let c of t.get(s)?.dependencies??[])if(c!==s&&t.has(c))i(c);n.pop(),r.add(s)};for(let s of[...t.keys()].sort())i(s);return[...o].sort()}function cg(e,t){return e<t?-1:e>t?1:0}function FA(e,t,r){return ae(t,WA(e,r))}function WA(e,t){try{return Qg(e,{strict:!0})}catch(r){throw new S("malformed_toon","Persistent work state is malformed TOON.",{path:t,message:r instanceof Error?r.message:String(r)})}}async function yt(e,t){await Qa(e,`${et(t)}
55
- `)}async function Qa(e,t){await no(e),await rs(ei(e),{recursive:!0}),await no(e);let r=_(ei(e),`.holycodex-write-${process.pid}-${crypto.randomUUID()}.tmp`);try{let n=await tp(r,"wx",384);try{await n.writeFile(t,"utf8"),await n.sync()}finally{await n.close()}await AL(r,e),await ep(ei(e))}catch(n){throw await Xo(r,{force:!0}),Se(n)}}async function zL(e,t){await no(e);try{let r=await tp(e,"wx",256);try{await r.writeFile(t,"utf8"),await r.sync()}finally{await r.close()}await ep(ei(e))}catch(r){if(oe(r,"EEXIST"))throw new S("archive_conflict","Archived plans are immutable.",{path:e});throw Se(r)}}async function ep(e){if(process.platform==="win32")return;try{let t=await tp(e,"r");try{await t.sync()}finally{await t.close()}}catch(t){if(oe(t,"EINVAL")||oe(t,"ENOSYS")||oe(t,"ENOTSUP")||oe(t,"EOPNOTSUPP")||oe(t,"EISDIR"))return;throw t}}async function Zo(e,t){let r=ei(e);await no(e),await rs(r,{recursive:!0});let n=!1;for(let a=0;a<200;a+=1)try{await rs(e),n=!0;break}catch(c){if(!oe(c,"EEXIST"))throw Se(c);try{let l=await Qt(e);if(l.isSymbolicLink()||!l.isDirectory())throw new S("schema_invalid","The work-state lock must be a real directory.",{path:e});let u=await KA(e);if(u.kind==="owned"&&!await GL(u.owner.pid)){await Xo(e,{recursive:!0,force:!0});continue}if(u.kind==="missing"&&Date.now()-l.mtimeMs>CL){await Xo(e,{recursive:!0,force:!0});continue}}catch(l){if(!oe(l,"ENOENT"))throw Se(l)}await new Promise((l)=>setTimeout(l,Math.min(5+a,50)))}if(!n)throw new S("stale_write","Another mutation is still in progress.",{lock:e});let o=_(e,".owner"),i=crypto.randomUUID(),s;try{await no(o),s=await tp(o,"wx",384),await s.writeFile(`${JSON.stringify({pid:process.pid,token:i})}
56
- `,"utf8"),await s.sync()}catch(a){if(s!==void 0)try{await s.close()}catch{}if(oe(a,"EEXIST"))throw new S("stale_write","Another mutation is still in progress.",{lock:e});throw Se(a)}if(s===void 0)throw Se(Error("The work-state lock owner was not opened."));try{return await t()}finally{try{await s.close()}finally{await YL(e,i)}}}async function KA(e){let t=_(e,".owner");try{let r=await Qt(t);if(r.isSymbolicLink()||!r.isFile())return{kind:"unknown"};let n=await dg(t,"utf8"),o;try{o=JSON.parse(n)}catch{return{kind:"unknown"}}let i=gr(kL,o);return He(i)?{kind:"owned",owner:i.right}:{kind:"unknown"}}catch(r){if(oe(r,"ENOENT"))return{kind:"missing"};throw Se(r)}}async function GL(e){if(e===process.pid)return!0;if(process.platform==="win32")return await JL(e);if(!["aix","android","darwin","freebsd","haiku","linux","openbsd","sunos","win32"].includes(process.platform))return!0;try{return process.kill(e,0),!0}catch(r){return oe(r,"EPERM")}}async function JL(e){if(!Number.isSafeInteger(e)||e>PL)return!1;try{let{stdout:t}=await ec("tasklist.exe",["/FI",`PID eq ${e}`,"/FO","CSV","/NH"],{encoding:"utf8",windowsHide:!0});return t.split(/\r?\n/u).some((r)=>/^"[^"]*","(\d+)",/u.exec(r)?.[1]===String(e))}catch{return!0}}async function YL(e,t){let r=await KA(e);if(r.kind!=="owned"||r.owner.token!==t)return;await Xo(e,{recursive:!0,force:!0})}async function ZL(e){let t=(await xn(e)).map((r)=>/^plan\.old-(\d{3})\.toon$/u.exec(r)?.[1]).filter((r)=>r!==void 0).map(Number);return _(e,`plan.old-${String((t.length?Math.max(...t):0)+1).padStart(3,"0")}.toon`)}async function Zu(e){try{return await TL(e),!0}catch(t){if(oe(t,"ENOENT"))return!1;throw Se(t)}}async function ts(e){try{let t=await Qt(e);return t.isFile()&&!t.isSymbolicLink()}catch(t){if(oe(t,"ENOENT")||oe(t,"ENOTDIR"))return!1;throw Se(t)}}async function lg(e,t){try{let r=await Qt(e);if(r.isSymbolicLink()||!r.isDirectory())throw new S("schema_invalid","Persistent work-state directories must be real directories.",{path:e});return!0}catch(r){if(oe(r,"ENOENT")&&t)return!1;throw Se(r)}}async function Ga(e){try{let t=await Qt(e);return t.isDirectory()&&!t.isSymbolicLink()}catch(t){if(oe(t,"ENOENT")||oe(t,"ENOTDIR"))return!1;throw Se(t)}}function ug(e,t,r,n){if(e.intent_id!==t||e.id!==r)throw new S("schema_invalid","Assignment provenance does not match its Intent or file name.",{path:n,expected_intent_id:t,actual_intent_id:e.intent_id,expected_assignment_id:r,actual_assignment_id:e.id})}async function no(e){let t=ns(e);while(!0){try{if((await Qt(t)).isSymbolicLink())throw new S("schema_invalid","Persistent work state must not contain symbolic links.",{path:t})}catch(n){if(!oe(n,"ENOENT"))throw Se(n)}let r=ei(t);if(r===t)break;t=r}}function oe(e,t){return typeof e==="object"&&e!==null&&"code"in e&&e.code===t}function Se(e){return e instanceof S?e:new S("io_failure","Persistent work-state I/O failed.",{message:e instanceof Error?e.message:String(e)})}function VA(e,t){let r=pg(e,t);return r===""||!r.startsWith(`..${QL()}`)&&r!==".."&&!IL(r)}function QL(){return process.platform==="win32"?"\\":"/"}var zA={state:`Usage: holycodex-agent state diagnose --intent <ref> [--repo <path>]
12
+ ${i(u)}}`;g=s(c,S)}}return r.delete(c),g}return String(c)}return l(e,0)}var Tg="[Circular]";function $n(e){return typeof e==="string"?JSON.stringify(e):String(e)}function dl(e){return e.map((t)=>`[${$n(t)}]`).join("")}function Ag(e){try{return e.toISOString()}catch{return"Invalid Date"}}function Og(e){try{let t=e.toString();return typeof t==="string"?t:String(t)}catch{return"[toString threw]"}}function fl(e,t){try{return e[t]}catch{return"[property access threw]"}}var cn=Symbol.for("nodejs.util.inspect.custom"),un=(e)=>{try{if(e=zo(e),W(e,"toJSON")&&on(e.toJSON)&&e.toJSON.length===0)return e.toJSON();else if(Array.isArray(e))return e.map(un);return e}catch{return"[toJSON threw]"}};var Sv={toJSON(){return un(this)},[cn](){return this.toJSON()},toString(){return G(this.toJSON())}};var Cg=()=>{let e=Object.getOwnPropertyDescriptor(Error,"stackTraceLimit");if(e===void 0)return Object.isExtensible(Error);return Object.hasOwn(e,"writable")?e.writable===!0:e.set!==void 0},Rg=Cg(),Wo=()=>Error.stackTraceLimit,Qs=(e)=>{if(Rg)Error.stackTraceLimit=e};class ln{constructor(e){this.value=e,this.done=!1}next(e){if(this.done)return this.value=e,this;return this.done=!0,{value:this.value,done:!1}}}var Pg=()=>{let t={["~effect/Utils/internal"]:(o)=>o()},n={["~effect/Utils/internal"]:(o)=>{try{return o()}finally{}}};return Wo()!==0&&t["~effect/Utils/internal"](()=>Error().stack)?.includes("~effect/Utils/internal")===!0?t["~effect/Utils/internal"]:n["~effect/Utils/internal"]},Or=Pg();var At="~effect/Effect",fn="~effect/Exit",Ng={_A:ce,_E:ce,_R:ce},ml=`${At}/identifier`,F=`${At}/args`,Z=`${At}/evaluate`,ie=`${At}/successCont`,je=`${At}/failureCont`,dn=`${At}/ensureCont`,pn=Symbol.for("effect/Effect/Yield"),mn={pipe(){return Fe(this,arguments)},toJSON(){return{...this}},toString(){return G(this.toJSON(),{ignoreToString:!0,space:2})},[cn](){return this.toJSON()}},Cv={[re](){return Gs(this,Object.keys(this))},[oe](e){let t=Object.keys(this),n=Object.keys(e);if(t.length!==n.length)return!1;for(let r=0;r<t.length;r++)if(t[r]!==n[r]||!le(this[t[r]],e[t[r]]))return!1;return!0}},Fg={[At]:Ng,...mn,[Symbol.iterator](){return new ln(this)},toJSON(){return{_id:"Effect",op:this[ml],...F in this?{args:this[F]}:void 0}}},Jo=(e)=>W(e,At),hl=(e)=>W(e,fn),Go="~effect/Cause",Ko="~effect/Cause/Reason",Ho=(e)=>W(e,Go);class jt{constructor(e){this[Go]=Go,this.reasons=e}pipe(){return Fe(this,arguments)}toJSON(){return{_id:"Cause",failures:this.reasons.map((e)=>e.toJSON())}}toString(){return`Cause(${G(this.reasons)})`}[cn](){return this.toJSON()}[oe](e){return Ho(e)&&this.reasons.length===e.reasons.length&&this.reasons.every((t,n)=>le(t,e.reasons[n]))}[re](){return Bo(this.reasons)}}var pl=new WeakMap;class Cr{[Ko];annotations;_tag;constructor(e,t,n){if(this[Ko]=Ko,this._tag=e,t!==Rr&&typeof n==="object"&&n!==null&&t.size>0){let r=pl.get(n);if(r)t=new Map([...r,...t]);pl.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((o,i)=>{if(t?.overwrite!==!0&&n.has(i))return;n.set(i,o)});let r=Object.assign(Object.create(Object.getPrototypeOf(this)),this);return r.annotations=n,r}pipe(){return Fe(this,arguments)}toString(){return G(this)}[cn](){return this.toString()}}var Rr=new Map;class Pr extends Cr{constructor(e,t=Rr){super("Fail",t,e);this.error=e}toString(){return`Fail(${G(this.error)})`}toJSON(){return{_tag:"Fail",error:this.error}}[oe](e){return hn(e)&&le(this.error,e.error)&&le(this.annotations,e.annotations)}[re](){return ue(Ie(this._tag))(ue(V(this.error))(V(this.annotations)))}}var Yo=(e)=>new jt(e);var gl=(e)=>new jt([new Pr(e)]);class ta extends Cr{constructor(e,t=Rr){super("Die",t,e);this.defect=e}toString(){return`Die(${G(this.defect)})`}toJSON(){return{_tag:"Die",defect:this.defect}}[oe](e){return Xo(e)&&le(this.defect,e.defect)&&le(this.annotations,e.annotations)}[re](){return ue(Ie(this._tag))(ue(V(this.defect))(V(this.annotations)))}}var Zo=(e)=>new jt([new ta(e)]),Nr=N((e)=>Ho(e[0]),(e,t,n)=>{if(t.mapUnsafe.size===0)return e;return new jt(e.reasons.map((r)=>r.annotate(t,n)))}),hn=(e)=>e._tag==="Fail",Xo=(e)=>e._tag==="Die",Qo=(e)=>e._tag==="Interrupt";function Dg(e){return St("Effect.evaluate: Not implemented")}var Be=(e)=>({...Fg,[ml]:e.op,[Z]:e[Z]??Dg,[ie]:e[ie],[je]:e[je],[dn]:e[dn]}),xt=(e)=>{let t=Be(e),n=function(r){this[F]=r};return n.prototype=t,function(r){return new n(r)}},yl=(e)=>{let t={[fn]:fn,_tag:e.op,get[e.prop](){return this[F]},...Be(e),toString(){return`${e.op}(${G(this[F])})`},toJSON(){return{_id:"Exit",_tag:e.op,[e.prop]:this[F]}},[oe](r){return hl(r)&&r._tag===this._tag&&le(this[F],r[F])},[re](){return ue(Ie(e.op),V(this[F]))}},n=function(r){this[F]=r};return n.prototype=t,function(r){return new n(r)}},fe=yl({op:"Success",prop:"value",[Z](e){let t=e.getCont(ie);return t?t[ie](this[F],e,this):e.yieldWith(this)}}),na={key:"effect/Cause/StackTrace"},xl={key:"effect/Cause/InterruptorStackTrace"},st=yl({op:"Failure",prop:"cause",[Z](e){let t=this[F],n=!1;if(e.cache.stackFrame)t=Nr(t,{mapUnsafe:new Map([[na.key,e.cache.stackFrame]])}),n=!0;let r=e.getCont(je);while(e.interruptible&&e._interruptedCause&&r)r=e.getCont(je);return r?r[je](t,e,n?void 0:this):e.yieldWith(n?st(t):this)}}),jn=(e)=>st(gl(e)),St=(e)=>st(Zo(e)),Bt=xt({op:"WithFiber",[Z](e){return this[F](e)}}),Lg=xt({op:"WithFiberSucceed",[Z](e){let t=this[F](e),n=e.getCont(ie);return n?n[ie](t,e):e.yieldWith(fe(t))}}),Ug=function(){class e extends globalThis.Error{}let t=Be({op:"YieldableError",[Z](){return jn(this)}});return delete t.toString,Object.assign(e.prototype,t),e}(),Sl=function(){let e=Symbol.for("effect/Data/Error/plainArgs");return class extends Ug{constructor(n){super(n?.message,n?.cause?{cause:n.cause}:void 0);if(n)ul(this,n),Object.defineProperty(this,e,{value:n,enumerable:!1})}toJSON(){return{...this[e],...this}}}}(),Fr=(e)=>{class t extends Sl{_tag=e}return t.prototype.name=e,t};var ea="~effect/Cause/Done";var Rv={[ea]:ea,_tag:"Done",value:void 0};var El="~effect/Option",bl={[El]:{_A:(e)=>e},...mn,[Symbol.iterator](){return new ln(this)}},Mg=Object.defineProperty(Object.assign(Object.create(bl),{_tag:"Some",_op:"Some",[oe](e){return ra(e)&&wl(e)&&le(this.value,e.value)},[re](){return ue(V(this._tag))(V(this.value))},toString(){return`some(${G(this.value)})`},toJSON(){return{_id:"Option",_tag:this._tag,value:un(this.value)}}}),"valueOrUndefined",{get(){return this.value}}),$g=V("None"),jg=Object.assign(Object.create(bl),{_tag:"None",_op:"None",valueOrUndefined:void 0,[oe](e){return ra(e)&&vl(e)},[re](){return $g},toString(){return"none()"},toJSON(){return{_id:"Option",_tag:this._tag}}}),ra=(e)=>W(e,El),vl=(e)=>e._tag==="None",wl=(e)=>e._tag==="Some",Il=Object.create(jg),_l=function(e){this.value=e};_l.prototype=Mg;var kl=(e)=>new _l(e);var Tl="~effect/Result",Al={[Tl]:{_A:(e)=>e,_E:(e)=>e},...mn,[Symbol.iterator](){return new ln(this)}},qg=Object.assign(Object.create(Al),{_tag:"Success",_op:"Success",[oe](e){return oa(e)&&sa(e)&&le(this.success,e.success)},[re](){return ue(V(this._tag))(V(this.success))},toString(){return`success(${G(this.success)})`},toJSON(){return{_id:"Result",_tag:this._tag,value:un(this.success)}}}),Vg=Object.assign(Object.create(Al),{_tag:"Failure",_op:"Failure",[oe](e){return oa(e)&&ia(e)&&le(this.failure,e.failure)},[re](){return ue(V(this._tag))(V(this.failure))},toString(){return`failure(${G(this.failure)})`},toJSON(){return{_id:"Result",_tag:this._tag,failure:un(this.failure)}}}),oa=(e)=>W(e,Tl),ia=(e)=>e._tag==="Failure",sa=(e)=>e._tag==="Success",Ol=function(e){this.failure=e};Ol.prototype=Vg;var Cl=(e)=>new Ol(e),Rl=function(e){this.success=e};Rl.prototype=qg;var Pl=(e)=>new Rl(e);function Wg(e){return(t,n)=>t===n?0:e(t,n)}var aa=Wg((e,t)=>{if(globalThis.Number.isNaN(e)&&globalThis.Number.isNaN(t))return 0;if(globalThis.Number.isNaN(e))return-1;if(globalThis.Number.isNaN(t))return 1;return e<t?-1:1});var Nl=(e)=>N(2,(t,n)=>e(t,n)===1);var Fl=(e)=>N(2,(t,n)=>e(t,n)!==-1);var ti=()=>Il,ni=kl;var at=Pl,De=Cl;var Ll=(e)=>{if(on(e))try{return at(e())}catch(t){return De(t)}else try{return at(e.try())}catch(t){return De(e.catch(t))}};var ct=ia,Et=sa;var Ul=N(2,(e,t)=>ct(e)?De(t(e.failure)):e);var ri=N(2,(e,{onFailure:t,onSuccess:n})=>ct(e)?t(e.failure):n(e.success));var ca=globalThis.Array;var Ml=(e)=>ca.isArray(e)?e:ca.from(e);var ua=N(2,(e,t)=>[...e,t]);var Yv=ca.isArray;var la=Ys,$l=Ys;var oi=()=>[];var jl=N(2,(e,t)=>e.map(t));var Bl=(e)=>Be({op:e.label,[Z]:e.evaluate});var ql="~effect/Context/Service",Vl=function(){function e(){}let t=e;Object.setPrototypeOf(t,Jg);let n=(r,o)=>{if(t.key=r,o?.defaultValue)t[pa]=pa,t.defaultValue=o.defaultValue;if(o?.make)t.make=o.make;if(o?.fiberCached)zl.add(r);return t};return arguments.length>0?n(arguments[0],arguments[1]):n},Jg={[ql]:ql,...Bl({label:"Service",evaluate(e){return fe(He(e.context,this))}}),toJSON(){return{_id:"Service",key:this.key}},of(e){return e},context(e){return ga(this,e)},use(e){return Bt((t)=>e(He(t.context,this)))},useSync(e){return Bt((t)=>fe(e(He(t.context,this))))}},zl=new Set,pa="~effect/Context/Reference",Wl="~effect/Context",Hg=8,Yg=8,ma=(e,t,n,r)=>{let o=Object.create(Zg);return o.cacheRoot=e??o,o.base=t,o.overlay=n,o.depth=r,o._flat=void 0,o.baseHits=0,o},Kl=(e,t)=>{if(!t)return;Kl(e,t.parent),e.set(t.key,t.value)},Gl=(e)=>{if(e._flat)return e._flat;if(!e.overlay)return e._flat=e.base;let t=new Map(e.base);return Kl(t,e.overlay),e._flat=t};var ha=Symbol(),Jl=(e,t)=>{let n=e;for(let o=n.overlay;o;o=o.parent)if(o.key===t)return o.value;let r=n.base.get(t);if(r===void 0&&!n.base.has(t))return ha;if(n.overlay&&++n.baseHits>=n.base.size&&n.baseHits>=Yg)n.base=Gl(n),n.overlay=void 0,n.depth=0;return r},ii=(e)=>ma(void 0,e,void 0,0),Zg={get mapUnsafe(){return Gl(this)},...mn,[Wl]:{_Services:(e)=>e},toJSON(){return{_id:"Context",services:Array.from(this.mapUnsafe).map(([e,t])=>({key:e,value:t}))}},[oe](e){if(!Xg(e))return!1;let t=this.mapUnsafe,n=e.mapUnsafe;if(t.size!==n.size)return!1;for(let[r,o]of t)if(!n.has(r)||!le(o,n.get(r)))return!1;return!0},[re](){return Ar(this.mapUnsafe.size)}},Hl=(e,t)=>e.cacheRoot===t.cacheRoot,Xg=(e)=>W(e,Wl);var Qg=(e)=>!!e[pa],si=()=>ey,ey=ii(new Map),ga=(e,t)=>ii(new Map([[e.key,t]])),Yl=N(3,(e,t,n)=>ty(e,t.key,n)),ty=(e,t,n)=>{let r=e,o=zl.has(t)?void 0:r.cacheRoot;if(r.depth>=Hg){let i=new Map(r.mapUnsafe);return i.set(t,n),ma(o,i,void 0,0)}return ma(o,r.base,{key:t,value:n,parent:r.overlay},r.depth+1)};var ai=(e,t)=>{let n=Jl(e,t);return n===ha?void 0:n},Zl=N(2,(e,t)=>{let n=Jl(e,t.key);if(n===ha){if(Qg(t))return ny(t);throw ry(t)}return n}),He=Zl,da="~effect/Context/defaultValue",ny=(e)=>{if(da in e)return e[da];return e[da]=e.defaultValue()},ry=(e)=>{let t=Error(`Service not found${e.key?`: ${String(e.key)}`:""}`);if(t.stack){let n=t.stack.split(`
13
+ `);n.splice(1,3),t.stack=n.join(`
14
+ `)}return t};var ut=Vl;var ui="~effect/Duration",sf=BigInt(0),af=BigInt(1),oy=BigInt(2),iy=BigInt(10);var sy=BigInt(1000);var li=(e)=>BigInt(e<0?Math.ceil(e-0.5):Math.floor(e+0.5)),cf=(e)=>li(e*1e6),Xl=(e,t)=>{let n=e.indexOf(".");if(n===-1)return BigInt(e)*t;let r=e[0]==="-",o=e.slice(n+1),i=iy**BigInt(o.length),s=(BigInt(e.slice(r?1:0,n))*i+BigInt(o))*t,a=s/i+(s%i*oy>=i?af:sf);return r?-a:a};var ay=/^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/,fi=(e)=>{switch(typeof e){case"number":return rf(e);case"bigint":return ci(e);case"string":{if(e==="Infinity")return tf;if(e==="-Infinity")return nf;let t=ay.exec(e);if(!t)break;let[n,r,o]=t;if(o==="nano"||o==="nanos")return ci(Xl(r,af));if(o==="micro"||o==="micros")return ci(Xl(r,sy));let i=Number(r);switch(o){case"milli":case"millis":return rf(i);case"second":case"seconds":return py(i);case"minute":case"minutes":return my(i);case"hour":case"hours":return hy(i);case"day":case"days":return gy(i);case"week":case"weeks":return yy(i)}break}case"object":{if(e===null)break;if(ui in e)return e;if(Array.isArray(e)){if(e.length!==2||!e.every(kr))return Ql(e);if(Number.isNaN(e[0])||Number.isNaN(e[1]))return dy;if(e[0]===-1/0||e[1]===-1/0)return nf;if(e[0]===1/0||e[1]===1/0)return tf;return qe(li(e[0]*1e9+e[1]))}let t=e,n=0;if(t.weeks)n+=t.weeks*604800000;if(t.days)n+=t.days*86400000;if(t.hours)n+=t.hours*3600000;if(t.minutes)n+=t.minutes*60000;if(t.seconds)n+=t.seconds*1000;if(t.milliseconds)n+=t.milliseconds;if(!t.microseconds&&!t.nanoseconds)return qe(n);return qe(li(n*1e6+(t.microseconds??0)*1000+(t.nanoseconds??0)))}}return Ql(e)},Ql=(e)=>{throw Error(`Invalid Input: ${e}`)};var ef={_tag:"Millis",millis:0},cy={_tag:"Infinity"},uy={_tag:"NegativeInfinity"},ly={[ui]:ui,[re](){switch(this.value._tag){case"Millis":{let e=this.value.millis*1e6;return Number.isFinite(e)?V(li(e)):Ar(this.value.millis)}case"Nanos":return V(this.value.nanos);default:return Js(this.value)}},[oe](e){return fy(e)&&by(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"}}},[cn](){return this.toJSON()},pipe(){return Fe(this,arguments)}},qe=(e)=>{let t=Object.create(ly);if(typeof e==="number")if(isNaN(e)||e===0||Object.is(e,-0))t.value=ef;else if(!Number.isFinite(e))t.value=e>0?cy:uy;else if(!Number.isInteger(e))t.value={_tag:"Nanos",nanos:cf(e)};else t.value={_tag:"Millis",millis:e};else if(e===sf)t.value=ef;else t.value={_tag:"Nanos",nanos:e};return t},fy=(e)=>W(e,ui);var dy=qe(0),tf=qe(1/0),nf=qe(-1/0),ci=(e)=>qe(e);var rf=(e)=>qe(e),py=(e)=>qe(e*1000),my=(e)=>qe(e*60000),hy=(e)=>qe(e*3600000),gy=(e)=>qe(e*86400000),yy=(e)=>qe(e*604800000),uf=(e)=>xy(fi(e),{onMillis:ce,onNanos:(t)=>Number(t)/1e6,onInfinity:()=>1/0,onNegativeInfinity:()=>-1/0});var of=(e)=>{let t=fi(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 cf(t.value.millis)}};var xy=N(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)()}}),Sy=N(3,(e,t,n)=>{if(e.value._tag==="Infinity"||e.value._tag==="NegativeInfinity"||t.value._tag==="Infinity"||t.value._tag==="NegativeInfinity")return n.onInfinity(e,t);if(e.value._tag==="Millis")return t.value._tag==="Millis"?n.onMillis(e.value.millis,t.value.millis):n.onNanos(of(e),t.value.nanos);else return n.onNanos(e.value.nanos,of(t))});var Ey=(e,t)=>Sy(e,t,{onMillis:(n,r)=>n===r,onNanos:(n,r)=>n===r,onInfinity:(n,r)=>n.value._tag===r.value._tag});var by=N(2,(e,t)=>Ey(e,t));var xa=ut("effect/Scheduler",{fiberCached:!0,defaultValue:()=>new di}),lf=(e)=>{let t=!1;return Promise.resolve().then(()=>{if(!t)e()}),()=>{t=!0}},wy="setImmediate"in globalThis?(e)=>{let t=globalThis.setImmediate(e);return()=>globalThis.clearImmediate(t)}:(e)=>{let t=setTimeout(e,0);return()=>clearTimeout(t)},ff=(e)=>{try{return wy(e)}catch{return lf(e)}};class df{buckets=[];scheduleTask(e,t){let n=this.buckets,r=n.length,o,i=0;for(;i<r;i++){if(n[i][0]>t)break;o=n[i]}if(o&&o[0]===t)o[1].push(e);else if(i===r)n.push([t,[e]]);else n.splice(i,0,[t,[e]])}drain(){let e=this.buckets;return this.buckets=[],e}}class di{executionMode;setImmediate;constructor(e="async",t){this.executionMode=e,this.setImmediate=t??(e==="sync"?lf:ff)}shouldYield(e){return e.currentOpCount>=e.cache.maxOpsBeforeYield}makeDispatcher(){return new pf(this.setImmediate)}}class pf{tasks=new df;running=void 0;setImmediate;constructor(e=ff){this.setImmediate=e}scheduleTask(e,t){if(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 r=0;r<n.length;r++)n[r]()}}flush(){while(this.tasks.buckets.length>0){if(this.running!==void 0)this.running(),this.running=void 0;this.runTasks()}}}var mf=ut("effect/Scheduler/MaxOpsBeforeYield",{fiberCached:!0,defaultValue:()=>2048}),hf=ut("effect/Scheduler/PreventSchedulerYield",{fiberCached:!0,defaultValue:()=>!1});var pi=Fr;var yf="~effect/encoding/EncodingError";class Dr extends pi("EncodingError"){[yf]=yf}var xf="effect/Tracer/ParentSpan";var Sf="effect/Tracer";var Ef="effect/Metric/FiberRuntimeMetrics";var bf=ut("effect/References/CurrentStackFrame",{fiberCached:!0,defaultValue:Er}),vf=ut("effect/References/TracerEnabled",{fiberCached:!0,defaultValue:qs});var wf=ut("effect/References/CurrentLogLevel",{fiberCached:!0,defaultValue:()=>"Info"}),If=ut("effect/References/MinimumLogLevel",{fiberCached:!0,defaultValue:()=>"Info"});class Af extends Cr{constructor(e,t=Rr){super("Interrupt",t,"Interrupted");this.fiberId=e}toString(){return`Interrupt(${this.fiberId})`}toJSON(){return{_tag:"Interrupt",fiberId:this.fiberId}}[oe](e){return Qo(e)&&this.fiberId===e.fiberId&&this.annotations===e.annotations}[re](){return ue(Ie(`${this._tag}:${this.fiberId}`))(jo(this.annotations))}}var Of=(e)=>new jt([new Af(e)]);var Lr=(e)=>{for(let t=0;t<e.reasons.length;t++){let n=e.reasons[t];if(n._tag==="Fail")return at(n.error)}return De(e)};var Cf=(e)=>{let t=e.reasons.find(Xo);return t?at(t.defect):De(e)},Rf=(e)=>e.reasons.some(Qo);var Cy=(e,t)=>{let n=new Map,r=[];for(let o of e.concat(t)){let i=V(o),s=n.get(i);if(s===void 0)n.set(i,[o]);else if(s.some((a)=>le(a,o)))continue;else s.push(o);r.push(o)}return r},gi=N(2,(e,t)=>{if(e.reasons.length===0)return t;else if(t.reasons.length===0)return e;let n=new jt(Cy(e.reasons,t.reasons));return le(e,n)?e:n}),Pf=N(2,(e,t)=>{let n=!1,r=e.reasons.map((o)=>{if(hn(o))return n=!0,new Pr(t(o.error),o.annotations);return o});return n?Yo(r):e}),Nf=(e)=>{let t;for(let n of e.reasons){if(n._tag==="Fail")return n.error;if(n._tag==="Die")t??=n}if(t!==void 0)return t.defect;if(e.reasons.length>0)return new globalThis.Error("All fibers interrupted without error");return new globalThis.Error("Empty cause")};var Ry="~effect/Fiber",Py={_A:ce,_E:ce},Ny={id:0},Fy=()=>globalThis[Mn];class va{constructor(e,t=!0){this.setContext(e),this.id=++Ny.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.cache.runtimeMetrics?.recordFiberStart(this.context)}get[Ry](){return Py}get currentDispatcher(){return this._dispatcher??=this.cache.scheduler.makeDispatcher()}getRef(e){return He(this.context,e)}addObserver(e){if(this._exit)return e(this._exit),Vs;if(this._observers===void 0)this._observers=[e];else this._observers.push(e);return()=>this.removeObserver(e)}removeObserver(e){if(this._exit||this._observers===void 0)return;let t=this._observers.indexOf(e);if(t>=0)this._observers.splice(t,1)}interruptUnsafe(e,t){if(this._exit)return;let n=Of(e);if(this.cache.stackFrame)n=Nr(n,ga(na,this.cache.stackFrame));if(t)n=Nr(n,t);if(this._interruptedCause=this._interruptedCause?gi(this._interruptedCause,n):n,this.interruptible)if(this._running)this._deferredInterrupt=!0;else this.evaluate(_e(this._interruptedCause))}pollUnsafe(){return this._exit}evaluate(e){if(this._exit)return;else if(this._yielded!==void 0){let r=this._yielded;this._yielded=void 0,r()}let t=this.runLoop(e);if(t===pn)return;let n=_f.interruptChildren&&_f.interruptChildren(this);if(n!==void 0)return this.evaluate(Ze(n,()=>t));if(this._exit=t,this.cache.runtimeMetrics?.recordFiberEnd(this.context,this._exit),this._parent)this._parent._children?.delete(this),this._parent=void 0;if(this._observers!==void 0){let r=this._observers;this._observers=void 0;for(let o=0;o<r.length;o++)r[o](t)}this._stack.length=0,this._children=void 0,this.context=si()}runLoop(e){let t=globalThis[Mn];globalThis[Mn]=this;let n=this._running;this._running=!0;let r=!1,o=e;this.currentOpCount=0;try{while(!0){if(this._deferredInterrupt)this._deferredInterrupt=!1,o=_e(this._interruptedCause);this.currentOpCount++;let i=this.cache;if(!r&&!i.preventYield&&i.scheduler.shouldYield(this)){r=!0;let s=o;o=Ze(wa,()=>s)}if(o=i.tracerContext?i.tracerContext(o,this):o[Z](this),o===pn){let s=this._yielded;if(fn in s)return this._deferredInterrupt=!1,this._yielded=void 0,s;else if(this._deferredInterrupt){this._yielded=void 0,s();continue}return pn}}}catch(i){if(!W(o,Z))return St(`Fiber.runLoop: Not a valid effect: ${String(o)}`);return this.runLoop(St(i))}finally{this._running=n,globalThis[Mn]=t}}getCont(e){if(this._deferredInterrupt)return this._deferredInterrupt=!1,Ly;while(!0){let t=this._stack.pop();if(!t)return;let n=t[dn];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&Uy-1)===0)return fe(e);let t=this.getCont(ie);return t?t[ie](e,this):this.yieldWith(fe(e))}yieldWith(e){return this._yielded=e,pn}children(){return this._children??=new Set}pipe(){return Fe(this,arguments)}setContext(e){let t=this.context;if(this.context=e,t!==void 0&&Hl(t,e))return;let n=e.cacheRoot,r=n._fiberCache??=Dy(e);if(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}}var Dy=(e)=>{let t=ai(e,Sf);return{scheduler:He(e,xa),tracer:t,tracerContext:t?t.context:void 0,tracerEnabled:He(e,vf),span:ai(e,xf),logLevel:He(e,wf),minimumLogLevel:He(e,If),stackFrame:He(e,bf),runtimeMetrics:ai(e,Ef),maxOpsBeforeYield:He(e,mf),preventYield:He(e,hf)}},Ly={[ie](e,t){return _e(t._interruptedCause)},[je](e,t){return _e(t._interruptedCause)}},Uy=32,_f={interruptChildren:void 0},Ff=(e)=>{if(!e.cache.stackFrame)return;let t=new Map;return t.set(xl.key,e.cache.stackFrame),ii(t)};var My=(e)=>Mr((t)=>{let n=e[Symbol.iterator](),r=[],o=void 0;function i(){let s=n.next();while(!s.done){if(s.value._exit){r.push(s.value._exit),s=n.next();continue}o=s.value.addObserver((a)=>{r.push(a),i()});return}t(Ye(r))}return i(),xn(()=>o?.())});var kf=(e)=>Bt((t)=>{let n=Ff(t),r=oi();for(let o of e)o.interruptUnsafe(t.id,n),r.push(o);return Kf(My(r))});var Ye=fe,_e=st,qn=jn,xn=xt({op:"Sync",[Z](e){let t=this[F](),n=e.getCont(ie);return n?n[ie](t,e):e.yieldWith(fe(t))}}),Ve=xt({op:"Suspend",[Z](e){return this[F]()}});var Df=ri({onFailure:qn,onSuccess:Ye});var Lf=xt({op:"Yield",[Z](e){let t=!1;return e.currentDispatcher.scheduleTask(()=>{if(t)return;e.evaluate(Ot)},this[F]??0),e.yieldWith(()=>{t=!0})}}),wa=Lf(0);var Uf=(e)=>Ve(()=>_e(e())),Ur=(e)=>St(e),Mf=(e)=>Ve(()=>qn(e())),qt=Ye(void 0);var $f=(e)=>{let t=typeof e==="function"?e:e.try,n=typeof e==="function"?(r)=>new bi(r,"An error occurred in Effect.try"):e.catch;return Ve(()=>{try{return Ye(t())}catch(r){return qn(n(r))}})};var jf=(e)=>{let t=typeof e==="function"?e:e.try,n=typeof e==="function"?(r)=>new bi(r,"An error occurred in Effect.tryPromise"):e.catch;return Bf(function(r,o){let i=(s)=>{try{r(qn(Or(()=>n(s))))}catch(a){r(Ur(a))}};try{t(o).then((s)=>r(Ye(s)),i)}catch(s){i(s)}},t.length!==0)};var Bf=function(){let e=Be({op:"Async",[Z](n){let r=!1,o=!1,i=this.withSignal?new AbortController:void 0,s=this.register.call(n.cache.scheduler,(a)=>{if(r)return;if(r=!0,o)n.evaluate(a);else o=a},i?.signal);if(o!==!1)return o;if(o=!0,n._yielded=()=>{r=!0},i===void 0&&s===void 0)return pn;return n._stack.push($y(()=>(r=!0,i?.abort(),s??Ot))),pn}}),t=function(n,r){this.register=n,this.withSignal=r};return t.prototype=e,function(n,r){return new t(n,r)}}(),$y=xt({op:"AsyncFinalizer",[dn](e){if(e.interruptible)e.interruptible=!1,e._stack.push(Ra)},[je](e,t){return Rf(e)?Ze(ad(st(e),this[F]()),()=>_e(e)):_e(e)}}),Mr=(e)=>Bf(e,e.length>=2),qf=Mr(Vs),Vf=(...e)=>{if(e.length===1){let r=e[0];return Ve(()=>hi(r()))}let[t,n]=e;return Ve(()=>hi(n.call(t.self)))};var jy=(e,t)=>Object.defineProperty(t,"length",{value:e,configurable:!0});var zf=(e,...t)=>jy(e.length,t.length===0?function(){return Tf(()=>e.apply(this,arguments))}:function(){let n=Tf(()=>e.apply(this,arguments));for(let r of t)n=r(n,...arguments);return n}),Tf=(e)=>{try{let t=e(),n=void 0;while(!0){let r=t.next(n);if(r.done)return Ye(r.value);let o=r.value;if(o&&o._tag==="Success"){n=o.value;continue}else if(o&&o._tag==="Failure")return r.value;else{let i=!0;return Ve(()=>{if(i)return i=!1,Ze(r.value,(s)=>hi(t,s));else return Ve(()=>hi(e()))})}}}catch(t){return Ur(t)}},hi=function(){let e=Be({op:"Iterator",[ie](n,r){let o=this.iterator;while(!0){let i=o.next(n);if(i.done)return Ye(i.value);if(!J(i.value))return r._stack.push(this),i.value;else if(i.value._tag==="Failure")return i.value;n=i.value.value}},[Z](n){return this[ie](this.initial,n)}}),t=function(n,r){this.iterator=n,this.initial=r};return t.prototype=e,function(n,r){return new t(n,r)}}(),yi=N(2,(e,t)=>new $r(e,Wf,Ye(t))),xi=function(e){return e._stack.push(this),this[F]},By=Be({op:"OnSuccess",[Z]:xi}),$r=function(e,t,n){this[F]=e,this[ie]=t,this.payload=n};$r.prototype=By;var Wf=function(){return this.payload};var Ia=(()=>({["~effect/Effect/stackProbe"]:function(){return Error().stack}})["~effect/Effect/stackProbe"]()?.includes("[as ~effect/Effect/stackProbe]")===!0)(),qy=function(e,t){let n=this.payload;return t.succeedWith(Ia?n(e):Or(()=>n(e)))},Vy=function(e){let t=this.payload;return t(e)};var Kf=(e)=>new $r(e,Wf,Ot);var Ze=N(2,(e,t)=>new $r(e,Vy,t));var J=(e)=>e[fn]!==void 0,Gf=N(2,(e,t)=>{if(J(e))return e._tag==="Success"?t(e.value):e;return Ze(e,t)});var _a=N(2,(e,t)=>new $r(e,qy,t)),Jf=N(2,(e,t)=>J(e)?Yf(e,t):_a(e,t)),Hf=N(2,(e,t)=>J(e)?Zf(e,t):Oa(e,t));var ka=(e)=>e._tag==="Success";var Ot=fe(void 0),Yf=N(2,(e,t)=>e._tag==="Success"?fe(t(e.value)):e),Zf=N(2,(e,t)=>{if(e._tag==="Success")return e;let n=Lr(e.cause);if(ct(n))return e;return jn(t(n.success))});var jr=N(2,(e,t)=>new Xf(e,t.length!==1?(n)=>t(n):t)),zy=Be({op:"OnFailure",[Z]:xi}),Xf=function(e,t){this[F]=e,this[je]=t};Xf.prototype=zy;var Ta=N(3,(e,t,n)=>jr(e,(r)=>{let o=t(r);return ct(o)?_e(o.failure):n(o.success,r)})),Aa=N(2,(e,t)=>Ta(e,Lr,(n)=>t(n)));var Qf=N(2,(e,t)=>Ta(e,Cf,t));var ed=N((e)=>Jo(e[0]),(e,t,n,r)=>jr(e,(o)=>{let i=Lr(o);if(ct(i))return _e(i.failure);if(!t(i.success))return r?r(i.success):_e(o);return n(i.success)}));var Oa=N(2,(e,t)=>Aa(e,(n)=>Mf(()=>t(n))));var td=(e)=>Aa(e,Ur);var mi=(e)=>sd(e,{onFailure:De,onSuccess:at}),nd=N(2,(e,t)=>new rd(e,t.onSuccess.length!==1?(n)=>t.onSuccess(n):t.onSuccess,t.onFailure.length!==1?(n)=>t.onFailure(n):t.onFailure)),Wy=Be({op:"OnSuccessAndFailure",[Z]:xi}),rd=function(e,t,n){this[F]=e,this[ie]=t,this[je]=n};rd.prototype=Wy;var Ky=function(e,t){let n=this.payload;return t.succeedWith(Ia?n.onSuccess(e):Or(()=>n.onSuccess(e)))},Gy=(e,t)=>{let n=Be({op:e,[Z]:xi,[ie]:Ky,[je]:t}),r=function(o,i){this[F]=o,this.payload=i};return r.prototype=n,r},Jy=Gy("Match",function(e,t){let n=e.reasons.find(hn);if(n===void 0)return _e(e);let r=this.payload;return t.succeedWith(Ia?r.onFailure(n.error):Or(()=>r.onFailure(n.error)))});var od=N(2,(e,t)=>nd(e,{onFailure:(n)=>{let r=n.reasons.find(hn);return r?t.onFailure(r.error):_e(n)},onSuccess:t.onSuccess})),id=N(2,(e,t)=>new Jy(e,t)),sd=N(2,(e,t)=>{if(J(e)){if(e._tag==="Success")return fe(t.onSuccess(e.value));let n=Lr(e.cause);if(ct(n))return e;return fe(t.onFailure(n.success))}return id(e,t)});var Ca=(e)=>J(e)?fe(e):Hy(e),Hy=xt({op:"Exit",[Z](e){return e._stack.push(this),this[F]},[ie](e,t,n){return t.succeedWith(n??fe(e))},[je](e,t,n){return t.succeedWith(n??st(e))}});var ad=(e,t)=>ka(e)?t:jr(t,(n)=>_e(gi(e.cause,n)));var Yy=function(){let e=Be({op:"OnExit",[Z](n){return n._stack.push(this),this.effect},[dn](n){if(n.interruptible&&this.interruptible!==!0)n._stack.push(Ra),n.interruptible=!1},[ie](n,r,o){o??=fe(n);let i;try{i=this.onExit(o)}catch(s){i=St(s)}return i?Ze(i,(s)=>o):o},[je](n,r,o){o??=st(n);let i;try{i=this.onExit(o)}catch(s){i=St(s)}return i?Ze(ad(o,i),(s)=>o):o}}),t=function(n,r,o){this.effect=n,this.onExit=r,this.interruptible=o};return t.prototype=e,t}(),cd=(e,t,n)=>new Yy(e,t,n);var ud=N(2,cd),ld=N(2,(e,t)=>ud(e,(n)=>t));var fd=(e)=>Bt((t)=>{if(!t.interruptible)return e;return t.interruptible=!1,t._stack.push(Ra),e}),Zy=xt({op:"SetInterruptible",[dn](e){if(e.interruptible=this[F],e._interruptedCause&&e.interruptible)return()=>_e(e._interruptedCause)}}),Ra=Zy(!0);var dd=(e,t)=>{if(Qu(e))return t?.mode==="result"?yn(e,mi,t):yn(e,ce,t);else if(t?.discard)return t.mode==="result"?yn(Object.values(e),mi,t):yn(Object.values(e),ce,t);return Ve(()=>{let n={};return yi(yn(Object.entries(e),([r,o])=>_a(t?.mode==="result"?mi(o):o,(i)=>{$t(n,r,i)}),{discard:!0,concurrency:t?.concurrency}),n)})};var pd=xt({op:"While",[ie](e,t){if(this[F].step(e),this[F].while())return t._stack.push(this),this[F].body();return Ot},[Z](e){if(this[F].while())return e._stack.push(this),this[F].body();return Ot}}),yn=N((e)=>typeof e[1]==="function",(e,t,n)=>Ve(()=>{let r=Br(n?.concurrency);if(r===1)return Xy(e,t,n);let o=Ml(e),i=o.length;if(i===0)return n?.discard?qt:Ye([]);let s=n?.discard?void 0:Array(i),a=Qy({f:t,out:s},o,{concurrency:r});return a?yi(a,s):Ye(s)}));var Xy=(e,t,n)=>Ve(()=>{let r=n?.discard?void 0:[],o=e[Symbol.iterator](),i=o.next(),s=0;return yi(pd({while:()=>!i.done,body:()=>t(i.value,s++),step:(a)=>{if(r)r.push(a);i=o.next()}}),r)}),Br=(e)=>e==="unbounded"?Number.POSITIVE_INFINITY:Math.max(1,e??1),Si=()=>(e)=>{let{onItem:t,step:n}=e,r=(i,s,a,l,m)=>Ze(Ca(m),(c)=>n(i,s[a],c,a)??o(i,s,a+1,l)??qt),o=(i,s,a=0,l=s.length)=>{for(;a<l;a++){let m=s[a],c=t(i,m,a);if(!J(c))return r(i,s,a,l,c);let u=n(i,m,c,a);if(u)return u._tag==="Failure"?u:void 0}};return o},md=(e)=>{let{onItem:t,step:n}=e;return(r,o,i)=>{let s=0,a=i.end??o.length,l=i.concurrency,m=!1,c,u,g,x,S,b=(p)=>{let h=St(p);return x=h,m=!0,u&&u.size>0?Ze(fd(kf(Array.from(u))),()=>x??h):h},y=()=>{let p=!1;for(;!x&&s<a;s++){let h=o[s],_=S??t(r,h,s);if(J(_)){if(x=n(r,h,_,s),x)break}else if(!c)return Mr((I)=>{c=Fy(),u=new Set,S=_,g=I;let k;try{k=y()}catch(M){return I(b(M))}if(k)return I(k);return Ve(()=>(x??=Ot,Ze(u?kf(u):qt,()=>x?._tag==="Failure"?x:qt)))});else{S=void 0;let I=ex(c,_,!0,!0,"inherit");if(I._exit){if(x=n(r,h,I._exit,s),x)break;continue}u.add(I);let k=s;if(I.addObserver((M)=>{u.delete(I);try{if(x){if(M._tag==="Failure"){let j=M.cause.reasons.filter((q)=>q._tag!=="Interrupt");if(j.length>0){let q=Yo(j);x=st(x._tag==="Failure"?gi(x.cause,q):q)}}}else{let j=n(r,h,M,k);if(j)x=j,y()}if(p){let j=y();if(j)g(j)}else if(m&&u.size===0)g(x??qt)}catch(j){g(b(j))}}),u.size<l)continue;p=!0,s++;return}}if(m=!0,x){if(u&&u.size>0){let h=Ff(c);u.forEach((_)=>_.interruptUnsafe(c.id,h));return}if(g||x._tag==="Failure")return x}else if(g){if(!u)return Ot;else if(u.size===0)g(qt)}};return y()}},Ei=()=>(e)=>md(e),Qy=md({onItem(e,t,n){return e.f(t,n)},step(e,t,n,r){if(n._tag==="Failure")return n;else if(e.out)e.out[r]=n.value}});var ex=(e,t,n=!1,r=!1,o=!1)=>{let i=e,s=o==="inherit"?i.interruptible:!o,a=new va(i.context,s);if(n)a.evaluate(t);else i.currentDispatcher.scheduleTask(()=>a.evaluate(t),0);if(!r&&!a._exit)i.children().add(a),a._parent=i;return a};var Pa=(e)=>(t,n)=>{let r=new va(n?.scheduler?Yl(e,xa,n.scheduler):e,n?.uninterruptible!==!0);if(r.evaluate(t),r._exit)return r;if(n?.signal)if(n.signal.aborted)r.interruptUnsafe();else{let o=()=>r.interruptUnsafe();n.signal.addEventListener("abort",o,{once:!0}),r.addObserver(()=>n.signal.removeEventListener("abort",o))}if(n?.onFiberStart)n.onFiberStart(r);return r};var hd=(e)=>{let t=Pa(e);return(n,r)=>{let o=t(n,r);return new Promise((i)=>{o.addObserver((s)=>i(s))})}};var gd=(e)=>{let t=hd(e);return(n,r)=>t(n,r).then((o)=>{if(o._tag==="Failure")throw Nf(o.cause);return o.value})},yd=gd(si()),xd=(e)=>{let t=Pa(e);return(n)=>{if(J(n))return n;let r=new di("sync"),o=t(n,{scheduler:r});return o._dispatcher?.flush(),o._exit??St(new Na(o))}},Sd=xd(si());var tx=ut("effect/Clock",{defaultValue:()=>new Ed}),Sa=2147483647;class Ed{currentTimeMillisUnsafe(){return Date.now()}currentTimeMillis=xn(()=>this.currentTimeMillisUnsafe());currentTimeNanosUnsafe(){return nx()}currentTimeNanos=xn(()=>this.currentTimeNanosUnsafe());monotonicTimeNanosUnsafe(){return vd()}monotonicTimeNanos=xn(()=>this.monotonicTimeNanosUnsafe());sleep(e){return this.sleepMillis(uf(e))}sleepMillis(e){if(e<=0)return wa;else if(!Number.isFinite(e))return qf;return Mr((t)=>{let n=e>Sa?this.sleepMillis(e-Sa):qt,r=setTimeout(()=>t(n),Math.min(e,Sa));return xn(()=>clearTimeout(r))})}}var bd=BigInt(1e6),vd=function(){let e=globalThis.process?.hrtime;if(typeof e?.bigint==="function")return()=>e.bigint();if(typeof performance<"u"&&typeof performance.now==="function")return()=>BigInt(Math.round(performance.now()*1e6));let t=BigInt(0);return()=>{let n=BigInt(Date.now())*bd;if(n>t)t=n;return t}}(),nx=function(){let e=BigInt(1e9),t;return()=>{let n=vd(),r=BigInt(Date.now())*bd;if(t===void 0)t=r-n;else{let o=t+n;if((r>o?r-o:o-r)>e)t=r-n}return t+n}}(),wd=(e)=>Bt((t)=>e(t.getRef(tx))),Id=(e)=>wd((t)=>t.sleep(fi(e)));var Ea="~effect/Cause/AsyncFiberError";class Na extends Fr("AsyncFiberError"){[Ea]=Ea;constructor(e){super({message:"An asynchronous Effect was executed with Effect.runSync",fiber:e})}}var ba="~effect/Cause/UnknownError";class bi extends Fr("UnknownError"){[ba]=ba;constructor(e,t){super({message:t,cause:e})}}var rx="~effect/Logger",Nw={[rx]:{_Message:ce,_Output:ce},pipe(){return Fe(this,arguments)}};var gn={bold:"1",red:"31",green:"32",yellow:"33",blue:"34",cyan:"36",white:"37",gray:"90",black:"30",bgBrightRed:"101"},Fw={None:[],All:[],Trace:[gn.gray],Debug:[gn.blue],Info:[gn.green],Warn:[gn.yellow],Error:[gn.red],Fatal:[gn.bgBrightRed,gn.black]};var vi=hn;var _d=Zo;var Sn=Pf;var Da=fe,Vr=st,Vn=jn;var zn=Ot;var En=ka;var kd=Jo,Td=dd;var Ad=yn;var Ii=jf,Q=Ye;var _i=Ve,ki=xn;var d=Vf,f=qn;var Ti=Uf,zr=Ur,Vt=$f;var Od=Df;var Xe=Ze;var Wr=Ca;var Wn=jr,D=Qf,U=ed;var Ai=Oa;var Kn=td;var Cd=Id;var Rd=od;var Gn=ld;var La=yd;var Jn=Sd;var Ua=Jf,Ma=Hf;var ke=Gf;var Pd=zf;var Ci=(e)=>ox(typeof e==="string"?ix.encode(e):e),Ri=(e)=>{let t=sx(e),n=t.length;if(n%4!==0)return De(new Dr({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 De(new Dr({kind:"Decode",module:"Base64",input:t,message:"Found a '=' character, but it is not at the end"}));try{let o=t.endsWith("==")?2:t.endsWith("=")?1:0,i=new Uint8Array(3*(n/4)-o);for(let s=0,a=0;s<n;s+=4,a+=3){let l=Oi(t.charCodeAt(s))<<18|Oi(t.charCodeAt(s+1))<<12|Oi(t.charCodeAt(s+2))<<6|Oi(t.charCodeAt(s+3));i[a]=l>>16,i[a+1]=l>>8&255,i[a+2]=l&255}return at(i)}catch(o){return De(new Dr({kind:"Decode",module:"Base64",input:t,message:o instanceof Error?o.message:"Invalid input"}))}};var ox=(e)=>{let t=e.length,n="",r;for(r=2;r<t;r+=3)n+=lt[e[r-2]>>2],n+=lt[(e[r-2]&3)<<4|e[r-1]>>4],n+=lt[(e[r-1]&15)<<2|e[r]>>6],n+=lt[e[r]&63];if(r===t+1)n+=lt[e[r-2]>>2],n+=lt[(e[r-2]&3)<<4],n+="==";if(r===t)n+=lt[e[r-2]>>2],n+=lt[(e[r-2]&3)<<4|e[r-1]>>4],n+=lt[(e[r-1]&15)<<2],n+="=";return n},ix=new TextEncoder;var sx=(e)=>e.replace(/[\n\r]/g,""),lt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Kr=new Uint8Array(123).fill(255);for(let e=0;e<lt.length;e++)Kr[lt.charCodeAt(e)]=e;Kr[61]=0;var Oi=(e)=>{if(e>=Kr.length||Kr[e]===255)throw TypeError(`Invalid character ${String.fromCharCode(e)}`);return Kr[e]};function $a(e){return e.checks?e.checks[e.checks.length-1].annotations:e.annotations}var Pi="~structural";var ja="~sentinels",Ba="~constructor";var Ni=br((e)=>{let t=$a(e)?.identifier;if(typeof t==="string")return t;return e.getExpected(Ni)});var L=Symbol();var de=Da,Qe=de(L),K=de(L),Gr=(e)=>e===L?ti():ni(e),Va=(e)=>e._tag==="None"?Qe:de(e.value);var Yr="~effect/SchemaIssue/Issue";function Wa(e){return W(e,Yr)&&e[Yr]===Yr}function ax(e){return Object.hasOwn(e,"input")}class ft{[Yr]=Yr;constructor(e,t){if(t?.reportInput===!0&&e!==L)this.input=e}}var Fd=class extends ft{_tag="Filter";filter;issue;constructor(e,t,n,r){super(n,r);this.filter=e,this.issue=t}},Dd=class extends ft{_tag="Encoding";ast;issue;constructor(e,t,n,r){super(n,r);this.ast=e,this.issue=t}},Rt=class extends ft{_tag="Pointer";path;issue;constructor(e,t){super();this.path=e,this.issue=t}},Qr=class extends ft{_tag="MissingKey";annotations;constructor(e){super();this.annotations=e}},Ka=class extends ft{_tag="UnexpectedKey";ast;constructor(e,t,n){super(t,n);this.ast=e}},xe=class extends ft{_tag="Composite";ast;issues;constructor(e,t,n,r){super(n,r);this.ast=e,this.issues=t}},bt=class extends ft{_tag="InvalidType";ast;constructor(e,t,n){super(t,n);this.ast=e}},ye=class extends ft{_tag="InvalidValue";annotations;constructor(e,t,n){super(t,n);this.annotations=e}};var eo=class extends ft{_tag="AnyOf";ast;issues;constructor(e,t,n,r){super(n,r);this.ast=e,this.issues=t}},Ld=class extends ft{_tag="OneOf";ast;successes;constructor(e,t,n,r){super(n,r);this.ast=e,this.successes=t}};function za(e,t,n){if(Wa(e))return e;if(typeof e==="string")return new ye({message:e},t,n);let r=typeof e.issue==="string"?new ye({message:e.issue},t,n):e.issue;return new Rt(e.path,r)}function Ud(e,t,n){if(e===void 0)return;if(typeof e==="boolean")return e?void 0:new ye(void 0,t,n);return za(e,t,n)}function Md(e,t,n,r){if(Array.isArray(t)){if(!$l(t))return;return t.length===1?za(t[0],n,r):new xe(e,jl(t,(o)=>za(o,n,r)),n,r)}return Ud(t,n,r)}var cx=(e)=>{let t=Xr(e);if(t!==void 0)return t;switch(e._tag){case"InvalidType":return Zr(Ni(e.ast),e);case"InvalidValue":{let n=$d(e);if(n!==void 0)return Zr(n,e);let r=Fi(e);return r===void 0?"Expected a valid value":`Invalid data ${r}`}case"MissingKey":return"Missing key";case"UnexpectedKey":{let n=Fi(e);return n===void 0?"Expected no excess property":`Unexpected key with value ${n}`}case"Forbidden":return"Forbidden operation";case"OneOf":{let n=Fi(e);return n===void 0?"Expected exactly one member to match":`Expected exactly one member to match the input ${n}`}}},ux=(e)=>Xr(e.issue)??Xr(e);function Fi(e){return ax(e)?G(e.input):void 0}function $d(e){let t=e.annotations?.expected;return typeof t==="string"?t:void 0}function Zr(e,t){let n=Fi(t);return n===void 0?`Expected ${e}`:`Expected ${e}, got ${n}`}function jd(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((n)=>jd(n)).join(" & ")}}function lx(){return(e)=>Hr(e,"")}var Bd=lx();function Hr(e,t){let n;switch(e._tag){case"Filter":{let r=ux(e);if(r!==void 0)n=r;else{if(e.issue._tag!=="InvalidValue")return Hr(e.issue,t);let o=$d(e.issue);n=o===void 0?Zr(jd(e.filter),e):Zr(o,e.issue)}break}case"Encoding":return Hr(e.issue,t);case"Pointer":return Hr(e.issue,t+dl(e.path));case"Composite":case"AnyOf":{if(e._tag==="Composite"||e.issues.length>0)return e.issues.map((r)=>Hr(r,t)).join(`
15
+ `);n=Xr(e)??Zr(Ni(e.ast),e);break}default:n=cx(e);break}return t?`${n}
16
+ at ${t}`:n}function Xr(e){if(e._tag==="Pointer")return;if(e._tag==="Encoding")return Xr(e.issue);let n=(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 n==="string")return n}function to(e){let t;for(let n of e.reasons){if(!vi(n)||!Wa(n.error))return;t??=n.error}return t}function no(e,t){let n=to(e);if(n===void 0)throw Error(t,{cause:e});return n}var Ga=(e)=>Object.assign(Object.create(js),e);var px=Ga({_tag:"Passthrough"});function Di(){return px}function Te(e){return Ga({_tag:"Transform",transform:e})}function zt(e){return Ga({_tag:"TransformEffect",transform:e})}function Ja(){return Te(globalThis.String)}function Li(){return Te(globalThis.Number)}function Vd(e){return zt((t,n)=>Vt({try:()=>JSON.parse(t,e?.reviver),catch:()=>new ye({expected:"a valid JSON string"},t,n)}))}function zd(e){return zt((t,n)=>Vt({try:()=>{let r=JSON.stringify(t,e?.replacer,e?.space);if(r===void 0)throw TypeError("Value cannot be represented as JSON");return r},catch:()=>new ye({expected:"a JSON-serializable value"},t,n)}))}function Wd(){return Te(Ci)}function Kd(){return zt((e,t)=>Ma(Od(Ri(e)),()=>new ye({expected:"a valid Base64 string"},e,t)))}var ro="~effect/SchemaTransformation/Transformation",ze=class extends Sr{[ro]=ro;_tag="Transformation";decode;encode;constructor(e,t){super();this.decode=e,this.encode=t}flip(){return new ze(this.encode,this.decode)}};function gx(e){return W(e,ro)&&e[ro]===ro}var Ya=(e)=>{if(gx(e))return e;return new ze(e.decode,e.encode)};function oo(e){return new ze(zt(e.decode),zt(e.encode))}function Gd(e){return new ze(Te(e.decode),Te(e.encode))}var yx=new ze(Di(),Di());function Ui(){return yx}var io=new ze(Li(),Ja());var Jd=oo({decode:(e,t)=>URL.canParse(e)?Q(new URL(e)):f(new ye({expected:"a valid URL string"},e,t)),encode:(e)=>Q(e.href)});var Hd=new ze(Kd(),Wd());function Yd(e){return new ze(Vd(e??{}),zd(e))}function _n(e){return(t)=>t._tag===e}var ip=_n("Declaration");var Ex=_n("Never");var Zn=_n("Literal"),Xa=_n("UniqueSymbol");var bx=_n("Arrays"),vx=_n("Objects");var sp=_n("Suspend"),et=class{to;transformation;constructor(e,t){this.to=e,this.transformation=t}},qi={},Xn=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}},Xd="~effect/Schema";class tt{[Xd]=Xd;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}>`}}var so=class extends tt{_tag="Declaration";typeParameters;run;encodingChecks;encodingRun;constructor(e,t,n,r,o,i,s,a){super(n,r,o,i);this.typeParameters=e,this.run=t,this.encodingChecks=s,this.encodingRun=a}getParser(){let e;return(t,n)=>{if(t===L)return Qe;return(e??=this.run(this.typeParameters))(t,this,n)}}_rebuild(e,t,n,r,o){let i=Qn(this.typeParameters,e);return i===this.typeParameters&&t===this.checks&&n===this.encodingChecks&&r===this.run&&o===this.encodingRun?this:new so(i,r,this.annotations,t,void 0,this.context,n,o)}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;if(typeof e==="string")return e;return"<Declaration>"}},wx=class extends tt{_tag="Null";getParser(){return Sc(this,null)}getExpected(){return"null"}},ic=new wx;var Ix=class extends tt{_tag="Undefined";getParser(){return Sc(this,void 0)}toCodecJson(){return dt(this,[_x])}getExpected(){return"undefined"}},_x=new et(ic,new ze(Te(()=>{return}),Te(()=>null))),sc=new Ix;var kx=class extends tt{_tag="Unknown";getParser(){return lo(this,Xu)}getExpected(){return"unknown"}},Qa=new kx;var Yn=class extends tt{_tag="Literal";literal;constructor(e,t,n,r,o){super(t,n,r,o);if(typeof e==="number"&&!globalThis.Number.isFinite(e))throw Error(`A numeric literal must be finite, got ${G(e)}`);this.literal=e}getParser(){return Sc(this,this.literal)}matchPart(e,t){return e===globalThis.String(this.literal)?this.literal:void 0}toCodecJson(){return typeof this.literal==="bigint"?Qd(this):this}toCodecStringTree(){return typeof this.literal==="string"?this:Qd(this)}getExpected(){return typeof this.literal==="string"?JSON.stringify(this.literal):globalThis.String(this.literal)}};function Qd(e){let t=globalThis.String(e.literal);return dt(e,[new et(new Yn(t),new ze(Te(()=>e.literal),Te(()=>t)))])}var Tx=class extends tt{_tag="String";getParser(){return lo(this,_r)}matchPart(e,t){let n=this.checks;return n&&!t.disableChecks&&Wt(n,e,void 0,this,t)?void 0:e}getExpected(){return"string"}},vn=new Tx,Ax=class extends tt{_tag="Number";getParser(){return lo(this,kr)}matchKey(e,t){return this._match(Yx,e,t)}matchPart(e,t){return this._match(oc,e,t)}_match(e,t,n){if(!e.test(t))return;let r=globalThis.Number(t);if(n.disableChecks||!this.checks)return r;return Wt(this.checks,r,void 0,this,n)?void 0:r}toCodecJson(){if(this.checks&&(ec(this.checks,"effect/schema/isFinite")||ec(this.checks,"effect/schema/isInt")))return this;return dt(this,[jx])}toCodecStringTree(){if(this.toCodecJson()===this)return dt(this,[Zx]);return dt(this,[Xx])}getExpected(){return"number"}};function ec(e,t){return e.some((n)=>n.annotations?.representation?.id===t||n._tag==="FilterGroup"&&ec(n.checks,t))}var ac=new Ax,Ox=class extends tt{_tag="Boolean";getParser(){return lo(this,Ju)}getExpected(){return"boolean"}},ap=new Ox;var Vi=class extends tt{_tag="Arrays";isMutable;elements;rest;encodingChecks;constructor(e,t,n,r,o,i,s,a){super(r,o,i,s);this.isMutable=e,this.elements=t,this.rest=n,this.encodingChecks=a;let l=!1;for(let m=0;m<t.length;m++)if(wn(t[m]))l=!0;else if(l)throw Error("A required element cannot follow an optional element. ts(1257)");if(l&&n.length>1)throw Error("A required element cannot follow an optional element. ts(1257)");for(let m=1;m<n.length;m++)if(wn(n[m]))throw Error("An optional element cannot follow a rest element. ts(1266)")}getParser(e,t=e){let n=this,r,o,i=n.elements.length,s=Math.max(0,n.rest.length-1);function a(c,u){if(u<i)return r[u];else if(u>=c)return o[u-c+1];return o[0]}let l=(c)=>{let{input:u,len:g,options:x}=c;if(n.rest.length===0&&g>i)for(let S=i;S<g;S++){let b=new Ka(n,u[S],x),y=new Rt([S],b);if(x.errors==="all")if(c.issues)c.issues.push(y);else c.issues=[y];else return f(new xe(n,[y],u,x))}if(c.issues)return f(new xe(n,c.issues,u,x));return de(c.output)},m=(c,u)=>{let g=c.length,x={ast:n,getParser:a,input:c,len:g,tailThreshold:Math.max(i,g-s),output:new globalThis.Array(g),issues:void 0,options:u},S=n.rest.length===0?i:Math.max(g,i+s),b=u.concurrency===void 0?1:Br(u.concurrency),y=b===1?Rx(x,c,0,S):Px(x,c,{concurrency:b,end:S});if(!y)return l(x);if(J(y))return ke(y,()=>l(x));let p=!0;return _i(()=>{if(!p)return m(c,u);return p=!1,Xe(y,()=>l(x))})};return(c,u)=>{if(c===L)return Qe;try{if(!Array.isArray(c))return f(new bt(n,c,u));if(!r)r=n.elements.map((g)=>({ast:g,parser:t(g)})),o=n.rest.map((g)=>({ast:g,parser:t(g)}));return m(c,u)}catch(g){return zr(g)}}}_rebuild(e,t,n){let r=Qn(this.elements,e),o=Qn(this.rest,e);return r===this.elements&&o===this.rest&&t===this.checks&&n===this.encodingChecks?this:new Vi(this.isMutable,r,o,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 $i(e,e.ast,r,n);let o=n===K?t:n[F];if(o!==L)e.output[r]=o;else{let i=e.getParser(e.tailThreshold,r);if(wn(i.ast))return;let s=new Rt([r],new Qr(i.ast.context?.annotations));if(e.options.errors==="all")if(e.issues)e.issues.push(s);else e.issues=[s];else return Vn(new xe(e.ast,[s],e.input,e.options))}}var cp={onItem(e,t,n){let r=n<e.len?t:L;return e.getParser(e.tailThreshold,n).parser(r,e.options)},step:Cx},Rx=Si()(cp),Px=Ei()(cp),$i=(e,t,n,r)=>{if(r.cause.reasons.length===0)return r;let o=to(r.cause);if(o===void 0)return Vr(Sn(r.cause,(s)=>new xe(t,[new Rt([n],s)],e.input,e.options)));let i=new Rt([n],o);if(e.options.errors==="all")if(e.issues)e.issues.push(i);else e.issues=[i];else return Vn(new xe(t,[i],e.input,e.options))},up="[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?";function Za(e,t,n=qi){let r,o;function i(s){switch(s._tag){case"String":case"TemplateLiteral":return(r??=Object.keys(e)).filter((a)=>s.matchPart(a,n)!==void 0);case"Number":return(r??=Object.keys(e)).filter((a)=>s.matchKey(a,n)!==void 0);case"Symbol":return(o??=Object.getOwnPropertySymbols(e)).filter((a)=>Object.prototype.propertyIsEnumerable.call(e,a)&&s.matchKey(a,n)!==void 0);case"Union":return[...new Set(s.types.flatMap(i))];default:return[]}}return i(Ec(xc(t)))}var cc=class{name;type;constructor(e,t){this.name=e,this.type=t}};function lp(e){switch(e._tag){case"String":case"Number":case"Symbol":case"TemplateLiteral":return!0;case"Union":return e.types.every(lp);default:return!1}}function fp(e){let t=Sp(e);switch(t._tag){case"String":case"Number":case"Symbol":case"TemplateLiteral":return!0;case"Union":return t.types.every(fp);default:return!1}}function Nx(e){return lp(e)&&fp(e)}var dp=class{parameter;type;constructor(e,t){if(!Nx(e))throw Error(`Invalid index signature parameter ${e._tag}`);if(this.parameter=e,this.type=t,wn(t)&&!Tp(t))throw Error("Cannot use `Schema.optionalKey` with index signatures, use `Schema.optional` instead.")}},uc=class extends tt{_tag="Objects";propertySignatures;indexSignatures;encodingChecks;constructor(e,t,n,r,o,i,s){super(n,r,o,i);this.propertySignatures=e,this.indexSignatures=t,this.encodingChecks=s}getParser(e,t=e){let n=this,r=n.propertySignatures.length,o=n.indexSignatures.length;if(!r&&!o)return lo(n,Zu);let i,s,a=()=>{if(!i)i=n.propertySignatures.map((u)=>({parser:t(u.type),name:u.name,type:u.type})),s=o?n.indexSignatures.map((u)=>({is:u,parserKey:e(Ec(u.parameter)),parserValue:t(u.type)})):void 0;return i},l=()=>{let u=new Set(n.propertySignatures.map((y)=>typeof y.name==="number"?globalThis.String(y.name):y.name)),g=(y,p,h,_,I)=>{if(I._tag==="Failure")return $i(y,n,p,I)??zn;let k=I===K?_:I[F];if(h!==L&&k!==L){if(r&&(u.has(p)||u.has(typeof h==="number"?globalThis.String(h):h)))return zn;$t(y.out,h,k)}return zn},x=(y,p,h,_)=>{if(!_){let j=h.parserKey(p,y.options);if(!J(j))return Xe(Wr(j),(q)=>x(y,p,h,q));_=j}if(_._tag==="Failure")return $i(y,n,p,_)??zn;let I=_===K?p:_[F],k=y.input[p],M=h.parserValue(k,y.options);return J(M)?g(y,p,I,k,M):Xe(Wr(M),(j)=>g(y,p,I,k,j))},S=(y,p,h)=>{let _=y.input[p],I=h.parserValue(_,y.options);return J(I)?g(y,p,p,_,I):Xe(Wr(I),(k)=>g(y,p,p,_,k))},b=o?Ei()({onItem:(y,[p,h])=>h.is.parameter===vn?S(y,p,h):x(y,p,h),step:(y,p,h)=>h._tag==="Failure"?h:void 0}):void 0;return Pd(function*(y,p){if(y===L)return L;if(!(typeof y==="object"&&y!==null&&!Array.isArray(y)))return yield*f(new bt(n,y,p));a();let h=y,_={},I={ast:n,input:h,out:_,issues:void 0,options:p},k=p.errors==="all",M=p.onExcessProperty==="error",j=p.concurrency===void 0?1:Br(p.concurrency),q=o&&M?n.indexSignatures.map((ae)=>Za(h,ae.parameter,p)):void 0;if(M){let ae=q?new Set(u):u;if(q)for(let Se of q)for(let Ee of Se)ae.add(Ee);let Ke=Reflect.ownKeys(h);for(let Se=0;Se<Ke.length;Se++){let Ee=Ke[Se];if(!ae.has(Ee)&&Object.prototype.propertyIsEnumerable.call(h,Ee)){let ot=new Ka(n,h[Ee],p),be=new Rt([Ee],ot);if(k){if(I.issues)I.issues.push(be);else I.issues=[be];continue}else return yield*f(new xe(n,[be],y,p))}}}if(r){let ae=j===1?ep(I,i):Fx(I,i,{concurrency:j});if(ae)yield*ae}if(o&&j===1)for(let ae=0;ae<o;ae++){let Ke=s[ae],Se=Ke.is.parameter===vn?S:x,Ee=q?.[ae]??(Ke.is.parameter===vn?Object.keys(h):Za(h,Ke.is.parameter,p));for(let ot=0;ot<Ee.length;ot++){let be=Se(I,Ee[ot],Ke);if(!J(be))yield*be;else if(be._tag==="Failure")return yield*be}}else if(b){let ae=oi();for(let Se=0;Se<o;Se++){let Ee=s[Se],ot=q?.[Se]??(Ee.is.parameter===vn?Object.keys(h):Za(h,Ee.is.parameter,p));for(let be=0;be<ot.length;be++)ae.push([ot[be],Ee])}let Ke=b(I,ae,{concurrency:j});if(Ke)yield*Ke}if(I.issues)return yield*f(new xe(n,I.issues,y,p));return _})};if(o)return l();let m,c=(u,g,x)=>{let S=i[g];return Xe(Wr(x),(b)=>{let y=tc(u,S,b);if(y)return y;let p=()=>de(u.out),h=ep(u,i.slice(g+1));return h?ke(h,p):p()})};return(u,g)=>{if(u===L)return Qe;if(g.errors==="all"||g.onExcessProperty!==void 0||g.concurrency!==void 0&&Br(g.concurrency)!==1)return(m??=l())(u,g);if(!(typeof u==="object"&&u!==null&&!Array.isArray(u)))return f(new bt(n,u,g));let x=a(),S=u,b={},y={ast:n,input:S,out:b,issues:void 0,options:g};try{for(let p=0;p<x.length;p++){let h=x[p],_=h.name,I=Hn(S,_),k=I?S[_]:L,M=h.parser(k,g);if(!J(M))return c(y,p,M);if(M===K){if(I)$t(b,_,k);continue}let j=tc(y,h,M);if(j)return j}}catch(p){return zr(p)}return de(b)}}_rebuild(e,t,n,r){let o=Qn(this.propertySignatures,(s)=>{let a=e(s.type);return a===s.type?s:new cc(s.name,a)}),i=Qn(this.indexSignatures,(s)=>{let a=t(s.parameter),l=e(s.type);return a===s.parameter&&l===s.type?s:new dp(a,l)});return o===this.propertySignatures&&i===this.indexSignatures&&n===this.checks&&r===this.encodingChecks?this:new uc(o,i,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(){if(this.propertySignatures.length===0&&this.indexSignatures.length===0)return"object | array";return"object"}};function tc(e,t,n){if(n._tag==="Failure")return $i(e,e.ast,t.name,n);if(n===K)return;let r=n[F];if(r!==L){$t(e.out,t.name,r);return}if(delete e.out[t.name],!wn(t.type)){let o=new Rt([t.name],new Qr(t.type.context?.annotations));if(e.options.errors==="all"){if(e.issues)e.issues.push(o);else e.issues=[o];return}else return Vn(new xe(e.ast,[o],e.input,e.options))}}var pp={onItem(e,t){if(!Hn(e.input,t.name))return t.parser(L,e.options);let n=e.input[t.name];return $t(e.out,t.name,n),t.parser(n,e.options)},step:tc},ep=Si()(pp),Fx=Ei()(pp);function mp(e,t){if(!e)return t;if(!t)return e;return[...e,...t]}function lc(e,t,n){return new uc(Reflect.ownKeys(e).map((r)=>new cc(r,e[r].ast)),[],n,t)}function fc(e){return e.ast}function dc(e,t=void 0){return new Vi(!1,e.map((n)=>n.ast),[],void 0,t)}function zi(e,t,n){return new er(e.map(fc),t,void 0,n)}var pc=Ln((e)=>{while(!0){if(sp(e))return Qa;let t=e.encoding;if(!t)return e.recur?.(pc,ce)??e;if(t.some((n)=>n.transformation._tag==="Middleware"&&n.transformation.decode!==ce))return Qa;e=t[t.length-1].to}});function hp(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(([,t])=>typeof t)));case"Literal":return[typeof e.literal];case"Union":return Array.from(new Set(e.types.flatMap(hp)));default:return["null","undefined","string","number","boolean","symbol","bigint","object","array","function"]}}function ji(e){switch(e._tag){default:return[];case"Declaration":{let t=e.annotations?.[ja];return Array.isArray(t)?t:[]}case"Objects":return e.propertySignatures.flatMap((t)=>{let n=t.type;if(!wn(n)){if(Zn(n))return[{key:t.name,literal:n.literal}];if(Xa(n))return[{key:t.name,literal:n.symbol}]}return[]});case"Arrays":return e.elements.flatMap((t,n)=>{if(!wn(t)){if(Zn(t))return[{key:n,literal:t.literal}];if(Xa(t))return[{key:n,literal:t.symbol}]}return[]});case"Union":{if(e.types.length===0)return[];let t=e.types.map((n)=>ji(pc(n)));return t[0].filter((n)=>t.every((r)=>r.some((o)=>o.key===n.key&&o.literal===n.literal)))}case"Suspend":return ji(e.thunk())}}var tp=new WeakMap,Mi=Object.freeze([]),np=(e)=>e===null?"null":Array.isArray(e)?"array":typeof e,Hn=(e,t)=>t==="__proto__"?Object.hasOwn(e,t):(t in e);function Dx(e){let t=tp.get(e);if(t)return t;let n,r=0,o,i,s=!0,a=[];for(let c=0;c<e.length;c++){let u=e[c],g=pc(u);if(Ex(g))continue;if(Zn(g)||Xa(g)){i??=new Map;let S=Zn(g)?g.literal:g.symbol;a[c]=S;let b=i.get(S);if(!b)i.set(S,b=[]);b.push(c)}else s=!1;let x=ji(g);if(x.length){n??=new Map,r++;for(let{key:S,literal:b}of x){let y=n.get(S);if(!y)n.set(S,y=[new Map,new Set]);y[1].add(c);let p=y[0].get(b);if(!p)y[0].set(b,p=new Set);p.add(c)}}else{o??={};let S=hp(g);for(let b of S)(o[b]??=[]).push(c)}}let l={},m=(c)=>l[c]??=Object.freeze(o?.[c]??Mi);if(s&&i)i.forEach(Object.freeze),t=(c)=>i.get(c)??Mi;else if(n?.size===1&&!o){let[c,[u]]=n.entries().next().value,g=new Map;for(let[S,b]of u)g.set(S,Object.freeze(Array.from(b)));let x=Object.freeze(e.map((S,b)=>b));t=(S,b)=>{if($o(S)){let y=Hn(S,c)?S[c]:void 0;if(y!==void 0)return g.get(y)??Mi;if(b)return x}return Mi}}else if(n){let c;for(let u of n)if((!c||u[1][0].size>c[1][0].size)&&u[1][1].size===r)c=u;t=(u,g)=>{let x=np(u);if(!$o(u))return m(x);let S=new Set(o?.[x]),b;if(c){let[y,[p]]=c,h=Hn(u,y),_=h?u[y]:void 0;if(h&&(!g||_!==void 0)){let I=p.get(_);if(!I)return m(x);for(let k of I)S.add(k);b=y}}if(b===void 0)for(let[y,[p,h]]of n){let _=Hn(u,y),I=_?u[y]:void 0;if(_&&(!g||I!==void 0)){let k=p.get(I);if(k)for(let M of k)S.add(M)}else if(g)for(let k of h)S.add(k)}for(let[y,[p,h]]of n){if(y===b)continue;let _=Hn(u,y),I=_?u[y]:void 0;if(_&&(!g||I!==void 0)){let k=p.get(I);for(let M of S)if(h.has(M)&&!k?.has(M))S.delete(M)}}return Array.from(S).sort((y,p)=>y-p)}}else t=(c)=>{let u=m(np(c));return i?u.filter((g)=>a[g]===void 0||a[g]===c):u};return tp.set(e,t),t}var er=class extends tt{_tag="Union";types;options;encodingChecks;constructor(e,t,n,r,o,i,s){super(n,r,o,i);this.types=e,this.options=t,this.encodingChecks=s}getParser(e,t){let n=this,r=t!==void 0,o=[],i=(a)=>o[a]??=e(n.types[a]),s;return(a,l)=>{if(a===L)return Qe;let m=(s??=Dx(n.types))(a,r);if(m.length===0)return f(new eo(n,[],a,l));if(m.length===1){let c=i(m[0])(a,l);if(c._tag==="Success")return c;return J(c)?gp(n,c.cause,a,l):Lx(n,c,a,l)}return Ux(n,i,m,a,l)}}_rebuild(e,t,n){let r=Qn(this.types,e);return r===this.types&&t===this.checks&&n===this.encodingChecks?this:new er(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}return}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((r)=>{let o=xc(r);switch(o._tag){case"Arrays":{let i=o.elements.filter(Zn);if(i.length>0)return`${rp(o.isMutable)}[ ${i.map((s)=>e(s)+op(s.context?.isOptional)).join(", ")}, ... ]`;break}case"Objects":{let i=o.propertySignatures.filter((s)=>Zn(s.type));if(i.length>0)return`{ ${i.map((s)=>`${rp(s.type.context?.isMutable)}${$n(s.name)}${op(s.type.context?.isOptional)}: ${e(s.type)}`).join(", ")}, ... }`;break}}return e(o)});return Array.from(new Set(n)).join(" | ")}};function gp(e,t,n,r){let o=to(t);if(!o)return Vr(t);return Vn(new eo(e,[o],n,r))}function Lx(e,t,n,r){return Wn(t,(o)=>gp(e,o,n,r))}function Ux(e,t,n,r,o){let i={ast:e,parser:t,input:r,out:void 0,successes:e.options?.mode==="oneOf"?[]:void 0,issues:void 0,options:o},s=$x(i,n);if(!s){if(i.out)return i.out;return f(new eo(e,i.issues??[],r,o))}return Mx(s,i)}function Mx(e,t){return ke(e,(n)=>{if(t.out===K)return Q(t.input);if(t.out)return t.out;return f(new eo(t.ast,t.issues??[],t.input,t.options))})}var $x=Si()({onItem(e,t){return e.parser(t)(e.input,e.options)},step(e,t,n){if(n._tag==="Failure"){let r=to(n.cause);if(r===void 0)return n;if(e.issues)e.issues.push(r);else e.issues=[r]}else{if(e.out&&e.successes)return e.successes.push(e.ast.types[t]),Vn(new Ld(e.ast,e.successes,e.input,e.options));if(e.out=n,e.successes)e.successes.push(e.ast.types[t]);else return zn}}}),yp=new er([new Yn("Infinity"),new Yn("-Infinity"),new Yn("NaN")]);function rp(e){return e?"":"readonly "}function op(e){return e?"?":""}var nc=class extends Sr{_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 nc(this.run,{...this.annotations,...e},this.aborted)}abort(){return new nc(this.run,this.annotations,!0)}and(e,t){return new Bi([this,e],t)}},Bi=class extends Sr{_tag="FilterGroup";checks;annotations;constructor(e,t=void 0){super();this.checks=e,this.annotations=t}annotate(e){return new Bi(this.checks,{...this.annotations,...e})}and(e,t){return new Bi([this,e],t)}};function Wi(e,t,n=!1){return new nc((r,o,i)=>Md(o,e(r,o,i),r,i),t,n)}function xp(e){return Wi((t)=>globalThis.Number.isFinite(t),{expected:"a finite number",representation:{id:"effect/schema/isFinite",payload:null},toJsonSchema:()=>({type:"number"}),toCode:()=>({runtime:"Schema.isFinite()"}),arbitraryConstraint:{number:"finite"},...e})}var mc=uo(ac,[xp()]),jx=new et(new er([mc,yp]),new ze(Li(),Te((e)=>globalThis.Number.isFinite(e)?e:globalThis.String(e))));function hc(e,t){let n=new globalThis.RegExp(e),r={source:n.source,flags:n.flags};return Wi((o)=>(n.lastIndex=0,n.test(o)),{expected:`a string matching the RegExp ${r.source}`,representation:{id:"effect/schema/isPattern",payload:r},toJsonSchema:()=>[{},!0],arbitraryConstraint:{patterns:[r]},...t})}var rc=new WeakMap;function ao(e,t){let n=Object.assign(Object.create(Object.getPrototypeOf(e)),e,t);if(Reflect.ownKeys(t).every((r)=>r==="context"||r==="encoding"))rc.set(n,Ki(e));return n}function Ki(e){let t=rc.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 rc.set(e,n),n}function dt(e,t){return e.encoding===t?e:ao(e,{encoding:t})}function co(e,t){if(e.context===t)return e;let n=Ki(e);if(n.context===t&&n.encoding===e.encoding)return n;return ao(e,{context:t})}function Sp(e){return e.encoding?Sp(e.encoding[e.encoding.length-1].to):e}function Gi(e,t){if(e.checks){let n=e.checks[e.checks.length-1];return Ep(e,ua(e.checks.slice(0,-1),n.annotate(t)))}return ao(e,{annotations:{...e.annotations,...t}})}function Ep(e,t){if(e._tag==="Suspend"&&t)throw Error("Cannot add checks to Suspend");if(e.checks===t)return e;return ao(e,{checks:t})}function uo(e,t){return Ep(e,mp(e.checks,t))}function Bx(e,t){let n=t(e.to);return n===e.to?e:new et(n,e.transformation)}function bp(e,t){let n=e,r=n[n.length-1],o=Bx(r,t);return o===r?e:ua(e.slice(0,e.length-1),o)}function qx(e){return(t)=>t.encoding?dt(t,bp(t.encoding,e)):t}function Vx(e,t){function n(r){if(r.encoding){let o=r.encoding[r.encoding.length-1];return t?.stopAt?.(o)?r:dt(r,bp(r.encoding,n))}return e(r)}return Ln(n)}function zx(e,t,n){let r=new et(e,t);return dt(n,n.encoding?[...n.encoding,r]:[r])}function Qn(e,t){let n;for(let r=0;r<e.length;r++){let o=e[r],i=t(o);if(n)n[r]=i;else if(i!==o){n=Array(e.length);for(let s=0;s<r;s++)n[s]=e[s];n[r]=i}}return n??e}function gc(e,t){let n=e.context?new Xn(e.context.isOptional,e.context.isMutable,e.context.constructorDefault,{...e.context.annotations,...t}):new Xn(!1,!1,void 0,t);return co(e,n)}var yc=Ln((e)=>{let t=e.context?e.context.isOptional===!1?new Xn(!0,e.context.isMutable,e.context.constructorDefault,e.context.annotations):e.context:new Xn(!0,!1);return Wx(co(e,t))}),Wx=qx(yc),vp=br((e)=>yc(new er([e,sc])));function wp(e,t){let n=e.context?new Xn(e.context.isOptional,e.context.isMutable,t,e.context.annotations):new Xn(!1,!1,t);return co(e,n)}function Ip(e,t,n){return zx(e,n,t)}function Kx(e){let t=[],n=[];function r(o){switch(o._tag){case"Literal":if(Yu(o.literal)&&!t.includes(o.literal))t.push(o.literal);return;case"UniqueSymbol":if(!t.includes(o.symbol))t.push(o.symbol);return;case"Never":return;case"Union":for(let i=0;i<o.types.length;i++)r(o.types[i]);return;default:n.push(o)}}return r(e),{literals:t,parameters:n}}function _p(e,t){let{literals:n,parameters:r}=Kx(e);return new uc(n.map((o)=>new cc(o,t)),r.map((o)=>new dp(o,t)))}function wn(e){return e.context?.isOptional??!1}function kp(e){return e.annotations?.[Pi]===!0||e._tag==="FilterGroup"&&e.checks.every(kp)}function Gx(e){function t(r){if(kp(r))return[r];return r._tag==="FilterGroup"?r.checks.flatMap(t):[]}let n=e.flatMap(t);return la(n)?n:void 0}function Jx(e){let t=!0;function n(r){if(t=t&&!r.encoding&&!sp(r),t&&"recur"in r)r.recur(n);return r}if("recur"in e)e.recur(n);return t}var In=Ln((e)=>{let t=Ki(e);if(t!==e){let r=In(t);return r===t&&e.encoding===void 0?e:co(r,e.context)}let n="recur"in e?e.recur(In):e;if("encodingChecks"in n&&n.encodingChecks){let r=Jx(e)?n.encodingChecks:bx(n)||vx(n)||ip(n)&&n.typeParameters.length>0?Gx(n.encodingChecks):void 0;return ao(n,{encodingChecks:void 0,checks:mp(n.checks,r)})}return n}),xc=Ln((e)=>In(Pt(e)));function Hx(e,t){let n=t,r=n.length,o=n[r-1],i=[new et(Pt(dt(e,void 0)),n[0].transformation.flip())];for(let a=1;a<r;a++)i.unshift(new et(Pt(n[a-1].to),n[a].transformation.flip()));let s=Pt(o.to);if(s.encoding)return dt(s,[...s.encoding,...i]);else return dt(s,i)}var Pt=br((e)=>{if(e.encoding)return Hx(e,e.encoding);let t=Ki(e);if(t!==e){let n=Pt(t);return n===t?e:co(n,e.context)}return"flip"in e?e.flip(Pt):("recur"in e)?e.recur(Pt):e});function Tp(e){switch(e._tag){case"Undefined":return!0;case"Union":return e.types.some(Tp);default:return!1}}function Sc(e,t){let n=t===0?K:de(t);return(r,o)=>{if(r===L)return Qe;if(r===t)return n;return f(new bt(e,r,o))}}function lo(e,t){return(n,r)=>{if(n===L)return Qe;if(t(n))return K;return f(new bt(e,n,r))}}var Ec=Vx((e)=>{switch(e._tag){default:return e;case"Number":return e.toCodecStringTree();case"Union":return e.recur(Ec)}});var oc=new globalThis.RegExp(`^${up}$`),Yx=new globalThis.RegExp(`^(?:${up}|Infinity|-Infinity|NaN)$`);function Ap(e){return hc(oc,{expected:"a string representing a finite number",representation:{id:"effect/schema/isStringFinite",payload:null},toJsonSchema:()=>({pattern:oc.source}),...e})}var Op=uo(vn,[Ap()]),Zx=new et(Op,io),Xx=new et(new er([Op,yp]),io),Qx="-?\\d+",aA=new globalThis.RegExp(`^${Qx}$`);var eS="Symbol\\(([\\s\\S]*)\\)",cA=new globalThis.RegExp(`^${eS}$`);function Wt(e,t,n,r,o){for(let i=0;i<e.length;i++){let s=e[i];if(s._tag==="FilterGroup"){if(n=Wt(s.checks,t,n,r,o),n&&(o.errors!=="all"||n[n.length-1].filter.aborted))return n}else{let a=s.run(t,r,o);if(a){let l=new Fd(s,a,t,o);if(n)n.push(l);else n=[l];if(o.errors!=="all"||s.aborted)return n}}}return n}function Cp(e){if(!ip(e))return;let t=e.annotations?.[Ba];return on(t)?t(e.typeParameters):void 0}function tS(e){return e===null||typeof e==="string"||typeof e==="boolean"||typeof e==="number"&&globalThis.Number.isFinite(e)}function nS(e){return e===void 0||typeof e==="string"}function Rp(e,t){let n=new WeakMap,r=[];e:while(!0){if(typeof e!=="object"||e===null){if(!t(e))return!1}else{let o=e,i=n.get(o);if(i===!1)return!1;if(i===void 0){let s=Array.isArray(o);if(!s){let a=Object.getPrototypeOf(o);if(a!==null&&a!==Object.prototype&&Object.getPrototypeOf(a)!==null)return!1}n.set(o,!1),r.push({value:o,keys:s?o.length:Object.keys(o),index:0})}}while(r.length>0){let o=r[r.length-1],i=o.keys;if(typeof i==="number"){if(o.index<i){e=o.value[o.index++];continue e}}else if(o.index<i.length){e=o.value[i[o.index++]];continue e}n.set(o.value,!0),r.pop()}return!0}}function rS(e){return Rp(e,tS)}var Pp=new so([],()=>(e,t,n)=>rS(e)?K:f(new bt(t,e,n)),{representation:{id:"effect/schema/Json",payload:null},expected:"JSON value",toCodecJson:()=>{return},toCodecStringTree:()=>sS});function oS(e){return Rp(e,nS)}var iS=new so([],()=>(e,t,n)=>oS(e)?K:f(new bt(t,e,n)),{expected:"StringTree",toCodecStringTree:()=>{return}}),sS=new et(iS,Ui());var Hi=(e,t,n)=>e===K?n(t):ke(e,n);function Fp(e){if(e._tag==="Middleware")return(n,r,o)=>{let i=n===K?e.decode(de(Gr(r)),o):e.decode(Ua(n,Gr),o);return Np(i)};let t=e.decode;switch(t._tag){case"Passthrough":return(n,r)=>n===K?de(r):n;case"Transform":{let n=(r)=>r===L?Qe:de(t.transform(r));return(r,o)=>Hi(r,o,n)}case"TransformOptional":{let n=(r)=>Va(t.transform(Gr(r)));return(r,o)=>Hi(r,o,n)}case"TransformEffect":return(n,r,o)=>Hi(n,r,(i)=>i===L?Qe:t.transform(i,o));case"TransformOptionalEffect":return(n,r,o)=>Hi(n,r,(i)=>Np(t.transform(Gr(i),o)))}}var Np=(e)=>ke(e,Va),Dp=(e,t,n,r)=>Wn(r,(o)=>Ti(()=>Sn(o,(i)=>new Dd(e,i,t,n))));function aS(e,t){let n=Fp(e.link.transformation),r;return(o,i)=>{if(o===L)return Qe;if(e.isConstructed(o))return K;let s=(r??=t(e.link.to))(o,i);return n(s,o,i)}}function cS(e,t){let n=e.context.constructorDefault;return(r,o)=>{if(r!==L&&r!==void 0)return t(r,o);let i=n;if(J(i)&&i._tag==="Success"){let s=t(i[F],o);return s===K?i:s}return ke(Dp(e,r,o,i),(s)=>{let a=t(s,o);return a===K?de(s):a})}}function bc(e,t){let n=t(e);return e.context?.constructorDefault===void 0?n:cS(e,n)}function fo(e,t,n,r,o){if(e._tag==="Declaration")for(let S of e.typeParameters)t(S);let i=n?Cp(e):void 0,s=i?aS(i,t):r??e.getParser(t,n),{checks:a,encoding:l}=e,m=l?.map((S)=>Fp(S.transformation)),c=e.encodingChecks;if(!l&&!a&&!c)return s;let u,g=(S,b)=>{let y=s(S,b);if(c&&!b.disableChecks)if(J(y)){if(y._tag==="Success"){let p=y===K?S:y[F];if(S!==L&&p!==L){let h=Wt(c,S,void 0,e,b);if(h)y=f(new xe(e,h,S,b))}}}else y=Xe(y,(p)=>{if(S!==L&&p!==L){let h=Wt(c,S,void 0,e,b);if(h)return f(new xe(e,h,S,b))}return Q(p)});if(a&&!b.disableChecks)if(J(y)){if(y._tag==="Success"){let p=y===K?S:y[F];if(p===L)return y;let h=Wt(a,p,void 0,e,b);if(h)y=f(new xe(e,h,p,b))}}else y=Xe(y,(p)=>{if(p!==L){let h=Wt(a,p,void 0,e,b);if(h)return f(new xe(e,h,p,b))}return Q(p)});return y},x=o===void 0?g:o(g);if(!l)return x;return(S,b)=>{let y=u??=l.map((_)=>t(_.to)),p=S,h=y[y.length-1](S,b);for(let _=l.length-1;_>=0;_--)if(h=m[_](h,p,b),_!==0){let I=y[_-1];if(h._tag==="Success")p=h[F],h=I(p,b);else h=ke(h,(k)=>{let M=I(k,b);return M===K?de(k):M})}if(h._tag==="Success"){let _=h[F],I=x(_,b);return I===K?h:I}return h=Dp(e,S,b,h),ke(h,(_)=>{let I=x(_,b);return I===K?de(_):I})}}var vc=Symbol(),Lp=new WeakMap,Up,wc=!1;var lS=(e)=>wc?Yi(vt,e,"parser"):vt(e).parser,Mp=(e)=>wc?Yi(vt,e,"makeEffect"):vt(e).makeEffect,fS=(e)=>bc(e,Mp);class Ic{ast;constructor(e){this.ast=e}get decodeEffect(){return this.cachedDecodeEffect??=fo(this.ast,lS)}get parser(){return this.decodeEffect}get makeEffect(){return this.cachedMakeEffect??=fo(this.ast,Mp,fS)}}class $p extends Ic{compiled;resolve;constructor(e,t,n){super(e);this.compiled=t,this.resolve=n}save(e,t){return Object.defineProperty(this,e,{value:t}),t}operation(e){let t=this.compiled;return typeof t==="function"?t(this.ast,this.resolve,e):t?.[e]}get is(){return this.save("is",this.operation("is"))}get decode(){return this.save("decode",this.operation("decode"))}get make(){return this.save("make",this.operation("make"))}get decodeEffect(){return this.save("decodeEffect",this.operation("decodeEffect")??fo(this.ast,(e)=>Yi(this.resolve,e,"parser")))}get parser(){let e=this.decode;return e===void 0?this.decodeEffect:this.save("parser",dS(e,()=>this.decodeEffect))}get makeEffect(){let e=this.operation("makeEffect");if(e!==void 0)return this.save("makeEffect",e);let t=(n)=>Yi(this.resolve,n,"makeEffect");return this.save("makeEffect",fo(this.ast,t,(n)=>bc(n,t)))}}function dS(e,t){let n;return(r,o)=>{if(r!==L)try{let i=e(r,o);if(i!==vc)return i===r?K:de(i)}catch(i){return zr(i)}return(n??=t())(r,o)}}function Yi(e,t,n){let r=e(t);if(r.compiled===void 0||Object.hasOwn(r,n))return r[n];let o;return(i,s)=>(o??=r[n])(i,s)}function vt(e){let t=Lp.get(e);if(t!==void 0)return t;let n=Up===void 0?new Ic(e):new $p(e,Up(e,vt),vt);return Lp.set(e,n),n}function _c(e){let t=e.ast,n;return(r,o)=>(n??=Bp(wS,In(t)))(r,o?.disableChecks?o?.parseOptions?{...o.parseOptions,disableChecks:!0}:{disableChecks:!0}:o?.parseOptions)}function kc(e){let t=_c(e);return(n,r)=>{let o=Jn(t(n,r));if(En(o))return ni(o.value);return no(o.cause,"Option adapter can only return none for schema issues"),ti()}}function Tc(e){return bS(In(e.ast))}function Ac(e,t){let n=gS(e.ast);return t===void 0?n:(r,o)=>n(r,hS(t,o))}function jp(e,t){return SS(Ac(e,t))}var hS=(e,t)=>t?{...e,...t}:e,Zi=(e)=>{if(e===L)return f(new ye);return Q(e)};function gS(e){return Bp(vS,e)}function yS(e,t){if(e===K)return Q(t);if(!J(e))return ke(e,Zi);return e[F]===L?Zi(L):e}function Bp(e,t){let n;return(r,o)=>{let i=(n??=e(t))(r,o??qi);if(i===K)return Q(r);if(!J(i))return ke(i,Zi);return i[F]===L?Zi(L):i}}function xS(e){return(t,n)=>Jn(e(t,n))}function SS(e){let t=xS(e);return(n,r)=>{let o=t(n,r);if(En(o))return at(o.value);return De(no(o.cause,"Result adapter can only return schema issues"))}}function ES(e,t){let n=Jn(e);if(En(n))return n.value;let r=no(n.cause,t);throw Error("Schema validation failed",{cause:r})}function bS(e){let t,n;return(r,o)=>{t??=vt(e);let i=o?.disableChecks?o.parseOptions?{...o.parseOptions,disableChecks:!0}:{disableChecks:!0}:o?.parseOptions??qi,s=t.make;if(s!==void 0&&r!==L){let l;try{l=s(r,i)}catch(m){throw no(_d(m),"Constructor adapter can only throw schema issues"),m}if(l!==vc&&l!==L)return l}let a=(n??=t.makeEffect)(r,i);return ES(yS(a,r),"Constructor adapter can only throw schema issues")}}var vS=(e)=>vt(e).parser,wS=(e)=>vt(e).makeEffect;var Oc="~effect/Schema/Schema",Vp=Symbol(),IS={[Oc]:Oc,get make(){let e=Tc(this);return Object.defineProperty(this,"make",{value:e,enumerable:!0}),e},get makeEffect(){let e=_c(this);return Object.defineProperty(this,"makeEffect",{value:e,enumerable:!0}),e},get makeOption(){let e=kc(this);return Object.defineProperty(this,"makeOption",{value:e,enumerable:!0}),e},pipe(){return Fe(this,arguments)},annotate(e){return this.rebuild(Gi(this.ast,e))},annotateKey(e){return this.rebuild(gc(this.ast,e))},check(...e){return this.rebuild(uo(this.ast,e))},rebuild(e){return Cc(e,this[Vp])}};function Cc(e,t){function n(){}let r=Object.setPrototypeOf(n,IS);if(t&&(Object.hasOwn(t,"name")||Object.hasOwn(t,"length")||Object.hasOwn(t,"__proto__")))Object.defineProperties(r,Object.getOwnPropertyDescriptors({...t}));else Object.assign(r,t);return r[Vp]=t,r.ast=e,r}var Xi=(e)=>e;var tr="~effect/Schema/SchemaError";function zp(e){return W(e,tr)&&e[tr]===tr}function TS(){return(e,t,n)=>se(new so(e.map(fc),(r)=>t(r.map((o)=>se(o))),n))}function AS(e,t){return TS()([],()=>(n,r,o)=>e(n)?Q(n):f(new bt(r,n,o)),t)}class Qi extends pi("SchemaError"){[tr]=tr;constructor(e){let t=Wo();Qs(0);try{super({issue:e})}finally{Qs(t)}}get message(){return Bd(this.issue)}toString(){return`SchemaError(${this.message})`}}function OS(e){return zp(e)}function CS(e){if(J(e))return RS(e);return Wn(e,(t)=>Ti(()=>Sn(t,(n)=>new Qi(n))))}function RS(e){return En(e)?e:Vr(Sn(e.cause,(t)=>new Qi(t)))}function PS(e,t){let n;for(let r of e.reasons){if(!vi(r)||!OS(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 NS(e){let t=Jn(e);if(En(t))return t.value;throw PS(t.cause,"Sync adapter can only throw schema errors")}function po(e,t){let n=Ac(e,t);return(r,o)=>CS(n(r,o))}function kn(e,t){let n=jp(e,t);return(r,o)=>Ul(n(r,o),(i)=>new Qi(i))}function Rc(e,t){let n=po(e,t);return(r,o)=>NS(n(r,o))}var se=Cc;var O=Xi((e)=>{let t=US(e);return se(vp(e.ast),{schema:t})});function Pc(e){let t=se(new Yn(e),{literal:e,transform(n){return t.pipe(Fc(Pc(n),{decode:Te(()=>n),encode:Te(()=>e)}))}});return t}var Kt=se(ic),FS=se(sc),R=se(vn);var Nc=se(ac),H=se(ap);function Kp(e,t){return se(e,{fields:t,mapFields(n,r){let o=n(this.fields);return Kp(lc(o,r?.unsafePreserveChecks?this.ast.checks:void 0),o)}})}function A(e){return Kp(lc(e,void 0),e)}function DS(e,t){return se(_p(e.ast,t.ast),{key:e,value:t})}function Gp(e,t){return se(e,{elements:t,mapElements(n,r){let o=n(this.elements);return Gp(dc(o,r?.unsafePreserveChecks?this.ast.checks:void 0),o)}})}function LS(e){return Gp(dc(e),e)}var P=Xi((e)=>se(new Vi(!1,[],[e.ast]),{value:e}));function Jp(e,t){return se(e,{members:t,mapMembers(n,r){let o=n(this.members);return Jp(zi(o,this.ast.options,r?.unsafePreserveChecks?this.ast.checks:void 0),o)}})}function ee(e,t){return Jp(zi(e,t,void 0),e)}function v(e){let t=e.map(Pc);return se(zi(t,void 0,void 0),{literals:e,members:t,mapMembers(n){return ee(n(this.members))},pick(n){return v(n)},transform(n){return ee(t.map((r,o)=>r.transform(n[o])))}})}var US=Xi((e)=>ee([e,FS]));function mo(e){return(t)=>se(t.ast,{schema:t,identifier:e})}function Fc(e,t){return(n)=>se(Ip(n.ast,e.ast,t?Ya(t):Ui()),{from:n,to:e})}function MS(e){return(t)=>se(wp(t.ast,e),{schema:t})}function Wp(e){return Pc(e).pipe(MS(Q(e)))}function nr(e,t){return AS((n)=>n instanceof e,t)}function rr(){return(e,t)=>new et(e.ast,Ya(t))}var We=Wi;function Ae(e,t){let{source:n,flags:r}=e,o=/^[dg]*uy?$/.test(r),i=r===""?`new RegExp(${G(n)})`:`new RegExp(${G(n)}, ${G(r)})`;return hc(e,{toJsonSchema:()=>o?{pattern:r.endsWith("y")?`^(?:${n})`:n}:[{},!0],toCode:()=>({runtime:`Schema.isPattern(${i})`}),...t})}function $S(e){let t=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;return Ae(t,{expected:"a base64 encoded string",representation:{id:"effect/schema/isBase64",payload:null},toJsonSchema:()=>({pattern:t.source}),toCode:()=>({runtime:"Schema.isBase64()"}),...e})}var jS=se(mc);function BS(e){let t=Nl(e.order),n=e.formatter??G;return(r,o)=>We((i)=>t(i,r),{expected:`a value greater than ${n(r)}`,arbitraryConstraint:{order:e.order,minimum:r,exclusiveMinimum:!0},...e.annotate?.(r),...o})}function qS(e){let t=Fl(e.order),n=e.formatter??G;return(r,o)=>We((i)=>t(i,r),{expected:`a value greater than or equal to ${n(r)}`,arbitraryConstraint:{order:e.order,minimum:r},...e.annotate?.(r),...o})}function Hp(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${G(e)}`);return e}var es=BS({order:aa,annotate:(e)=>({representation:{id:"effect/schema/isGreaterThan",payload:{exclusiveMinimum:Hp(e)}},toJsonSchema:()=>({exclusiveMinimum:e}),toCode:()=>({runtime:`Schema.isGreaterThan(${G(e)})`})})}),Yp=qS({order:aa,annotate:(e)=>({representation:{id:"effect/schema/isGreaterThanOrEqualTo",payload:{minimum:Hp(e)}},toJsonSchema:()=>({minimum:e}),toCode:()=>({runtime:`Schema.isGreaterThanOrEqualTo(${G(e)})`})})});function Dc(e){return We((t)=>globalThis.Number.isSafeInteger(t),{expected:"an integer",representation:{id:"effect/schema/isInt",payload:null},toJsonSchema:()=>[{type:"integer"},!0],toCode:()=>({runtime:"Schema.isInt()"}),arbitraryConstraint:{number:"integer"},...e})}var ts=Nc.check(Dc());function Oe(e,t){return e=zS(e),VS(e,Math.ceil(e/2),t)}function VS(e,t,n){return We((r)=>r.length>=e,{expected:`a value with a length of at least ${e}`,representation:{id:"effect/schema/isMinLength",payload:{minLength:e}},toJsonSchema:({type:r})=>r==="string"?e<=1?{minLength:t}:[{minLength:t},!0]:r==="array"?{minItems:e}:r===void 0?[{minLength:t,minItems:e},!0]:[{},!0],toCode:()=>({runtime:`Schema.isMinLength(${e})`}),[Pi]:!0,arbitraryConstraint:{minLength:e},...n})}function zS(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${e}`);return Math.max(0,Math.floor(e))}var sC=nr(globalThis.RegExp,{representation:{id:"effect/schema/RegExp",payload:null},toCode:()=>({runtime:"Schema.RegExp",Type:"globalThis.RegExp"}),expected:"RegExp",toCodecJson:()=>rr()(A({source:R,flags:R}),oo({decode:(e,t)=>Vt({try:()=>new globalThis.RegExp(e.source,e.flags),catch:()=>new ye({expected:"valid RegExp source and flags"},e,t)}),encode:(e)=>Q({source:e.source,flags:e.flags})}))}),WS=R.annotate({expected:"a string that will be decoded as a URL"}),aC=nr(globalThis.URL,{representation:{id:"effect/schema/URL",payload:null},toCode:()=>({runtime:"Schema.URL",Type:"globalThis.URL"}),expected:"URL",toCodecJson:()=>rr()(WS,Jd)});var KS=R.annotate({expected:"a string that will be decoded as JSON",contentMediaType:"application/json"});function Zp(e,t){return KS.pipe(Fc(e,Yd(t)))}var GS=nr(globalThis.File,{representation:{id:"effect/schema/File",payload:null},toCode:()=>({runtime:"Schema.File",Type:"globalThis.File"}),expected:"File",toCodecJson:()=>rr()(A({data:R.check($S()),type:R,name:R,lastModified:ts}),oo({decode:(e,t)=>ri(Ri(e.data),{onFailure:()=>f(new ye({expected:"a valid Base64 string"},e.data,t)),onSuccess:(n)=>{let r=new globalThis.Uint8Array(n);return Q(new globalThis.File([r],e.name,{type:e.type,lastModified:e.lastModified}))}}),encode:(e,t)=>Ii({try:async()=>{let n=new globalThis.Uint8Array(await e.arrayBuffer());return{data:Ci(n),type:e.type,name:e.name,lastModified:e.lastModified}},catch:()=>new ye({expected:"a readable File"},e,t)})}))}),cC=nr(globalThis.FormData,{representation:{id:"effect/schema/FormData",payload:null},toCode:()=>({runtime:"Schema.FormData",Type:"globalThis.FormData"}),expected:"FormData",toCodecJson:()=>rr()(P(LS([R,ee([A({_tag:Wp("String"),value:R}),A({_tag:Wp("File"),value:GS})])])),oo({decode:(e)=>{let t=new globalThis.FormData;for(let[n,r]of e)t.append(n,r.value);return Q(t)},encode:(e)=>Q(globalThis.Array.from(e.entries()).map(([t,n])=>{if(typeof n==="string")return[t,{_tag:"String",value:n}];else return[t,{_tag:"File",value:n}]}))}))});var uC=nr(globalThis.URLSearchParams,{representation:{id:"effect/schema/URLSearchParams",payload:null},toCode:()=>({runtime:"Schema.URLSearchParams",Type:"globalThis.URLSearchParams"}),expected:"URLSearchParams",toCodecJson:()=>rr()(R.annotate({expected:"a query string that will be decoded as URLSearchParams"}),Gd({decode:(e)=>new globalThis.URLSearchParams(e),encode:(e)=>e.toString()}))});var Xp=R.annotate({expected:"a string that will be decoded as a finite number"}).pipe(Fc(jS,io));var JS=R.annotate({expected:"a base64 encoded string that will be decoded as Uint8Array",format:"byte",contentEncoding:"base64"}),lC=nr(globalThis.Uint8Array,{representation:{id:"effect/schema/Uint8Array",payload:null},toCode:()=>({runtime:"Schema.Uint8Array",Type:"globalThis.Uint8Array"}),expected:"Uint8Array",toCodecJson:()=>rr()(JS,Hd)});var HS=-8640000000000000,YS=8640000000000000,fC=HS+50400000,dC=YS-50400000;var ho=se(Gi(Pp,{toCode:()=>({runtime:"Schema.Json",Type:"Schema.Json"})})),Qp=DS(R,ho);var ZS={onExcessProperty:"error"};function pt(e,t){return kn(e,ZS)(t)}var tm=/^0\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-(?:0|[1-9]\d*))?$/u,Lc=R.check(Ae(tm));function XS(e){let t=kn(Lc)(e);return Et(t)?t.success:void 0}function nm(e){return XS(e)!==void 0}function rm(e){return nm(e)&&!e.includes("-")}var QS=R.check(We(rm));function em(e){if(e===void 0||e.length===0||e[0]==="0")return!1;for(let t of e)if(t<"0"||t>"9")return!1;return!0}function eE(e){let[t,n,r]=e.split("-");if(t===void 0||n===void 0||r!==void 0)return!1;if(!rm(t))return!1;let[o,i,s,a]=n.split(".");return o==="dev"&&a===void 0&&em(i)&&em(s)}var om=R.check(We(eE)),tE=ee([Lc,om]);var Mc=v(["browser_use","computer_use","frontend","security","sites"]),nE=v(["browser_use","computer_use","sites"]),rE=v(["installed","disabled","missing","uncertain"]),oE=v(["healthy","missing","disabled","uncertain"]),im=Object.freeze(["openai-curated","openai-curated-remote"]),gC=v(im),sm=Object.freeze(["build-web-apps","codex-security"]),yC=v(sm),am=Object.freeze(["browser","computer-use","sites"]),xC=v(am);var Nt=Object.freeze({coding:!0,computer_use:!1,browser_use:!0,sites:!0,frontend:!0,security:!0}),Gt=Object.freeze({frontend:Object.freeze([{skillId:"build-web-apps:frontend-app-builder",appliesWhen:"a new visually-driven UI or meaningful redesign"},{skillId:"build-web-apps:frontend-testing-debugging",appliesWhen:"a rendered UI or interaction defect"},{skillId:"build-web-apps:react-best-practices",appliesWhen:"a relevant React or Next implementation or review"}]),security:Object.freeze([]),computer_use:Object.freeze([]),browser_use:Object.freeze([]),sites:Object.freeze([])}),iE=Gt.frontend,sE={frontend:{name:"frontend",pluginIds:["build-web-apps@openai-curated"],defaultSelected:Nt.frontend,semanticSkillIds:Object.freeze(Gt.frontend.map(({skillId:e})=>e)),applicability:Gt.frontend,ownership:"shared-preserve"},security:{name:"security",pluginIds:["codex-security@openai-curated"],defaultSelected:Nt.security,semanticSkillIds:["codex-security:security-scan","codex-security:security-diff-scan","codex-security:threat-model"],applicability:Gt.security,ownership:"shared-preserve"},computer_use:{name:"computer_use",pluginIds:["computer-use@openai-bundled"],defaultSelected:Nt.computer_use,migrationKey:"computer_use",semanticSkillIds:["computer-use:computer-use"],applicability:Gt.computer_use,ownership:"shared-preserve"},browser_use:{name:"browser_use",pluginIds:[],defaultSelected:Nt.browser_use,migrationKey:"browser_use",semanticSkillIds:[],applicability:Gt.browser_use,ownership:"shared-preserve"},sites:{name:"sites",pluginIds:["sites@openai-bundled"],defaultSelected:Nt.sites,migrationKey:"sites",semanticSkillIds:[],applicability:Gt.sites,ownership:"shared-preserve"}},Uc=Object.freeze(sE),aE=Object.freeze(["browser_use","computer_use","sites"]),cE=Object.freeze(["frontend","security"]),uE=Object.freeze([...Uc.frontend.pluginIds,...Uc.security.pluginIds]),lE=Object.freeze(["writing-instructions","babysit-ci","dev-server","visual-loop"]),fE=Object.freeze({browser_use:Nt.browser_use,computer_use:Nt.computer_use,sites:Nt.sites});var lm=v(["local.repository.edit","local.repository.check","local.repository.lint","local.repository.format","local.repository.commit","external.read","specialist.dispatch","vcs.server.mutation","vcs.server.ci-trigger","unknown.effect"]),dE=A({identifier:lm,label:R,requiresRootApproval:H});function It(e){return A({identifier:v([e]),label:R,requiresRootApproval:H})}var pE=A({localRepositoryEdit:It("local.repository.edit"),localRepositoryCheck:It("local.repository.check"),localRepositoryLint:It("local.repository.lint"),localRepositoryFormat:It("local.repository.format"),localRepositoryCommit:It("local.repository.commit"),externalRead:It("external.read"),specialistDispatch:It("specialist.dispatch"),versionControlServerMutation:It("vcs.server.mutation"),versionControlServerCiTrigger:It("vcs.server.ci-trigger"),unknownEffect:It("unknown.effect")}),$c={localRepositoryEdit:{identifier:"local.repository.edit",label:"local repository edit",requiresRootApproval:!1},localRepositoryCheck:{identifier:"local.repository.check",label:"local repository check",requiresRootApproval:!1},localRepositoryLint:{identifier:"local.repository.lint",label:"local repository lint",requiresRootApproval:!1},localRepositoryFormat:{identifier:"local.repository.format",label:"local repository format",requiresRootApproval:!1},localRepositoryCommit:{identifier:"local.repository.commit",label:"local repository commit",requiresRootApproval:!1},externalRead:{identifier:"external.read",label:"external read",requiresRootApproval:!1},specialistDispatch:{identifier:"specialist.dispatch",label:"specialist dispatch",requiresRootApproval:!1},versionControlServerMutation:{identifier:"vcs.server.mutation",label:"version-control-server mutation",requiresRootApproval:!0},versionControlServerCiTrigger:{identifier:"vcs.server.ci-trigger",label:"version-control-server CI triggering",requiresRootApproval:!0},unknownEffect:{identifier:"unknown.effect",label:"unclassified effect",requiresRootApproval:!0}};yt($c);var mE=v(["never","root"]),fm=Object.values($c);function cm(e){let t=e.map((r)=>r.label),n=t.at(-1);if(n===void 0)return"";if(t.length===1)return n;return`${t.slice(0,-1).join(", ")}, and ${n}`}function um(e){return e.length===0?e:`${e[0]?.toUpperCase()??""}${e.slice(1)}`}var hE=fm.filter((e)=>!e.requiresRootApproval),gE=fm.filter((e)=>e.requiresRootApproval),yE=Object.freeze({noRootApproval:`${um(cm(hE))} actions do not require Root approval.`,rootApproval:`${um(cm(gE))} require Root approval.`});var mt=R.check(Ae(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),jc=R.check(Ae(/^[0-9a-f]{64}$/u)),IC=mt.pipe(mo("RunId")),_C=mt.pipe(mo("ProjectId")),kC=mt.pipe(mo("TrustId")),TC=jc.pipe(mo("Sha256Digest"));var xE=A({run_id:mt,objective_lineage:mt,parent_run_id:O(ee([mt,Kt]))}),SE=A({project_id:mt,trust_id:mt,trust_digest:jc}),EE=A({project_id:mt,project_digest:jc}),bE=R.check(Ae(/^state-[0-9]+\.[0-9]+$/u));var os=v(["low","default","high"]),hm=v(["go","Go","plus-low","plus","plus-high","pro-5x","pro-20x"]),vE=ee([os,hm]);var gm=v(["standard","fast","fast-all"]),wE=v(["low","medium","high","xhigh"]),ym="Satisfy the complete requested outcome correctly, elegantly, and mergeably; never weaken or reinterpret it to shrink the patch. Then make the smallest coherent patch within the authorized boundary. Prefer simple, cohesive, idiomatic solutions with appropriate abstraction and minimal accidental complexity. Avoid unrelated code, prose, configuration, documentation, instructions, tests, restructuring, formatting churn, files, and operations. Preserve unrelated work; return material scope expansion to Root.",ns="Treat unnecessary text, headings, subheadings, typography hierarchy, cards, pills, badges, decorative containers, labels, microcopy, repeated information, and grouping without information or interaction value as design defects. Use these primitives when they materially improve hierarchy, comprehension, composition, interaction, or content. Every visible item must be necessary or usefully complementary to the content and design.",or="Do not modify repository source or the implementation under validation; observation, analysis, and proof artifacts only.",IE="For current library, framework, SDK, API, CLI, or cloud-service facts, resolve the library identity and query Context7 narrowly before model memory or web search. Return the typed context7 evidence state with version/source evidence. Use web search only when Context7 is unavailable, lacks relevant coverage or the required version, fails for authentication or quota, or a conflict remains after checking authoritative first-party documentation.",_E=v(["none"]),xm=Object.freeze(["implementation","review","validation","integration","vcs"]),kE=v(["read-only","workspace-write"]),Jt=[{role:"Explorer",sharedInstruction:`Keep discovery within the assigned repository scope and return exact paths, symbols, callers, tests, and constraints. ${or}`,tasks:[{name:"map",description:"Bounded repository structure mapping specialist.",instruction:"Map the assigned repository area: locate its relevant packages, entry points, ownership boundaries, and nearby tests or docs. Return a compact path map and identify where a follow-up lookup or trace should start; do not trace runtime behavior or resolve an unrelated fact.",permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{name:"lookup",description:"Repository fact lookup specialist.",instruction:"Find the specific requested repository fact and cite its exact path or symbol; keep the search narrower than a structure map or execution trace.",permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{name:"trace",description:"Repository execution and reference tracing specialist.",instruction:"Follow the assigned execution or reference path across callers, boundaries, and tests; explain the evidence-backed flow and stop at the assigned boundary.",permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}}],capability:"repository-read",authority:"Read only the delegated Assignment repository scope; Git/VCS writes, Intent lifecycle, and material decisions remain Root-only.",evidence:"Return exact paths, symbols, callers, tests, and constraints.",completion:"Account for every in-scope caller and constraint.",permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{role:"Librarian",sharedInstruction:`${IE} ${or}`,tasks:[{name:"lookup",description:"Authoritative external fact lookup specialist.",instruction:"Answer the specific external fact with its current authoritative source.",permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{name:"research",description:"Current authoritative-source research specialist.",instruction:"Compare and synthesize the assigned current sources with citations, noting conflicts and uncertainty.",permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}}],capability:"current-research",authority:"Research only the delegated Assignment current sources without repository mutation; Git/VCS writes, Intent lifecycle, and material decisions remain Root-only.",evidence:"Return sourced facts, dates, and explicit uncertainty.",completion:"Resolve the assigned external fact or report the exact evidence gap.",permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{role:"Worker",sharedInstruction:"Keep all implementation, repair, or proof within the assigned scope and return concise evidence proportionate to the work.",tasks:[{name:"mechanical",description:"Deterministic bounded-edit specialist.",instruction:"Apply the exact already-decided transformation within the assigned files and verify it.",permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}},{name:"implementation",description:"Bounded behavior implementation specialist.",instruction:"Design and implement the assigned behavior within its bounded seam, then verify the changed behavior.",permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}},{name:"visual",description:"Rendered visual implementation and interaction specialist.",instruction:`Produce mergeable visual implementation within the Assignment, including frontend, 3D, browser-driven UI, and interactive visualization. Inspect the actual rendered and interacted-with result against acceptance criteria and references; iterate on material discrepancies in visual quality, UI, UX, accessibility, responsiveness, interaction, task adherence, and reference adherence. Use the projected skills appropriate to this visual work. Return changed paths and observable rendered/interaction evidence for independent Reviewer.visual review. ${ns}`,permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}},{name:"integration",description:"Decided seam integration specialist.",instruction:"Connect already-decided component seams, resolve interface mismatches within the assigned boundary, and verify their combined behavior.",permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}},{name:"operations",description:"Exact-ref or SHA terminal operations observer.",instruction:`Use babysit-ci to observe the assigned CI or release gate for the Root-supplied exact ref or SHA until terminal; report the matching result and failure evidence. ${or}`,permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{name:"validation",description:"Independent local behavioral validation specialist.",instruction:`Independently exercise the assigned local behavior with the smallest relevant checks, classify failures, and report reproducible evidence; generated proof state is allowed, but do not repair the implementation or substitute for code review. ${or}`,permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!1}},{name:"debugging",description:"Reproducible bounded defect-repair specialist.",instruction:"Use the debugging skill to repair the assigned defect within its bounded seam.",permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}}],capability:"task-scoped-assignment",authority:"Concrete task permissions govern observation, proof writes, or source repair within the delegated Assignment; no role-level source-mutation authority is granted. Intent lifecycle, Git/VCS writes, and material choices remain Root-only.",evidence:"Return changed files, verification results, and remaining risk.",completion:"Finish the delegated Assignment with proportional proof or an exact blocker and return a compact structured outcome.",permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{role:"Reviewer",sharedInstruction:"Challenge the assigned target against its acceptance criteria and return reproducible evidence. Repair concrete defects to a fixed point when the concrete task permits source mutation; review-only tasks remain observational.",tasks:[{name:"code",description:"Adversarial implemented-code review specialist.",instruction:"Review and repair the implemented code to a fixed point. Batch relevant evidence, then follow up on concrete uncertainty. Check correctness, safety, compatibility, test quality, generated-artifact hygiene, and the canonical patch-quality rule.",permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}},{name:"testing",description:"Broad test review, repair, and proof specialist.",instruction:"Review testing across the assigned scope, repair concrete test or behavior defects within the Assignment, and prove the affected behavior. Return material testing strategy or architecture decisions to Root.",permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}},{name:"visual",description:"Independent rendered visual, UI, UX, and interaction review specialist.",instruction:`Independently inspect the implementation and actual rendered/interacted-with result against acceptance criteria and references. Review visual quality, UI, UX, accessibility, responsiveness, interactions, task adherence, and reference adherence. Do not implement repairs. Return concrete reproducible discrepancies or sufficient acceptance evidence to Root for its final independent visual pass. ${ns} ${or}`,permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!1}},{name:"artifact",description:"Adversarial produced-artifact review specialist.",instruction:"Inspect the assigned produced artifact against its requested content, usability, and delivery constraints; repair concrete defects within the artifact boundary and repeat inspection until no actionable findings remain.",permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}},{name:"audit",description:"Bounded audit and repair specialist.",instruction:"Review the assigned code for the requested concerns, repair concrete findings within the Assignment to a fixed point, and verify affected behavior.",permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}},{name:"security",description:"Codex Security review and bounded repair specialist.",instruction:"Use the installed `codex-security:security-diff-scan` skill for an assigned change or `codex-security:security-scan` for an assigned repository scope, then follow applicable `codex-security:validation` and `codex-security:fix-finding` guidance rather than repeating their procedures. Repair validated vulnerabilities within the Assignment and verify affected behavior. Return material security risk, product, and architecture decisions to Root.",permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}}],capability:"task-scoped-review",authority:"Concrete task permissions govern observational review or bounded repair within the delegated Assignment; no role-level source-mutation authority is granted. Intent lifecycle, Git/VCS writes, and material choices remain Root-only.",evidence:"Return findings, repaired paths, verification, and residual risk.",completion:"Reach a fixed point or report each reproducible blocker as a compact structured outcome.",permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}}];yt(Jt);var CC=new Map(Jt.map((e)=>[e.role,e])),Sm=Jt.flatMap((e)=>e.tasks.map((t)=>`${e.role}:${t.name}`)),TE=Sm.map((e)=>e.replace(":",".")),Bc=v(["Explorer","Librarian","Worker","Reviewer"]),Em=v(["map","lookup","trace"]),bm=v(["lookup","research"]),vm=v(["mechanical","implementation","visual","integration","operations","validation","debugging"]),wm=v(["code","testing","visual","artifact","audit","security"]),go=ee([A({role:v(["Explorer"]),task:Em}),A({role:v(["Librarian"]),task:bm}),A({role:v(["Worker"]),task:vm}),A({role:v(["Reviewer"]),task:wm})]),qc=v(["Explorer:map","Explorer:lookup","Explorer:trace","Librarian:lookup","Librarian:research","Worker:mechanical","Worker:implementation","Worker:visual","Worker:integration","Worker:operations","Worker:validation","Worker:debugging","Reviewer:code","Reviewer:testing","Reviewer:visual","Reviewer:artifact","Reviewer:audit","Reviewer:security"]),Im=v(["Explorer.map","Explorer.lookup","Explorer.trace","Librarian.lookup","Librarian.research","Worker.mechanical","Worker.implementation","Worker.visual","Worker.integration","Worker.operations","Worker.validation","Worker.debugging","Reviewer.code","Reviewer.testing","Reviewer.visual","Reviewer.artifact","Reviewer.audit","Reviewer.security"]),yo=Object.freeze(Sm.map((e)=>Rc(qc)(e))),_m=Object.freeze(TE.map((e)=>Rc(Im)(e))),km=Object.freeze(["worker","explorer","reviewer","librarian"]);var Tm=A({profile:os,service_tier:O(gm)}),rs=Object.freeze(["user_interaction","intent","material_decisions","orchestration_lifecycle","integration_acceptance","completion","git_vcs","external_effects","visual_judgment","dev_server"]),AE=v([...rs]),OE=v(["delegated","root_direct","unavailable"]),CE=v([...rs]),Vc=v(["used","no_coverage","unavailable","auth_or_quota_failure","source_conflict"]),Am=Object.freeze({rule:"Prove success with the smallest meaningful validation proportionate to changed behavior, scope, risk, uncertainty, and acceptance criteria; preserve required repository gates. Reuse already-conclusive evidence. Do not manufacture proof work, add redundant tests, or test unrelated surfaces merely to increase confidence. Broaden or repeat validation only after relevant changes, failures, elevated risk, or unresolved material concerns. Avoid tests that mirror implementation for reversible low-impact changes.",avoidImplementationMirrorTestsForLowImpactReversibleChanges:!0,broadenOrRepeatOnlyAfter:Object.freeze(["source_change","proof_failure","unresolved_material_concern","change_breadth_or_risk"]),mandatoryRepositoryGatesRemainRequired:!0,reviewerCodeRemainsRequired:!0}),RE=Object.freeze({requiredFor:Object.freeze(["library","framework","sdk","api","cli","cloud_service"]),resolveIdentityBeforeQuery:!0,queryNarrowly:!0,evidenceStates:Object.freeze(["used","no_coverage","unavailable","auth_or_quota_failure","source_conflict"]),webFallbackEvidenceStates:Object.freeze(["no_coverage","unavailable","auth_or_quota_failure"]),missingRequiredVersionAllowsFallback:!0,successfulEvidenceAloneAllowsFallback:!1,checkFirstPartyDocsBeforeFallbackForConflict:!0,unresolvedConflictAfterFirstPartyAllowsFallback:!0,materialDecisionsRemainRootOwned:!0}),PE=/\b(?:libraries?|frameworks?|sdks?|apis?|clis?|cloud[ _-]?services?|packages?|dependencies?|technical|documentation|docs?|context7)\b/iu,NE=/\b(?:historical|history|legacy|archived?|past)\b/iu;function zc(e){if(e.role!=="Librarian"||e.task!=="lookup"&&e.task!=="research")return!1;let t=[e.objective,...e.scope,...e.constraints,...e.exclusions,...e.dependencies,...e.acceptanceCriteria].join(" ");return PE.test(t)&&!NE.test(t)}var FE=Object.freeze({repositoryAndUserRequirementsPrecedePluginDefaults:!0,specialistsOwnImplementationAndInteractionProof:!0,specialistVisualImplementationInstruction:"Assign material rendered implementation to Worker.visual, independent rendered review to Reviewer.visual, then perform Root's independent visual pass. Root remains final visual authority and actively looks for issues both specialists missed. Dispatch only bounded repairs for material discrepancies, repeat only affected review and judgment, and reuse unaffected evidence.",rootOwnsVisualJudgment:!0,designJudgment:ns,rootOwnsSharedDevServer:!0,rootAcceptsTerminalVisualEvidence:!0,sourceChangesInvalidateRenderEvidence:!0,specialistReportsIncludeObservableRenderedEvidence:!0,logicOnlyChangesRequireVisualAcceptance:!1,fixedPoint:Object.freeze(["worker_visual_implements_and_inspects","reviewer_visual_independently_reviews","root_independently_judges","root_assigns_bounded_visual_repair","repeat_affected_review_and_judgment"])}),DE=Object.freeze({interactiveCapabilitiesRemainSpecialistOwned:!0,rootMayInspectForVisualJudgment:!0,credentialEntryAndSubmissionRemainUserOwned:!0,specialistsMustNeverHandleCredentials:!0,missingAuthorizedPathIsCapabilityBlocker:!0}),LE=Object.freeze({threatModelForMaterialTrustBoundaryChanges:!0,securityDiffScanRequiredForSecuritySensitiveDiffs:!0,fullScanOnlyForAuditNewExposedSurfaceOrSystemicConcern:!0,validateSupportedFindingsBeforeBlocking:!0,introducedOrWorsenedValidatedVulnerabilityBlocksVcs:!0,preExistingUnrelatedFindingsDoNotExpandScope:!0,securityEditsInvalidateCodeReview:!0,securitySensitiveCodeReviewEditsInvalidateSecurityReview:!0,materialDecisionsRemainRootOwned:!0}),UE=Object.freeze({requiresDelegation:!0,explicitUserDirectExecutionOverridesDelegation:!0,assignmentStartAndDispatchPrecedeDelegableExecution:!0,trivialWorkRequiresDelegation:!0,preparatoryAndExploratoryWorkRequiresDelegation:!0,genericDirectWorkFallback:!1,concreteSpecialistDispatchRequired:!0,registeredSpecialistAgentTypes:_m,roleFamiliesAreLabelsOnly:!0,forbiddenGenericAgentTypes:km,missingConcreteRouteIsBlocker:!0,delegableActions:Object.freeze(["repository_discovery","file_source_test_doc_inspection","fact_finding","research","implementation","debugging","testing","validation","frontend_work","security_work","browser_use","computer_use","review","ci_release_observation"]),directExecutionExceptions:rs,rootOwnedAuthority:rs,requestUserInputGates:Object.freeze(["missing_authorization_for_consequential_effect","ambiguity_or_missing_material_input"]),surgicalMutationRule:ym,phaseOrder:xm,phaseGates:Object.freeze({implementedScopeStableBeforeReview:!0,reviewerCodeAndWorkerValidationMayOverlapOnNonConflictingScopes:!0,currentValidationBeforeRootIntegration:!0,rootIntegrationBeforeVcs:!0}),initialDispatch:Object.freeze({independentAssignments:!0,substantiveIndependentConcurrency:!0,routinePostdispatchSteering:!1,collectiveWaits:!0,evidenceReusedAcrossPhases:!0}),atomicLifecycleTransitions:Object.freeze({relatedAssignmentAndIntentWrites:!0,oneLockOneCommit:!0,staleRevisionChecksRetained:!0,repositoryDriftChecksRetained:!0}),supersession:Object.freeze({explicitOnly:!0,unfinishedPredecessorOnly:!0,validatedRelatedReplacement:!0,reasonAndProvenanceRequired:!0,supersededExcludedFromCompletionBlockers:!0}),specialistTerminalResultPersistence:Object.freeze({ownActiveInvocationCapabilityRequired:!0,ownAssignmentOnly:!0,terminalOutcomeOnly:!0,rootOwnedIntentLifecycle:!0,rootOwnedAcceptanceReviewAndCiGates:!0,rootOwnedVcsAndExternalEffects:!0,sharedRuntimeCallerIdentityUnavailable:!0,legacyResultCompatibilityPreserved:!0}),normalSpawnForkTurns:"none",normalSpawnRequiresExplicitForkTurns:!0,normalSpawnUsesConcreteRegisteredAgentType:!0,semanticStateBoundary:"Use holycodex-agent semantic operations for Intent and Assignment state. Do not edit TOON state. Resume the current Intent or create one for new work; record verification, acceptance, and readiness, and complete only when holycodex-agent confirms every completion predicate. There is no HolyCodex planning workflow or automatic Plan approval gate; preserve existing Plan state when resuming work that uses it.",routeConfigurationBeforeDispatch:"Use the active profile's registered Role.task configuration, including model, effort, tier, permissions, shell, and capabilities. Verify the registration once per configuration generation; recheck after configuration changes or when resuming an unverified thread. Pass fields required by the dispatch tool; registered settings need not be copied into Assignment prose. Never inherit Root settings, substitute a generic route, or override the selected route. Report a missing or incompatible route before dispatch.",assignmentInvocationLifecycle:"Before each specialist spawn, persist the bounded Assignment and call holycodex-agent assignment start. Keep the returned active_invocation_id and capability in Root; give the specialist only the bounded Assignment, never the capability. After a terminal report, record the result with that invocation ID and capability. Recover an interrupted invocation only after confirming it stopped, using the matching Root-held capability; never share that capability.",assignmentContextIsTaskSpecificOnly:!0,configuredRouteModelAndEffortPreserved:!0,normalProgressMessages:!1,normalHeartbeatMessages:!1,normalIntermediateEvidence:!1,userUpdatesUsefulOrImportantOnly:!0,routinePerToolOrSubagentNarrationForbidden:!0,routineStatusOnlyChatterForbidden:!0,fixedCadenceUserUpdatesForbidden:!0,materialUserUpdateKinds:Object.freeze(["significant_findings_or_decisions","consequential_blockers_or_input_needs","release_milestones"]),outOfBoundaryRequiresNewAssignment:!0,rootWaitTool:"collaboration.wait_agent",rootWaitTimeoutMs:600000,specialistCoordinationInstruction:"Coordinate through terminal reports, not conversation. After dispatch, do not inspect a running specialist. Do not message, poll, request status from, or follow up with a running specialist. The only exception is a genuine lifecycle interruption or supersession caused by materially changed user intent, cancellation, or Assignment invalidation that makes continuation incorrect; use the lifecycle mechanism without normal steering. Do not use Root sleep for specialist coordination or create polling/status loops. Wait with the exact required timeout and let specialist completion wake the collective wait. Dispatch already-known independent Assignments before waiting. After a specialist reports, judge its evidence; when compatible follow-up work remains, prefer the same warm specialist if its concrete task fits, its context is useful, independent review and parallelism remain sound, and write ownership does not conflict. Reuse relevant warm context rather than discarding it without reason. Minimize Root model turns: return to judgment for decisions, orchestration boundaries, integration, contradictions, and completion, not for polling, heartbeat traffic, or incremental steering.",rootWaitRequiresExactTimeout:!0,earlySpecialistCompletionWakesWait:!0,collectiveMailboxIncludesRelevantAgents:!0,idleRootWaitRepeatsRequiredTimeout:!0,shortRootWaitsForbidden:!0,busyPollingForbidden:!0,statusOnlyCoordinationLoopsForbidden:!0,batchIndependentLifecycleActions:!0,releaseLeavesAfterAcceptedOutcome:!0,specialistOutcomes:Object.freeze(["completed","blocked","needs_root_input","failed"]),evidenceFirstConciseStructuredReports:!0,specialistReportFields:Object.freeze(["changed paths","checks","observable evidence","blockers","Root decisions needed","remaining risk"]),rootLargeReadsOnlyFor:Object.freeze(["material decisions","conflicts","failures","findings"]),stableFactsReused:!0,reportDrivenSpecialistCoordination:!0,runningSpecialistMessagesForbidden:!0,runningSpecialistInspectionForbidden:!0,runningSpecialistFollowupForbidden:!0,followupRequiresTerminalReport:!0,rootSleepForSpecialistCoordinationForbidden:!0,pollingAndStatusLoopsForbidden:!0,warmSpecialistReusePreferred:!0,warmReuseRequiresContextAndOwnershipFit:!0,independentAssignmentsDispatchedBeforeWait:!0,rootDecisionBoundariesMinimized:!0,duplicatePolicyForbidden:!0,stableBoundedComponentScopesAreCanonical:!0,lifecycleWorkerOwnsDeterministicApi:!0,materialDecisionsRemainRootOwned:!0,lifecycleRemainsRootOwned:!0,integrationAndCompletionRemainRootOwned:!0,routineSafeReversibleInScopeDecisionsProceedAutonomously:!0,userInstructionsOverrideSkillGuidelinesExceptHardInvariants:!0,authorizedWorkContinuesThroughRequestedTerminalState:!0,testingPolicy:Am,codeReviewRequiredForImplementation:!0,codeReviewRequiredBeforeVcs:!0,externalVerificationMustBeTerminal:!0,postVcsFlow:"discover_topology_observe_repair_repeat"});var Om=v(["blocked","completed","failed","partial"]),Cm=ee([v(["high","max","xhigh"]),Kt]),Rm=ho,ME=Qp,$E=A({blocked:H,changed_files:P(R),confidence:Nc,context_owner:ee([R,Kt]),material_findings:P(R),needs_more_context:H,needs_root_decision:H,needs_verification:H,relevant_files:P(R),remaining_risk:P(R),reuse_recommended:H,status:Om,suggested_followup:ee([R,Kt]),suggested_luna_effort:Cm,suggested_specialist:ee([Bc,Kt]),verification:P(R),verification_passed:H}),Wc="holycodex-specialist-outcome-2",pe=R.check(Oe(1)),ir=A({state:Vc,evidence:P(pe).check(Oe(1)),library:O(pe),version:O(pe)}),xo={protocol_version:v([Wc]),route:go,evidence:P(pe),context7:O(ir)},jE=A(xo),BE=A({...xo,status:v(["completed"]),summary:pe}),qE=A({...xo,status:v(["blocked"]),reason:pe,needs_root_decision:H}),VE=A({...xo,status:v(["partial"]),summary:pe,completed:P(pe),remaining:P(pe),needs_root_decision:H}),zE=A({...xo,status:v(["failed"]),error:pe}),WE=ee([BE,qE,VE,zE]),is={protocol_version:v([Wc]),capability:Mc,route:ee([go,Kt]),evidence:P(pe),context7:O(ir),data:Rm},KE=A({...is,status:v(["completed"]),summary:pe}),GE=A({...is,status:v(["blocked"]),reason:pe,needs_root_decision:H}),JE=A({...is,status:v(["partial"]),summary:pe,completed:P(pe),remaining:P(pe),needs_root_decision:H}),HE=A({...is,status:v(["failed"]),error:pe}),YE=ee([KE,GE,JE,HE]);var Pm=P(R),Nm=R.check(Ae(/^[a-z][a-z0-9-]*(?: [a-z][a-z0-9-]*)*$/u)),Fm=v([As]),ZE=A({code:mt,message:R,details:ME}),Dm=A({schema_version:Fm,ok:v([!0]),command:Nm,data:Rm,warnings:Pm}),Lm=A({schema_version:Fm,ok:v([!1]),command:Nm,error:ZE,warnings:Pm}),XE=ee([Dm,Lm]);var ss="gpt-6.1-sol",So="gpt-6-luna";function QE(e,t,n){return{key:`${e}:${t}`,role:e,task:t,model:So,effort:n}}var eb=new Set(yo),Gc=[{profile:"low",rationale:"Cheapest practical configuration without dropping Luna below its useful agentic threshold.",efforts:{"Explorer:map":"medium","Explorer:lookup":"medium","Explorer:trace":"high","Librarian:lookup":"medium","Librarian:research":"high","Worker:mechanical":"medium","Worker:implementation":"high","Worker:integration":"high","Worker:operations":"medium","Worker:validation":"medium","Worker:debugging":"high","Worker:visual":"high","Reviewer:code":"high","Reviewer:testing":"medium","Reviewer:audit":"medium","Reviewer:security":"high","Reviewer:artifact":"high","Reviewer:visual":"high"}},{profile:"default",rationale:"Best general whole-task cost/performance: Sol medium orchestration and Luna medium/high execution.",efforts:{"Explorer:map":"medium","Explorer:lookup":"medium","Explorer:trace":"high","Librarian:lookup":"medium","Librarian:research":"high","Worker:mechanical":"medium","Worker:implementation":"high","Worker:integration":"high","Worker:operations":"medium","Worker:validation":"high","Worker:debugging":"high","Worker:visual":"high","Reviewer:code":"high","Reviewer:testing":"high","Reviewer:audit":"high","Reviewer:security":"high","Reviewer:artifact":"high","Reviewer:visual":"high"}},{profile:"high",rationale:"Highest practical reliability without indiscriminate reasoning waste; use high effort consistently across all live routes.",efforts:{"Explorer:map":"high","Explorer:lookup":"medium","Explorer:trace":"high","Librarian:lookup":"high","Librarian:research":"high","Worker:mechanical":"high","Worker:implementation":"high","Worker:integration":"high","Worker:operations":"high","Worker:validation":"high","Worker:debugging":"high","Worker:visual":"high","Reviewer:code":"high","Reviewer:testing":"high","Reviewer:audit":"high","Reviewer:security":"high","Reviewer:artifact":"high","Reviewer:visual":"high"}}];yt(Gc);var tb=new Map(Gc.map((e)=>[e.profile,e]));function nb(e){let t=tb.get(e);if(t===void 0)throw new $e("catalog_invalid","A profile has no route effort policy.",{profile:e});return Jt.flatMap((n)=>n.tasks.map((r)=>{let o=`${n.role}:${r.name}`,i=t.efforts[o];if(i===void 0)throw new $e("catalog_invalid","A route effort policy is incomplete.",{profile:e,route:o});return QE(n.role,r.name,i)}))}function Kc(e){return{name:e.name,root:{model:e.rootModel,effort:e.rootEffort},specialistModel:So,defaultServiceTier:"standard",routes:nb(e.name)}}var Jc=[Kc({name:"low",rootModel:ss,rootEffort:"low"}),Kc({name:"default",rootModel:ss,rootEffort:"medium"}),Kc({name:"high",rootModel:ss,rootEffort:"medium"})];function rb(e){let t=["low","default","high"];if(e.length!==t.length)throw new $e("catalog_invalid","The profile catalog has an invalid size.");for(let n=0;n<t.length;n+=1){let r=e[n],o=t[n];if(!r||r.name!==o)throw new $e("catalog_invalid","The profile catalog order is invalid.",{index:n});let i=ss,s=o==="low"?"low":"medium";if(r.root.model!==i||r.root.effort!==s||r.specialistModel!==So)throw new $e("catalog_invalid","A profile has an invalid model route.",{profile:r.name});if(r.routes.length!==yo.length)throw new $e("catalog_invalid","A profile is incomplete.",{profile:r.name});let a=new Set;for(let l of r.routes){if(a.has(l.key)||!eb.has(l.key)||l.model!==So||`${l.role}:${l.task}`!==l.key)throw new $e("catalog_invalid","A profile contains an invalid route.",{profile:r.name});a.add(l.key)}if(a.size!==yo.length)throw new $e("catalog_invalid","A profile is missing a specialist route.",{profile:r.name})}}rb(Jc);yt(Jc);var Um=Jc,ob=new Map,ib=new Map;for(let e of Um){ob.set(e.name,e);let t=new Map;for(let n of e.routes)t.set(n.key,n);ib.set(e.name,t)}function Hc(e,t=new Set){if(e===null||typeof e==="string"||typeof e==="boolean")return!0;if(typeof e==="number")return Number.isFinite(e);if(typeof e!=="object")return!1;if(t.has(e))return!1;let n=new Set(t);if(n.add(e),Array.isArray(e)){if(Object.getOwnPropertySymbols(e).length>0)return!1;for(let r=0;r<e.length;r+=1){let o=Object.getOwnPropertyDescriptor(e,String(r));if(!o||!o.enumerable||!("value"in o)||!Hc(o.value,n))return!1}return Object.getOwnPropertyNames(e).every((r)=>{if(r==="length")return!0;let o=Number(r),i=Object.getOwnPropertyDescriptor(e,r);return Number.isInteger(o)&&o>=0&&o<e.length&&String(o)===r&&i!==void 0&&i.enumerable&&"value"in i})}if(Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null||Object.getOwnPropertySymbols(e).length>0)return!1;return Object.getOwnPropertyNames(e).every((r)=>{let o=Object.getOwnPropertyDescriptor(e,r);return o!==void 0&&o.enumerable&&"value"in o&&Hc(o.value,n)})}var KC=ho.check(We((e)=>Hc(e))),GC=R.check(Oe(1),Ae(/^[^\0]+$/u));import{execFile as ab}from"child_process";import{createHash as cb,randomBytes as ub}from"crypto";import{lstat as nt,mkdir as cr,open as ps,readFile as ru,readdir as Lt,realpath as lb,rename as fb,rm as Cn,stat as db}from"fs/promises";import{basename as Yc,dirname as Rn,isAbsolute as pb,join as w,relative as nu,resolve as ur}from"path";import{promisify as mb}from"util";var ms="holycodex-intent-1",ou="holycodex-plan-1",iu="holycodex-assignment-1",Yt="toon-4",C=R.check(We((e)=>e.trim().length>0)),me=R.check(Ae(/^[a-z0-9][a-z0-9-]{0,95}$/u)),hs=R.check(Ae(/^[a-f0-9]{64}$/u)),Km=R.check(Ae(/^[a-f0-9]{40}$/u)),lr=ts.check(Yp(1)),rt=R.check(We((e)=>!Number.isNaN(Date.parse(e)))),te=P(C),hb=A({pid:ts.check(es(0)),token:C}),gb=120000,yb=4294967295,gs=A({role:v(["Explorer","Librarian","Worker","Reviewer"]),task:C}).check(We((e)=>Jt.some((t)=>t.role===e.role&&t.tasks.some((n)=>n.name===e.task)))),Nn=A({kind:v(["changed_path","check","repository_fact","ci","behavior","uncertainty"]),value:C,result:O(v(["passed","failed","observed","unknown"]))}),su=A({root:C,git_common_dir:C,initial_head:C,expected_head:C,expected_changes:te,expected_status_digest:hs,integrated_commit:O(Km),updated_at:rt}),fr=v(["scoping","ready","executing","verifying","reviewing","blocked","needs_root_input","complete","abandoned"]),xb=v(["scoping","ready","executing","verifying","reviewing"]),Mm=A({required:H,status:v(["not_required","missing","passed","failed","accepted","rejected"]),evidence:P(Nn)}),Pn=A({schema_version:v([ms]),toon_compatibility:v([Yt]),id:me,slug:me,title:C,goal:C,acceptance_criteria:te,state:fr,revision:lr,plan_required:H,active_plan_revision:O(lr),active_plan_digest:O(hs),blockers:te,resume_state:O(xb),verification:Mm,review:Mm,acceptance_met:H,root_readiness:H,evidence:P(Nn),baseline:su,created_at:rt,updated_at:rt}),vo=A({schema_version:v([ou]),toon_compatibility:v([Yt]),intent_id:me,revision:lr,predecessor_digest:O(hs),approach:C,scope:te,exclusions:te,assignments:te,dependencies:te,architecture:te,risks:te,assumptions:te,open_questions:te,verification:te,recovery:te,updated_at:rt}),au=v(["completed","blocked","needs_root_input","failed"]),Gm=v(["pending","executing","completed","blocked","needs_root_input","failed","superseded"]),cu=A({id:me,outcome:au,started_at:rt,finished_at:rt,summary:C,evidence:P(Nn),context7:O(ir),blocker:O(C),remaining_risk:te}),Qt=hs,uu={schema_version:v([iu]),toon_compatibility:v([Yt]),intent_id:me,id:me,objective:C,owner:ee([gs,A({role:v(["Reviewer"]),task:v(["plan"])})]),scope:te,constraints:te,exclusions:te,dependencies:te,acceptance_criteria:te,status:Gm,revision:lr,invocations:P(cu),active_invocation_id:O(C),active_started_at:O(rt),supersedes:O(me),superseded_by:O(me),supersession_reason:O(C),supersession_provenance:O(C),evidence:P(Nn),blocker:O(C),remaining_risk:te,created_at:rt,updated_at:rt},lu=A(uu),Jm=A({...uu,capability:Qt}),wo=A({...uu,active_invocation_capability_verifier:O(Qt),active_invocation_capability:O(Qt)}),as=".holycodex-transaction.toon",Hm="holycodex-work-state-transaction-1",$m=A({schema_version:v([Hm]),state:v(["prepared","committed"]),files:P(A({path:C,previous:R,next:R})).check(Oe(1))}),Ym=A({schema_version:v(["holycodex-intent-0"]),id:me,slug:me,title:C,goal:C,acceptance_criteria:te,state:fr,revision:lr,baseline:su,created_at:rt,updated_at:rt});class E extends Error{code;details;constructor(e,t,n={}){super(t);this.name="IntentStoreError",this.code=e,this.details=n}}var ys=A({title:C,goal:C,acceptanceCriteria:P(C).check(Oe(1)),planRequired:O(H),verificationRequired:O(H),reviewRequired:O(H)}),Zm=A({approach:C,scope:O(P(C)),exclusions:O(P(C)),assignments:O(P(C)),dependencies:O(P(C)),architecture:O(P(C)),risks:O(P(C)),assumptions:O(P(C)),openQuestions:O(P(C)),verification:O(P(C)),recovery:O(P(C))}),xs=A({id:O(C),objective:C,owner:gs,scope:P(C).check(Oe(1)),constraints:O(P(C)),exclusions:O(P(C)),dependencies:O(P(C)),acceptanceCriteria:P(C).check(Oe(1))}),Ss=A({scope:P(C).check(Oe(1))}),Es=A({scope:O(P(C).check(Oe(1)))}),bs=A({replacementId:me,replacementRevision:O(lr),reason:C,provenance:C}),vs=A({commit:Km}),ko=A({invocationId:O(C),capability:O(Qt),outcome:au,startedAt:O(C),summary:C,scope:O(P(C).check(Oe(1))),evidence:O(P(Nn)),context7:O(ir),blocker:O(C),remainingRisk:O(P(C))}),Sb=A({invocationId:C,startedAt:rt,capability:Qt,interruptionReason:C}),ws=A({evidence:O(P(Nn)),verification:O(v(["passed","failed"])),review:O(v(["accepted","rejected"])),acceptanceMet:O(H),rootReadiness:O(H),clearBlockers:O(H)}),To=mb(ab);class Is{repositoryRoot;stateRoot;#e;diagnose(e){let t=this;return d(function*(){yield*t.#a();let n=yield*T(()=>Lt(t.stateRoot)).pipe(U(()=>!0,(p)=>d(function*(){if(B(p,"ENOENT"))return yield*f(new E("not_found","Intent was not found.",{reference:e}));return yield*f(Y(p))}))),r=[];for(let p of n.sort()){let h=w(t.stateRoot,p);if(!(yield*bo(h))||!(yield*ar(w(h,"intent.toon"))))continue;let _;if((yield*d(function*(){return _=yield*Cb(w(h,"intent.toon")),{kind:"none"}}).pipe(D((k)=>f(k))).pipe(U(()=>!0,(k)=>d(function*(){if(Io(k)){if(p===e||k.code!=="not_found"&&(yield*Rb(w(h,"intent.toon"),e)))return yield*f(k);return{kind:"continue"}}return yield*f(k)})))).kind==="continue")continue;if([_.id,_.slug,p].includes(e))r.push({directory:h,intent:_})}if(r.length!==1)return yield*f(new E(r.length?"current_ambiguous":"not_found",r.length?"Intent reference is ambiguous.":"Intent was not found.",{reference:e}));let{directory:o,intent:i}=r[0],s=[],a=(p,h,_)=>{s.push({code:p,subject:h,repair:_})},l=w(o,as);{let p=yield*d(function*(){let h=yield*T(()=>nt(l));if(h.isSymbolicLink()||!h.isFile())a("transaction_journal_invalid","intent","Restore the transaction journal as a regular repository-local file.");else a("pending_transaction","intent","Recover the interrupted work-state transaction before relying on this diagnosis.");return{kind:"none"}}).pipe(D((h)=>f(h))).pipe(U(()=>!0,(h)=>d(function*(){if(!B(h,"ENOENT")&&!B(h,"ENOTDIR"))return yield*f(Y(h));return{kind:"none"}})))}let m=w(o,"plan.toon"),c,u=!1;{let p=yield*d(function*(){return c=yield*Ob(m,vo),{kind:"none"}}).pipe(D((h)=>f(h))).pipe(U(()=>!0,(h)=>d(function*(){if(!Io(h))return yield*f(h);return u=!0,a("plan_unreadable","plan","Repair the canonical Plan record before continuing."),{kind:"none"}})))}if(c!==void 0){let p=ht(`${ge(c)}
17
+ `);if(c.intent_id!==i.id||i.active_plan_revision!==c.revision||i.active_plan_digest!==p)a("plan_provenance_mismatch","plan","Reconcile the canonical Plan and Intent provenance.")}else if(!u&&(i.active_plan_revision!==void 0||i.active_plan_digest!==void 0))a("stale_plan_reference","intent","Restore or reconcile the referenced Plan.");let g=w(o,"assignments"),x=[];{let p=yield*d(function*(){if(yield*eu(g,!0))x=(yield*T(()=>Lt(g))).filter((h)=>h.endsWith(".toon")).sort();return{kind:"none"}}).pipe(D((h)=>f(h))).pipe(U(()=>!0,(h)=>d(function*(){if(!Io(h))return yield*f(h);return a("assignment_directory_invalid","assignments","Restore the Assignments directory as a real repository-local directory."),{kind:"none"}})))}let S=[];for(let p of x){let h;if((yield*d(function*(){return h=yield*On(w(g,p),wo),{kind:"none"}}).pipe(D((I)=>f(I))).pipe(U(()=>!0,(I)=>d(function*(){if(!Io(I))return yield*f(I);return a("assignment_unreadable",p,"Repair this Assignment record before continuing."),{kind:"continue"};return{kind:"none"}})))).kind==="continue")continue;if(h.intent_id!==i.id||p!==`${h.id}.toon`){a("assignment_identity_mismatch",p,"Reconcile the Assignment identity and path.");continue}S.push(h)}let b=new Map(S.map((p)=>[p.id,p]));for(let p of S){let h=`assignment:${p.id}`,_=p.active_invocation_id,I=_!==void 0,k=I||p.active_started_at!==void 0||p.active_invocation_capability!==void 0||p.active_invocation_capability_verifier!==void 0;if(p.status==="executing"&&!I)a("missing_active_invocation",h,"Reconcile the executing Assignment's invocation.");if(p.status!=="executing"&&k)a("orphaned_active_invocation",h,"Reconcile the active invocation and Assignment status.");if(I&&p.active_started_at===void 0)a("missing_invocation_start",h,"Reconcile the active invocation start time.");let M=new Set;for(let q of p.invocations){if(M.has(q.id))a("duplicate_invocation_id",h,"Reconcile duplicate invocation records.");M.add(q.id)}if(_!==void 0&&M.has(_))a("active_invocation_reused",h,"Reconcile the active invocation identity.");if(p.status==="superseded"&&p.superseded_by===void 0)a("missing_replacement",h,"Record or reconcile the replacement Assignment.");if(p.superseded_by!==void 0){let q=b.get(p.superseded_by);if(p.superseded_by===p.id||q?.supersedes!==p.id||p.status!=="superseded")a("stale_supersession",h,"Reconcile both ends of the supersession relation.");else if(p.supersession_reason===void 0||p.supersession_provenance===void 0||q.supersession_reason===void 0||q.supersession_provenance===void 0)a("supersession_metadata_missing",h,"Record the reason and provenance on both Assignments.");else if(p.supersession_reason!==q.supersession_reason||p.supersession_provenance!==q.supersession_provenance)a("supersession_metadata_mismatch",h,"Reconcile the reason and provenance on both Assignments.")}if(p.supersedes!==void 0&&(p.supersedes===p.id||b.get(p.supersedes)?.superseded_by!==p.id))a("stale_predecessor",h,"Reconcile the predecessor Assignment reference.");for(let q of p.dependencies)if(q===p.id)a("self_dependency",h,"Remove the Assignment's dependency on itself.");else if(q.startsWith("assignment-")&&!b.has(q))a("stale_dependency",h,`Reconcile missing dependency ${q}.`);else if(b.get(q)?.status==="superseded")a("superseded_dependency",h,`Reconcile dependency ${q} with its replacement Assignment.`);let j=p.invocations.at(-1);if(p.status==="completed"){if(j?.outcome!=="completed"||j.evidence.length===0&&j.context7===void 0)a("completion_evidence_missing",h,"Reconcile the completed invocation result and its evidence.")}else if(["blocked","needs_root_input","failed"].includes(p.status)&&j?.outcome!==p.status)a("assignment_result_mismatch",h,"Reconcile the status with its latest result.");if(["blocked","needs_root_input"].includes(p.status)&&p.blocker===void 0)a("assignment_blocker_missing",h,"Record the Assignment's current blocker.");if(p.status==="pending"&&p.invocations.length>0)a("pending_assignment_has_history",h,"Reconcile pending status with its results.");if(!["completed","superseded"].includes(p.status))a("assignment_unresolved",h,i.state==="abandoned"?"Treat as intentionally unfinished; create a new Intent if work resumes.":"Resume, repair, or explicitly supersede this Assignment.")}if(c!==void 0){for(let p of c.assignments)if(p.startsWith("assignment-")&&!b.has(p))a("stale_plan_assignment","plan",`Reconcile missing Assignment ${p}.`);else if(b.get(p)?.status==="superseded")a("superseded_plan_assignment","plan",`Reconcile Plan reference ${p} with its replacement Assignment.`)}let y=Pb(S);for(let p of y)a("dependency_cycle",`assignment:${p}`,"Remove the cyclic Assignment dependency before continuing.");if(i.state==="complete"&&S.some((p)=>!["completed","superseded"].includes(p.status)))a("terminal_intent_with_unresolved_work","intent","Reconcile terminal state and unfinished Assignments.");if(i.state==="complete"&&S.length===0)a("assignment_required","intent","Reconcile the required Assignment record.");if(["complete","abandoned"].includes(i.state)&&i.blockers.length>0)a("terminal_intent_with_blockers","intent","Reconcile terminal state and blockers.");if(["blocked","needs_root_input"].includes(i.state)){if(i.blockers.length===0)a("blocked_without_reason","intent","Record the blocker or resume the previous state.");if(i.resume_state===void 0)a("resume_state_missing","intent","Record the state to resume after the blocker clears.")}else if(i.resume_state!==void 0)a("stale_resume_state","intent","Clear the stale blocked-state resume target.");if(i.state==="complete"){if(i.verification.required&&(i.verification.status!=="passed"||!Bm(i.verification.evidence)))a("verification_evidence_missing","intent","Reconcile required verification evidence.");if(i.review.required&&(i.review.status!=="accepted"||i.review.evidence.length===0))a("review_evidence_missing","intent","Reconcile required review evidence.");if(!i.acceptance_met||!i.root_readiness||i.evidence.length===0)a("completion_evidence_missing","intent","Reconcile acceptance and Root readiness evidence.")}{let p=yield*d(function*(){return yield*t.#o(i,S.filter((h)=>h.status==="executing").flatMap((h)=>h.scope)),{kind:"none"}}).pipe(D((h)=>f(h))).pipe(U(()=>!0,(h)=>d(function*(){if(!(h instanceof E)||h.code!=="repository_drift")return yield*f(h);return a("repository_drift","repository","Reconcile the recorded baseline with the current repository state."),{kind:"none"}})))}return s.sort((p,h)=>Qc(p.subject,h.subject)||Qc(p.code,h.code)||Qc(p.repair,h.repair)),{intent_id:i.id,issues:s}})}#s;constructor(e,t={}){this.repositoryRoot=ur(e),this.stateRoot=w(this.repositoryRoot,".holycodex"),this.#e=t.now??(()=>new Date);let n=t.repositorySnapshot;this.#s=n===void 0?()=>Eb(this.repositoryRoot):()=>_i(()=>{let r=n();return kd(r)?r:T(()=>Promise.resolve(r))})}recover(){let e=this;return d(function*(){if(yield*e.#a(),!(yield*us(e.stateRoot)))return[];return yield*An(w(e.stateRoot,".intent-store"),()=>d(function*(){let t=yield*e.#u(e.stateRoot),n=yield*e.#h();return[...t,...n].sort()}))})}#u(e,t=!1){let n=this;return d(function*(){let r;{let i=yield*d(function*(){return r=t?yield*T(()=>Lt(e,{recursive:!0})):yield*T(()=>Lt(e)),{kind:"none"}}).pipe(D((s)=>f(s))).pipe(U(()=>!0,(s)=>d(function*(){if(B(s,"ENOENT"))return{kind:"return",value:[]};return yield*f(Y(s))})));if(i.kind==="return")return i.value}let o=[];for(let i of r){let s=Yc(i);if(!s.startsWith(".holycodex-write-")||!s.endsWith(".tmp"))continue;let a=w(e,i);yield*Xt(a),yield*T(()=>Cn(a,{force:!0})),o.push(nu(n.stateRoot,a).replaceAll("\\","/"))}return o.sort()})}#h(){let e=this;return d(function*(){let t;{let r=yield*d(function*(){return t=yield*T(()=>Lt(e.stateRoot)),{kind:"none"}}).pipe(D((o)=>f(o))).pipe(U(()=>!0,(o)=>d(function*(){if(B(o,"ENOENT"))return{kind:"return",value:[]};return yield*f(Y(o))})));if(r.kind==="return")return r.value}let n=[];for(let r of t){if(r===".intent-store")continue;let o=w(e.stateRoot,r);if(!(yield*bo(o)))continue;yield*An(w(o,".intent-store"),()=>d(function*(){n.push(...yield*e.#l(o))}))}return n.sort()})}#l(e){let t=this;return d(function*(){let n=[],r=w(e,as);if(yield*t.#d(e))n.push(nu(t.stateRoot,r).replaceAll("\\","/"));return n.push(...yield*t.#u(e,!0)),n})}#d(e){let t=this;return d(function*(){let n=w(e,as);yield*Xt(n);let r;{let c=yield*d(function*(){return r=yield*T(()=>nt(n)),{kind:"none"}}).pipe(D((u)=>f(u))).pipe(U(()=>!0,(u)=>d(function*(){if(B(u,"ENOENT"))return{kind:"return",value:!1};return yield*f(Y(u))})));if(c.kind==="return")return c.value}if(r.isSymbolicLink()||!r.isFile())return yield*f(new E("schema_invalid","The work-state transaction journal must be a regular file.",{path:n}));let o=yield*On(n,$m),i=o.files.filter((c)=>Zt(c.path)==="intent.toon"),s=o.files.filter((c)=>{let u=Zt(c.path);return u!==void 0&&/^assignments\/[a-z0-9][a-z0-9-]{0,95}\.toon$/u.test(u)});if(o.files.length<2||i.length!==1||s.length<1||i.length+s.length!==o.files.length)return yield*f(new E("schema_invalid","The work-state transaction must pair one or more Assignments with their Intent.",{path:n}));let a=new Set,l=yield*Ad(o.files,(c)=>d(function*(){let u=Zt(c.path);if(u===void 0)return yield*f(new E("schema_invalid","The work-state transaction contains an invalid target path.",{path:n,target:c.path}));let g=zm(e,c.path);if(a.has(g))return yield*f(new E("schema_invalid","The work-state transaction has duplicate targets.",{path:n,target:c.path}));a.add(g);let x=o.state==="committed"?c.next:c.previous,S=u==="intent.toon"?yield*Wm(x,Pn,g):yield*Wm(x,wo,g);return{canonical:u,target:g,contents:x,record:S}})),m=l.find((c)=>c.canonical==="intent.toon")?.record?.id;if(m===void 0)return yield*f(new E("schema_invalid","The work-state transaction has no Intent.",{path:n}));for(let c of l)if(yield*Xt(c.target),c.canonical!=="intent.toon"){let u=c.canonical.slice(12,-5);tu(c.record,m,u,c.target)}for(let c of l)yield*_o(c.target,c.contents);return yield*T(()=>Cn(n,{force:!0})),yield*ds(e),!0})}#a(){let e=this;return d(function*(){{let t=yield*d(function*(){let n=yield*T(()=>nt(e.stateRoot));if(n.isSymbolicLink()||!n.isDirectory())return yield*f(new E("schema_invalid","Repository-local work state must be a real directory.",{path:e.stateRoot}));return{kind:"none"}}).pipe(D((n)=>f(n))).pipe(U(()=>!0,(n)=>d(function*(){if(B(n,"ENOENT"))return{kind:"return",value:void 0};return yield*f(Y(n))})));if(t.kind==="return")return t.value}})}createIntent(e){let t=this;return d(function*(){let n=z(ys,e);if(!n.title.trim()||!n.goal.trim()||n.acceptanceCriteria.length===0)return yield*f(Re("Intent title, goal, and acceptance criteria are required."));return yield*t.recover(),yield*T(()=>cr(t.stateRoot,{recursive:!0})),yield*An(w(t.stateRoot,".intent-store"),()=>d(function*(){let r=yield*t.#s(),o=_b(n.title),i=ht([r.root,n.title.trim(),n.goal.trim()].join("\x00")).slice(0,10),s=`${o}-${i}`,a=1;while(yield*us(w(t.stateRoot,s)))a+=1,s=`${o}-${i}-${String(a).padStart(2,"0")}`;let l=`intent-${i}${a===1?"":`-${String(a).padStart(2,"0")}`}`,m=t.#e().toISOString(),c=z(Pn,{schema_version:ms,toon_compatibility:Yt,id:l,slug:o,title:n.title.trim(),goal:n.goal.trim(),acceptance_criteria:[...n.acceptanceCriteria],state:"scoping",revision:1,plan_required:n.planRequired??!1,blockers:[],verification:ls(n.verificationRequired??!0),review:ls(n.reviewRequired??!0),acceptance_met:!1,root_readiness:!1,evidence:[],baseline:Zc(r,m),created_at:m,updated_at:m}),u=w(t.stateRoot,s);return yield*T(()=>cr(w(u,"assignments"),{recursive:!0})),yield*Ce(w(u,"intent.toon"),c),yield*_o(w(t.stateRoot,"current"),`${s}
18
+ `),c}))})}listIntents(){let e=this;return d(function*(){if(yield*e.#a(),!(yield*us(e.stateRoot)))return[];return yield*An(w(e.stateRoot,".intent-store"),()=>d(function*(){yield*e.#u(e.stateRoot);let t;{let r=yield*d(function*(){return t=yield*T(()=>Lt(e.stateRoot)),{kind:"none"}}).pipe(D((o)=>f(o))).pipe(U(()=>!0,(o)=>d(function*(){if(B(o,"ENOENT"))return{kind:"return",value:[]};return yield*f(Y(o))})));if(r.kind==="return")return r.value}let n=[];for(let r of t.sort()){if(r===".intent-store")continue;let o=w(e.stateRoot,r);if(!(yield*bo(o)))continue;yield*An(w(o,".intent-store"),()=>d(function*(){yield*e.#l(o);let i=w(o,"intent.toon");if(yield*ar(i))n.push(yield*e.#t(i))}))}return n.sort((r,o)=>r.id.localeCompare(o.id))}))})}readIntent(e){let t=this;return d(function*(){let n=yield*t.#n(e);return yield*t.#r(n,()=>d(function*(){return yield*t.#t(w(n,"intent.toon"))}))})}currentIntent(){let e=this;return d(function*(){yield*e.#a(),yield*e.recover();let t=w(e.stateRoot,"current"),n=yield*T(()=>nt(t)).pipe(U(()=>!0,(i)=>d(function*(){if(B(i,"ENOENT"))return;return yield*f(Y(i))})));if(n?.isSymbolicLink()||n&&!n.isFile())return yield*f(new E("schema_invalid","The current Intent pointer must be a regular file."));let r=n?(yield*T(()=>ru(t,"utf8"))).trim():"";if(n&&!r)return yield*f(new E("schema_invalid","The current Intent pointer must select a work-state directory."));if(r){let i=ur(e.stateRoot,r);if(!nh(e.stateRoot,i))return yield*f(new E("schema_invalid","The current Intent pointer escapes repository-local state.",{directory:r}));if(!(yield*bo(i)))return yield*f(new E("schema_invalid","The current Intent pointer does not select a work-state directory.",{directory:r}));return yield*e.#r(i,()=>d(function*(){return yield*e.#t(w(i,"intent.toon"))}))}let o=(yield*e.listIntents()).filter((i)=>i.state!=="complete"&&i.state!=="abandoned");if(o.length===1)return o[0];return yield*f(new E(o.length?"current_ambiguous":"not_found",o.length?"Multiple active Intents require explicit selection.":"No current Intent exists.",{intent_ids:o.map((i)=>i.id)}))})}selectCurrent(e){let t=this;return d(function*(){let n=yield*t.#n(e),r=yield*t.#t(w(n,"intent.toon"));return yield*An(w(t.stateRoot,".intent-store"),()=>d(function*(){return yield*_o(w(t.stateRoot,"current"),`${Yc(n)}
19
+ `)})),r})}transitionIntent(e,t,n,r){let o=this;return d(function*(){let i=z(fr,t),s=r===void 0?void 0:z(C,r);if(!Number.isSafeInteger(n)||n<1)return yield*f(Re("Intent revision must be a positive integer."));let a=yield*o.#n(e);return yield*o.#r(a,()=>d(function*(){let l=yield*o.#t(w(a,"intent.toon"));if(Le(l.revision,n),i==="complete")return yield*f(new E("invalid_transition","Use the predicate-checked complete operation."));if(i==="abandoned")return yield*o.#m(a,l);return yield*o.#g(a,l,i,s)}))})}completeIntent(e,t){let n=this;return d(function*(){let r=yield*n.#n(e);return yield*n.#r(r,()=>d(function*(){let o=yield*n.#t(w(r,"intent.toon"));if(Le(o.revision,t),Dt(o),yield*n.#o(o),o.active_plan_revision!==void 0)yield*n.readPlan(e);let i=yield*n.#c(r,o),s=[];if(o.state!=="reviewing")s.push("intent_not_reviewing");if(o.blockers.length)s.push("global_blockers_unresolved");if(i.length===0)s.push("assignment_required");if(i.some((l)=>l.status!=="completed"&&l.status!=="superseded"))s.push("assignments_unresolved");if(o.verification.required&&o.verification.status!=="passed")s.push("verification_unresolved");if(o.review.required&&o.review.status!=="accepted")s.push("review_unresolved");if(!o.acceptance_met)s.push("acceptance_criteria_unmet");if(!o.root_readiness)s.push("root_readiness_missing");if(s.length)return{completed:!1,reasons:s};let a=Ft(o,n.#e,{state:"complete"});return yield*Ce(w(r,"intent.toon"),a),a}))})}abandonIntent(e,t){let n=this;return d(function*(){let r=yield*n.#n(e);return yield*n.#r(r,()=>d(function*(){let o=yield*n.#t(w(r,"intent.toon"));return Le(o.revision,t),yield*n.#m(r,o)}))})}recordIntentEvidence(e,t,n){let r=this;return d(function*(){let o=z(ws,n),i=yield*r.#n(e);return yield*r.#r(i,()=>d(function*(){let s=yield*r.#t(w(i,"intent.toon"));if(Le(s.revision,t),Dt(s),o.verification!==void 0||o.review!==void 0)yield*r.#o(s);if(o.verification!==void 0&&s.state!=="verifying")return yield*f(new E("invalid_transition","Verification evidence is only accepted while the Intent is verifying.",{state:s.state}));let a=[...s.verification.evidence,...o.evidence??[]];if(o.verification==="passed"&&!Bm(a))return yield*f(new E("invalid_input","Verification cannot pass without meaningful successful check or behavioral evidence.",{required_evidence:["check","behavior","ci"]}));if(o.review!==void 0&&s.state!=="reviewing")return yield*f(new E("invalid_transition","Review evidence is only accepted while the Intent is reviewing.",{state:s.state}));let l=[...s.evidence,...o.evidence??[]],m=o.verification===void 0?s.verification:{...s.verification,status:o.verification,evidence:[...s.verification.evidence,...o.evidence??[]]},c=o.review===void 0?s.review:{...s.review,status:o.review,evidence:[...s.review.evidence,...o.evidence??[]]},u=o.review==="rejected"&&s.state==="reviewing"?"executing":s.state,g=Ft(s,r.#e,{state:u,evidence:l,verification:m,review:c,...o.acceptanceMet===void 0?{}:{acceptance_met:o.acceptanceMet},...o.rootReadiness===void 0?{}:{root_readiness:o.rootReadiness},...o.clearBlockers?{blockers:[]}:{}});return yield*Ce(w(i,"intent.toon"),g),g}))})}recordVcsIntegration(e,t,n){let r=this;return d(function*(){let o=z(vs,n),i=yield*r.#n(e);return yield*r.#r(i,()=>d(function*(){let s=yield*r.#t(w(i,"intent.toon"));if(Le(s.revision,t),Dt(s),s.state!=="reviewing")return yield*f(new E("invalid_transition","VCS integration is only accepted after review while the Intent is reviewing.",{state:s.state}));if(s.review.required&&s.review.status!=="accepted")return yield*f(new E("not_ready","VCS integration requires accepted review evidence.",{review_status:s.review.status}));let a=yield*r.#s();if(a.root!==s.baseline.root||a.gitCommonDir!==s.baseline.git_common_dir)return yield*f(new E("repository_drift","VCS integration repository identity does not match the Intent baseline.",{expected_root:s.baseline.root,actual_root:a.root}));if(a.head!==o.commit)return yield*f(new E("repository_drift","VCS integration requires the requested commit to be the current HEAD.",{expected_head:o.commit,actual_head:a.head}));if(a.changedPaths.length)return yield*f(new E("repository_drift","VCS integration requires a clean worktree.",{changed_paths:[...a.changedPaths].sort()}));let l=yield*bb(r.repositoryRoot,o.commit);if(l.parents[0]!==s.baseline.expected_head)return yield*f(new E("repository_drift","VCS integration commit parent does not match the recorded baseline HEAD.",{expected_parent:s.baseline.expected_head,actual_parents:l.parents}));let m=yield*vb(r.repositoryRoot,s.baseline.expected_head,o.commit),c=[...new Set(Xc(s.baseline.expected_changes,m))].sort();if(m.join("\x00")!==c.join("\x00"))return yield*f(new E("repository_drift","VCS integration commit tree does not match the recorded expected change set.",{expected_changes:c,actual_changes:m}));let u=r.#e().toISOString(),g={kind:"repository_fact",value:`Root VCS integration recorded at ${o.commit}; ${String(m.length)} expected path(s) committed.`,result:"observed"},x=Ft(s,r.#e,{baseline:Zc(a,u,s.baseline.initial_head,o.commit),evidence:[...s.evidence,g]});return yield*Ce(w(i,"intent.toon"),x),x}))})}readPlan(e){let t=this;return d(function*(){let n=yield*t.#n(e),r=w(n,"plan.toon");if(!(yield*ar(r)))return;let o=yield*On(r,vo),i=yield*t.#t(w(n,"intent.toon")),s=ht(`${ge(o)}
20
+ `);if(o.intent_id!==i.id||i.active_plan_revision!==o.revision||i.active_plan_digest!==s)return yield*f(new E("schema_invalid","Canonical Plan provenance does not match its Intent.",{intent_id:i.id,plan_revision:o.revision}));return o})}revisePlan(e,t,n,r){let o=this;return d(function*(){let i=z(Zm,t);if(!i.approach.trim())return yield*f(Re("Plan approach is required."));let s=yield*o.#n(e);return yield*o.#r(s,()=>d(function*(){let a=yield*o.#t(w(s,"intent.toon"));Le(a.revision,n),Dt(a),yield*o.#o(a);let l=w(s,"plan.toon"),m=(yield*ar(l))?yield*On(l,vo):void 0;if(m===void 0&&r!==void 0)Le(0,r);if(m!==void 0)Le(m.revision,r);let c,u;if(m){let b=`${ge(m)}
21
+ `;u=ht(b),c=yield*Ub(s),yield*Nb(c,b)}let g=z(vo,{schema_version:ou,toon_compatibility:Yt,intent_id:a.id,revision:(m?.revision??0)+1,...u?{predecessor_digest:u}:{},approach:i.approach.trim(),scope:[...i.scope??[]],exclusions:[...i.exclusions??[]],assignments:[...i.assignments??[]],dependencies:[...i.dependencies??[]],architecture:[...i.architecture??[]],risks:[...i.risks??[]],assumptions:[...i.assumptions??[]],open_questions:[...i.openQuestions??[]],verification:[...i.verification??[]],recovery:[...i.recovery??[]],updated_at:o.#e().toISOString()});yield*Ce(l,g);let x=ht(`${ge(g)}
22
+ `),S=Ft(a,o.#e,{active_plan_revision:g.revision,active_plan_digest:x,verification:sr(a.verification),review:sr(a.review),acceptance_met:!1,root_readiness:!1});return yield*Ce(w(s,"intent.toon"),S),{intent:S,plan:g,...c?{archived:Yc(c)}:{}}}))})}createAssignment(e,t,n){let r=this;return d(function*(){let o=z(xs,t);if(!o.objective.trim()||o.scope.length===0||o.acceptanceCriteria.length===0)return yield*f(Re("Assignment objective, scope, and acceptance criteria are required."));let i=fs(o.scope),s=yield*r.#n(e);return yield*r.#r(s,()=>d(function*(){let a=yield*r.#t(w(s,"intent.toon"));if(Le(a.revision,n),Dt(a),yield*r.#o(a,i),o.owner.role==="Worker"&&o.owner.task==="operations"&&a.baseline.integrated_commit!==a.baseline.expected_head)return yield*f(new E("not_ready","Worker.operations requires a successfully integrated exact commit.",{expected_head:a.baseline.expected_head}));let l=o.id??`assignment-${ht([a.id,o.objective,...i].join("\x00")).slice(0,10)}`;if(!/^[a-z0-9][a-z0-9-]{0,95}$/u.test(l))return yield*f(Re("Assignment id is invalid."));let m=w(s,"assignments",`${l}.toon`);if(yield*us(m))return yield*f(new E("already_exists","Assignment already exists.",{id:l}));let c=r.#e().toISOString(),u=z(lu,{schema_version:iu,toon_compatibility:Yt,intent_id:a.id,id:l,objective:o.objective.trim(),owner:o.owner,scope:i,constraints:[...o.constraints??[]],exclusions:[...o.exclusions??[]],dependencies:[...o.dependencies??[]],acceptance_criteria:[...o.acceptanceCriteria],status:"pending",revision:1,invocations:[],evidence:[],remaining_risk:[],created_at:c,updated_at:c});return yield*T(()=>cr(Rn(m),{recursive:!0})),yield*Ce(m,u),u}))})}reviseAssignmentScope(e,t,n,r){let o=this;return d(function*(){let i=z(Ss,n),s=fs(i.scope),a=z(me,t),l=yield*o.#n(e);return yield*o.#r(l,()=>d(function*(){let m=yield*o.#t(w(l,"intent.toon"));Dt(m);let c=yield*o.#i(l,m,a);if(Le(c.revision,r),c.status==="completed"||c.status==="superseded")return yield*f(new E("invalid_transition","A completed or superseded Assignment cannot have its scope revised."));let u=Eo(c,o.#e,{scope:s});return yield*Ce(w(l,"assignments",`${a}.toon`),u),Tn(u)}))})}supersedeAssignment(e,t,n,r){let o=this;return d(function*(){let i=z(bs,r),s=z(me,t),a=yield*o.#n(e);return yield*o.#r(a,()=>d(function*(){let l=yield*o.#t(w(a,"intent.toon"));if(Dt(l),l.acceptance_met||l.root_readiness||l.review.status==="accepted")return yield*f(new E("invalid_transition","Accepted Intent evidence cannot be superseded.",{intent_id:l.id}));let m=yield*o.#i(a,l,s);Le(m.revision,n);let c=yield*o.#i(a,l,i.replacementId);if(i.replacementRevision!==void 0)Le(c.revision,i.replacementRevision);if(c.id===m.id)return yield*f(Re("An Assignment cannot supersede itself."));if(m.status==="completed"||m.status==="superseded")return yield*f(new E("invalid_transition","Only unfinished, non-superseded Assignments may be replaced.",{assignment_id:m.id,status:m.status}));if(m.status==="executing")return yield*f(new E("invalid_transition","An executing Assignment must record its active invocation before supersession.",{assignment_id:m.id}));if(m.superseded_by!==void 0)return yield*f(new E("invalid_transition","An Assignment with an existing replacement cannot be superseded again.",{assignment_id:m.id,replacement_id:m.superseded_by}));if(c.status==="completed"||c.status==="executing"||c.status==="superseded")return yield*f(new E("invalid_transition","A supersession replacement must be unfinished and inactive.",{assignment_id:c.id,status:c.status}));if(c.supersedes!==void 0||c.superseded_by!==void 0)return yield*f(new E("invalid_transition","An Assignment already participating in a supersession cannot be reused.",{assignment_id:c.id}));if(!m.scope.some((y)=>c.scope.some((p)=>Ht(y,p)||Ht(p,y))))return yield*f(Re("A supersession replacement must overlap the predecessor bounded scope."));let g=yield*o.#c(a,l);yield*o.#o(l,[...m.scope,...c.scope,...g.filter((y)=>y.status==="executing").flatMap((y)=>y.scope)]);let x=Eo(m,o.#e,{status:"superseded",blocker:void 0,active_invocation_id:void 0,active_started_at:void 0,active_invocation_capability_verifier:void 0,active_invocation_capability:void 0,superseded_by:c.id,supersession_reason:i.reason.trim(),supersession_provenance:i.provenance.trim()}),S=Eo(c,o.#e,{supersedes:m.id,supersession_reason:i.reason.trim(),supersession_provenance:i.provenance.trim()}),b=Ft(l,o.#e,{state:l.blockers.length===0&&["blocked","needs_root_input","verifying","reviewing"].includes(l.state)?"executing":l.state,blockers:[...l.blockers],...l.blockers.length===0?{resume_state:void 0}:{},verification:sr(l.verification),review:sr(l.review),acceptance_met:!1,root_readiness:!1,evidence:[...l.evidence,{kind:"behavior",value:`Assignment ${m.id} superseded by ${c.id}: ${i.reason.trim()} (${i.provenance.trim()})`,result:"observed"}]});return yield*o.#p(a,[{path:`assignments/${m.id}.toon`,previous:`${ge(m)}
23
+ `,next:`${ge(x)}
24
+ `},{path:`assignments/${c.id}.toon`,previous:`${ge(c)}
25
+ `,next:`${ge(S)}
26
+ `},{path:"intent.toon",previous:`${ge(l)}
27
+ `,next:`${ge(b)}
28
+ `}]),{assignment:Tn(x),replacement:Tn(S),intent:b}}))})}readAssignment(e,t){let n=this;return d(function*(){let r=z(me,t),o=yield*n.#n(e);return yield*n.#r(o,()=>d(function*(){let i=yield*n.#t(w(o,"intent.toon"));return Tn(yield*n.#i(o,i,r))}))})}isLegacyExecutingAssignment(e,t){let n=this;return d(function*(){let r=z(me,t),o=yield*n.#n(e);return yield*n.#r(o,()=>d(function*(){let i=yield*n.#t(w(o,"intent.toon")),s=yield*n.#i(o,i,r);return s.status==="executing"&&s.active_invocation_capability_verifier===void 0&&s.active_invocation_capability===void 0}))})}#i(e,t,n){let r=this;return d(function*(){let o=w(e,"assignments");yield*eu(o,!0);let i=w(o,`${n}.toon`);if(!(yield*ar(i)))return yield*f(new E("not_found","Assignment was not found.",{assignment_id:n}));let s=yield*On(i,wo);return tu(s,t.id,n,i),s})}listAssignments(e){let t=this;return d(function*(){let n=yield*t.#n(e);return yield*t.#r(n,()=>d(function*(){return(yield*t.#c(n,yield*t.#t(w(n,"intent.toon")))).map(Tn)}))})}#c(e,t){let n=this;return d(function*(){let r=w(e,"assignments");if(!(yield*eu(r,!0)))return[];let o;{let s=yield*d(function*(){return o=yield*T(()=>Lt(r)),{kind:"none"}}).pipe(D((a)=>f(a))).pipe(U(()=>!0,(a)=>d(function*(){if(B(a,"ENOENT"))return{kind:"return",value:[]};return yield*f(Y(a))})));if(s.kind==="return")return s.value}return yield*Td(o.filter((s)=>s.endsWith(".toon")).sort().map((s)=>d(function*(){let a=w(r,s),l=yield*On(a,wo),m=s.slice(0,-5);return tu(l,t.id,m,a),l})))})}startAssignment(e,t,n,r={}){let o=this;return d(function*(){let i=z(Es,r),s=z(me,t),a=yield*o.#n(e);return yield*o.#r(a,()=>d(function*(){let l=yield*o.#t(w(a,"intent.toon"));Dt(l);let m=yield*o.#i(a,l,s);if(Le(m.revision,n),!Et(kn(gs)(m.owner)))return yield*f(Re("This Assignment owner is retired; supersede it with a current route."));let c=Vm(m.scope,i.scope);if(yield*o.#o(l,c),m.status==="completed")return yield*f(new E("invalid_transition","A completed Assignment cannot be restarted."));if(m.status==="superseded")return yield*f(new E("invalid_transition","A superseded Assignment cannot be restarted.",{assignment_id:m.id}));if(m.status==="executing")return yield*f(new E("invalid_transition","Assignment is already executing; record its active invocation result first.",{assignment_id:m.id,...m.active_invocation_id?{invocation_id:m.active_invocation_id}:{}}));let u=o.#e().toISOString(),g=qm(m),x=Ib(),S=Eo(m,o.#e,{status:"executing",scope:c,blocker:void 0,active_invocation_id:g,active_started_at:u,active_invocation_capability_verifier:ht(x),active_invocation_capability:void 0});return yield*Ce(w(a,"assignments",`${s}.toon`),S),z(Jm,{...Tn(S),capability:x})}))})}recordAssignmentResult(e,t,n,r){let o=this;return d(function*(){return yield*o.#f(e,t,n,r,!1)})}recordSpecialistAssignmentResult(e,t,n,r){let o=this;return d(function*(){if(z(ko,r).capability===void 0)return yield*f(Re("Specialist Assignment results require an active invocation capability."));return yield*o.#f(e,t,n,r,!0)})}recoverInterruptedAssignment(e,t,n,r){let o=this;return d(function*(){let i=z(Sb,r),s=i.interruptionReason.trim(),a={kind:"behavior",value:`Interrupted invocation ${i.invocationId} started at ${i.startedAt} recovered as failed: ${s}`,result:"failed"};return yield*o.#f(e,t,n,{invocationId:i.invocationId,capability:i.capability,outcome:"failed",startedAt:i.startedAt,summary:`Interrupted invocation recovered as failed: ${s}`,evidence:[a]},!0,{invocationId:i.invocationId,startedAt:i.startedAt})})}#f(e,t,n,r,o,i){let s=this;return d(function*(){let a=z(ko,r),l=z(me,t),m=yield*s.#n(e);return yield*s.#r(m,()=>d(function*(){let c=yield*s.#t(w(m,"intent.toon"));if(Dt(c),i!==void 0&&e!==c.id)return yield*f(Re("Interruption recovery requires the exact Intent ID reference."));let u=yield*s.#i(m,c,l);if(Le(u.revision,n),u.status!=="executing")return yield*f(new E("invalid_transition",`Assignment result requires an executing Assignment; current status is ${u.status}.`,{assignment_id:u.id,status:u.status}));if(i===void 0&&!o&&a.capability===void 0&&(u.active_invocation_capability_verifier!==void 0||u.active_invocation_capability!==void 0))return yield*f(new E("invalid_transition","This Assignment invocation requires its active capability to record a result.",{assignment_id:u.id}));if(i!==void 0){if(u.active_invocation_id!==i.invocationId||u.active_started_at!==i.startedAt)return yield*f(new E("invalid_transition","Interruption recovery does not match the active invocation identity and start time.",{assignment_id:u.id,expected_invocation_id:u.active_invocation_id,expected_started_at:u.active_started_at}))}if(u.active_invocation_id!==void 0&&a.invocationId!==void 0&&u.active_invocation_id!==a.invocationId)return yield*f(new E("invalid_transition","Assignment result does not match the active invocation.",{assignment_id:u.id,expected_invocation_id:u.active_invocation_id,actual_invocation_id:a.invocationId}));if(o&&(u.active_invocation_id===void 0||a.invocationId===void 0))return yield*f(new E("invalid_transition",i===void 0?"Specialist Assignment results require the active invocation identity.":"Interruption recovery requires the active invocation identity.",{assignment_id:u.id}));if(o&&u.active_invocation_capability_verifier===void 0&&u.active_invocation_capability===void 0)return yield*f(new E("invalid_transition",i===void 0?"The active Assignment invocation has no capability to authorize a specialist result.":"The active Assignment invocation has no capability to authorize interruption recovery.",{assignment_id:u.id}));if(a.capability!==void 0&&(u.active_invocation_capability_verifier!==void 0?ht(a.capability)!==u.active_invocation_capability_verifier:u.active_invocation_capability!==a.capability))return yield*f(new E("invalid_transition","Assignment result capability does not match the active invocation.",{assignment_id:u.id}));if((a.outcome==="blocked"||a.outcome==="needs_root_input")&&!a.blocker?.trim())return yield*f(Re("Blocked results require a local blocker."));if(i===void 0&&zc({role:u.owner.role,task:u.owner.task,objective:u.objective,scope:u.scope,constraints:u.constraints,exclusions:u.exclusions,dependencies:u.dependencies,acceptanceCriteria:u.acceptance_criteria})&&a.context7===void 0)return yield*f(new E("invalid_input","This Librarian Assignment result requires typed Context7 evidence.",{assignment_id:u.id,required_evidence:"context7"}));let g=Vm(u.scope,a.scope),x=yield*s.#s(),S=Xc(c.baseline.expected_changes,x.changedPaths),b=[...a.evidence??[]],y=new Set(b.filter((X)=>X.kind==="changed_path").map((X)=>X.value)),p=[...y].filter((X)=>!g.some((dr)=>Ht(X,dr)));if(p.length)return yield*f(new E("repository_drift","Assignment evidence declares paths outside its bounded scope.",{assignment_id:u.id,out_of_scope_paths:p.sort()}));let _=(yield*s.#c(m,c)).filter((X)=>X.id!==u.id&&X.status==="executing"),I=x.changedPaths.filter((X)=>_.some((dr)=>dr.scope.some((uh)=>Ht(X,uh)))),k=new Set(I),M=new Set([...S,...y,...I]),j=x.changedPaths.filter((X)=>!M.has(X)),q=new Set(S),ae=x.changedPaths.filter((X)=>g.some((dr)=>Ht(X,dr))&&!q.has(X)&&!y.has(X)&&!k.has(X)),Ke=x.root!==c.baseline.root||x.gitCommonDir!==c.baseline.git_common_dir,Se=jm(x.statusDigest)!==c.baseline.expected_status_digest,Ee=x.head!==c.baseline.expected_head||Se||[...new Set(S)].sort().join("\x00")!==[...new Set(x.changedPaths)].sort().join("\x00"),ot=[...y].some((X)=>x.changedPaths.includes(X)),be=I.length>0;if(i===void 0&&(Ke||j.length||ae.length||Se&&!ot&&!be||x.head!==c.baseline.expected_head&&!ot&&!be))return yield*f(new E("repository_drift","Repository state changed outside the recorded Assignment result.",{expected_head:c.baseline.expected_head,actual_head:x.head,unexpected_paths:[...new Set([...j,...ae])].sort(),concurrent_assignments:_.map((X)=>X.id).sort()}));let ks=s.#e().toISOString(),Ts=u.active_invocation_id??a.invocationId??qm(u);if(u.invocations.some((X)=>X.id===Ts))return yield*f(new E("already_exists","Assignment invocation already exists.",{invocation_id:Ts}));let ih=z(cu,{id:Ts,outcome:a.outcome,started_at:u.active_started_at??a.startedAt??ks,finished_at:ks,summary:a.summary,evidence:b,...a.context7===void 0?{}:{context7:a.context7},...a.blocker?{blocker:a.blocker}:{},remaining_risk:[...a.remainingRisk??[]]}),mu=Eo(u,s.#e,{status:a.outcome,scope:g,invocations:[...u.invocations,ih],active_invocation_id:void 0,active_started_at:void 0,active_invocation_capability_verifier:void 0,active_invocation_capability:void 0,evidence:[...u.evidence,...b],blocker:a.blocker,remaining_risk:[...a.remainingRisk??[]]}),hu=u.owner.role==="Worker"&&u.owner.task==="operations",gu=c.baseline.integrated_commit!==void 0&&c.baseline.integrated_commit===c.baseline.expected_head&&x.head===c.baseline.expected_head&&x.changedPaths.length===0,sh=hu&&a.outcome==="failed",ah=hu&&a.outcome==="completed"&&gu&&c.state==="reviewing"&&(!c.verification.required||c.verification.status==="passed")&&(!c.review.required||c.review.status==="accepted"),ch=Ee||a.outcome==="failed",yu=Ft(c,s.#e,{baseline:i===void 0?Zc(x,ks,c.baseline.initial_head,gu?c.baseline.integrated_commit:void 0):c.baseline,...ah||!ch?{}:{state:sh?"executing":c.state,verification:sr(c.verification),review:sr(c.review),acceptance_met:!1,root_readiness:!1}});return yield*s.#y(m,l,u,mu,c,yu),{assignment:Tn(mu),intent:yu}}))})}#g(e,t,n,r){let o=this;return d(function*(){let i=t.state;if(n==="blocked"||n==="needs_root_input"){if(["complete","abandoned","blocked","needs_root_input"].includes(i))return yield*f(cs(i,n));if(!r?.trim())return yield*f(Re("A blocker or required input is required."));let a=Ft(t,o.#e,{state:n,blockers:[r.trim()],resume_state:i});return yield*Ce(w(e,"intent.toon"),a),a}if(i==="blocked"||i==="needs_root_input"){if(n!==t.resume_state||t.blockers.length)return yield*f(cs(i,n))}else if(!{scoping:["ready"],ready:["executing"],executing:["verifying"],verifying:["reviewing","executing"],reviewing:["executing"]}[i]?.includes(n))return yield*f(cs(i,n));if(n==="ready"){let a=[];if(!t.goal.trim())a.push("goal_missing");if(!t.acceptance_criteria.length)a.push("acceptance_criteria_missing");if((t.active_plan_revision===void 0?void 0:yield*o.readPlan(t.id))?.open_questions.length)a.push("material_open_questions");if(a.length)return yield*f(new E("not_ready","Intent readiness predicates failed.",{reasons:a}))}if(n==="executing"&&i==="ready")yield*o.#o(t);if(n==="reviewing"&&t.verification.required&&t.verification.status!=="passed")return yield*f(new E("invalid_transition","Verification must pass before review."));if(n==="reviewing")yield*o.#o(t);let s=Ft(t,o.#e,{state:n,resume_state:void 0});return yield*Ce(w(e,"intent.toon"),s),s})}#r(e,t){let n=this;return d(function*(){return yield*An(w(e,".intent-store"),()=>d(function*(){return yield*n.#l(e),yield*t()}))})}#y(e,t,n,r,o,i){let s=this;return d(function*(){yield*s.#p(e,[{path:`assignments/${t}.toon`,previous:`${ge(n)}
29
+ `,next:`${ge(r)}
30
+ `},{path:"intent.toon",previous:`${ge(o)}
31
+ `,next:`${ge(i)}
32
+ `}])})}#p(e,t){let n=this;return d(function*(){let r=w(e,as),o=z($m,{schema_version:Hm,state:"prepared",files:t.map((s)=>({...s}))}),i=o.files.map((s)=>zm(e,s.path));yield*Ce(r,o);{let s=yield*d(function*(){for(let[a,l]of i.entries())yield*_o(l,o.files[a].next);return yield*Ce(r,{...o,state:"committed"}),{kind:"none"}}).pipe(D((a)=>f(a))).pipe(U(()=>!0,(a)=>d(function*(){{let l=yield*d(function*(){return yield*n.#d(e),{kind:"none"}}).pipe(D((m)=>f(m))).pipe(U(()=>!0,(m)=>d(function*(){return yield*f(Y(m))})))}return yield*f(a)})))}yield*T(()=>Cn(r,{force:!0})),yield*ds(e)})}#m(e,t){let n=this;return d(function*(){if(t.state==="complete"||t.state==="abandoned")return yield*f(cs(t.state,"abandoned"));let r=Ft(t,n.#e,{state:"abandoned",blockers:[]});return yield*Ce(w(e,"intent.toon"),r),r})}#o(e,t){let n=this;return d(function*(){let r=yield*n.#s(),o=[...Xc(e.baseline.expected_changes,r.changedPaths)].sort(),i=[...r.changedPaths].sort(),s=new Set(t===void 0?[]:i.filter((l)=>t.some((m)=>Ht(l,m)))),a=[...new Set([...o,...s])].sort();if(r.root!==e.baseline.root||r.gitCommonDir!==e.baseline.git_common_dir||r.head!==e.baseline.expected_head||a.join("\x00")!==i.join("\x00")||jm(r.statusDigest)!==e.baseline.expected_status_digest&&s.size===0)return yield*f(new E("repository_drift","Repository baseline no longer matches recorded assumptions.",{expected_head:e.baseline.expected_head,actual_head:r.head,expected_changes:a,actual_changes:i}))})}#n(e){let t=this;return d(function*(){yield*t.#a();let n;{let o=yield*d(function*(){return n=yield*T(()=>Lt(t.stateRoot)),{kind:"none"}}).pipe(D((i)=>f(i))).pipe(U(()=>!0,(i)=>d(function*(){if(B(i,"ENOENT"))return yield*f(new E("not_found","Intent was not found.",{reference:e}));return yield*f(Y(i))})))}let r=[];for(let o of n.sort()){let i=w(t.stateRoot,o);if(!(yield*bo(i)))continue;let s=w(i,"intent.toon");if(!(yield*ar(s)))continue;let a=yield*t.#t(s);if(a.id===e||a.slug===e||o===e)r.push(i)}if(r.length===1)return r[0];if(r.length>1)return yield*f(new E("current_ambiguous","Intent reference is ambiguous.",{reference:e}));return yield*f(new E("not_found","Intent was not found.",{reference:e}))})}#t(e){let t=this;return d(function*(){let n=yield*_s(e),r=pt(Pn,n);if(Et(r))return r.success;let o=pt(Ym,n);if(ct(o))return yield*f(new E("schema_invalid","Persisted Intent failed schema validation.",{path:e,error:String(r.failure)}));let i=Xm(o.success);return yield*Ce(e,i),i})}}function Eb(e){return d(function*(){let t=yield*T(()=>lb(e)),n=(...m)=>d(function*(){{let c=yield*d(function*(){return{kind:"return",value:(yield*T(()=>To("git",["-C",t,...m],{encoding:"utf8"}))).stdout.trimEnd()}}).pipe(D((u)=>f(u))).pipe(U(()=>!0,(u)=>d(function*(){return yield*f(new E("io_failure","Repository identity requires an accessible Git worktree.",{message:u instanceof Error?u.message:String(u)}))})));if(c.kind==="return")return c.value}}),r=yield*n("rev-parse","--git-common-dir"),o=(yield*wb(t,"rev-parse","--verify","HEAD"))??"unborn",i=yield*n("status","--porcelain=v1","-z","--untracked-files=all"),s=yield*n("status","--porcelain=v1","--untracked-files=all"),a=i.split("\x00"),l=[];for(let m=0;m<a.length;m+=1){let c=a[m];if(!c)continue;if(l.push(c.slice(3)),c.slice(0,2).includes("R")||c.slice(0,2).includes("C"))m+=1}return l.sort(),{root:t,gitCommonDir:ur(t,r),head:o,changedPaths:l,statusDigest:ht(s)}})}function bb(e,t){return d(function*(){{let n=yield*d(function*(){let r=(yield*T(()=>To("git",["-C",e,"show","-s","--format=%H%n%P",t],{encoding:"utf8"}))).stdout.trim(),[o,i=""]=r.split(`
33
+ `);if(o!==t)return yield*f(Error(`Resolved commit ${o??""} does not match requested ${t}.`));return{kind:"return",value:{hash:o,parents:i?i.split(/\s+/u):[]}}}).pipe(D((r)=>f(r))).pipe(U(()=>!0,(r)=>d(function*(){return yield*f(new E("repository_drift","VCS integration commit could not be inspected.",{commit:t,message:r instanceof Error?r.message:String(r)}))})));if(n.kind==="return")return n.value}})}function vb(e,t,n){return d(function*(){{let r=yield*d(function*(){return{kind:"return",value:(yield*T(()=>To("git",["-C",e,"diff","--name-only","-z","--no-ext-diff",t,n],{encoding:"utf8"}))).stdout.split("\x00").filter(Boolean).sort()}}).pipe(D((o)=>f(o))).pipe(U(()=>!0,(o)=>d(function*(){return yield*f(new E("repository_drift","VCS integration commit tree could not be inspected.",{parent:t,commit:n,message:o instanceof Error?o.message:String(o)}))})));if(r.kind==="return")return r.value}})}function wb(e,...t){return d(function*(){{let n=yield*d(function*(){return{kind:"return",value:(yield*T(()=>To("git",["-C",e,...t],{encoding:"utf8"}))).stdout.trim()}}).pipe(D((r)=>f(r))).pipe(U(()=>!0,(r)=>d(function*(){return{kind:"return",value:void 0}})));if(n.kind==="return")return n.value}})}function Xm(e){return z(Pn,{...e,schema_version:ms,toon_compatibility:Yt,plan_required:!1,blockers:[],verification:ls(!0),review:ls(!0),acceptance_met:!1,root_readiness:!1,evidence:[]})}function ls(e){return{required:e,status:e?"missing":"not_required",evidence:[]}}function sr(e){return{...e,status:e.required?"missing":"not_required"}}function Zc(e,t,n=e.head,r){return{root:e.root,git_common_dir:e.gitCommonDir,initial_head:n,expected_head:e.head,expected_changes:[...e.changedPaths].sort(),expected_status_digest:/^[a-f0-9]{64}$/u.test(e.statusDigest)?e.statusDigest:ht(e.statusDigest),...r===void 0?{}:{integrated_commit:r},updated_at:t}}function jm(e){return/^[a-f0-9]{64}$/u.test(e)?e:ht(e)}function Bm(e){return e.some((t)=>["check","behavior","ci"].includes(t.kind)&&["passed","observed"].includes(t.result??""))}function Ib(){return ub(32).toString("hex")}function qm(e){let t=e.invocations.length+1,n=`invocation-${String(t).padStart(3,"0")}`;while(e.invocations.some((r)=>r.id===n))t+=1,n=`invocation-${String(t).padStart(3,"0")}`;return n}function Ft(e,t,n){return z(Pn,Qm({...e,...n,revision:e.revision+1,updated_at:t().toISOString()}))}function Eo(e,t,n){return z(wo,Qm({...e,...n,revision:e.revision+1,updated_at:t().toISOString()}))}function Tn(e){let{active_invocation_capability_verifier:t,active_invocation_capability:n,...r}=e;return z(lu,r)}function Qm(e){let t={...e};for(let[n,r]of Object.entries(t))if(r===void 0)delete t[n];return t}function _b(e){return e.normalize("NFKD").toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-|-$/gu,"").slice(0,48).replace(/-$/u,"")||"intent"}function fs(e){let t=e.map((n)=>{let r=Zt(n);if(r===void 0)throw Re("Assignment scope must contain canonical repository-relative paths.");return r});return[...new Set(t)].sort()}function Vm(e,t){let n=fs(e);if(t===void 0)return n;let r=fs(t);if(n.some((i)=>!r.includes(i)))throw Re("Assignment scope expansion must preserve the existing scope.");if(r.filter((i)=>!n.some((s)=>kb(i,s))).length)throw Re("Assignment scope expansion exceeds the declared component authority.");return r}function kb(e,t){if(Ht(e,t))return!0;let n=Zt(t);if(n===void 0||n===".")return!1;let r=n.split("/"),o=r.at(-1);if(o===void 0||!o.includes("."))return!1;let i=r.slice(0,-1).join("/")||".";return e!==i&&Ht(e,i)}function Ht(e,t){let n=Zt(e),r=Zt(t);if(n===void 0||r===void 0)return!1;return r==="."||n===r||n.startsWith(`${r}/`)}function Zt(e){let t=e.replaceAll("\\","/");if(!t||t.startsWith("/")||/^[a-z]:/iu.test(t))return;let n=t.split("/");if(n.some((o)=>o===".."))return;let r=n.filter((o)=>o!==""&&o!==".");return r.length===0?".":r.join("/")}function zm(e,t){let n=Zt(t);if(n===void 0||n!=="intent.toon"&&!/^assignments\/[a-z0-9][a-z0-9-]{0,95}\.toon$/u.test(n))throw new E("schema_invalid","The work-state transaction target is outside the supported Intent records.",{path:t});let r=ur(e,n);if(!nh(ur(e),r))throw new E("schema_invalid","The work-state transaction target escapes the Intent directory.",{path:t});return r}function Xc(e,t){let n=new Set(t);return e.map((r)=>{if(n.has(r))return r;let o=Ab(r);return o!==void 0&&n.has(o)?o:r})}var Tb={a:7,b:8,t:9,n:10,v:11,f:12,r:13,"\\":92,'"':34};function Ab(e){if(e.length<2||e[0]!=='"'||e[e.length-1]!=='"')return;let t=[],n=new TextEncoder,r=e.slice(1,-1);for(let i=0;i<r.length;){let s=r.codePointAt(i);if(s===void 0)return;if(s!==92){if(s===34||s<32||s===127)return;let c=String.fromCodePoint(s);t.push(...n.encode(c)),i+=c.length;continue}let a=r[i+1];if(a===void 0)return;let l=Tb[a];if(l!==void 0){t.push(l),i+=2;continue}if(a<"0"||a>"7")return;let m=i+2;while(m<r.length&&m<i+4&&r[m]>="0"&&r[m]<="7")m+=1;t.push(Number.parseInt(r.slice(i+1,m),8)),i=m}let o=Ll(()=>new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(Uint8Array.from(t)));return Et(o)?o.success:void 0}function ht(e){return cb("sha256").update(e).digest("hex")}function Le(e,t){if(t===void 0||e!==t)throw new E("stale_write","Persisted revision changed before mutation.",{expected_revision:t,actual_revision:e})}function Re(e){return new E("invalid_input",e)}function Dt(e){if(e.state==="complete"||e.state==="abandoned")throw new E("invalid_transition","Terminal Intents cannot be mutated.",{state:e.state})}function cs(e,t){return new E("invalid_transition",`Intent cannot transition from ${e} to ${t}.`,{source:e,target:t})}function z(e,t){let n=pt(e,t);if(ct(n))throw new E("schema_invalid","Value failed Effect Schema validation.",{error:String(n.failure)});return n.success}function _s(e){return d(function*(){let t;{let n=yield*d(function*(){let r=yield*T(()=>nt(e));if(r.isSymbolicLink()||!r.isFile())return yield*f(new E("schema_invalid","Persistent work state must be a regular file.",{path:e}));return t=yield*T(()=>ru(e,"utf8")),{kind:"none"}}).pipe(D((r)=>f(r))).pipe(U(()=>!0,(r)=>d(function*(){if(B(r,"ENOENT"))return yield*f(new E("not_found","Persistent work state was not found.",{path:e}));return yield*f(Y(r))})))}return yield*eh(t,e)})}function On(e,t){return d(function*(){return z(t,yield*_s(e))})}function Ob(e,t){return d(function*(){let n;{let r=yield*d(function*(){return n=yield*T(()=>nt(e)),{kind:"none"}}).pipe(D((o)=>f(o))).pipe(U(()=>!0,(o)=>d(function*(){if(B(o,"ENOENT")||B(o,"ENOTDIR"))return{kind:"return",value:void 0};return yield*f(Y(o))})));if(r.kind==="return")return r.value}if(n.isSymbolicLink()||!n.isFile())return yield*f(new E("schema_invalid","Persistent work state must be a regular file.",{path:e}));return yield*On(e,t)})}function Cb(e){return d(function*(){let t=yield*_s(e),n=pt(Pn,t);if(Et(n))return n.success;let r=pt(Ym,t);if(ct(r))return yield*f(new E("schema_invalid","Persisted Intent failed schema validation.",{path:e,error:String(n.failure)}));return Xm(r.success)})}function Rb(e,t){return d(function*(){let n;{let o=yield*d(function*(){return n=yield*_s(e),{kind:"none"}}).pipe(D((i)=>f(i))).pipe(U(()=>!0,(i)=>d(function*(){if(Io(i))return{kind:"return",value:!1};return yield*f(i)})));if(o.kind==="return")return o.value}if(typeof n!=="object"||n===null||Array.isArray(n))return!1;let r=n;return r.id===t||r.slug===t})}function Io(e){return e instanceof E&&["malformed_toon","schema_invalid","not_found"].includes(e.code)}function Pb(e){let t=new Map(e.map((s)=>[s.id,s])),n=new Set,r=[],o=new Set,i=(s)=>{let a=r.indexOf(s);if(a>=0){for(let l of r.slice(a))o.add(l);return}if(n.has(s))return;r.push(s);for(let l of t.get(s)?.dependencies??[])if(l!==s&&t.has(l))i(l);r.pop(),n.add(s)};for(let s of[...t.keys()].sort())i(s);return[...o].sort()}function Qc(e,t){return e<t?-1:e>t?1:0}function Wm(e,t,n){return eh(e,n).pipe(Xe((r)=>Vt({try:()=>z(t,r),catch:(o)=>o})))}function eh(e,t){return Vt({try:()=>Ku(e,{strict:!0}),catch:(n)=>new E("malformed_toon","Persistent work state is malformed TOON.",{path:t,message:n instanceof Error?n.message:String(n)})})}function Ce(e,t){return d(function*(){yield*_o(e,`${ge(t)}
34
+ `)})}function _o(e,t){return d(function*(){yield*Xt(e),yield*T(()=>cr(Rn(e),{recursive:!0})),yield*Xt(e);let n=w(Rn(e),`.holycodex-write-${process.pid}-${crypto.randomUUID()}.tmp`);{let r=yield*d(function*(){let o=yield*T(()=>ps(n,"wx",384));{let i=yield*d(function*(){return yield*T(()=>o.writeFile(t,"utf8")),yield*T(()=>o.sync()),{kind:"none"}}).pipe(D((s)=>f(s))).pipe(Gn(d(function*(){return yield*T(()=>o.close()),{kind:"none"}}).pipe(Kn)))}return yield*T(()=>fb(n,e)),yield*ds(Rn(e)),{kind:"none"}}).pipe(D((o)=>f(o))).pipe(U(()=>!0,(o)=>d(function*(){return yield*T(()=>Cn(n,{force:!0})),yield*f(Y(o));return{kind:"none"}})))}})}function Nb(e,t){return d(function*(){yield*Xt(e);{let n=yield*d(function*(){let r=yield*T(()=>ps(e,"wx",256));{let o=yield*d(function*(){return yield*T(()=>r.writeFile(t,"utf8")),yield*T(()=>r.sync()),{kind:"none"}}).pipe(D((i)=>f(i))).pipe(Gn(d(function*(){return yield*T(()=>r.close()),{kind:"none"}}).pipe(Kn)))}return yield*ds(Rn(e)),{kind:"none"}}).pipe(D((r)=>f(r))).pipe(U(()=>!0,(r)=>d(function*(){if(B(r,"EEXIST"))return yield*f(new E("archive_conflict","Archived plans are immutable.",{path:e}));return yield*f(Y(r))})))}})}function ds(e){return d(function*(){if(process.platform==="win32")return;{let t=yield*d(function*(){let n=yield*T(()=>ps(e,"r"));{let r=yield*d(function*(){return yield*T(()=>n.sync()),{kind:"none"}}).pipe(D((o)=>f(o))).pipe(Gn(d(function*(){return yield*T(()=>n.close()),{kind:"none"}}).pipe(Kn)))}return{kind:"none"}}).pipe(D((n)=>f(n))).pipe(U(()=>!0,(n)=>d(function*(){if(B(n,"EINVAL")||B(n,"ENOSYS")||B(n,"ENOTSUP")||B(n,"EOPNOTSUPP")||B(n,"EISDIR"))return{kind:"return",value:void 0};return yield*f(n)})));if(t.kind==="return")return t.value}})}function An(e,t){return d(function*(){let n=Rn(e);yield*Xt(e),yield*T(()=>cr(n,{recursive:!0}));let r=!1;for(let a=0;a<200;a+=1){let l=yield*d(function*(){return yield*T(()=>cr(e)),r=!0,{kind:"break"};return{kind:"none"}}).pipe(D((m)=>f(m))).pipe(U(()=>!0,(m)=>d(function*(){if(!B(m,"EEXIST"))return yield*f(Y(m));if((yield*d(function*(){let u=yield*T(()=>nt(e));if(u.isSymbolicLink()||!u.isDirectory())return yield*f(new E("schema_invalid","The work-state lock must be a real directory.",{path:e}));let g=yield*th(e);if(g.kind==="owned"&&!(yield*Fb(g.owner.pid)))return yield*T(()=>Cn(e,{recursive:!0,force:!0})),{kind:"continue"};if(g.kind==="missing"&&Date.now()-u.mtimeMs>gb)return yield*T(()=>Cn(e,{recursive:!0,force:!0})),{kind:"continue"};return{kind:"none"}}).pipe(D((u)=>f(u))).pipe(U(()=>!0,(u)=>d(function*(){if(!B(u,"ENOENT"))return yield*f(Y(u));return{kind:"none"}})))).kind==="continue")return{kind:"continue"};return yield*Cd(Math.min(5+a,50)),{kind:"none"}})));if(l.kind==="break")break;if(l.kind==="continue")continue}if(!r)return yield*f(new E("stale_write","Another mutation is still in progress.",{lock:e}));let o=w(e,".owner"),i=crypto.randomUUID(),s;{let a=yield*d(function*(){return yield*Xt(o),s=yield*T(()=>ps(o,"wx",384)),yield*T(()=>s.writeFile(`${JSON.stringify({pid:process.pid,token:i})}
35
+ `,"utf8")),yield*T(()=>s.sync()),{kind:"none"}}).pipe(D((l)=>f(l))).pipe(U(()=>!0,(l)=>d(function*(){if(s!==void 0){let m=yield*d(function*(){return yield*T(()=>s.close()),{kind:"none"}}).pipe(D((c)=>f(c))).pipe(U(()=>!0,(c)=>d(function*(){return{kind:"none"}})))}if(B(l,"EEXIST"))return yield*f(new E("stale_write","Another mutation is still in progress.",{lock:e}));return yield*f(Y(l))})))}if(s===void 0)return yield*f(Y(Error("The work-state lock owner was not opened.")));{let a=yield*d(function*(){return{kind:"return",value:yield*t()}}).pipe(D((l)=>f(l))).pipe(Gn(d(function*(){{let l=yield*d(function*(){return yield*T(()=>s.close()),{kind:"none"}}).pipe(D((m)=>f(m))).pipe(Gn(d(function*(){return yield*Lb(e,i),{kind:"none"}}).pipe(Kn)))}return{kind:"none"}}).pipe(Kn)));if(a.kind==="return")return a.value}})}function th(e){return d(function*(){let t=w(e,".owner");{let n=yield*d(function*(){let r=yield*T(()=>nt(t));if(r.isSymbolicLink()||!r.isFile())return{kind:"return",value:{kind:"unknown"}};let o=yield*T(()=>ru(t,"utf8")),i;{let a=yield*d(function*(){return i=JSON.parse(o),{kind:"none"}}).pipe(D((l)=>f(l))).pipe(U(()=>!0,(l)=>d(function*(){return{kind:"return",value:{kind:"unknown"}}})));if(a.kind==="return")return{kind:"return",value:a.value}}let s=pt(hb,i);return{kind:"return",value:Et(s)?{kind:"owned",owner:s.success}:{kind:"unknown"}}}).pipe(D((r)=>f(r))).pipe(U(()=>!0,(r)=>d(function*(){if(B(r,"ENOENT"))return{kind:"return",value:{kind:"missing"}};if(B(r,"EPERM")||B(r,"EACCES"))return{kind:"return",value:{kind:"unknown"}};return yield*f(Y(r))})));if(n.kind==="return")return n.value}})}function Fb(e){return d(function*(){if(e===process.pid)return!0;if(process.platform==="win32")return yield*Db(e);if(!["aix","android","darwin","freebsd","haiku","linux","openbsd","sunos","win32"].includes(process.platform))return!0;{let n=yield*d(function*(){return process.kill(e,0),{kind:"return",value:!0};return{kind:"none"}}).pipe(D((r)=>f(r))).pipe(U(()=>!0,(r)=>d(function*(){return{kind:"return",value:B(r,"EPERM")}})));if(n.kind==="return")return n.value}})}function Db(e){return d(function*(){if(!Number.isSafeInteger(e)||e>yb)return!1;{let t=yield*d(function*(){let{stdout:n}=yield*T(()=>To("tasklist.exe",["/FI",`PID eq ${e}`,"/FO","CSV","/NH"],{encoding:"utf8",windowsHide:!0}));return{kind:"return",value:n.split(/\r?\n/u).some((r)=>/^"[^"]*","(\d+)",/u.exec(r)?.[1]===String(e))}}).pipe(D((n)=>f(n))).pipe(U(()=>!0,(n)=>d(function*(){return{kind:"return",value:!0}})));if(t.kind==="return")return t.value}})}function Lb(e,t){return d(function*(){let n=yield*th(e);if(n.kind!=="owned"||n.owner.token!==t)return;yield*T(()=>Cn(e,{recursive:!0,force:!0}))})}function Ub(e){return d(function*(){let t=(yield*T(()=>Lt(e))).map((n)=>/^plan\.old-(\d{3})\.toon$/u.exec(n)?.[1]).filter((n)=>n!==void 0).map(Number);return w(e,`plan.old-${String((t.length?Math.max(...t):0)+1).padStart(3,"0")}.toon`)})}function us(e){return d(function*(){{let t=yield*d(function*(){return yield*T(()=>db(e)),{kind:"return",value:!0};return{kind:"none"}}).pipe(D((n)=>f(n))).pipe(U(()=>!0,(n)=>d(function*(){if(B(n,"ENOENT"))return{kind:"return",value:!1};return yield*f(Y(n))})));if(t.kind==="return")return t.value}})}function ar(e){return d(function*(){{let t=yield*d(function*(){let n=yield*T(()=>nt(e));return{kind:"return",value:n.isFile()&&!n.isSymbolicLink()}}).pipe(D((n)=>f(n))).pipe(U(()=>!0,(n)=>d(function*(){if(B(n,"ENOENT")||B(n,"ENOTDIR"))return{kind:"return",value:!1};return yield*f(Y(n))})));if(t.kind==="return")return t.value}})}function eu(e,t){return d(function*(){{let n=yield*d(function*(){let r=yield*T(()=>nt(e));if(r.isSymbolicLink()||!r.isDirectory())return yield*f(new E("schema_invalid","Persistent work-state directories must be real directories.",{path:e}));return{kind:"return",value:!0}}).pipe(D((r)=>f(r))).pipe(U(()=>!0,(r)=>d(function*(){if(B(r,"ENOENT")&&t)return{kind:"return",value:!1};return yield*f(Y(r))})));if(n.kind==="return")return n.value}})}function bo(e){return d(function*(){{let t=yield*d(function*(){let n=yield*T(()=>nt(e));return{kind:"return",value:n.isDirectory()&&!n.isSymbolicLink()}}).pipe(D((n)=>f(n))).pipe(U(()=>!0,(n)=>d(function*(){if(B(n,"ENOENT")||B(n,"ENOTDIR"))return{kind:"return",value:!1};return yield*f(Y(n))})));if(t.kind==="return")return t.value}})}function tu(e,t,n,r){if(e.intent_id!==t||e.id!==n)throw new E("schema_invalid","Assignment provenance does not match its Intent or file name.",{path:r,expected_intent_id:t,actual_intent_id:e.intent_id,expected_assignment_id:n,actual_assignment_id:e.id})}function Xt(e){return d(function*(){let t=ur(e);while(!0){{let r=yield*d(function*(){if((yield*T(()=>nt(t))).isSymbolicLink())return yield*f(new E("schema_invalid","Persistent work state must not contain symbolic links.",{path:t}));return{kind:"none"}}).pipe(D((o)=>f(o))).pipe(U(()=>!0,(o)=>d(function*(){if(!B(o,"ENOENT"))return yield*f(Y(o));return{kind:"none"}})))}let n=Rn(t);if(n===t)break;t=n}})}function B(e,t){return typeof e==="object"&&e!==null&&"code"in e&&e.code===t}function Y(e){return e instanceof E?e:new E("io_failure","Persistent work-state I/O failed.",{message:e instanceof Error?e.message:String(e)})}function nh(e,t){let n=nu(e,t);return n===""||!n.startsWith(`..${Mb()}`)&&n!==".."&&!pb(n)}function Mb(){return process.platform==="win32"?"\\":"/"}function T(e){return Ii({try:e,catch:(t)=>t})}var rh={state:`Usage: holycodex-agent state diagnose --intent <ref> [--repo <path>]
57
36
 
58
37
  Read-only diagnosis of one Intent, its active Plan, Assignments, and repository baseline.
59
38
  `,"state diagnose":`Usage: holycodex-agent state diagnose --intent <ref> [--repo <path>]
@@ -154,7 +133,7 @@ for legacy executing records with neither a persisted verifier nor a raw capabil
154
133
  The operation atomically persists the Assignment and Intent revisions and returns both current
155
134
  records. Worker evidence
156
135
  cannot set Root gates; actual repository evolution or failure invalidates prior gates.
157
- `};function bg(e){return zA[e.slice(0,2).join(" ")]??zA[e[0]??""]??`Usage: holycodex-agent <intent|assignment|state> <command> [options]
136
+ `};function fu(e){return rh[e.slice(0,2).join(" ")]??rh[e[0]??""]??`Usage: holycodex-agent <intent|assignment|state> <command> [options]
158
137
 
159
138
  Deterministic model-facing work-state API. JSON responses use holycodex-agent-response-1.
160
139
  Updates to existing records require --revision and are atomic. No command prompts or emits ANSI.
@@ -165,6 +144,6 @@ Commands:
165
144
  state diagnose
166
145
 
167
146
  Use -h or --help at any command depth. Failures are classified and exit nonzero.
168
- `}function _g(e){return e.includes("-h")||e.includes("--help")||e.length===0}var GA="holycodex-agent-response-1",XL=z(Q),eD=U({invocationId:Q,startedAt:Q,capability:oo,interruptionReason:Q});async function tD(e=Bun.argv.slice(2),t={cwd:process.cwd(),writeStdout:(r)=>process.stdout.write(r),writeStderr:(r)=>process.stderr.write(r)}){try{let r=wg(XL,e);if(r[0]==="plan")throw new Ct("invalid_usage","Planning commands were removed. Use --help.");let n=r.filter((a)=>!a.startsWith("-")).slice(0,2);if(_g(r))return t.writeStdout(bg(n)),0;let o=nD(r),i=new dp(o.options.repo??t.cwd??process.cwd()),s=await rD(i,o.command,o.subcommand,o.options);return t.writeStdout(`${JSON.stringify({schema_version:GA,ok:!0,operation:`${o.command}.${o.subcommand}`,data:s})}
169
- `),0}catch(r){let n=sD(r);return t.writeStderr(`${JSON.stringify({schema_version:GA,ok:!1,error:n})}
170
- `),n.code==="invalid_usage"||n.code==="invalid_input"?2:n.code==="completion_refused"?3:1}}async function rD(e,t,r,n){let o=n.intent;if(t==="intent"){if(r==="create"){let i=Sn(ip,St(n,"input"));if(i.planRequired)throw new Ct("invalid_input","New Intents cannot require a Plan.");return await e.createIntent(i)}if(r==="list")return await e.listIntents();if(r==="current")return await e.currentIntent();if(r==="read")return await e.readIntent(Qe(o,"intent"));if(r==="select")return await e.selectCurrent(Qe(o,"intent"));if(r==="transition")return await e.transitionIntent(Qe(o,"intent"),wg(is,St(n,"state")),Sr(n),n.blocker);if(r==="evidence")return await e.recordIntentEvidence(Qe(o,"intent"),Sr(n),Sn(pp,St(n,"input")));if(r==="integrate")return await e.recordVcsIntegration(Qe(o,"intent"),Sr(n),Sn(up,St(n,"input")));if(r==="abandon")return await e.abandonIntent(Qe(o,"intent"),Sr(n));if(r==="complete"){let i=await e.completeIntent(Qe(o,"intent"),Sr(n));if("completed"in i&&!i.completed)throw new Ct("completion_refused","Intent completion predicates failed.",{reasons:i.reasons});return i}}if(t==="assignment"){if(r==="create")return await e.createAssignment(Qe(o,"intent"),Sn(sp,St(n,"input")),Sr(n));if(r==="revise")return await e.reviseAssignmentScope(Qe(o,"intent"),St(n,"assignment"),Sn(ap,St(n,"input")),Sr(n));if(r==="supersede")return await e.supersedeAssignment(Qe(o,"intent"),St(n,"assignment"),Sr(n),Sn(lp,St(n,"input")));if(r==="list")return await e.listAssignments(Qe(o,"intent"));if(r==="read")return await e.readAssignment(Qe(o,"intent"),St(n,"assignment"));if(r==="start")return await e.startAssignment(Qe(o,"intent"),St(n,"assignment"),Sr(n),n.input===void 0?{}:Sn(cp,n.input));if(r==="recover")return await e.recoverInterruptedAssignment(Qe(o,"intent"),St(n,"assignment"),Sr(n),Sn(eD,St(n,"input")));if(r==="result"){let i=Sn(Xa,St(n,"input")),s=Qe(o,"intent"),a=St(n,"assignment"),c=Sr(n);if(i.capability===void 0&&await e.isLegacyExecutingAssignment(s,a))return await e.recordAssignmentResult(s,a,c,i);return await e.recordSpecialistAssignmentResult(s,a,c,i)}}if(t==="state"&&r==="diagnose")return await e.diagnose(Qe(o,"intent"));throw new Ct("invalid_usage","Unknown command. Use --help.")}function nD(e){let t=e[0],r=e[1];if(!t||!r||t.startsWith("-")||r.startsWith("-"))throw new Ct("invalid_usage","A command and subcommand are required. Use --help.");let n={},o=oD(t,r);for(let i=2;i<e.length;i+=2){let s=e[i],a=e[i+1];if(!s?.startsWith("--")||a===void 0||a.startsWith("--"))throw new Ct("invalid_usage","Options require --name value pairs.");let c=s.slice(2);if(n[c]!==void 0)throw new Ct("invalid_usage",`Duplicate option --${c}.`);if(!o.has(c))throw new Ct("invalid_usage",`Unknown option --${c}.`);n[c]=a}return{command:t,subcommand:r,options:n}}function oD(e,t){let r=["repo"],n={"intent create":["input"],"intent list":[],"intent current":[],"intent read":["intent"],"intent select":["intent"],"intent transition":["intent","revision","state","blocker"],"intent evidence":["intent","revision","input"],"intent integrate":["intent","revision","input"],"intent complete":["intent","revision"],"intent abandon":["intent","revision"],"assignment create":["intent","revision","input"],"assignment revise":["intent","assignment","revision","input"],"assignment supersede":["intent","assignment","revision","input"],"assignment list":["intent"],"assignment read":["intent","assignment"],"assignment start":["intent","assignment","revision","input"],"assignment recover":["intent","assignment","revision","input"],"assignment result":["intent","assignment","revision","input"],"state diagnose":["intent"]};return new Set([...r,...n[`${e} ${t}`]??[]])}class Ct extends Error{code;details;constructor(e,t,r={}){super(t);this.code=e,this.details=r}}function Sn(e,t){let r;try{r=JSON.parse(t)}catch{throw new Ct("invalid_input","--input must be valid JSON.")}return wg(e,r)}function wg(e,t){let r=Qn(e,{onExcessProperty:"error"})(t);if(ge(r))throw new Ct("invalid_input","Input failed Effect Schema validation.",{issue:String(r.left)});return r.right}function St(e,t){return Qe(e[t],t)}function Qe(e,t){if(!e)throw new Ct("invalid_usage",`Missing --${t}.`);return e}function Sr(e){return iD(e.revision,"revision")}function iD(e,t){let r=Number(e);if(!Number.isSafeInteger(r)||r<1)throw new Ct("invalid_input",`--${t} must be a positive integer.`);return r}function sD(e){if(e instanceof S||e instanceof Ct)return{code:e.code,message:e.message,details:e.details};return{code:"internal_error",message:e instanceof Error?e.message:"Agent CLI failed.",details:{}}}if(import.meta.main)process.exitCode=await tD();export{bg as agentHelp,_g as agentHelpRequested,tD as runAgentBinary};
147
+ `}function du(e){return e.includes("-h")||e.includes("--help")||e.length===0}var oh="holycodex-agent-response-1",$b=P(R),jb=R.check(Oe(1)),Bb=Xp.check(Dc(),es(0)),qb=A({invocationId:R,startedAt:R,capability:Qt,interruptionReason:R});function Vb(e=Bun.argv.slice(2),t={cwd:process.cwd(),writeStdout:(n)=>process.stdout.write(n),writeStderr:(n)=>process.stderr.write(n)}){let n=d(function*(){let r=yield*pu($b,e);if(r[0]==="plan")return yield*f(new Ue("invalid_usage","Planning commands were removed. Use --help."));let o=r.filter((l)=>!l.startsWith("-")).slice(0,2);if(du(r))return yield*ki(()=>t.writeStdout(fu(o))),0;let i=yield*Wb(r),s=new Is(i.options.repo??t.cwd??process.cwd()),a=yield*zb(s,i.command,i.subcommand,i.options);return yield*ki(()=>t.writeStdout(`${JSON.stringify({schema_version:oh,ok:!0,operation:`${i.command}.${i.subcommand}`,data:a})}
148
+ `)),0}).pipe(Rd({onFailure:(r)=>{let o=Jb(r);return ki(()=>(t.writeStderr(`${JSON.stringify({schema_version:oh,ok:!1,error:o})}
149
+ `),o.code==="invalid_usage"||o.code==="invalid_input"?2:o.code==="completion_refused"?3:1))},onSuccess:Q}));return La(n)}function zb(e,t,n,r){return d(function*(){let o=r.intent;if(t==="intent"){if(n==="create"){let i=yield*Ut(ys,yield*Pe(r,"input"));if(i.planRequired)return yield*f(new Ue("invalid_input","New Intents cannot require a Plan."));return yield*e.createIntent(i)}if(n==="list")return yield*e.listIntents();if(n==="current")return yield*e.currentIntent();if(n==="read")return yield*e.readIntent(yield*he(o,"intent"));if(n==="select")return yield*e.selectCurrent(yield*he(o,"intent"));if(n==="transition")return yield*e.transitionIntent(yield*he(o,"intent"),yield*pu(fr,yield*Pe(r,"state")),yield*gt(r),r.blocker);if(n==="evidence")return yield*e.recordIntentEvidence(yield*he(o,"intent"),yield*gt(r),yield*Ut(ws,yield*Pe(r,"input")));if(n==="integrate")return yield*e.recordVcsIntegration(yield*he(o,"intent"),yield*gt(r),yield*Ut(vs,yield*Pe(r,"input")));if(n==="abandon")return yield*e.abandonIntent(yield*he(o,"intent"),yield*gt(r));if(n==="complete"){let i=yield*e.completeIntent(yield*he(o,"intent"),yield*gt(r));if("completed"in i&&!i.completed)return yield*f(new Ue("completion_refused","Intent completion predicates failed.",{reasons:i.reasons}));return i}}if(t==="assignment"){if(n==="create")return yield*e.createAssignment(yield*he(o,"intent"),yield*Ut(xs,yield*Pe(r,"input")),yield*gt(r));if(n==="revise")return yield*e.reviseAssignmentScope(yield*he(o,"intent"),yield*Pe(r,"assignment"),yield*Ut(Ss,yield*Pe(r,"input")),yield*gt(r));if(n==="supersede")return yield*e.supersedeAssignment(yield*he(o,"intent"),yield*Pe(r,"assignment"),yield*gt(r),yield*Ut(bs,yield*Pe(r,"input")));if(n==="list")return yield*e.listAssignments(yield*he(o,"intent"));if(n==="read")return yield*e.readAssignment(yield*he(o,"intent"),yield*Pe(r,"assignment"));if(n==="start"){let i=r.input,s=i===void 0?{}:yield*Ut(Es,i);return yield*e.startAssignment(yield*he(o,"intent"),yield*Pe(r,"assignment"),yield*gt(r),s)}if(n==="recover")return yield*e.recoverInterruptedAssignment(yield*he(o,"intent"),yield*Pe(r,"assignment"),yield*gt(r),yield*Ut(qb,yield*Pe(r,"input")));if(n==="result"){let i=yield*Ut(ko,yield*Pe(r,"input")),s=yield*he(o,"intent"),a=yield*Pe(r,"assignment"),l=yield*gt(r);if(i.capability===void 0&&(yield*e.isLegacyExecutingAssignment(s,a)))return yield*e.recordAssignmentResult(s,a,l,i);return yield*e.recordSpecialistAssignmentResult(s,a,l,i)}}if(t==="state"&&n==="diagnose")return yield*e.diagnose(yield*he(o,"intent"));return yield*f(new Ue("invalid_usage","Unknown command. Use --help."))})}function Wb(e){return d(function*(){let t=e[0],n=e[1];if(!t||!n||t.startsWith("-")||n.startsWith("-"))return yield*f(new Ue("invalid_usage","A command and subcommand are required. Use --help."));let r={},o=Kb(t,n);for(let i=2;i<e.length;i+=2){let s=e[i],a=e[i+1];if(!s?.startsWith("--")||a===void 0||a.startsWith("--"))return yield*f(new Ue("invalid_usage","Options require --name value pairs."));let l=s.slice(2);if(r[l]!==void 0)return yield*f(new Ue("invalid_usage",`Duplicate option --${l}.`));if(!o.has(l))return yield*f(new Ue("invalid_usage",`Unknown option --${l}.`));r[l]=a}return{command:t,subcommand:n,options:r}})}function Kb(e,t){let n=["repo"],r={"intent create":["input"],"intent list":[],"intent current":[],"intent read":["intent"],"intent select":["intent"],"intent transition":["intent","revision","state","blocker"],"intent evidence":["intent","revision","input"],"intent integrate":["intent","revision","input"],"intent complete":["intent","revision"],"intent abandon":["intent","revision"],"assignment create":["intent","revision","input"],"assignment revise":["intent","assignment","revision","input"],"assignment supersede":["intent","assignment","revision","input"],"assignment list":["intent"],"assignment read":["intent","assignment"],"assignment start":["intent","assignment","revision","input"],"assignment recover":["intent","assignment","revision","input"],"assignment result":["intent","assignment","revision","input"],"state diagnose":["intent"]};return new Set([...n,...r[`${e} ${t}`]??[]])}class Ue extends Error{code;details;constructor(e,t,n={}){super(t);this.code=e,this.details=n}}function Ut(e,t){return pu(Zp(e),t)}function pu(e,t){return po(e,{onExcessProperty:"error"})(t).pipe(Ai((n)=>new Ue("invalid_input","Input failed Effect Schema validation.",{issue:String(n)})))}function Pe(e,t){return he(e[t],t)}function he(e,t){if(e===void 0)return f(new Ue("invalid_usage",`Missing --${t}.`));return po(jb)(e).pipe(Ai(()=>new Ue("invalid_input",`--${t} must not be empty.`)))}function gt(e){return Gb(e.revision,"revision")}function Gb(e,t){return po(Bb)(e).pipe(Ai(()=>new Ue("invalid_input",`--${t} must be a positive integer.`)))}function Jb(e){if(e instanceof E||e instanceof Ue)return{code:e.code,message:e.message,details:e.details};return{code:"internal_error",message:e instanceof Error?e.message:"Agent CLI failed.",details:{}}}if(import.meta.main)process.exitCode=await Vb();export{fu as agentHelp,du as agentHelpRequested,Vb as runAgentBinary};