holycodex 0.16.11-dev.121.1 → 0.16.12-dev.124.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 +73 -35
- package/dist/assets/plugin/plugin.json +1 -1
- package/dist/assets/plugin/skills/auto-reset/SKILL.md +14 -0
- package/dist/assets/plugin/skills/auto-reset/agents/openai.yaml +6 -0
- package/dist/assets/plugin/skills/session-audit/SKILL.md +12 -0
- package/dist/assets/plugin/skills/session-audit/agents/openai.yaml +6 -0
- package/dist/index.js +101 -55
- package/package.json +2 -2
package/dist/agent.js
CHANGED
|
@@ -1,40 +1,77 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
var
|
|
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
|
|
6
|
-
`),t)}function
|
|
7
|
-
${
|
|
8
|
-
`+
|
|
9
|
-
${
|
|
10
|
-
${
|
|
3
|
+
import{readFile as vI}from"fs/promises";import{homedir as bI}from"os";import{join as ax}from"path";var gi="0.15";function Ht(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&&yx(r.value))Ht(r.value,t)}Object.freeze(e)}function yx(e){return typeof e==="object"&&e!==null}var Jo={comma:",",tab:"\t",pipe:"|"},cn=Jo.comma;function st(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 Cf(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 Af(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 i=e.slice(n+2,n+6);if(!/^[0-9a-f]{4}$/i.test(i))throw SyntaxError(`Invalid escape sequence: \\u must be followed by 4 hex digits, got "${i}"`);let o=Number.parseInt(i,16);if(o>=55296&&o<=57343)throw SyntaxError(`Invalid escape sequence: \\u${i} is a lone surrogate. Supplementary code points MUST appear as literal UTF-8`);t+=String.fromCodePoint(o),n+=6;continue}throw SyntaxError(`Invalid escape sequence: \\${r}`)}t+=e[n],n++}return t}function Qo(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 He(e,t,n=0){let r=!1,i=n;while(i<e.length){if(e[i]==="\\"&&i+1<e.length&&r){i+=2;continue}if(e[i]==='"'){r=!r,i++;continue}if(e[i]===t&&!r)return i;i++}return-1}var he=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 Ye(e,t){try{return t()}catch(n){if(n instanceof he)throw n;if(n instanceof Error)throw new he(n.message,{line:e.lineNumber,source:e.raw,cause:n});throw n}}var Sx=/^[ \t]*/;function xx(){return{lineNumber:0,blankLines:[]}}function Ex(e,t,n,r){t.lineNumber++;let i=t.lineNumber;if(i===1&&e[0]==="\uFEFF")e=e.slice(1);if(e[e.length-1]==="\r")e=e.slice(0,-1);let o=Sx.exec(e)[0],a=o.indexOf("\t"),s=r&&a!==-1?a:o.length,u=r||a===-1?0:o.split("\t").length-1,p=bx(e.slice(s));if(a===-1&&p[0]==="#")return;let c=vx(s-u,n)+u;if(!p){t.blankLines.push({lineNumber:i,indent:s,depth:c});return}if(r){if(a!==-1)throw new he("Tabs are not allowed in indentation in strict mode",{line:i,source:e});if(s>0&&s%n!==0)throw new he(`Indentation must be exact multiple of ${n}, but found ${s} spaces`,{line:i,source:e})}return{raw:e,indent:s,content:p,depth:c,lineNumber:i}}function vx(e,t){return Math.floor(e/t)}function bx(e){let t=e.length;while(t>0&&e[t-1]===" ")t--;return t===e.length?e:e.slice(0,t)}var Of=Symbol("fetch-line");function wx(e){return{buffer:[],done:!1,lastLine:void 0,scanState:xx(),indentSize:e.indentSize,strict:e.strict}}function*Pf(e){while(e.buffer.length===0&&!e.done){let t=yield Of;if(t===void 0){e.done=!0;return}let n=Ex(t,e.scanState,e.indentSize,e.strict);if(n!==void 0)e.buffer.push(n)}}function*kt(e){return yield*Pf(e),e.buffer[0]}function*ht(e){yield*Pf(e);let t=e.buffer[0];if(t!==void 0)e.buffer.shift(),e.lastLine=t;return t}function*_x(e,t){let n=e[Symbol.iterator](),r=t.next();while(!r.done)if(r.value===Of){let i=n.next();r=t.next(i.done?void 0:i.value)}else yield r.value,r=t.next()}var kx=/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:e[+-]?\d+)?$/i;function Nf(e){return e==="true"||e==="false"||e==="null"}function Tx(e){if(!e)return!1;if(!kx.test(e))return!1;let t=Number(e);return!Number.isNaN(t)&&Number.isFinite(t)}function Ho(e,t){let n=e.trimStart(),r=-1;if(n.startsWith('"')){let A=Qo(n,0);if(A===-1)return{kind:"notHeader"};if(!n.slice(A+1).startsWith("["))return{kind:"notHeader"};let V=e.length-n.length+A+1;r=e.indexOf("[",V)}else r=He(e,"[");if(r===-1)return{kind:"notHeader"};let i=He(e,":");if(i!==-1&&i<r)return{kind:"notHeader"};let o=He(e,"]",r);if(o===-1)return{kind:"notHeader"};let a=o+1,s=a,u=He(e,"{",o);if(u!==-1&&u<He(e,":",o)){let A=e.slice(o+1,u);if(A!==""){let z=A.trim();return{kind:"invalid",reason:z===""?"Unexpected whitespace between bracket segment and field list":`Unexpected content "${z}" between bracket segment and field list`}}let V=cc(e,u);if(V!==-1)s=V+1}if(a=He(e,":",Math.max(o,s)),a===-1)return{kind:"notHeader"};let p=Math.max(o+1,s),c=e.slice(p,a);if(c!==""){let A=c.trim();return{kind:"invalid",reason:A===""?"Unexpected whitespace between bracket segment and colon":`Unexpected content "${A}" between bracket segment and colon`}}let l;if(r>0){let A=e.slice(0,r);if(A!==A.trimEnd())return{kind:"invalid",reason:"Unexpected whitespace between key and bracket segment"};l=A.startsWith('"')?Yo(A):A}let g=st(e.slice(a+1)),v=e.slice(r+1,o),w;try{w=Rx(v,t)}catch(A){return{kind:"invalid",reason:A.message}}let{length:k,delimiter:E,keyed:m}=w,h;if(u!==-1&&u<a){let A=cc(e,u);if(A!==-1&&A<a){let V=e.slice(u+1,A),z=Ox(V,E);if(z!==void 0)return{kind:"invalid",reason:`Header delimiter mismatch: bracket declares "${wf(E)}" but field list contains unquoted "${wf(z)}"`};try{h=Lf(V,E)}catch(Y){return{kind:"invalid",reason:Y.message}}}}let R=h?Mf(h):void 0,I=R?`Duplicate field name "${R}" in field list`:void 0;if(m&&!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:l,length:k,delimiter:E,fields:h,keyed:m},inlineValues:g||void 0,strictError:I}}var Ix=/^(?:0|[1-9]\d*)$/;function Rx(e,t){let n=e,r=t;if(n.endsWith("\t"))r=Jo.tab,n=n.slice(0,-1);else if(n.endsWith("|"))r=Jo.pipe,n=n.slice(0,-1);let i=!1;if(n.endsWith(":"))i=!0,n=n.slice(0,-1);if(!Ix.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:i}}function Lf(e,t){return Cx(e,t).map((n)=>{let r=st(n);if(!r)throw SyntaxError("Empty field name in field list");let i=He(r,"{");if(i===-1)return{name:Yo(r)};let o=st(r.slice(0,i));if(!o)throw SyntaxError("Missing field name before nested field group");let a=cc(r,i);if(a===-1)throw SyntaxError("Unmatched brace in field list");if(a!==r.length-1)throw SyntaxError("Unexpected content after nested field group");let s=Lf(r.slice(i+1,a),t);return{name:Yo(o),children:s}})}function Cx(e,t){let n=[],r="",i=!1,o=0,a=0;while(a<e.length){let s=e[a];if(s==="\\"&&a+1<e.length&&i){r+=s+e[a+1],a+=2;continue}if(s==='"'){i=!i,r+=s,a++;continue}if(!i){if(s==="{")o++;else if(s==="}")o--;else if(s===t&&o===0){n.push(r),r="",a++;continue}}r+=s,a++}return n.push(r),n}function cc(e,t){let n=!1,r=0,i=t;while(i<e.length){let o=e[i];if(o==="\\"&&i+1<e.length&&n){i+=2;continue}if(o==='"'){n=!n,i++;continue}if(!n){if(o==="{")r++;else if(o==="}"){if(r--,r===0)return i}}i++}return-1}function Mf(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=Mf(n.children);if(r!==void 0)return r}}}function dc(e){let t=0;for(let n of e)t+=n.children?dc(n.children):1;return t}var Ax=[",","\t","|"];function Ox(e,t){for(let n of Ax){if(n===t)continue;if(He(e,n)!==-1)return n}}function wf(e){if(e==="\t")return"\\t";return e}function fc(e,t){let n=[],r="",i=!1,o=0;while(o<e.length){let a=e[o];if(a==="\\"&&o+1<e.length&&i){r+=a+e[o+1],o+=2;continue}if(a==='"'){i=!i,r+=a,o++;continue}if(a===t&&!i){n.push(st(r)),r="",o++;continue}r+=a,o++}if(r||n.length>0)n.push(st(r));return n}function pc(e){return e.map((t)=>ea(t))}function ea(e){let t=st(e);if(!t)return"";if(t.startsWith('"'))return Yo(t);if(Nf(t)){if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null}if(Tx(t)){let n=Number.parseFloat(t);return Object.is(n,-0)?0:n}return t}function Yo(e){let t=st(e);if(t.startsWith('"')){let n=Qo(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 Af(t.slice(1,n))}return t}function Px(e,t){let n=He(e,":",t);if(n===-1)throw SyntaxError("Missing colon after key");return{key:st(e.slice(t,n)),end:n+1}}function Nx(e,t){let n=Qo(e,t);if(n===-1)throw SyntaxError("Unterminated quoted key");let r=Af(e.slice(t+1,n)),i=n+1;if(i>=e.length||e[i]!==":")throw SyntaxError("Missing colon after key");return i++,{key:r,end:i}}function Ff(e,t){return e[t]==='"'?Nx(e,t):Px(e,t)}function Df(e){return e.trim().startsWith("[")&&He(e,":")!==-1}function Lx(e){return He(e,":")!==-1}function zn(e,t,n,r,i){if(r.strict&&e!==t)throw new he(`Expected ${t} ${n}, but got ${e}`,{line:i.lineNumber,source:i.raw})}function Mx(e,t,n){if(e?.depth===t&&e.content.startsWith("- "))throw new he(`Expected ${n} list-form items, but found more`,{line:e.lineNumber,source:e.raw})}function Fx(e,t,n){if(e?.depth===t&&!e.content.startsWith("- ")&&Uf(e.content,n.delimiter))throw new he(`Expected ${n.length} tabular rows, but found more`,{line:e.lineNumber,source:e.raw})}function mc(e,t,n,r,i){if(!r)return;let o=n.find((a)=>a.lineNumber>e&&a.lineNumber<t);if(o)throw new he(`Blank lines inside ${i} are not allowed in strict mode`,{line:o.lineNumber})}function Uf(e,t){let n=He(e,":"),r=He(e,t);if(n===-1)return!0;if(r!==-1&&r<n)return!0;return!1}function Dx(e){return{indentSize:e?.indentSize??e?.indent??2,strict:e?.strict??!0}}function Ux(e,t){let n=Dx(t);return _x(e,$x(wx(n),n))}function*$x(e,t){let n=yield*kt(e);if(!n){yield{type:"startObject"},yield{type:"endObject"};return}if(st(n.content)==="[]"){yield*ht(e),yield{type:"startArray",length:0},yield{type:"endArray"},yield*_f(e,t.strict);return}if(Df(n.content)){let o=Ye(n,()=>Xo(Ho(n.content,cn),t.strict));if(o){yield*ht(e),yield*Zo(o.header,o.inlineValues,e,0,t,n),yield*_f(e,t.strict);return}}yield*ht(e);let r=yield*kt(e);if(r===void 0&&!Tf(n)){yield{type:"primitive",value:Ye(n,()=>ea(n.content))};return}if(!Tf(n)&&r?.depth===0)throw new he("Top-level document must start with a key-value or array-header line",{line:n.lineNumber,source:n.raw});let i=t.strict?new Set:void 0;yield{type:"startObject"},yield*Si(n,e,0,t,i);while(!0){let o=yield*kt(e);if(!o)break;if(o.depth!==0){if(t.strict)throw $f(o,0);jf(o),yield*ht(e);continue}yield*ht(e),yield*Si(o,e,0,t,i)}yield{type:"endObject"}}function jx(e,t,n){if(n&&e.depth>t+1)throw new he(`Indentation depth jump: expected depth ${t+1}, but found ${e.depth}`,{line:e.lineNumber,source:e.raw})}function $f(e,t){return new he(`Over-indented line: expected depth ${t}, but found ${e.depth}`,{line:e.lineNumber,source:e.raw})}function jf(e){if(e.content.startsWith("- ")||e.content==="-"||He(e.content,":")!==-1)return;throw new he("Unexpected bare token line outside root primitive position",{line:e.lineNumber,source:e.raw})}function Bf(e){return new he("Keyless keyed header is only valid at the document root",{line:e.lineNumber,source:e.raw})}function Bx(e){return new he("Keyless array header is only valid at the document root or as a list item",{line:e.lineNumber,source:e.raw})}function qx(e){return new he("Keyless header with a field list is only valid at the document root",{line:e.lineNumber,source:e.raw})}function*_f(e,t){if(!t)return;let n=yield*kt(e);if(n)throw new he("Unexpected content after the document root",{line:n.lineNumber,source:n.raw})}function uc(e,t,n){if(!n)return;if(n.has(e))throw new he(`Duplicate sibling key "${e}"`,{line:t.lineNumber,source:t.raw});n.add(e)}function*Si(e,t,n,r,i){let o=e.content,a=Ye(e,()=>Xo(Ho(o,cn),r.strict));if(a&&a.header.key!==void 0){uc(a.header.key,e,i),yield{type:"key",key:a.header.key},yield*Zo(a.header,a.inlineValues,t,n,r,e);return}if(a&&a.header.key===void 0&&r.strict)throw a.header.keyed?Bf(e):Bx(e);let{key:s,end:u}=Ye(e,()=>Ff(o,0)),p=st(o.slice(u));if(uc(s,e,i),yield{type:"key",key:s},!p){let c=yield*kt(t);if(c&&c.depth>n){jx(c,n,r.strict),yield{type:"startObject"},yield*Vx(t,n+1,r),yield{type:"endObject"};return}yield{type:"startObject"},yield{type:"endObject"};return}if(p==="[]"){yield{type:"startArray",length:0},yield{type:"endArray"};return}yield{type:"primitive",value:Ye(e,()=>ea(p))}}function*Vx(e,t,n){let r,i=n.strict?new Set:void 0;while(!0){let o=yield*kt(e);if(!o||o.depth<t)break;if(r===void 0&&o.depth>=t)r=o.depth;if(o.depth===r)yield*ht(e),yield*Si(o,e,r,n,i);else if(r!==void 0&&o.depth>r){if(n.strict)throw $f(o,r);jf(o),yield*ht(e)}else break}}function*Zo(e,t,n,r,i,o){if(e.keyed){yield*Kx(e,n,r,i,o);return}if(yield{type:"startArray",length:e.length},t){yield*zx(e,t,i,o),yield{type:"endArray"};return}if(e.fields&&e.fields.length>0){yield*Gx(e,n,r,i,o),yield{type:"endArray"};return}yield*Wx(e,n,r,i,o),yield{type:"endArray"}}function*zx(e,t,n,r){if(!st(t)){zn(0,e.length,"inline-form values",n,r);return}let i=Ye(r,()=>fc(t,e.delimiter)),o=Ye(r,()=>pc(i));zn(o.length,e.length,"inline-form values",n,r);for(let a of o)yield{type:"primitive",value:a}}function*Kx(e,t,n,r,i){let o=n+1,a=dc(e.fields),s=r.strict?new Set:void 0,u=0,p,c,l=i;yield{type:"startObject"};while(!0){let g=yield*kt(t);if(!g||g.depth<=n)break;if(g.depth>o){if(r.strict)throw new he("Unexpected indentation inside keyed tabular object",{line:g.lineNumber,source:g.raw});yield*ht(t);continue}if(He(g.content,":")===-1){if(r.strict)throw new he("Expected entry row inside keyed tabular object",{line:g.lineNumber,source:g.raw});yield*ht(t);continue}if(yield*ht(t),p===void 0)p=g.lineNumber;c=g.lineNumber,l=g;let{key:v,end:w}=Ye(g,()=>Ff(g.content,0));uc(v,g,s),yield{type:"key",key:v};let k=st(g.content.slice(w)),E=k===""?[]:Ye(g,()=>fc(k,e.delimiter));zn(E.length,a,"keyed entry cells",r,g);let m=Ye(g,()=>pc(E));yield*qf(e.fields,m),u++}if(zn(u,e.length,"keyed entries",r,l),r.strict&&p!==void 0&&c!==void 0)mc(p,c,t.scanState.blankLines,r.strict,"keyed tabular object");yield{type:"endObject"}}function*Gx(e,t,n,r,i){let o=n+1,a=0,s,u,p=i;while(!r.strict||a<e.length){let c=yield*kt(t);if(!c||c.depth<o)break;if(c.depth===o){if(!Uf(c.content,e.delimiter))break;if(s===void 0)s=c.lineNumber;u=c.lineNumber,p=c,yield*ht(t);let l=Ye(c,()=>fc(c.content,e.delimiter));zn(l.length,dc(e.fields),"tabular row values",r,c);let g=Ye(c,()=>pc(l));yield*qf(e.fields,g),a++}else break}if(zn(a,e.length,"tabular rows",r,p),r.strict&&s!==void 0&&u!==void 0)mc(s,u,t.scanState.blankLines,r.strict,"tabular array");if(r.strict)Fx(yield*kt(t),o,e)}function*Wx(e,t,n,r,i){let o=n+1,a=0,s,u,p=i;while(!r.strict||a<e.length){let c=yield*kt(t);if(!c||c.depth<o)break;let l=c.content.startsWith("- ")||c.content==="-";if(c.depth===o&&l){if(s===void 0)s=c.lineNumber;u=c.lineNumber,p=c,yield*Jx(t,o,r);let g=t.lastLine;if(g)u=g.lineNumber,p=g;a++}else break}if(zn(a,e.length,"list-form items",r,p),r.strict&&s!==void 0&&u!==void 0)mc(s,u,t.scanState.blankLines,r.strict,"list-form array");if(r.strict)Mx(yield*kt(t),o,e.length)}function*Jx(e,t,n){let r=yield*ht(e);if(!r)throw ReferenceError("Expected list item");let i;if(r.content==="-"){yield{type:"startObject"},yield{type:"endObject"};return}else if(r.content.startsWith("- "))i=r.content.slice(2);else throw new he('Expected list item to start with "- "',{line:r.lineNumber,source:r.raw});if(!st(i)){yield{type:"startObject"},yield{type:"endObject"};return}if(st(i)==="[]"){yield{type:"startArray",length:0},yield{type:"endArray"};return}let o={...r,content:i};if(Df(i)){let s=Ye(o,()=>Xo(Ho(i,cn),n.strict));if(s)if(s.header.keyed||s.header.fields!==void 0){if(n.strict)throw s.header.keyed?Bf(o):qx(o)}else{yield*Zo(s.header,s.inlineValues,e,t,n,o);return}}let a=Ye(o,()=>Xo(Ho(i,cn),n.strict));if(a&&a.header.key!==void 0&&a.header.fields!==void 0){let s=a.header,u=n.strict?new Set([s.key]):void 0;yield{type:"startObject"},yield{type:"key",key:s.key},yield*Zo(s,a.inlineValues,e,t+1,n,o),yield*kf(e,t+1,n,u),yield{type:"endObject"};return}if(Lx(i)){let s=n.strict?new Set:void 0;yield{type:"startObject"},yield*Si(o,e,t+1,n,s),yield*kf(e,t+1,n,s),yield{type:"endObject"};return}yield{type:"primitive",value:Ye(o,()=>ea(i))}}function*kf(e,t,n,r){while(!0){let i=yield*kt(e);if(!i||i.depth<t)break;if(i.depth===t&&!i.content.startsWith("- "))yield*ht(e),yield*Si(i,e,t,n,r);else break}}function Tf(e){let t=e.content;if(t.startsWith('"')){let n=Qo(t,0);if(n===-1)return!1;return t.slice(n+1).includes(":")}else return t.includes(":")}function Xo(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*qf(e,t){let n=0;function*r(i){yield{type:"startObject"};for(let o of i){if(!o.children&&n>=t.length)continue;if(yield{type:"key",key:o.name},o.children)yield*r(o.children);else yield{type:"primitive",value:t[n++]}}yield{type:"endObject"}}yield*r(e)}function yi(e,t,n){if(t==="__proto__"){Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0});return}e[t]=n}function Hx(e){let t={stack:[],root:void 0};for(let n of e)Yx(t,n);return Zx(t)}function Yx(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 i=n[n.length-1];if(i.type==="object"){if(i.currentKey===void 0)throw Error("Object startObject event without preceding key");yi(i.obj,i.currentKey,r),i.currentKey=void 0}else if(i.type==="array")i.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 i=n[n.length-1];if(i.type==="object"){if(i.currentKey===void 0)throw Error("Array startArray event without preceding key");yi(i.obj,i.currentKey,r),i.currentKey=void 0}else if(i.type==="array")i.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");yi(r.obj,r.currentKey,t.value),r.currentKey=void 0}else if(r.type==="array")r.arr.push(t.value)}break}}function Zx(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 Xx=new RegExp("(?:^\uFEFF?|\\n) *#"),Qx=class{constructor(e){if(Xx.test(e))throw TypeError(`Raw string must not contain a line starting with "#": ${JSON.stringify(e)}`);this.value=e}};function vi(e){return e instanceof Qx}var eE=/[\uD800-\uDFFF]/;function Vn(e){if(e===null)return null;if(vi(e))return e;if(typeof e==="object"&&e!==null&&"toJSON"in e&&typeof e.toJSON==="function"){let t=e.toJSON();if(t!==e)return Vn(t)}if(typeof e==="string")return If(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(Vn);if(e instanceof Set)return Array.from(e).map(Vn);if(e instanceof Map)return Object.fromEntries(Array.from(e,([t,n])=>[String(t),Vn(n)]));if(nE(e)){let t={};for(let n in e)if(Object.hasOwn(e,n))If(n,"object key"),yi(t,n,Vn(e[n]));return t}return null}function If(e,t){if(!eE.test(e))return;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r<55296||r>57343)continue;let i=r<=56319,o=e.charCodeAt(n+1);if(i&&o>=56320&&o<=57343){n++;continue}throw TypeError(`Cannot encode ${t} containing an unpaired surrogate U+${r.toString(16).toUpperCase()} at index ${n}`)}}function tE(e){return e===null||typeof e==="string"||typeof e==="number"||typeof e==="boolean"}function Gn(e){return tE(e)||vi(e)}function Kn(e){return Array.isArray(e)}function un(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)&&!vi(e)}function xi(e){return Object.keys(e).length===0}function nE(e){if(e===null||typeof e!=="object")return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function Ei(e){return e.length===0||e.every((t)=>Gn(t))}function rE(e){return e.length===0||e.every((t)=>Kn(t))}function Vf(e){return e.length===0||e.every((t)=>un(t))}var iE=/^[+-]?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i;function oE(e){if(!Object.values(Jo).includes(e))throw TypeError(`Invalid delimiter ${JSON.stringify(e)}. Valid delimiters are: comma (,), tab (\\t), pipe (|)`)}function aE(e){return/^[A-Z_][\w.]*$/i.test(e)}function sE(e,t=cn){if(!e)return!1;if(/^[ \t]|[ \t]$/.test(e))return!1;if(Nf(e)||cE(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 cE(e){return iE.test(e)}function bi(e,t){if(vi(e))return e.value;if(e===null)return"null";if(typeof e==="boolean")return String(e);if(typeof e==="number")return String(e);return uE(e,t)}function uE(e,t=cn){if(sE(e,t))return e;return`"${Cf(e)}"`}function kr(e){if(aE(e))return e;return`"${Cf(e)}"`}function hc(e,t=cn){return e.map((n)=>bi(n,t)).join(t)}function sn(e,t){let n=t?.key,r=t?.fields,i=t?.delimiter??",",o="";if(n!=null)o+=kr(n);if(o+=`[${e}${t?.keyed?":":""}${i!==cn?i:""}]`,r)o+=`{${zf(r,i)}}`;return o+=":",o}function zf(e,t){return e.map((n)=>kr(n.name)+(n.children?`{${zf(n.children,t)}}`:"")).join(t)}function ta(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 i of t)if(!Object.hasOwn(r,i))return}let n=[];for(let r of t){let i=lE(r,e.map((o)=>o[r]));if(!i)return;n.push(i)}return n}function gc(e){let t=Object.values(e);if(t.length<2)return;if(!t.every((n)=>un(n)&&!xi(n)))return;return ta(t)}function Kf(e,t){let n=[];return Gf(e,t,n),n}function lE(e,t){if(t.every((r)=>Gn(r)))return{name:e};if(!t.every((r)=>un(r)&&!xi(r)))return;let n=ta(t);if(!n)return;return{name:e,children:n}}function Gf(e,t,n){for(let r of t){let i=e[r.name];if(r.children)Gf(i,r.children,n);else n.push(i)}}function*dE(e,t,n){if(Gn(e)){let r=bi(e,t.delimiter);if(r!=="")yield r;return}if(Kn(e))yield*Hf(void 0,e,n,t);else if(un(e)){let r=gc(e);if(r){yield*Wf(void 0,e,r,n,t);return}yield*_r(e,n,t)}}function*_r(e,t,n){for(let[r,i]of Object.entries(e))yield*fE(r,i,t,n)}function*fE(e,t,n,r){let i=kr(e);if(Gn(t))yield Tt(n,`${i}: ${bi(t,r.delimiter)}`,r.indentSize);else if(Kn(t))yield*Hf(e,t,n,r);else if(un(t)){let o=gc(t);if(o){yield*Wf(e,t,o,n,r);return}if(yield Tt(n,`${i}:`,r.indentSize),!xi(t))yield*_r(t,n+1,r)}}function*Wf(e,t,n,r,i){let o=Object.entries(t);yield Tt(r,sn(o.length,{key:e,fields:n,delimiter:i.delimiter,keyed:!0}),i.indentSize),yield*Jf(o,n,r+1,i)}function*Jf(e,t,n,r){for(let[i,o]of e){let a=Kf(o,t);yield Tt(n,`${kr(i)}: ${hc(a,r.delimiter)}`,r.indentSize)}}function*Hf(e,t,n,r){if(t.length===0){yield Tt(n,e!=null?`${kr(e)}: []`:"[]",r.indentSize);return}if(Ei(t)){yield Tt(n,na(t,r.delimiter,e),r.indentSize);return}if(rE(t)){if(t.every((i)=>Ei(i))){yield*pE(e,t,n,r);return}}if(Vf(t)){let i=ta(t);if(i)yield*mE(e,t,i,n,r);else yield*Rf(e,t,n,r);return}yield*Rf(e,t,n,r)}function*pE(e,t,n,r){yield Tt(n,sn(t.length,{key:e,delimiter:r.delimiter}),r.indentSize);for(let i of t)if(Ei(i)){let o=na(i,r.delimiter);yield Ft(n+1,o,r.indentSize)}}function na(e,t,n){let r=sn(e.length,{key:n,delimiter:t}),i=hc(e,t);if(e.length===0)return r;return`${r} ${i}`}function*mE(e,t,n,r,i){yield Tt(r,sn(t.length,{key:e,fields:n,delimiter:i.delimiter}),i.indentSize),yield*Yf(t,n,r+1,i)}function*Yf(e,t,n,r){for(let i of e)yield Tt(n,hc(Kf(i,t),r.delimiter),r.indentSize)}function*Rf(e,t,n,r){yield Tt(n,sn(t.length,{key:e,delimiter:r.delimiter}),r.indentSize);for(let i of t)yield*yc(i,n+1,r)}function*hE(e,t,n){if(xi(e)){yield Tt(t,"-",n.indentSize);return}let r=Object.entries(e),[i,o]=r[0],a=r.slice(1);if(Kn(o)&&Vf(o)){let u=ta(o);if(u){if(yield Ft(t,sn(o.length,{key:i,fields:u,delimiter:n.delimiter}),n.indentSize),yield*Yf(o,u,t+2,n),a.length>0)yield*_r(Object.fromEntries(a),t+1,n);return}}if(un(o)){let u=gc(o);if(u){let p=Object.entries(o);if(yield Ft(t,sn(p.length,{key:i,fields:u,delimiter:n.delimiter,keyed:!0}),n.indentSize),yield*Jf(p,u,t+2,n),a.length>0)yield*_r(Object.fromEntries(a),t+1,n);return}}let s=kr(i);if(Gn(o))yield Ft(t,`${s}: ${bi(o,n.delimiter)}`,n.indentSize);else if(Kn(o))if(o.length===0)yield Ft(t,`${s}: []`,n.indentSize);else if(Ei(o))yield Ft(t,`${s}${na(o,n.delimiter)}`,n.indentSize);else{yield Ft(t,`${s}${sn(o.length,{delimiter:n.delimiter})}`,n.indentSize);for(let u of o)yield*yc(u,t+2,n)}else if(un(o)){if(yield Ft(t,`${s}:`,n.indentSize),!xi(o))yield*_r(o,t+2,n)}if(a.length>0)yield*_r(Object.fromEntries(a),t+1,n)}function*yc(e,t,n){if(Gn(e))yield Ft(t,bi(e,n.delimiter),n.indentSize);else if(Kn(e))if(Ei(e))yield Ft(t,na(e,n.delimiter),n.indentSize);else{yield Ft(t,sn(e.length,{delimiter:n.delimiter}),n.indentSize);for(let r of e)yield*yc(r,t+1,n)}else if(un(e))yield*hE(e,t,n)}function Tt(e,t,n){return" ".repeat(n*e)+t}function Ft(e,t,n){return Tt(e,"- "+t,n)}function gE(e,t){let n=t("",e,[]);if(n===void 0)return lc(e,t,[]);return Sc(e,n,t,[])}function Sc(e,t,n,r){if(vi(t)&&!Gn(e))return lc(e,n,r);return lc(Vn(t),n,r)}function lc(e,t,n){if(un(e))return yE(e,t,n);if(Kn(e))return SE(e,t,n);return e}function yE(e,t,n){let r={};for(let[i,o]of Object.entries(e)){let a=[...n,i],s=t(i,o,a);if(s===void 0)continue;yi(r,i,Sc(o,s,t,a))}return r}function SE(e,t,n){let r=[];for(let i=0;i<e.length;i++){let o=e[i],a=[...n,i],s=t(String(i),o,a);if(s===void 0)continue;r.push(Sc(o,s,t,a))}return r}function Ue(e,t){return Array.from(xE(e,t)).join(`
|
|
5
|
+
`)}function Zf(e,t){return EE(e.split(`
|
|
6
|
+
`),t)}function xE(e,t){let n=Vn(e),r=vE(t);return dE(r.replacer?gE(n,r.replacer):n,r,0)}function EE(e,t){return Hx(Ux(e,bE(t)))}function vE(e){let t=e?.delimiter??cn;return oE(t),{indentSize:e?.indentSize??e?.indent??2,delimiter:t,replacer:e?.replacer}}function bE(e){return{indentSize:e?.indentSize??e?.indent??2,strict:e?.strict??!0}}class ct extends Error{code;details;constructor(e,t,n={},r){super(t,r);this.name="CoreError",this.code=e,this.details=n,Ht(this.details),Object.freeze(this)}}function ra(e){return{ok:!0,value:e}}function ia(e){return{ok:!1,error:e}}function oa(e,t){return new ct("invalid_input",`Invalid ${e}.`,{field:e},t===void 0?void 0:{cause:t})}var ut=(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,i=t.length;r<i;r++)n=t[r](n);return n}}},xc={pipe(){return ut(this,arguments)}},wi=function(){function e(){}return e.prototype=xc,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(i){return t(i,n)}};case 3:return function(n,r,i){if(arguments.length>=3)return t(n,r,i);return function(o){return t(o,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 pe=(e)=>e;var sa=(e)=>()=>e,Ec=sa(!0),Xf=sa(!1);var Tr=sa(void 0),vc=Tr;function _i(e){let t=new WeakMap;return(n)=>{let r=t.get(n);if(r!==void 0)return r;let i=e(n);return t.set(n,i),i}}function Ir(e){let t=new WeakMap;return(n)=>{let r=t.get(n);if(r!==void 0)return r;let i=e(n);if(t.set(n,i),i!==n)t.set(i,i);return i}}var ki=(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 i=Reflect.ownKeys(r);for(let o=0;o<i.length;o++)t.add(i[o]);r=Object.getPrototypeOf(r)}if(t.has("constructor")&&typeof e.constructor==="function"&&n===e.constructor.prototype)t.delete("constructor");return t},Ti=new WeakSet,Ii=(e)=>new Uint8Array(e.buffer,e.byteOffset,e.byteLength);var ca=0,Qf=()=>{ca++};function Rr(e){return typeof e==="string"}function Ri(e){return typeof e==="number"}function ep(e){return typeof e==="boolean"}function tp(e){return typeof e==="symbol"}function np(e){return Rr(e)||Ri(e)||tp(e)}function Wn(e){return typeof e==="function"}function bc(e){return e!==void 0}function rp(e){return e!=null}function ip(e){return!0}function ua(e){return typeof e==="object"&&e!==null||Wn(e)}var Z=N(2,(e,t)=>ua(e)&&(t in e));function op(e){return Z(e,Symbol.iterator)||Rr(e)}var ge="~effect/Hash",X=(e)=>{switch(typeof e){case"number":return Ci(e);case"bigint":return Ze(e.toString(10));case"string":return Ze(e);case"function":case"object":if(e===null)break;else if(e instanceof Date){if(Number.isNaN(e.getTime()))return Ze("Invalid Date");return Ze(e.toISOString())}else if(e instanceof RegExp)return Ze(e.toString());else{if(Ti.has(e))return la(e);let t=sp.get(e);if(t!==void 0)return t;if(kc.has(e))return Qf(),Ze("[Circular]");kc.add(e);let n=ca,r;try{if(ge in e)r=e[ge]();else if(typeof e==="function")r=la(e);else if(e instanceof DataView)r=da(Ii(e));else if(Array.isArray(e)||ArrayBuffer.isView(e))r=da(e);else if(e instanceof Map)r=wE(e);else if(e instanceof Set)r=_E(e);else r=Ic(e)}finally{kc.delete(e)}if(n===ca)sp.set(e,r);return r}}return _n(cp(Ze(String(e))))},la=(e)=>{if(!_c.has(e))_c.set(e,_n(Math.random()*4294967296|0));return _c.get(e)},cp=(e)=>(e^=e>>>16,e=Math.imul(e,2246822507),e^=e>>>13,e=Math.imul(e,3266489909),e^e>>>16),ve=N(2,(e,t)=>cp(Math.imul(e,2654435761)+Math.imul(t,2246822507))),_n=(e)=>e&3221225471|e>>>1&1073741824;var wc=new DataView(new ArrayBuffer(8)),Ci=(e)=>{let t=e|0;if(t===e)return _n(t);return wc.setFloat64(0,e!==e?NaN:e),_n(ve(wc.getInt32(0),wc.getInt32(4)))},Ze=(e)=>{let t=5381,n=e.length;while(n)t=t*33^e.charCodeAt(--n);return _n(t)},Tc=(e,t)=>{let n=12289;for(let r of t)n^=ve(X(r),X(e[r]));return _n(n)},Ic=(e)=>Tc(e,ki(e)),up=(e,t)=>(n)=>{let r=e;for(let i of n)r^=t(i);return _n(r)},da=(e)=>{let t=6151;for(let n of e)t=ve(t,X(n));return _n(t)},wE=up(Ze("Map"),([e,t])=>ve(X(e),X(t))),ap=Ze("Set"),_E=up(ap,(e)=>ve(ap,X(e))),_c=new WeakMap,sp=new WeakMap,kc=new WeakSet;var ye="~effect/Equal";function be(){if(arguments.length===1)return(e)=>Hn(e,arguments[0]);return Hn(arguments[0],arguments[1])}function Hn(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(Ti.has(e)||Ti.has(t))return!1;return kE(e,t)}function kE(e,t){let n=fa.length;for(let o=n;o-- >0;)if(fa[o]===e&&Rc[o]===t)return!0;if(n)return lp(e,t);let r=dp.get(e);if(!r)dp.set(e,r=new WeakMap);let i=r.get(t);if(i===void 0)r.set(t,i=lp(e,t));return i}function lp(e,t){fa.push(e),Rc.push(t);try{return TE(e,t)}finally{fa.pop(),Rc.pop()}}var fa=[],Rc=[],dp=new WeakMap;function TE(e,t){if(X(e)!==X(t))return!1;else if(e instanceof Date){if(!(t instanceof Date))return!1;let r=e.getTime(),i=t.getTime();return r===i||Number.isNaN(r)&&Number.isNaN(i)}else if(e instanceof RegExp)return t instanceof RegExp&&e.toString()===t.toString();let n=mp(e);if(n!==mp(t)||typeof e==="function"&&!n)return!1;else if(n)return e[ye](t);else if(Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return!1;return IE(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 fp(Ii(e),Ii(t));return fp(e,t)}else if(e instanceof Map){if(!(t instanceof Map)||e.size!==t.size)return!1;return pp(e,t,CE,AE)}else if(e instanceof Set){if(!(t instanceof Set)||e.size!==t.size)return!1;return pp(e,t,X,Hn)}return RE(e,t)}function IE(e,t){for(let n=0;n<e.length;n++)if(!Hn(e[n],t[n]))return!1;return!0}function fp(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 RE(e,t){let n=ki(e),r=ki(t);if(n.size!==r.size)return!1;for(let i of n)if(!r.has(i)||!Hn(e[i],t[i]))return!1;return!0}function pp(e,t,n,r){let i=new Map;for(let o of t){let a=n(o),s=i.get(a);if(s)s.push(o);else i.set(a,[o])}e:for(let o of e){let a=i.get(n(o));if(a){for(let s=0;s<a.length;s++)if(r(o,a[s])){a[s]=a[a.length-1],a.pop();continue e}}return!1}return!0}var CE=(e)=>X(e[0]),AE=(e,t)=>Hn(e[0],t[0])&&Hn(e[1],t[1]);var mp=(e)=>Z(e,ye);var Cc=(e)=>e.length>0;function ln(e,t,n){if(t==="__proto__")Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0});else e[t]=n}function hp(e,t){for(let n of Reflect.ownKeys(t))if(Object.prototype.propertyIsEnumerable.call(t,n))ln(e,n,t[n])}var Ai=Symbol.for("~effect/Redactable"),PE=(e)=>Z(e,Ai);function Or(e){if(PE(e))return Oc(e);return e}function Oc(e){return e[Ai](globalThis[Pr]?.context??NE)}var Pr="~effect/Fiber/currentFiber",gp=new Map,NE={"~effect/Context":{},base:gp,depth:0,mapUnsafe:gp,pipe(){return ut(this,arguments)}};function Q(e,t){let n=t?.space??0,r=new WeakSet,i=!n?"":typeof n==="number"?" ".repeat(n):n,o=(c)=>i.repeat(c),a=(c,l)=>{let g=c?.constructor;return g&&g!==Object.prototype.constructor&&g.name?`${g.name}(${l})`:l},s=(c)=>{try{return Reflect.ownKeys(c)}catch{return["[ownKeys threw]"]}};function u(c,l=0){try{return p(c,l)}catch{if(typeof c==="object"&&c!==null||typeof c==="function")r.delete(c);return"[inspection threw]"}}function p(c,l=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 LE;r.add(c);let g;if(Ai in c)g=u(Oc(c),l);else if(Array.isArray(c))g=!i||c.length<=1?`[${c.map((v)=>u(v,l)).join(",")}]`:`[
|
|
7
|
+
${o(l+1)}${c.map((v)=>u(v,l+1)).join(`,
|
|
8
|
+
`+o(l+1))}
|
|
9
|
+
${o(l)}]`;else if(c instanceof Date)g=ME(c);else if(!t?.ignoreToString&&Z(c,"toString")&&typeof c.toString==="function"&&c.toString!==Object.prototype.toString&&c.toString!==Array.prototype.toString){let v=FE(c);g=c instanceof Error&&c.cause!==void 0?`${v} (cause: ${u(c.cause,l)})`:v}else if(Symbol.iterator in c)g=`${c.constructor.name}(${u(Array.from(c),l)})`;else{let v=s(c);if(!i||v.length<=1){let w=`{${v.map((k)=>`${Nr(k)}:${u(yp(c,k),l)}`).join(",")}}`;g=a(c,w)}else{let w=`{
|
|
10
|
+
${v.map((k)=>`${o(l+1)}${Nr(k)}: ${u(yp(c,k),l+1)}`).join(`,
|
|
11
11
|
`)}
|
|
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(`
|
|
12
|
+
${o(l)}}`;g=a(c,w)}}return r.delete(c),g}return String(c)}return u(e,0)}var LE="[Circular]";function Nr(e){return typeof e==="string"?JSON.stringify(e):String(e)}function Sp(e){return e.map((t)=>`[${Nr(t)}]`).join("")}function ME(e){try{return e.toISOString()}catch{return"Invalid Date"}}function FE(e){try{let t=e.toString();return typeof t==="string"?t:String(t)}catch{return"[toString threw]"}}function yp(e,t){try{return e[t]}catch{return"[property access threw]"}}function Oi(e,t){let n=[];return JSON.stringify(e,function(r,i){let o=Object.getOwnPropertyDescriptor(this,r)?.value,a=Z(o,Ai)?Or(o):Or(i);if(typeof a==="bigint")return Q(a);if(typeof a!=="object"||a===null)return a;let s=a instanceof Error&&!Z(a,"toJSON")?{...a,name:a.name,message:a.message}:a;while(n.length>0&&n[n.length-1]!==this)n.pop();if(n.includes(a))return;if(n.push(a),s!==a)n.push(s);return s},t?.space)??"null"}var Yn=Symbol.for("nodejs.util.inspect.custom"),kn=(e)=>{try{if(e=Or(e),Z(e,"toJSON")&&Wn(e.toJSON)&&e.toJSON.length===0)return e.toJSON();else if(Array.isArray(e))return e.map(kn);return e}catch{return"[toJSON threw]"}},xp=(e,t=2)=>{if(typeof e==="string")return e;try{return typeof e==="object"?Oi(e,{space:t}):Q(e,{space:t})}catch{return String(e)}},oR={toJSON(){return kn(this)},[Yn](){return this.toJSON()},toString(){return Q(this.toJSON())}};var DE=()=>{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},UE=DE(),Lr=()=>Error.stackTraceLimit,Mr=(e)=>{if(UE)Error.stackTraceLimit=e};class Zn{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 $E=()=>{let t={["~effect/Utils/internal"]:(i)=>i()},n={["~effect/Utils/internal"]:(i)=>{try{return i()}finally{}}};return Lr()!==0&&t["~effect/Utils/internal"](()=>Error().stack)?.includes("~effect/Utils/internal")===!0?t["~effect/Utils/internal"]:n["~effect/Utils/internal"]},Pi=$E();var dn="~effect/Effect",Xn="~effect/Exit",jE={_A:pe,_E:pe,_R:pe},vp=`${dn}/identifier`,D=`${dn}/args`,ce=`${dn}/evaluate`,Se=`${dn}/successCont`,gt=`${dn}/failureCont`,Qn=`${dn}/ensureCont`,er=Symbol.for("effect/Effect/Yield"),tr={pipe(){return ut(this,arguments)},toJSON(){return{...this}},toString(){return Q(this.toJSON(),{ignoreToString:!0,space:2})},[Yn](){return this.toJSON()}},gR={[ge](){return Tc(this,Object.keys(this))},[ye](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]||!be(this[t[r]],e[t[r]]))return!1;return!0}},BE={[dn]:jE,...tr,[Symbol.iterator](){return new Zn(this)},toJSON(){return{_id:"Effect",op:this[vp],...D in this?{args:this[D]}:void 0}}},nr=(e)=>Z(e,dn),bp=(e)=>Z(e,Xn),ma="~effect/Cause",pa="~effect/Cause/Reason",Ni=(e)=>Z(e,ma);class fn{constructor(e){this[ma]=ma,this.reasons=e}pipe(){return ut(this,arguments)}toJSON(){return{_id:"Cause",failures:this.reasons.map((e)=>e.toJSON())}}toString(){return`Cause(${Q(this.reasons)})`}[Yn](){return this.toJSON()}[ye](e){return Ni(e)&&this.reasons.length===e.reasons.length&&this.reasons.every((t,n)=>be(t,e.reasons[n]))}[ge](){return da(this.reasons)}}var Ep=new WeakMap;class Li{[pa];annotations;_tag;constructor(e,t,n){if(this[pa]=pa,this._tag=e,t!==Mi&&typeof n==="object"&&n!==null&&t.size>0){let r=Ep.get(n);if(r)t=new Map([...r,...t]);Ep.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((i,o)=>{if(t?.overwrite!==!0&&n.has(o))return;n.set(o,i)});let r=Object.assign(Object.create(Object.getPrototypeOf(this)),this);return r.annotations=n,r}pipe(){return ut(this,arguments)}toString(){return Q(this)}[Yn](){return this.toString()}}var Mi=new Map;class Fi extends Li{constructor(e,t=Mi){super("Fail",t,e);this.error=e}toString(){return`Fail(${Q(this.error)})`}toJSON(){return{_tag:"Fail",error:this.error}}[ye](e){return Tn(e)&&be(this.error,e.error)&&be(this.annotations,e.annotations)}[ge](){return ve(Ze(this._tag))(ve(X(this.error))(X(this.annotations)))}}var Fr=(e)=>new fn(e),Nc=new fn([]),wp=(e)=>new fn([new Fi(e)]);class Lc extends Li{constructor(e,t=Mi){super("Die",t,e);this.defect=e}toString(){return`Die(${Q(this.defect)})`}toJSON(){return{_tag:"Die",defect:this.defect}}[ye](e){return ga(e)&&be(this.defect,e.defect)&&be(this.annotations,e.annotations)}[ge](){return ve(Ze(this._tag))(ve(X(this.defect))(X(this.annotations)))}}var ha=(e)=>new fn([new Lc(e)]),Di=N((e)=>Ni(e[0]),(e,t,n)=>{if(t.mapUnsafe.size===0)return e;return new fn(e.reasons.map((r)=>r.annotate(t,n)))}),Tn=(e)=>e._tag==="Fail",ga=(e)=>e._tag==="Die",ya=(e)=>e._tag==="Interrupt";function qE(e){return Zt("Effect.evaluate: Not implemented")}var yt=(e)=>({...BE,[vp]:e.op,[ce]:e[ce]??qE,[Se]:e[Se],[gt]:e[gt],[Qn]:e[Qn]}),Yt=(e)=>{let t=yt(e),n=function(r){this[D]=r};return n.prototype=t,function(r){return new n(r)}},_p=(e)=>{let t={[Xn]:Xn,_tag:e.op,get[e.prop](){return this[D]},...yt(e),toString(){return`${e.op}(${Q(this[D])})`},toJSON(){return{_id:"Exit",_tag:e.op,[e.prop]:this[D]}},[ye](r){return bp(r)&&r._tag===this._tag&&be(this[D],r[D])},[ge](){return ve(Ze(e.op),X(this[D]))}},n=function(r){this[D]=r};return n.prototype=t,function(r){return new n(r)}},we=_p({op:"Success",prop:"value",[ce](e){let t=e.getCont(Se);return t?t[Se](this[D],e,this):e.yieldWith(this)}}),Sa={key:"effect/Cause/StackTrace"},Mc={key:"effect/Cause/InterruptorStackTrace"},Dt=_p({op:"Failure",prop:"cause",[ce](e){let t=this[D],n=!1;if(e.cache.stackFrame)t=Di(t,{mapUnsafe:new Map([[Sa.key,e.cache.stackFrame]])}),n=!0;let r=e.getCont(gt);while(e.interruptible&&e._interruptedCause&&r)r=e.getCont(gt);return r?r[gt](t,e,n?void 0:this):e.yieldWith(n?Dt(t):this)}}),Dr=(e)=>Dt(wp(e)),Zt=(e)=>Dt(ha(e)),$e=Yt({op:"WithFiber",[ce](e){return this[D](e)}}),VE=Yt({op:"WithFiberSucceed",[ce](e){let t=this[D](e),n=e.getCont(Se);return n?n[Se](t,e):e.yieldWith(we(t))}}),zE=function(){class e extends globalThis.Error{}let t=yt({op:"YieldableError",[ce](){return Dr(this)}});return delete t.toString,Object.assign(e.prototype,t),e}(),kp=function(){let e=Symbol.for("effect/Data/Error/plainArgs");return class extends zE{constructor(n){super(n?.message,n?.cause?{cause:n.cause}:void 0);if(n)hp(this,n),Object.defineProperty(this,e,{value:n,enumerable:!1})}toJSON(){return{...this[e],...this}}}}(),Ur=(e)=>{class t extends kp{_tag=e}return t.prototype.name=e,t};var Pc="~effect/Cause/Done";var yR={[Pc]:Pc,_tag:"Done",value:void 0};var Tp="~effect/Option",Ip={[Tp]:{_A:(e)=>e},...tr,[Symbol.iterator](){return new Zn(this)}},KE=Object.defineProperty(Object.assign(Object.create(Ip),{_tag:"Some",_op:"Some",[ye](e){return Fc(e)&&Uc(e)&&be(this.value,e.value)},[ge](){return ve(X(this._tag))(X(this.value))},toString(){return`some(${Q(this.value)})`},toJSON(){return{_id:"Option",_tag:this._tag,value:kn(this.value)}}}),"valueOrUndefined",{get(){return this.value}}),GE=X("None"),WE=Object.assign(Object.create(Ip),{_tag:"None",_op:"None",valueOrUndefined:void 0,[ye](e){return Fc(e)&&Dc(e)},[ge](){return GE},toString(){return"none()"},toJSON(){return{_id:"Option",_tag:this._tag}}}),Fc=(e)=>Z(e,Tp),Dc=(e)=>e._tag==="None",Uc=(e)=>e._tag==="Some",Rp=Object.create(WE),Cp=function(e){this.value=e};Cp.prototype=KE;var Ap=(e)=>new Cp(e);var Op="~effect/Result",Pp={[Op]:{_A:(e)=>e,_E:(e)=>e},...tr,[Symbol.iterator](){return new Zn(this)}},HE=Object.assign(Object.create(Pp),{_tag:"Success",_op:"Success",[ye](e){return $c(e)&&Bc(e)&&be(this.success,e.success)},[ge](){return ve(X(this._tag))(X(this.success))},toString(){return`success(${Q(this.success)})`},toJSON(){return{_id:"Result",_tag:this._tag,value:kn(this.success)}}}),YE=Object.assign(Object.create(Pp),{_tag:"Failure",_op:"Failure",[ye](e){return $c(e)&&jc(e)&&be(this.failure,e.failure)},[ge](){return ve(X(this._tag))(X(this.failure))},toString(){return`failure(${Q(this.failure)})`},toJSON(){return{_id:"Result",_tag:this._tag,failure:kn(this.failure)}}}),$c=(e)=>Z(e,Op),jc=(e)=>e._tag==="Failure",Bc=(e)=>e._tag==="Success",Np=function(e){this.failure=e};Np.prototype=YE;var Lp=(e)=>new Np(e),Mp=function(e){this.success=e};Mp.prototype=HE;var Fp=(e)=>new Mp(e);function Dp(e){return(t,n)=>t===n?0:e(t,n)}var $r=Dp((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 Up=N(2,(e,t)=>Dp((n,r)=>e(t(n),t(r))));var Ea=(e)=>N(2,(t,n)=>e(t,n)===1),$p=(e)=>N(2,(t,n)=>e(t,n)!==1),jp=(e)=>N(2,(t,n)=>e(t,n)!==-1);var Xt=()=>Rp,pn=Ap;var va=Dc,qc=Uc;var qp=N(2,(e,t)=>va(e)?Xt():t(e.value)?pn(e.value):Xt());var St=Fp,je=Lp;var Vp=(e)=>{if(Wn(e))try{return St(e())}catch(t){return je(t)}else try{return St(e.try())}catch(t){return je(e.catch(t))}};var Ce=jc,Xe=Bc;var zp=N(2,(e,t)=>Ce(e)?je(t(e.failure)):e);var wa=N(2,(e,{onFailure:t,onSuccess:n})=>Ce(e)?t(e.failure):n(e.success));var Vc=globalThis.Array;var zc=(e)=>Vc.isArray(e)?e:Vc.from(e);var Kc=N(2,(e,t)=>[...e,t]);var FR=Vc.isArray;var Gc=Cc,Kp=Cc;var _a=()=>[];var Gp=N(2,(e,t)=>e.map(t));var Wp=(e)=>yt({op:e.label,[ce]:e.evaluate});var Jp="~effect/Context/Service",Hp=function(){function e(){}let t=e;Object.setPrototypeOf(t,ev);let n=(r,i)=>{if(t.key=r,i?.defaultValue)t[Hc]=Hc,t.defaultValue=i.defaultValue;if(i?.make)t.make=i.make;if(i?.fiberCached)Yp.add(r);return t};return arguments.length>0?n(arguments[0],arguments[1]):n},ev={[Jp]:Jp,...Wp({label:"Service",evaluate(e){return we(It(e.context,this))}}),toJSON(){return{_id:"Service",key:this.key}},of(e){return e},context(e){return Xc(this,e)},use(e){return $e((t)=>e(It(t.context,this)))},useSync(e){return $e((t)=>we(e(It(t.context,this))))}},Yp=new Set,Hc="~effect/Context/Reference",Zp="~effect/Context",tv=8,nv=8,Yc=(e,t,n,r)=>{let i=Object.create(rv);return i.cacheRoot=e??i,i.base=t,i.overlay=n,i.depth=r,i._flat=void 0,i.baseHits=0,i},Xp=(e,t)=>{if(!t)return;Xp(e,t.parent),e.set(t.key,t.value)},Qp=(e)=>{if(e._flat)return e._flat;if(!e.overlay)return e._flat=e.base;let t=new Map(e.base);return Xp(t,e.overlay),e._flat=t};var Zc=Symbol(),em=(e,t)=>{let n=e;for(let i=n.overlay;i;i=i.parent)if(i.key===t)return i.value;let r=n.base.get(t);if(r===void 0&&!n.base.has(t))return Zc;if(n.overlay&&++n.baseHits>=n.base.size&&n.baseHits>=nv)n.base=Qp(n),n.overlay=void 0,n.depth=0;return r},ka=(e)=>Yc(void 0,e,void 0,0),rv={get mapUnsafe(){return Qp(this)},...tr,[Zp]:{_Services:(e)=>e},toJSON(){return{_id:"Context",services:Array.from(this.mapUnsafe).map(([e,t])=>({key:e,value:t}))}},[ye](e){if(!iv(e))return!1;let t=this.mapUnsafe,n=e.mapUnsafe;if(t.size!==n.size)return!1;for(let[r,i]of t)if(!n.has(r)||!be(i,n.get(r)))return!1;return!0},[ge](){return Ci(this.mapUnsafe.size)}},tm=(e,t)=>e.cacheRoot===t.cacheRoot,iv=(e)=>Z(e,Zp);var ov=(e)=>!!e[Hc],jr=()=>av,av=ka(new Map),Xc=(e,t)=>ka(new Map([[e.key,t]])),nm=N(3,(e,t,n)=>sv(e,t.key,n)),sv=(e,t,n)=>{let r=e,i=Yp.has(t)?void 0:r.cacheRoot;if(r.depth>=tv){let o=new Map(r.mapUnsafe);return o.set(t,n),Yc(i,o,void 0,0)}return Yc(i,r.base,{key:t,value:n,parent:r.overlay},r.depth+1)};var Ta=(e,t)=>{let n=em(e,t);return n===Zc?void 0:n},rm=N(2,(e,t)=>{let n=em(e,t.key);if(n===Zc){if(ov(t))return cv(t);throw uv(t)}return n}),It=rm,Jc="~effect/Context/defaultValue",cv=(e)=>{if(Jc in e)return e[Jc];return e[Jc]=e.defaultValue()},uv=(e)=>{let t=Error(`Service not found${e.key?`: ${String(e.key)}`:""}`);if(t.stack){let n=t.stack.split(`
|
|
13
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
|
-
`);
|
|
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
|
-
|
|
19
|
-
`)}
|
|
20
|
-
`)
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
`
|
|
25
|
-
|
|
26
|
-
|
|
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
|
-
|
|
32
|
-
`}
|
|
33
|
-
`);if(
|
|
34
|
-
|
|
35
|
-
|
|
14
|
+
`)}return t};var Be=Hp;var Ca="~effect/Duration",Br=BigInt(0),dm=BigInt(1),lv=BigInt(2),dv=BigInt(10),im=BigInt(24),Ia=BigInt(60),eu=BigInt(1000),om=BigInt(1e6);var Aa=(e)=>BigInt(e<0?Math.ceil(e-0.5):Math.floor(e+0.5)),fm=(e)=>Aa(e*1e6),am=(e,t)=>{let n=e.indexOf(".");if(n===-1)return BigInt(e)*t;let r=e[0]==="-",i=e.slice(n+1),o=dv**BigInt(i.length),a=(BigInt(e.slice(r?1:0,n))*o+BigInt(i))*t,s=a/o+(a%o*lv>=o?dm:Br);return r?-s:s};var fv=/^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/,Ui=(e)=>{switch(typeof e){case"number":return lm(e);case"bigint":return Ra(e);case"string":{if(e==="Infinity")return tu;if(e==="-Infinity")return um;let t=fv.exec(e);if(!t)break;let[n,r,i]=t;if(i==="nano"||i==="nanos")return Ra(am(r,dm));if(i==="micro"||i==="micros")return Ra(am(r,eu));let o=Number(r);switch(i){case"milli":case"millis":return lm(o);case"second":case"seconds":return vv(o);case"minute":case"minutes":return bv(o);case"hour":case"hours":return wv(o);case"day":case"days":return _v(o);case"week":case"weeks":return kv(o)}break}case"object":{if(e===null)break;if(Ca in e)return e;if(Array.isArray(e)){if(e.length!==2||!e.every(Ri))return sm(e);if(Number.isNaN(e[0])||Number.isNaN(e[1]))return Ev;if(e[0]===-1/0||e[1]===-1/0)return um;if(e[0]===1/0||e[1]===1/0)return tu;return Qe(Aa(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(Aa(n*1e6+(t.microseconds??0)*1000+(t.nanoseconds??0)))}}return sm(e)},sm=(e)=>{throw Error(`Invalid Input: ${e}`)};var cm={_tag:"Millis",millis:0},pv={_tag:"Infinity"},mv={_tag:"NegativeInfinity"},hv={[Ca]:Ca,[ge](){switch(this.value._tag){case"Millis":{let e=this.value.millis*1e6;return Number.isFinite(e)?X(Aa(e)):Ci(this.value.millis)}case"Nanos":return X(this.value.nanos);default:return Ic(this.value)}},[ye](e){return gv(e)&&Cv(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"}}},[Yn](){return this.toJSON()},pipe(){return ut(this,arguments)}},Qe=(e)=>{let t=Object.create(hv);if(typeof e==="number")if(isNaN(e)||e===0||Object.is(e,-0))t.value=cm;else if(!Number.isFinite(e))t.value=e>0?pv:mv;else if(!Number.isInteger(e))t.value={_tag:"Nanos",nanos:fm(e)};else t.value={_tag:"Millis",millis:e};else if(e===Br)t.value=cm;else t.value={_tag:"Nanos",nanos:e};return t},gv=(e)=>Z(e,Ca);var yv=(e)=>{switch(e.value._tag){case"Millis":return e.value.millis===0;case"Nanos":return e.value.nanos===Br;case"Infinity":case"NegativeInfinity":return!1}},Sv=(e)=>{switch(e.value._tag){case"Millis":return e.value.millis<0;case"Nanos":return e.value.nanos<Br;case"NegativeInfinity":return!0;case"Infinity":return!1}};var xv=(e)=>{switch(e.value._tag){case"Infinity":case"NegativeInfinity":return tu;case"Millis":return e.value.millis<0?Qe(-e.value.millis):e;case"Nanos":return e.value.nanos<Br?Qe(-e.value.nanos):e}};var Ev=Qe(0),tu=Qe(1/0),um=Qe(-1/0),Ra=(e)=>Qe(e);var lm=(e)=>Qe(e),vv=(e)=>Qe(e*1000),bv=(e)=>Qe(e*60000),wv=(e)=>Qe(e*3600000),_v=(e)=>Qe(e*86400000),kv=(e)=>Qe(e*604800000),pm=(e)=>Tv(Ui(e),{onMillis:pe,onNanos:(t)=>Number(t)/1e6,onInfinity:()=>1/0,onNegativeInfinity:()=>-1/0});var nu=(e)=>{let t=Ui(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 fm(t.value.millis)}};var Tv=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)()}}),Iv=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(nu(e),t.value.nanos);else return n.onNanos(e.value.nanos,nu(t))});var Rv=(e,t)=>Iv(e,t,{onMillis:(n,r)=>n===r,onNanos:(n,r)=>n===r,onInfinity:(n,r)=>n.value._tag===r.value._tag});var Cv=N(2,(e,t)=>Rv(e,t)),Av=(e)=>{if(e.value._tag==="Infinity")return{days:1/0,hours:1/0,minutes:1/0,seconds:1/0,millis:1/0,nanos:1/0};if(e.value._tag==="NegativeInfinity")return{days:-1/0,hours:-1/0,minutes:-1/0,seconds:-1/0,millis:-1/0,nanos:-1/0};let t=nu(e),n=t<Br,r=n?-t:t,i=r/om,o=i/eu,a=o/Ia,s=a/Ia,u=s/im,p=n?-1:1;return{days:p*Number(u),hours:p*Number(s%im),minutes:p*Number(a%Ia),seconds:p*Number(o%Ia),millis:p*Number(i%eu),nanos:p*Number(r%om)}},ru=(e)=>{if(e.value._tag==="Infinity")return"Infinity";if(e.value._tag==="NegativeInfinity")return"-Infinity";if(yv(e))return"0";if(Sv(e))return"-"+ru(xv(e));let t=Av(e),n=[];if(t.days!==0)n.push(`${t.days}d`);if(t.hours!==0)n.push(`${t.hours}h`);if(t.minutes!==0)n.push(`${t.minutes}m`);if(t.seconds!==0)n.push(`${t.seconds}s`);if(t.millis!==0)n.push(`${t.millis}ms`);if(t.nanos!==0)n.push(`${t.nanos}ns`);return n.join(" ")};var iu=Be("effect/Scheduler",{fiberCached:!0,defaultValue:()=>new Oa}),mm=(e)=>{let t=!1;return Promise.resolve().then(()=>{if(!t)e()}),()=>{t=!0}},Pv="setImmediate"in globalThis?(e)=>{let t=globalThis.setImmediate(e);return()=>globalThis.clearImmediate(t)}:(e)=>{let t=setTimeout(e,0);return()=>clearTimeout(t)},hm=(e)=>{try{return Pv(e)}catch{return mm(e)}};class gm{buckets=[];scheduleTask(e,t){let n=this.buckets,r=n.length,i,o=0;for(;o<r;o++){if(n[o][0]>t)break;i=n[o]}if(i&&i[0]===t)i[1].push(e);else if(o===r)n.push([t,[e]]);else n.splice(o,0,[t,[e]])}drain(){let e=this.buckets;return this.buckets=[],e}}class Oa{executionMode;setImmediate;constructor(e="async",t){this.executionMode=e,this.setImmediate=t??(e==="sync"?mm:hm)}shouldYield(e){return e.currentOpCount>=e.cache.maxOpsBeforeYield}makeDispatcher(){return new ym(this.setImmediate)}}class ym{tasks=new gm;running=void 0;setImmediate;constructor(e=hm){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 Sm=Be("effect/Scheduler/MaxOpsBeforeYield",{fiberCached:!0,defaultValue:()=>2048}),xm=Be("effect/Scheduler/PreventSchedulerYield",{fiberCached:!0,defaultValue:()=>!1});var Pa=Ur;var vm="~effect/encoding/EncodingError";class $i extends Pa("EncodingError"){[vm]=vm}var bm="effect/Tracer/ParentSpan";var wm="effect/Tracer";var _m="effect/Metric/FiberRuntimeMetrics";var km=Be("effect/References/CurrentStackFrame",{fiberCached:!0,defaultValue:Tr}),Tm=Be("effect/References/TracerEnabled",{fiberCached:!0,defaultValue:Ec});var ou=Be("effect/References/CurrentLogAnnotations",{defaultValue:()=>({})}),Im=Be("effect/References/CurrentLogLevel",{fiberCached:!0,defaultValue:()=>"Info"}),Rm=Be("effect/References/MinimumLogLevel",{fiberCached:!0,defaultValue:()=>"Info"});var Cm=Be("effect/References/CurrentLogSpans",{defaultValue:()=>[]});class Lm extends Li{constructor(e,t=Mi){super("Interrupt",t,"Interrupted");this.fiberId=e}toString(){return`Interrupt(${this.fiberId})`}toJSON(){return{_tag:"Interrupt",fiberId:this.fiberId}}[ye](e){return ya(e)&&this.fiberId===e.fiberId&&this.annotations===e.annotations}[ge](){return ve(Ze(`${this._tag}:${this.fiberId}`))(la(this.annotations))}}var Mm=(e)=>new fn([new Lm(e)]);var Fm=(e)=>{let t=e.reasons.find(Tn);return t?St(t):je(e)},Bi=(e)=>{for(let t=0;t<e.reasons.length;t++){let n=e.reasons[t];if(n._tag==="Fail")return St(n.error)}return je(e)};var Dm=(e)=>{let t=e.reasons.find(ga);return t?St(t.defect):je(e)},Um=(e)=>e.reasons.some(ya);var Uv=(e,t)=>{let n=new Map,r=[];for(let i of e.concat(t)){let o=X(i),a=n.get(o);if(a===void 0)n.set(o,[i]);else if(a.some((s)=>be(s,i)))continue;else a.push(i);r.push(i)}return r},Ma=N(2,(e,t)=>{if(e.reasons.length===0)return t;else if(t.reasons.length===0)return e;let n=new fn(Uv(e.reasons,t.reasons));return be(e,n)?e:n}),$m=N(2,(e,t)=>{let n=!1,r=e.reasons.map((i)=>{if(Tn(i))return n=!0,new Fi(t(i.error),i.annotations);return i});return n?Fr(r):e}),du=(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")},jm=(e,t)=>{let n=[],r=[];if(e.reasons.length===0)return n;let i=Lr();if(i!==0)Mr(1);try{for(let o of e.reasons){if(o._tag==="Interrupt"){r.push(o);continue}n.push(su(o._tag==="Die"?o.defect:o.error,o.annotations,t))}if(n.length===0){let o=Error("The fiber was interrupted by:");o.name="InterruptCause",o.stack=qv(o,r);let a=new globalThis.Error("All fibers interrupted without error",{cause:o});a.name="InterruptError",a.stack=`${a.name}: ${a.message}`,n.push(su(a,r[0].annotations,t))}}finally{if(i!==0)Mr(i)}return n},su=(e,t,n)=>{let r=typeof e,i;if(e&&r==="object"){if(i=new globalThis.Error($v(e),{cause:e.cause?su(e.cause):void 0}),typeof e.name==="string")i.name=e.name;if(typeof e.stack==="string")i.stack=Bv(e.stack,i,t);else{let o=`${i.name}: ${i.message}`;i.stack=t?Bm(o,t):o}if(n?.includeCauseInStack)i.stack=Vm(i);for(let o of Object.keys(e))if(!(o in i))i[o]=e[o]}else i=new globalThis.Error(!e?`Unknown error: ${e}`:r==="string"?e:Oi(e));return i},$v=(e)=>{if(typeof e.message==="string")return e.message;else if(typeof e.toString==="function"&&e.toString!==Object.prototype.toString&&e.toString!==Array.prototype.toString)try{return e.toString()}catch{}return Oi(e)},jv=/\((.*)\)/g,Bv=(e,t,n)=>{let r=`${t.name}: ${t.message}`,i=(e.startsWith(r)?e.slice(r.length):e).split(`
|
|
15
|
+
`),o=[r];for(let a=1;a<i.length;a++){if(/Generator\.next|~effect\/(?:Effect|Utils)/.test(i[a]))break;o.push(i[a])}return n?Bm(o.join(`
|
|
16
|
+
`),n):o.join(`
|
|
17
|
+
`)},Bm=(e,t)=>{let n=t?.get(Sa.key);if(n)e=`${e}
|
|
18
|
+
${qm(n)}`;return e},qv=(e,t)=>{let n=[`${e.name}: ${e.message}`];for(let r of t){let i=r.fiberId!==void 0?`#${r.fiberId}`:"unknown",o=r.annotations.get(Mc.key);if(n.push(` at fiber (${i})`),o)n.push(qm(o))}return n.join(`
|
|
19
|
+
`)},qm=(e)=>{let t=[],n=e,r=0;while(n&&r<10){let i=n.stack();if(i){let o=i.matchAll(jv),a=!1;for(let[,s]of o)a=!0,t.push(` at ${n.name} (${s})`);if(!a)t.push(` at ${n.name} (${i.replace(/^at /,"")})`)}else t.push(` at ${n.name}`);n=n.parent,r++}return t.join(`
|
|
20
|
+
`)},fu=(e)=>jm(e).map(Vm).join(`
|
|
21
|
+
`),Vm=(e)=>e.cause?`${e.stack} {
|
|
22
|
+
${zm(e.cause," ")}
|
|
23
|
+
}`:e.stack,zm=(e,t)=>{let n=e.stack.split(`
|
|
24
|
+
`),r=`${t}[cause]: ${n[0]}`;for(let i=1,o=n.length;i<o;i++)r+=`
|
|
25
|
+
${t}${n[i]}`;if(e.cause)r+=` {
|
|
26
|
+
${zm(e.cause,`${t} `)}
|
|
27
|
+
${t}}`;return r},Km="~effect/Fiber",Vv={_A:pe,_E:pe},zv={id:0},Gm=()=>globalThis[Pr];class pu{constructor(e,t=!0){this.setContext(e),this.id=++zv.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[Km](){return Vv}get currentDispatcher(){return this._dispatcher??=this.cache.scheduler.makeDispatcher()}getRef(e){return It(this.context,e)}addObserver(e){if(this._exit)return e(this._exit),vc;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=Mm(e);if(this.cache.stackFrame)n=Di(n,Xc(Sa,this.cache.stackFrame));if(t)n=Di(n,t);if(this._interruptedCause=this._interruptedCause?Ma(this._interruptedCause,n):n,this.interruptible)if(this._running)this._deferredInterrupt=!0;else this.evaluate(ke(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===er)return;let n=Am.interruptChildren&&Am.interruptChildren(this);if(n!==void 0)return this.evaluate(Ae(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 i=0;i<r.length;i++)r[i](t)}this._stack.length=0,this._children=void 0,this.context=jr()}runLoop(e){let t=globalThis[Pr];globalThis[Pr]=this;let n=this._running;this._running=!0;let r=!1,i=e;this.currentOpCount=0;try{while(!0){if(this._deferredInterrupt)this._deferredInterrupt=!1,i=ke(this._interruptedCause);this.currentOpCount++;let o=this.cache;if(!r&&!o.preventYield&&o.scheduler.shouldYield(this)){r=!0;let a=i;i=Ae(mu,()=>a)}if(i=o.tracerContext?o.tracerContext(i,this):i[ce](this),i===er){let a=this._yielded;if(Xn in a)return this._deferredInterrupt=!1,this._yielded=void 0,a;else if(this._deferredInterrupt){this._yielded=void 0,a();continue}return er}}}catch(o){if(!Z(i,ce))return Zt(`Fiber.runLoop: Not a valid effect: ${String(i)}`);return this.runLoop(Zt(o))}finally{this._running=n,globalThis[Pr]=t}}getCont(e){if(this._deferredInterrupt)return this._deferredInterrupt=!1,Gv;while(!0){let t=this._stack.pop();if(!t)return;let n=t[Qn];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&Wv-1)===0)return we(e);let t=this.getCont(Se);return t?t[Se](e,this):this.yieldWith(we(e))}yieldWith(e){return this._yielded=e,er}children(){return this._children??=new Set}pipe(){return ut(this,arguments)}setContext(e){let t=this.context;if(this.context=e,t!==void 0&&tm(t,e))return;let n=e.cacheRoot,r=n._fiberCache??=Kv(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 Kv=(e)=>{let t=Ta(e,wm);return{scheduler:It(e,iu),tracer:t,tracerContext:t?t.context:void 0,tracerEnabled:It(e,Tm),span:Ta(e,bm),logLevel:It(e,Im),minimumLogLevel:It(e,Rm),stackFrame:It(e,km),runtimeMetrics:Ta(e,_m),maxOpsBeforeYield:It(e,Sm),preventYield:It(e,xm)}},Gv={[Se](e,t){return ke(t._interruptedCause)},[gt](e,t){return ke(t._interruptedCause)}},Wv=32,Am={interruptChildren:void 0},Wm=(e)=>{if(!e.cache.stackFrame)return;let t=new Map;return t.set(Mc.key,e.cache.stackFrame),ka(t)};var Jm=(e)=>{let t=e;if(t._exit)return _e(t._exit);return Qt((n)=>{if(t._exit)return n(_e(t._exit));return Rt(e.addObserver((r)=>n(_e(r))))})},Hm=(e)=>Qt((t)=>{let n=e[Symbol.iterator](),r=[],i=void 0;function o(){let a=n.next();while(!a.done){if(a.value._exit){r.push(a.value._exit),a=n.next();continue}i=a.value.addObserver((s)=>{r.push(s),o()});return}t(_e(r))}return o(),Rt(()=>i?.())});var ji=(e)=>$e((t)=>{let n=Wm(t),r=_a();for(let i of e)i.interruptUnsafe(t.id,n),r.push(i);return ch(Hm(r))});var _e=we,ke=Dt,or=Dr,Rt=Yt({op:"Sync",[ce](e){let t=this[D](),n=e.getCont(Se);return n?n[Se](t,e):e.yieldWith(we(t))}}),lt=Yt({op:"Suspend",[ce](e){return this[D]()}});var Ym=wa({onFailure:or,onSuccess:_e});var Zm=Yt({op:"Yield",[ce](e){let t=!1;return e.currentDispatcher.scheduleTask(()=>{if(t)return;e.evaluate(Ut)},this[D]??0),e.yieldWith(()=>{t=!0})}}),mu=Zm(0);var Xm=(e)=>lt(()=>ke(e())),qi=(e)=>Zt(e),Qm=(e)=>lt(()=>or(e())),qe=_e(void 0);var eh=(e)=>{let t=typeof e==="function"?e:e.try,n=typeof e==="function"?(r)=>new Ba(r,"An error occurred in Effect.try"):e.catch;return lt(()=>{try{return _e(t())}catch(r){return or(n(r))}})};var th=(e)=>{let t=typeof e==="function"?e:e.try,n=typeof e==="function"?(r)=>new Ba(r,"An error occurred in Effect.tryPromise"):e.catch;return nh(function(r,i){let o=(a)=>{try{r(or(Pi(()=>n(a))))}catch(s){r(qi(s))}};try{t(i).then((a)=>r(_e(a)),o)}catch(a){o(a)}},t.length!==0)};var nh=function(){let e=yt({op:"Async",[ce](n){let r=!1,i=!1,o=this.withSignal?new AbortController:void 0,a=this.register.call(n.cache.scheduler,(s)=>{if(r)return;if(r=!0,i)n.evaluate(s);else i=s},o?.signal);if(i!==!1)return i;if(i=!0,n._yielded=()=>{r=!0},o===void 0&&a===void 0)return er;return n._stack.push(Jv(()=>(r=!0,o?.abort(),a??Ut))),er}}),t=function(n,r){this.register=n,this.withSignal=r};return t.prototype=e,function(n,r){return new t(n,r)}}(),Jv=Yt({op:"AsyncFinalizer",[Qn](e){if(e.interruptible)e.interruptible=!1,e._stack.push(Da)},[gt](e,t){return Um(e)?Ae(Ph(Dt(e),this[D]()),()=>ke(e)):ke(e)}}),Qt=(e)=>nh(e,e.length>=2),rh=Qt(vc),ih=(...e)=>{if(e.length===1){let r=e[0];return lt(()=>La(r()))}let[t,n]=e;return lt(()=>La(n.call(t.self)))};var Hv=(e,t)=>Object.defineProperty(t,"length",{value:e,configurable:!0});var oh=(e,...t)=>Hv(e.length,t.length===0?function(){return Om(()=>e.apply(this,arguments))}:function(){let n=Om(()=>e.apply(this,arguments));for(let r of t)n=r(n,...arguments);return n}),Om=(e)=>{try{let t=e(),n=void 0;while(!0){let r=t.next(n);if(r.done)return _e(r.value);let i=r.value;if(i&&i._tag==="Success"){n=i.value;continue}else if(i&&i._tag==="Failure")return r.value;else{let o=!0;return lt(()=>{if(o)return o=!1,Ae(r.value,(a)=>La(t,a));else return lt(()=>La(e()))})}}}catch(t){return qi(t)}},La=function(){let e=yt({op:"Iterator",[Se](n,r){let i=this.iterator;while(!0){let o=i.next(n);if(o.done)return _e(o.value);if(!oe(o.value))return r._stack.push(this),o.value;else if(o.value._tag==="Failure")return o.value;n=o.value.value}},[ce](n){return this[Se](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)}}(),Vi=N(2,(e,t)=>new zi(e,ah,_e(t))),Fa=function(e){return e._stack.push(this),this[D]},Yv=yt({op:"OnSuccess",[ce]:Fa}),zi=function(e,t,n){this[D]=e,this[Se]=t,this.payload=n};zi.prototype=Yv;var ah=function(){return this.payload};var hu=(()=>({["~effect/Effect/stackProbe"]:function(){return Error().stack}})["~effect/Effect/stackProbe"]()?.includes("[as ~effect/Effect/stackProbe]")===!0)(),Zv=function(e,t){let n=this.payload;return t.succeedWith(hu?n(e):Pi(()=>n(e)))},Xv=function(e){let t=this.payload;return t(e)};var sh=(e)=>Ki(e,pn);var ch=(e)=>new zi(e,ah,Ut);var uh=(e,t)=>$e((n)=>{let r=new Set;return _u(n,()=>r.size===0?void 0:ji(r)),Qt((i)=>{let o=zc(e),a=o.length,s=0,u=!1,p=[],c=(l,g,v)=>{if(s++,l._tag==="Failure"){if(p.push(...l.cause.reasons),s>=a)i(ke(Fr(p)));return}let w=!u;if(u=!0,i(l),w&&t?.onWinner)t.onWinner({fiber:g,index:v,parentFiber:n})};for(let l=0;l<a;l++){let g=Tu(n,o[l],!0,!0,!1);if(r.add(g),g.addObserver((v)=>{r.delete(g),c(v,g,l)}),u)break}})}),lh=(e,t)=>$e((n)=>{let r=new Set;return _u(n,()=>r.size===0?void 0:ji(r)),Qt((i)=>{let o=!1,a=0;for(let s of e){if(o)break;let u=a++,p=Tu(n,s,!0,!0,!1);r.add(p),p.addObserver((c)=>{r.delete(p);let l=!o;if(o=!0,i(c),l&&t?.onWinner)t.onWinner({fiber:p,index:u,parentFiber:n})})}})}),dh=N((e)=>nr(e[1]),(e,t,n)=>uh([e,t],n)),fh=N((e)=>nr(e[1]),(e,t,n)=>lh([e,t],n)),Ae=N(2,(e,t)=>new zi(e,Xv,t));var oe=(e)=>e[Xn]!==void 0,ph=N(2,(e,t)=>{if(oe(e))return e._tag==="Success"?t(e.value):e;return Ae(e,t)}),mh=(e)=>Ae(e,pe),Ki=N(2,(e,t)=>new zi(e,Zv,t)),hh=N(2,(e,t)=>oe(e)?xh(e,t):Ki(e,t)),gh=N(2,(e,t)=>oe(e)?Eh(e,t):xu(e,t));var gu=(e)=>e._tag==="Success";var yh=(e)=>e._tag==="Failure";var Sh=(e)=>e._tag==="Failure"?St(e.cause):je(e);var Ut=we(void 0),xh=N(2,(e,t)=>e._tag==="Success"?we(t(e.value)):e),Eh=N(2,(e,t)=>{if(e._tag==="Success")return e;let n=Bi(e.cause);if(Ce(n))return e;return Dr(t(n.success))});var Gi=N(2,(e,t)=>new vh(e,t.length!==1?(n)=>t(n):t)),Qv=yt({op:"OnFailure",[ce]:Fa}),vh=function(e,t){this[D]=e,this[gt]=t};vh.prototype=Qv;var yu=N(3,(e,t,n)=>Gi(e,(r)=>{let i=t(r);return Ce(i)?ke(i.failure):n(i.success,r)})),Su=N(2,(e,t)=>yu(e,Bi,(n)=>t(n)));var bh=N(2,(e,t)=>yu(e,Dm,t));var wh=N((e)=>nr(e[0]),(e,t,n,r)=>Gi(e,(i)=>{let o=Bi(i);if(Ce(o))return ke(o.failure);if(!t(o.success))return r?r(o.success):ke(i);return n(o.success)}));var xu=N(2,(e,t)=>Su(e,(n)=>Qm(()=>t(n))));var _h=(e)=>Su(e,qi);var kh=N((e)=>nr(e[0]),(e,t)=>{if(!t?.log)return vu(e,{onFailure:(r)=>qe,onSuccess:(r)=>qe});let n=ag(t.log===!0?void 0:t.log);return Eu(e,{onFailure(r){let i=Fm(r);return Ce(i)?ke(i.failure):t.message===void 0?n(r):n(t.message,r)},onSuccess:(r)=>qe})});var Na=(e)=>Rh(e,{onFailure:je,onSuccess:St}),Eu=N(2,(e,t)=>new Th(e,t.onSuccess.length!==1?(n)=>t.onSuccess(n):t.onSuccess,t.onFailure.length!==1?(n)=>t.onFailure(n):t.onFailure)),eb=yt({op:"OnSuccessAndFailure",[ce]:Fa}),Th=function(e,t,n){this[D]=e,this[Se]=t,this[gt]=n};Th.prototype=eb;var tb=function(e,t){let n=this.payload;return t.succeedWith(hu?n.onSuccess(e):Pi(()=>n.onSuccess(e)))},nb=(e,t)=>{let n=yt({op:e,[ce]:Fa,[Se]:tb,[gt]:t}),r=function(i,o){this[D]=i,this.payload=o};return r.prototype=n,r},rb=nb("Match",function(e,t){let n=e.reasons.find(Tn);if(n===void 0)return ke(e);let r=this.payload;return t.succeedWith(hu?r.onFailure(n.error):Pi(()=>r.onFailure(n.error)))});var vu=N(2,(e,t)=>Eu(e,{onFailure:(n)=>{let r=n.reasons.find(Tn);return r?t.onFailure(r.error):ke(n)},onSuccess:t.onSuccess})),Ih=N(2,(e,t)=>new rb(e,t)),Rh=N(2,(e,t)=>{if(oe(e)){if(e._tag==="Success")return we(t.onSuccess(e.value));let n=Bi(e.cause);if(Ce(n))return e;return we(t.onFailure(n.success))}return Ih(e,t)});var bu=(e)=>oe(e)?we(e):ib(e),ib=Yt({op:"Exit",[ce](e){return e._stack.push(this),this[D]},[Se](e,t,n){return t.succeedWith(n??we(e))},[gt](e,t,n){return t.succeedWith(n??Dt(e))}});var Ch=N(2,(e,t)=>Ae(Oh(e,t.duration),(n)=>va(n)?t.orElse():_e(n.value))),ob=(e)=>new Au(`Operation timed out after '${ru(e)}'`),Ah=N(2,(e,t)=>{let n=Ui(t);return Ch(e,{duration:n,orElse:()=>or(ob(n))})}),Oh=N(2,(e,t)=>fh(sh(e),Vi(Cu(t),Xt())));var Ph=(e,t)=>gu(e)?t:Gi(t,(n)=>ke(Ma(e.cause,n)));var Nh=function(){let e=yt({op:"OnExit",[ce](n){return n._stack.push(this),this.effect},[Qn](n){if(n.interruptible&&this.interruptible!==!0)n._stack.push(Da),n.interruptible=!1},[Se](n,r,i){i??=we(n);let o;try{o=this.onExit(i)}catch(a){o=Zt(a)}return o?Ae(o,(a)=>i):i},[gt](n,r,i){i??=Dt(n);let o;try{o=this.onExit(i)}catch(a){o=Zt(a)}return o?Ae(Ph(i,o),(a)=>i):i}}),t=function(n,r,i){this.effect=n,this.onExit=r,this.interruptible=i};return t.prototype=e,t}(),wu=(e,t,n)=>new Nh(e,t,n),_u=(e,t)=>{e._stack.push(new Nh(void 0,t,void 0))},ku=N(2,wu),Lh=N(2,(e,t)=>ku(e,(n)=>t));var Mh=N(3,(e,t,n)=>ku(e,(r)=>{let i=t(r);return Ce(i)?qe:n(i.success,r)})),Fh=N(2,(e,t)=>Mh(e,Sh,t));var Dh=(e,t,n)=>qh((r)=>Ae(e,(i)=>wu(lt(()=>r(t(i))),(o)=>n(i,o),!0)));var Uh=(e)=>Rt(()=>{let t=lb(!1),n=!1,r,i=Ae(t.await,()=>r);return $e((o)=>{if(r!==void 0)return r;if(n)return i;return n=!0,_u(o,(a)=>Rt(()=>{r=a,t.openUnsafe()})),e})});var $h=(e)=>$e((t)=>{if(!t.interruptible)return e;return t.interruptible=!1,t._stack.push(Da),e}),jh=Yt({op:"SetInterruptible",[Qn](e){if(e.interruptible=this[D],e._interruptedCause&&e.interruptible)return()=>ke(e._interruptedCause)}}),Da=jh(!0),ab=jh(!1),sb=(e)=>{if(e.interruptible=!0,e._stack.push(ab),e._interruptedCause)return ke(e._interruptedCause)};var Bh=(e)=>$e((t)=>{if(t.interruptible)return e;return sb(t)??e}),qh=(e)=>$e((t)=>{if(!t.interruptible)return e(pe);return t.interruptible=!1,t._stack.push(Da),e(Bh)});var Vh=(e,t)=>{if(op(e))return t?.mode==="result"?ir(e,Na,t):ir(e,pe,t);else if(t?.discard)return t.mode==="result"?ir(Object.values(e),Na,t):ir(Object.values(e),pe,t);return lt(()=>{let n={};return Vi(ir(Object.entries(e),([r,i])=>Ki(t?.mode==="result"?Na(i):i,(o)=>{ln(n,r,o)}),{discard:!0,concurrency:t?.concurrency}),n)})};var zh=Yt({op:"While",[Se](e,t){if(this[D].step(e),this[D].while())return t._stack.push(this),this[D].body();return Ut},[ce](e){if(this[D].while())return e._stack.push(this),this[D].body();return Ut}}),ir=N((e)=>typeof e[1]==="function",(e,t,n)=>lt(()=>{let r=Wi(n?.concurrency);if(r===1)return cb(e,t,n);let i=zc(e),o=i.length;if(o===0)return n?.discard?qe:_e([]);let a=n?.discard?void 0:Array(o),s=ub({f:t,out:a},i,{concurrency:r});return s?Vi(s,a):_e(a)}));var cb=(e,t,n)=>lt(()=>{let r=n?.discard?void 0:[],i=e[Symbol.iterator](),o=i.next(),a=0;return Vi(zh({while:()=>!o.done,body:()=>t(o.value,a++),step:(s)=>{if(r)r.push(s);o=i.next()}}),r)}),Wi=(e)=>e==="unbounded"?Number.POSITIVE_INFINITY:Math.max(1,e??1),Ua=()=>(e)=>{let{onItem:t,step:n}=e,r=(o,a,s,u,p)=>Ae(bu(p),(c)=>n(o,a[s],c,s)??i(o,a,s+1,u)??qe),i=(o,a,s=0,u=a.length)=>{for(;s<u;s++){let p=a[s],c=t(o,p,s);if(!oe(c))return r(o,a,s,u,c);let l=n(o,p,c,s);if(l)return l._tag==="Failure"?l:void 0}};return i},Kh=(e)=>{let{onItem:t,step:n}=e;return(r,i,o)=>{let a=0,s=o.end??i.length,u=o.concurrency,p=!1,c,l,g,v,w,k=(m)=>{let h=Zt(m);return v=h,p=!0,l&&l.size>0?Ae($h(ji(Array.from(l))),()=>v??h):h},E=()=>{let m=!1;for(;!v&&a<s;a++){let h=i[a],R=w??t(r,h,a);if(oe(R)){if(v=n(r,h,R,a),v)break}else if(!c)return Qt((I)=>{c=Gm(),l=new Set,w=R,g=I;let A;try{A=E()}catch(V){return I(k(V))}if(A)return I(A);return lt(()=>(v??=Ut,Ae(l?ji(l):qe,()=>v?._tag==="Failure"?v:qe)))});else{w=void 0;let I=Tu(c,R,!0,!0,"inherit");if(I._exit){if(v=n(r,h,I._exit,a),v)break;continue}l.add(I);let A=a;if(I.addObserver((V)=>{l.delete(I);try{if(v){if(V._tag==="Failure"){let z=V.cause.reasons.filter((Y)=>Y._tag!=="Interrupt");if(z.length>0){let Y=Fr(z);v=Dt(v._tag==="Failure"?Ma(v.cause,Y):Y)}}}else{let z=n(r,h,V,A);if(z)v=z,E()}if(m){let z=E();if(z)g(z)}else if(p&&l.size===0)g(v??qe)}catch(z){g(k(z))}}),l.size<u)continue;m=!0,a++;return}}if(p=!0,v){if(l&&l.size>0){let h=Wm(c);l.forEach((R)=>R.interruptUnsafe(c.id,h));return}if(g||v._tag==="Failure")return v}else if(g){if(!l)return Ut;else if(l.size===0)g(qe)}};return E()}},$a=()=>(e)=>Kh(e),ub=Kh({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 Tu=(e,t,n=!1,r=!1,i=!1)=>{let o=e,a=i==="inherit"?o.interruptible:!i,s=new pu(o.context,a);if(n)s.evaluate(t);else o.currentDispatcher.scheduleTask(()=>s.evaluate(t),0);if(!r&&!s._exit)o.children().add(s),s._parent=o;return s};var ja=(e)=>(t,n)=>{let r=new pu(n?.scheduler?nm(e,iu,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 i=()=>r.interruptUnsafe();n.signal.addEventListener("abort",i,{once:!0}),r.addObserver(()=>n.signal.removeEventListener("abort",i))}if(n?.onFiberStart)n.onFiberStart(r);return r};var Gh=ja(jr());var Wh=(e)=>{let t=ja(e);return(n,r)=>{let i=t(n,r);return new Promise((o)=>{i.addObserver((a)=>o(a))})}};var Jh=(e)=>{let t=Wh(e);return(n,r)=>t(n,r).then((i)=>{if(i._tag==="Failure")throw du(i.cause);return i.value})},Hh=Jh(jr()),Iu=(e)=>{let t=ja(e);return(n)=>{if(oe(n))return n;let r=new Oa("sync"),i=t(n,{scheduler:r});return i._dispatcher?.flush(),i._exit??Zt(new Ou(i))}},Yh=Iu(jr()),Zh=(e)=>{let t=Iu(e);return(n)=>{let r=t(n);if(r._tag==="Failure")throw du(r.cause);return r.value}},Xh=Zh(jr()),Pm=_e(!0),Nm=_e(!1);class Qh{waiters=[];scheduled=void 0;_isOpen;constructor(e){this._isOpen=e}scheduleUnsafe(e){if(this.waiters.length===0)return Pm;if(this.scheduled===void 0)this.scheduled=this.waiters,e.currentDispatcher.scheduleTask(this.flushScheduled,0);else for(let t=0;t<this.waiters.length;t++)this.scheduled.push(this.waiters[t]);return this.waiters=[],Pm}flushScheduled=()=>{if(this.scheduled===void 0)return;let e=this.scheduled;this.scheduled=void 0;for(let t=0;t<e.length;t++)e[t](Ut)};flushWaiters(){let e=this.waiters;this.waiters=[],this.flushScheduled();for(let t=0;t<e.length;t++)e[t](Ut)}open=$e((e)=>{if(this._isOpen)return Nm;return this._isOpen=!0,this.scheduleUnsafe(e)});release=$e((e)=>this._isOpen?Nm:this.scheduleUnsafe(e));openUnsafe(){if(this._isOpen)return!1;return this._isOpen=!0,this.flushWaiters(),!0}await=Qt((e)=>{if(this._isOpen)return e(qe);return this.waiters.push(e),Rt(()=>{let t=this.waiters.indexOf(e);if(t!==-1)this.waiters.splice(t,1);else if(this.scheduled!==void 0){if(t=this.scheduled.indexOf(e),t!==-1)this.scheduled.splice(t,1)}})});closeUnsafe(){if(!this._isOpen)return!1;return this._isOpen=!1,!0}close=Rt(()=>this.closeUnsafe());whenOpen=(e)=>Ae(this.await,()=>e);isOpen(){return this._isOpen}}var lb=(e)=>new Qh(e??!1);var Ru=Be("effect/Clock",{defaultValue:()=>new eg}),au=2147483647;class eg{currentTimeMillisUnsafe(){return Date.now()}currentTimeMillis=Rt(()=>this.currentTimeMillisUnsafe());currentTimeNanosUnsafe(){return db()}currentTimeNanos=Rt(()=>this.currentTimeNanosUnsafe());monotonicTimeNanosUnsafe(){return ng()}monotonicTimeNanos=Rt(()=>this.monotonicTimeNanosUnsafe());sleep(e){return this.sleepMillis(pm(e))}sleepMillis(e){if(e<=0)return mu;else if(!Number.isFinite(e))return rh;return Qt((t)=>{let n=e>au?this.sleepMillis(e-au):qe,r=setTimeout(()=>t(n),Math.min(e,au));return Rt(()=>clearTimeout(r))})}}var tg=BigInt(1e6),ng=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())*tg;if(n>t)t=n;return t}}(),db=function(){let e=BigInt(1e9),t;return()=>{let n=ng(),r=BigInt(Date.now())*tg;if(t===void 0)t=r-n;else{let i=t+n;if((r>i?r-i:i-r)>e)t=r-n}return t+n}}(),rg=(e)=>$e((t)=>e(t.getRef(Ru))),Cu=(e)=>rg((t)=>t.sleep(Ui(e)));var cu="~effect/Cause/TimeoutError";class Au extends Ur("TimeoutError"){[cu]=cu;constructor(e){super({message:e})}}var uu="~effect/Cause/AsyncFiberError";class Ou extends Ur("AsyncFiberError"){[uu]=uu;constructor(e){super({message:"An asynchronous Effect was executed with Effect.runSync",fiber:e})}}var lu="~effect/Cause/UnknownError";class Ba extends Ur("UnknownError"){[lu]=lu;constructor(e,t){super({message:t,cause:e})}}var fb=Be("effect/Console",{defaultValue:()=>globalThis.console}),pb=(e)=>{switch(e){case"All":return Number.MIN_SAFE_INTEGER;case"Fatal":return 50000;case"Error":return 40000;case"Warn":return 30000;case"Info":return 20000;case"Debug":return 1e4;case"Trace":return 0;case"None":return Number.MAX_SAFE_INTEGER}},mb=Up($r,pb),hb=Ea(mb),ig=Be("effect/Logger/CurrentLoggers",{defaultValue:()=>new Set([bb,wb])}),gb=Be("effect/Logger/LogToStderr",{defaultValue:Xf});var yb="~effect/Logger",Sb={[yb]:{_Message:pe,_Output:pe},pipe(){return ut(this,arguments)}},og=(e)=>{let t=Object.create(Sb);return t.log=e,t},xb=(e)=>e.replace(/[\s="]/g,"_"),Eb=(e,t)=>`${xb(e[0])}=${t-e[1]}ms`;var ag=(e)=>(...t)=>{let n=void 0;for(let r=0,i=t.length;r<i;r++){let o=t[r];if(Ni(o)){if(n)t.splice(r,1);else t=t.slice(0,r).concat(t.slice(r+1));n=n?Fr(n.reasons.concat(o.reasons)):o,r--}}if(n===void 0)n=Nc;return $e((r)=>{let i=e??r.cache.logLevel;if(hb(r.cache.minimumLogLevel,i))return qe;let o=r.getRef(Ru),a=r.getRef(ig);if(a.size>0){let s=new Date(o.currentTimeMillisUnsafe());for(let u of a)u.log({cause:n,fiber:r,date:s,logLevel:i,message:t})}return qe})};var rr={bold:"1",red:"31",green:"32",yellow:"33",blue:"34",cyan:"36",white:"37",gray:"90",black:"30",bgBrightRed:"101"},EC={None:[],All:[],Trace:[rr.gray],Debug:[rr.blue],Info:[rr.green],Warn:[rr.yellow],Error:[rr.red],Fatal:[rr.bgBrightRed,rr.black]};var vb=(e)=>`${e.getHours().toString().padStart(2,"0")}:${e.getMinutes().toString().padStart(2,"0")}:${e.getSeconds().toString().padStart(2,"0")}.${e.getMilliseconds().toString().padStart(3,"0")}`;var bb=og(({cause:e,date:t,fiber:n,logLevel:r,message:i})=>{let o=Array.isArray(i)?i.slice():[i];if(e.reasons.length>0)o.push(fu(e));let a=t.getTime(),s=n.getRef(Cm),u="";for(let g of s)u+=` ${Eb(g,a)}`;let p=n.getRef(ou);if(Object.keys(p).length>0)o.push(p);let c=n.getRef(fb);(n.getRef(gb)?c.error:c.log)(`[${vb(t)}] ${r.toUpperCase()} (#${n.id})${u}:`,...o)}),wb=og(({cause:e,fiber:t,logLevel:n,message:r})=>{let i=t.getRef(Ru),o=t.getRef(ou),a=t.cache.span;if(a===void 0||a._tag==="ExternalSpan")return;let s={};for(let[u,p]of Object.entries(o))ln(s,u,p);if(s["effect.fiberId"]=t.id,s["effect.logLevel"]=n.toUpperCase(),e.reasons.length>0)s["effect.cause"]=fu(e);a.event(xp(Array.isArray(r)&&r.length===1?r[0]:r),i.currentTimeNanosUnsafe(),s)});var Va=Tn;var Pu=ha;var In=$m;var Nu=we,Hi=Dt,qr=Dr;var Vr=Ut;var hn=gu,Lu=yh;var sg=nr,za=Vh;var cg=ir;var K=th,J=_e;var Ka=lt,dt=Rt,Mu=qe;var ug=Qt;var f=ih,d=or;var Zi=Xm,Xi=qi,ie=eh;var lg=Ym;var xe=Ae,Ga=mh;var ar=bu,zr=Ki;var sr=Gi,j=bh,F=wh;var gn=xu;var Rn=_h;var et=kh;var dg=Ah;var Wa=Cu;var fg=dh;var Ja=vu;var pg=Dh;var xt=Lh,Ha=Fh;var Qi=Uh;var Kr=Gh;var Oe=Hh;var Cn=Xh;var cr=Yh;var Ya=hh,Fu=gh;var tt=ph;var mg=oh;var Xa=(e)=>_b(typeof e==="string"?kb.encode(e):e),Qa=(e)=>{let t=Tb(e),n=t.length;if(n%4!==0)return je(new $i({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 je(new $i({kind:"Decode",module:"Base64",input:t,message:"Found a '=' character, but it is not at the end"}));try{let i=t.endsWith("==")?2:t.endsWith("=")?1:0,o=new Uint8Array(3*(n/4)-i);for(let a=0,s=0;a<n;a+=4,s+=3){let u=Za(t.charCodeAt(a))<<18|Za(t.charCodeAt(a+1))<<12|Za(t.charCodeAt(a+2))<<6|Za(t.charCodeAt(a+3));o[s]=u>>16,o[s+1]=u>>8&255,o[s+2]=u&255}return St(o)}catch(i){return je(new $i({kind:"Decode",module:"Base64",input:t,message:i instanceof Error?i.message:"Invalid input"}))}};var _b=(e)=>{let t=e.length,n="",r;for(r=2;r<t;r+=3)n+=$t[e[r-2]>>2],n+=$t[(e[r-2]&3)<<4|e[r-1]>>4],n+=$t[(e[r-1]&15)<<2|e[r]>>6],n+=$t[e[r]&63];if(r===t+1)n+=$t[e[r-2]>>2],n+=$t[(e[r-2]&3)<<4],n+="==";if(r===t)n+=$t[e[r-2]>>2],n+=$t[(e[r-2]&3)<<4|e[r-1]>>4],n+=$t[(e[r-1]&15)<<2],n+="=";return n},kb=new TextEncoder;var Tb=(e)=>e.replace(/[\n\r]/g,""),$t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",eo=new Uint8Array(123).fill(255);for(let e=0;e<$t.length;e++)eo[$t.charCodeAt(e)]=e;eo[61]=0;var Za=(e)=>{if(e>=eo.length||eo[e]===255)throw TypeError(`Invalid character ${String.fromCharCode(e)}`);return eo[e]};function Du(e){return e.checks?e.checks[e.checks.length-1].annotations:e.annotations}var to="~structural";var Uu="~sentinels",$u="~constructor";var es=_i((e)=>{let t=Du(e)?.identifier;if(typeof t==="string")return t;return e.getExpected(es)});var q=Symbol();var Pe=Nu,Ct=Pe(q),ne=Pe(q),no=(e)=>e===q?Xt():pn(e),Bu=(e)=>e._tag==="None"?Ct:Pe(e.value);var oo="~effect/SchemaIssue/Issue";function Vu(e){return Z(e,oo)&&e[oo]===oo}function Ib(e){return Object.hasOwn(e,"input")}class jt{[oo]=oo;constructor(e,t){if(t?.reportInput===!0&&e!==q)this.input=e}}var gg=class extends jt{_tag="Filter";filter;issue;constructor(e,t,n,r){super(n,r);this.filter=e,this.issue=t}},yg=class extends jt{_tag="Encoding";ast;issue;constructor(e,t,n,r){super(n,r);this.ast=e,this.issue=t}},yn=class extends jt{_tag="Pointer";path;issue;constructor(e,t){super();this.path=e,this.issue=t}},co=class extends jt{_tag="MissingKey";annotations;constructor(e){super();this.annotations=e}},zu=class extends jt{_tag="UnexpectedKey";ast;constructor(e,t,n){super(t,n);this.ast=e}},ze=class extends jt{_tag="Composite";ast;issues;constructor(e,t,n,r){super(n,r);this.ast=e,this.issues=t}},en=class extends jt{_tag="InvalidType";ast;constructor(e,t,n){super(t,n);this.ast=e}},Ve=class extends jt{_tag="InvalidValue";annotations;constructor(e,t,n){super(t,n);this.annotations=e}};var uo=class extends jt{_tag="AnyOf";ast;issues;constructor(e,t,n,r){super(n,r);this.ast=e,this.issues=t}},Sg=class extends jt{_tag="OneOf";ast;successes;constructor(e,t,n,r){super(n,r);this.ast=e,this.successes=t}};function qu(e,t,n){if(Vu(e))return e;if(typeof e==="string")return new Ve({message:e},t,n);let r=typeof e.issue==="string"?new Ve({message:e.issue},t,n):e.issue;return new yn(e.path,r)}function xg(e,t,n){if(e===void 0)return;if(typeof e==="boolean")return e?void 0:new Ve(void 0,t,n);return qu(e,t,n)}function Eg(e,t,n,r){if(Array.isArray(t)){if(!Kp(t))return;return t.length===1?qu(t[0],n,r):new ze(e,Gp(t,(i)=>qu(i,n,r)),n,r)}return xg(t,n,r)}var Rb=(e)=>{let t=so(e);if(t!==void 0)return t;switch(e._tag){case"InvalidType":return ao(es(e.ast),e);case"InvalidValue":{let n=vg(e);if(n!==void 0)return ao(n,e);let r=ts(e);return r===void 0?"Expected a valid value":`Invalid data ${r}`}case"MissingKey":return"Missing key";case"UnexpectedKey":{let n=ts(e);return n===void 0?"Expected no excess property":`Unexpected key with value ${n}`}case"Forbidden":return"Forbidden operation";case"OneOf":{let n=ts(e);return n===void 0?"Expected exactly one member to match":`Expected exactly one member to match the input ${n}`}}},Cb=(e)=>so(e.issue)??so(e);function ts(e){return Ib(e)?Q(e.input):void 0}function vg(e){let t=e.annotations?.expected;return typeof t==="string"?t:void 0}function ao(e,t){let n=ts(t);return n===void 0?`Expected ${e}`:`Expected ${e}, got ${n}`}function bg(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)=>bg(n)).join(" & ")}}function Ab(){return(e)=>io(e,"")}var wg=Ab();function io(e,t){let n;switch(e._tag){case"Filter":{let r=Cb(e);if(r!==void 0)n=r;else{if(e.issue._tag!=="InvalidValue")return io(e.issue,t);let i=vg(e.issue);n=i===void 0?ao(bg(e.filter),e):ao(i,e.issue)}break}case"Encoding":return io(e.issue,t);case"Pointer":return io(e.issue,t+Sp(e.path));case"Composite":case"AnyOf":{if(e._tag==="Composite"||e.issues.length>0)return e.issues.map((r)=>io(r,t)).join(`
|
|
28
|
+
`);n=so(e)??ao(es(e.ast),e);break}default:n=Rb(e);break}return t?`${n}
|
|
29
|
+
at ${t}`:n}function so(e){if(e._tag==="Pointer")return;if(e._tag==="Encoding")return so(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 lo(e){let t;for(let n of e.reasons){if(!Va(n)||!Vu(n.error))return;t??=n.error}return t}function An(e,t){let n=lo(e);if(n===void 0)throw Error(t,{cause:e});return n}var fo=(e)=>Object.assign(Object.create(xc),e);var Nb=fo({_tag:"Passthrough"});function po(){return Nb}function nt(e){return fo({_tag:"Transform",transform:e})}function On(e){return fo({_tag:"TransformEffect",transform:e})}function kg(e){return fo({_tag:"TransformOptional",transform:e})}function Lb(e){return fo({_tag:"TransformOptionalEffect",transform:e})}function Tg(){return kg(()=>Xt())}function Ig(e){return Lb((t)=>{let n=qp(t,bc);return qc(n)?J(n):Ya(e,pn)})}function Ku(){return nt(globalThis.String)}function ns(){return nt(globalThis.Number)}function Rg(e){return On((t,n)=>ie({try:()=>JSON.parse(t,e?.reviver),catch:()=>new Ve({expected:"a valid JSON string"},t,n)}))}function Cg(e){return On((t,n)=>ie({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 Ve({expected:"a JSON-serializable value"},t,n)}))}function Ag(){return nt(Xa)}function Og(){return On((e,t)=>Fu(lg(Qa(e)),()=>new Ve({expected:"a valid Base64 string"},e,t)))}var mo="~effect/SchemaTransformation/Transformation",Et=class extends wi{[mo]=mo;_tag="Transformation";decode;encode;constructor(e,t){super();this.decode=e,this.encode=t}flip(){return new Et(this.encode,this.decode)}};function Db(e){return Z(e,mo)&&e[mo]===mo}var Wu=(e)=>{if(Db(e))return e;return new Et(e.decode,e.encode)};function ho(e){return new Et(On(e.decode),On(e.encode))}function Pg(e){return new Et(nt(e.decode),nt(e.encode))}var Ub=new Et(po(),po());function rs(){return Ub}var go=new Et(ns(),Ku());var Ng=ho({decode:(e,t)=>URL.canParse(e)?J(new URL(e)):d(new Ve({expected:"a valid URL string"},e,t)),encode:(e)=>J(e.href)});var Lg=new Et(Og(),Ag());function is(e){return new Et(Rg(e??{}),Cg(e))}function fr(e){return(t)=>t._tag===e}var qg=fr("Declaration");var Bb=fr("Never");var Jr=fr("Literal"),Yu=fr("UniqueSymbol");var qb=fr("Arrays"),Vb=fr("Objects");var Vg=fr("Suspend"),At=class{to;transformation;constructor(e,t){this.to=e,this.transformation=t}},pr={},Hr=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}},Mg="~effect/Schema";class Ot{[Mg]=Mg;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 yo=class extends Ot{_tag="Declaration";typeParameters;run;encodingChecks;encodingRun;constructor(e,t,n,r,i,o,a,s){super(n,r,i,o);this.typeParameters=e,this.run=t,this.encodingChecks=a,this.encodingRun=s}getParser(){let e;return(t,n)=>{if(t===q)return Ct;return(e??=this.run(this.typeParameters))(t,this,n)}}_rebuild(e,t,n,r,i){let o=Yr(this.typeParameters,e);return o===this.typeParameters&&t===this.checks&&n===this.encodingChecks&&r===this.run&&i===this.encodingRun?this:new yo(o,r,this.annotations,t,void 0,this.context,n,i)}recur(e){return this._rebuild(e,this.checks,this.encodingChecks,this.run,this.encodingRun)}flip(e){return this._rebuild(e,this.encodingChecks,this.checks,this.encodingRun??this.run,this.run)}getExpected(){let e=this.annotations?.expected;if(typeof e==="string")return e;return"<Declaration>"}},zb=class extends Ot{_tag="Null";getParser(){return ml(this,null)}getExpected(){return"null"}},nl=new zb;var Kb=class extends Ot{_tag="Undefined";getParser(){return ml(this,void 0)}toCodecJson(){return Bt(this,[Gb])}getExpected(){return"undefined"}},Gb=new At(nl,new Et(nt(()=>{return}),nt(()=>null))),rl=new Kb;var Wb=class extends Ot{_tag="Unknown";getParser(){return vo(this,ip)}getExpected(){return"unknown"}},as=new Wb;var Wr=class extends Ot{_tag="Literal";literal;constructor(e,t,n,r,i){super(t,n,r,i);if(typeof e==="number"&&!globalThis.Number.isFinite(e))throw Error(`A numeric literal must be finite, got ${Q(e)}`);this.literal=e}getParser(){return ml(this,this.literal)}matchPart(e,t){return e===globalThis.String(this.literal)?this.literal:void 0}toCodecJson(){return typeof this.literal==="bigint"?Fg(this):this}toCodecStringTree(){return typeof this.literal==="string"?this:Fg(this)}getExpected(){return typeof this.literal==="string"?JSON.stringify(this.literal):globalThis.String(this.literal)}};function Fg(e){let t=globalThis.String(e.literal);return Bt(e,[new At(new Wr(t),new Et(nt(()=>e.literal),nt(()=>t)))])}var Jb=class extends Ot{_tag="String";getParser(){return vo(this,Rr)}matchPart(e,t){let n=this.checks;return n&&!t.disableChecks&&Nn(n,e,void 0,this,t)?void 0:e}getExpected(){return"string"}},lr=new Jb,Hb=class extends Ot{_tag="Number";getParser(){return vo(this,Ri)}matchKey(e,t){return this._match(yw,e,t)}matchPart(e,t){return this._match(tl,e,t)}_match(e,t,n){if(!e.test(t))return;let r=globalThis.Number(t);if(n.disableChecks||!this.checks)return r;return Nn(this.checks,r,void 0,this,n)?void 0:r}toCodecJson(){if(this.checks&&(Zu(this.checks,"effect/schema/isFinite")||Zu(this.checks,"effect/schema/isInt")))return this;return Bt(this,[sw])}toCodecStringTree(){if(this.toCodecJson()===this)return Bt(this,[Sw]);return Bt(this,[xw])}getExpected(){return"number"}};function Zu(e,t){return e.some((n)=>n.annotations?.representation?.id===t||n._tag==="FilterGroup"&&Zu(n.checks,t))}var il=new Hb,Yb=class extends Ot{_tag="Boolean";getParser(){return vo(this,ep)}getExpected(){return"boolean"}},zg=new Yb;var ls=class extends Ot{_tag="Arrays";isMutable;elements;rest;encodingChecks;constructor(e,t,n,r,i,o,a,s){super(r,i,o,a);this.isMutable=e,this.elements=t,this.rest=n,this.encodingChecks=s;let u=!1;for(let p=0;p<t.length;p++)if(dr(t[p]))u=!0;else if(u)throw Error("A required element cannot follow an optional element. ts(1257)");if(u&&n.length>1)throw Error("A required element cannot follow an optional element. ts(1257)");for(let p=1;p<n.length;p++)if(dr(n[p]))throw Error("An optional element cannot follow a rest element. ts(1266)")}getParser(e,t=e){let n=this,r,i,o=n.elements.length,a=Math.max(0,n.rest.length-1);function s(c,l){if(l<o)return r[l];else if(l>=c)return i[l-c+1];return i[0]}let u=(c)=>{let{input:l,len:g,options:v}=c;if(n.rest.length===0&&g>o)for(let w=o;w<g;w++){let k=new zu(n,l[w],v),E=new yn([w],k);if(v.errors==="all")if(c.issues)c.issues.push(E);else c.issues=[E];else return d(new ze(n,[E],l,v))}if(c.issues)return d(new ze(n,c.issues,l,v));return Pe(c.output)},p=(c,l)=>{let g=c.length,v={ast:n,getParser:s,input:c,len:g,tailThreshold:Math.max(o,g-a),output:new globalThis.Array(g),issues:void 0,options:l},w=n.rest.length===0?o:Math.max(g,o+a),k=l.concurrency===void 0?1:Wi(l.concurrency),E=k===1?Xb(v,c,0,w):Qb(v,c,{concurrency:k,end:w});if(!E)return u(v);if(oe(E))return tt(E,()=>u(v));let m=!0;return Ka(()=>{if(!m)return p(c,l);return m=!1,xe(E,()=>u(v))})};return(c,l)=>{if(c===q)return Ct;try{if(!Array.isArray(c))return d(new en(n,c,l));if(!r)r=n.elements.map((g)=>({ast:g,parser:t(g)})),i=n.rest.map((g)=>({ast:g,parser:t(g)}));return p(c,l)}catch(g){return Xi(g)}}}_rebuild(e,t,n){let r=Yr(this.elements,e),i=Yr(this.rest,e);return r===this.elements&&i===this.rest&&t===this.checks&&n===this.encodingChecks?this:new ls(this.isMutable,r,i,this.annotations,t,void 0,this.context,n)}recur(e){return this._rebuild(e,this.checks,this.encodingChecks)}flip(e){return this._rebuild(e,this.encodingChecks,this.checks)}getExpected(){return"array"}};function Zb(e,t,n,r){if(n._tag==="Failure")return ss(e,e.ast,r,n);let i=n===ne?t:n[D];if(i!==q)e.output[r]=i;else{let o=e.getParser(e.tailThreshold,r);if(dr(o.ast))return;let a=new yn([r],new co(o.ast.context?.annotations));if(e.options.errors==="all")if(e.issues)e.issues.push(a);else e.issues=[a];else return qr(new ze(e.ast,[a],e.input,e.options))}}var Kg={onItem(e,t,n){let r=n<e.len?t:q;return e.getParser(e.tailThreshold,n).parser(r,e.options)},step:Zb},Xb=Ua()(Kg),Qb=$a()(Kg),ss=(e,t,n,r)=>{if(r.cause.reasons.length===0)return r;let i=lo(r.cause);if(i===void 0)return Hi(In(r.cause,(a)=>new ze(t,[new yn([n],a)],e.input,e.options)));let o=new yn([n],i);if(e.options.errors==="all")if(e.issues)e.issues.push(o);else e.issues=[o];else return qr(new ze(t,[o],e.input,e.options))},Gg="[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?";function Hu(e,t,n=pr){let r,i;function o(a){switch(a._tag){case"String":case"TemplateLiteral":return(r??=Object.keys(e)).filter((s)=>a.matchPart(s,n)!==void 0);case"Number":return(r??=Object.keys(e)).filter((s)=>a.matchKey(s,n)!==void 0);case"Symbol":return(i??=Object.getOwnPropertySymbols(e)).filter((s)=>Object.prototype.propertyIsEnumerable.call(e,s)&&a.matchKey(s,n)!==void 0);case"Union":return[...new Set(a.types.flatMap(o))];default:return[]}}return o(hl(Ss(t)))}var ol=class{name;type;constructor(e,t){this.name=e,this.type=t}};function Wg(e){switch(e._tag){case"String":case"Number":case"Symbol":case"TemplateLiteral":return!0;case"Union":return e.types.every(Wg);default:return!1}}function Jg(e){let t=ty(e);switch(t._tag){case"String":case"Number":case"Symbol":case"TemplateLiteral":return!0;case"Union":return t.types.every(Jg);default:return!1}}function ew(e){return Wg(e)&&Jg(e)}var Hg=class{parameter;type;constructor(e,t){if(!ew(e))throw Error(`Invalid index signature parameter ${e._tag}`);if(this.parameter=e,this.type=t,dr(t)&&!uy(t))throw Error("Cannot use `Schema.optionalKey` with index signatures, use `Schema.optional` instead.")}},ds=class extends Ot{_tag="Objects";propertySignatures;indexSignatures;encodingChecks;constructor(e,t,n,r,i,o,a){super(n,r,i,o);this.propertySignatures=e,this.indexSignatures=t,this.encodingChecks=a}getParser(e,t=e){let n=this,r=n.propertySignatures.length,i=n.indexSignatures.length;if(!r&&!i)return vo(n,rp);let o,a,s=()=>{if(!o)o=n.propertySignatures.map((l)=>({parser:t(l.type),name:l.name,type:l.type})),a=i?n.indexSignatures.map((l)=>({is:l,parserKey:e(hl(l.parameter)),parserValue:t(l.type)})):void 0;return o},u=()=>{let l=new Set(n.propertySignatures.map((E)=>typeof E.name==="number"?globalThis.String(E.name):E.name)),g=(E,m,h,R,I)=>{if(I._tag==="Failure")return ss(E,n,m,I)??Vr;let A=I===ne?R:I[D];if(h!==q&&A!==q){if(r&&(l.has(m)||l.has(typeof h==="number"?globalThis.String(h):h)))return Vr;ln(E.out,h,A)}return Vr},v=(E,m,h,R)=>{if(!R){let z=h.parserKey(m,E.options);if(!oe(z))return xe(ar(z),(Y)=>v(E,m,h,Y));R=z}if(R._tag==="Failure")return ss(E,n,m,R)??Vr;let I=R===ne?m:R[D],A=E.input[m],V=h.parserValue(A,E.options);return oe(V)?g(E,m,I,A,V):xe(ar(V),(z)=>g(E,m,I,A,z))},w=(E,m,h)=>{let R=E.input[m],I=h.parserValue(R,E.options);return oe(I)?g(E,m,m,R,I):xe(ar(I),(A)=>g(E,m,m,R,A))},k=i?$a()({onItem:(E,[m,h])=>h.is.parameter===lr?w(E,m,h):v(E,m,h),step:(E,m,h)=>h._tag==="Failure"?h:void 0}):void 0;return mg(function*(E,m){if(E===q)return q;if(!(typeof E==="object"&&E!==null&&!Array.isArray(E)))return yield*d(new en(n,E,m));s();let h=E,R={},I={ast:n,input:h,out:R,issues:void 0,options:m},A=m.errors==="all",V=m.onExcessProperty==="error",z=m.concurrency===void 0?1:Wi(m.concurrency),Y=i&&V?n.indexSignatures.map((Ee)=>Hu(h,Ee.parameter,m)):void 0;if(V){let Ee=Y?new Set(l):l;if(Y)for(let Ge of Y)for(let We of Ge)Ee.add(We);let _t=Reflect.ownKeys(h);for(let Ge=0;Ge<_t.length;Ge++){let We=_t[Ge];if(!Ee.has(We)&&Object.prototype.propertyIsEnumerable.call(h,We)){let Mt=new zu(n,h[We],m),Je=new yn([We],Mt);if(A){if(I.issues)I.issues.push(Je);else I.issues=[Je];continue}else return yield*d(new ze(n,[Je],E,m))}}}if(r){let Ee=z===1?Dg(I,o):tw(I,o,{concurrency:z});if(Ee)yield*Ee}if(i&&z===1)for(let Ee=0;Ee<i;Ee++){let _t=a[Ee],Ge=_t.is.parameter===lr?w:v,We=Y?.[Ee]??(_t.is.parameter===lr?Object.keys(h):Hu(h,_t.is.parameter,m));for(let Mt=0;Mt<We.length;Mt++){let Je=Ge(I,We[Mt],_t);if(!oe(Je))yield*Je;else if(Je._tag==="Failure")return yield*Je}}else if(k){let Ee=_a();for(let Ge=0;Ge<i;Ge++){let We=a[Ge],Mt=Y?.[Ge]??(We.is.parameter===lr?Object.keys(h):Hu(h,We.is.parameter,m));for(let Je=0;Je<Mt.length;Je++)Ee.push([Mt[Je],We])}let _t=k(I,Ee,{concurrency:z});if(_t)yield*_t}if(I.issues)return yield*d(new ze(n,I.issues,E,m));return R})};if(i)return u();let p,c=(l,g,v)=>{let w=o[g];return xe(ar(v),(k)=>{let E=Xu(l,w,k);if(E)return E;let m=()=>Pe(l.out),h=Dg(l,o.slice(g+1));return h?tt(h,m):m()})};return(l,g)=>{if(l===q)return Ct;if(g.errors==="all"||g.onExcessProperty!==void 0||g.concurrency!==void 0&&Wi(g.concurrency)!==1)return(p??=u())(l,g);if(!(typeof l==="object"&&l!==null&&!Array.isArray(l)))return d(new en(n,l,g));let v=s(),w=l,k={},E={ast:n,input:w,out:k,issues:void 0,options:g};try{for(let m=0;m<v.length;m++){let h=v[m],R=h.name,I=Gr(w,R),A=I?w[R]:q,V=h.parser(A,g);if(!oe(V))return c(E,m,V);if(V===ne){if(I)ln(k,R,A);continue}let z=Xu(E,h,V);if(z)return z}}catch(m){return Xi(m)}return Pe(k)}}_rebuild(e,t,n,r){let i=Yr(this.propertySignatures,(a)=>{let s=e(a.type);return s===a.type?a:new ol(a.name,s)}),o=Yr(this.indexSignatures,(a)=>{let s=t(a.parameter),u=e(a.type);return s===a.parameter&&u===a.type?a:new Hg(s,u)});return i===this.propertySignatures&&o===this.indexSignatures&&n===this.checks&&r===this.encodingChecks?this:new ds(i,o,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 Xu(e,t,n){if(n._tag==="Failure")return ss(e,e.ast,t.name,n);if(n===ne)return;let r=n[D];if(r!==q){ln(e.out,t.name,r);return}if(delete e.out[t.name],!dr(t.type)){let i=new yn([t.name],new co(t.type.context?.annotations));if(e.options.errors==="all"){if(e.issues)e.issues.push(i);else e.issues=[i];return}else return qr(new ze(e.ast,[i],e.input,e.options))}}var Yg={onItem(e,t){if(!Gr(e.input,t.name))return t.parser(q,e.options);let n=e.input[t.name];return ln(e.out,t.name,n),t.parser(n,e.options)},step:Xu},Dg=Ua()(Yg),tw=$a()(Yg);function al(e,t){if(!e)return t;if(!t)return e;return[...e,...t]}function sl(e,t,n){return new ds(Reflect.ownKeys(e).map((r)=>new ol(r,e[r].ast)),[],n,t)}function fs(e){return e.ast}function cl(e,t=void 0){return new ls(!1,e.map((n)=>n.ast),[],void 0,t)}function ps(e,t,n){return new Zr(e.map(fs),t,void 0,n)}function Zg(e,t){if(e.encoding||t.some((o)=>o.encoding))throw Error("StructWithRest does not support encodings");let{propertySignatures:n,indexSignatures:r,checks:i}=e;for(let o of t){for(let a of o.propertySignatures)if(n.some((s)=>s.name===a.name))throw Error(`Duplicate identifier: ${JSON.stringify(a.name)}. ts(2300)`);n=n.concat(o.propertySignatures),r=r.concat(o.indexSignatures),i=al(i,o.checks)}return new ds(n,r,void 0,i)}var ul=Ir((e)=>{while(!0){if(Vg(e))return as;let t=e.encoding;if(!t)return e.recur?.(ul,pe)??e;if(t.some((n)=>n.transformation._tag==="Middleware"&&n.transformation.decode!==pe))return as;e=t[t.length-1].to}});function Xg(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(Xg)));default:return["null","undefined","string","number","boolean","symbol","bigint","object","array","function"]}}function cs(e){switch(e._tag){default:return[];case"Declaration":{let t=e.annotations?.[Uu];return Array.isArray(t)?t:[]}case"Objects":return e.propertySignatures.flatMap((t)=>{let n=t.type;if(!dr(n)){if(Jr(n))return[{key:t.name,literal:n.literal}];if(Yu(n))return[{key:t.name,literal:n.symbol}]}return[]});case"Arrays":return e.elements.flatMap((t,n)=>{if(!dr(t)){if(Jr(t))return[{key:n,literal:t.literal}];if(Yu(t))return[{key:n,literal:t.symbol}]}return[]});case"Union":{if(e.types.length===0)return[];let t=e.types.map((n)=>cs(ul(n)));return t[0].filter((n)=>t.every((r)=>r.some((i)=>i.key===n.key&&i.literal===n.literal)))}case"Suspend":return cs(e.thunk())}}var Ug=new WeakMap,os=Object.freeze([]),$g=(e)=>e===null?"null":Array.isArray(e)?"array":typeof e,Gr=(e,t)=>t==="__proto__"?Object.hasOwn(e,t):(t in e);function nw(e){let t=Ug.get(e);if(t)return t;let n,r=0,i,o,a=!0,s=[];for(let c=0;c<e.length;c++){let l=e[c],g=ul(l);if(Bb(g))continue;if(Jr(g)||Yu(g)){o??=new Map;let w=Jr(g)?g.literal:g.symbol;s[c]=w;let k=o.get(w);if(!k)o.set(w,k=[]);k.push(c)}else a=!1;let v=cs(g);if(v.length){n??=new Map,r++;for(let{key:w,literal:k}of v){let E=n.get(w);if(!E)n.set(w,E=[new Map,new Set]);E[1].add(c);let m=E[0].get(k);if(!m)E[0].set(k,m=new Set);m.add(c)}}else{i??={};let w=Xg(g);for(let k of w)(i[k]??=[]).push(c)}}let u={},p=(c)=>u[c]??=Object.freeze(i?.[c]??os);if(a&&o)o.forEach(Object.freeze),t=(c)=>o.get(c)??os;else if(n?.size===1&&!i){let[c,[l]]=n.entries().next().value,g=new Map;for(let[w,k]of l)g.set(w,Object.freeze(Array.from(k)));let v=Object.freeze(e.map((w,k)=>k));t=(w,k)=>{if(ua(w)){let E=Gr(w,c)?w[c]:void 0;if(E!==void 0)return g.get(E)??os;if(k)return v}return os}}else if(n){let c;for(let l of n)if((!c||l[1][0].size>c[1][0].size)&&l[1][1].size===r)c=l;t=(l,g)=>{let v=$g(l);if(!ua(l))return p(v);let w=new Set(i?.[v]),k;if(c){let[E,[m]]=c,h=Gr(l,E),R=h?l[E]:void 0;if(h&&(!g||R!==void 0)){let I=m.get(R);if(!I)return p(v);for(let A of I)w.add(A);k=E}}if(k===void 0)for(let[E,[m,h]]of n){let R=Gr(l,E),I=R?l[E]:void 0;if(R&&(!g||I!==void 0)){let A=m.get(I);if(A)for(let V of A)w.add(V)}else if(g)for(let A of h)w.add(A)}for(let[E,[m,h]]of n){if(E===k)continue;let R=Gr(l,E),I=R?l[E]:void 0;if(R&&(!g||I!==void 0)){let A=m.get(I);for(let V of w)if(h.has(V)&&!A?.has(V))w.delete(V)}}return Array.from(w).sort((E,m)=>E-m)}}else t=(c)=>{let l=p($g(c));return o?l.filter((g)=>s[g]===void 0||s[g]===c):l};return Ug.set(e,t),t}var Zr=class extends Ot{_tag="Union";types;options;encodingChecks;constructor(e,t,n,r,i,o,a){super(n,r,i,o);this.types=e,this.options=t,this.encodingChecks=a}getParser(e,t){let n=this,r=t!==void 0,i=[],o=(s)=>i[s]??=e(n.types[s]),a;return(s,u)=>{if(s===q)return Ct;let p=(a??=nw(n.types))(s,r);if(p.length===0)return d(new uo(n,[],s,u));if(p.length===1){let c=o(p[0])(s,u);if(c._tag==="Success")return c;return oe(c)?Qg(n,c.cause,s,u):rw(n,c,s,u)}return iw(n,o,p,s,u)}}_rebuild(e,t,n){let r=Yr(this.types,e);return r===this.types&&t===this.checks&&n===this.encodingChecks?this:new Zr(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 i=Ss(r);switch(i._tag){case"Arrays":{let o=i.elements.filter(Jr);if(o.length>0)return`${jg(i.isMutable)}[ ${o.map((a)=>e(a)+Bg(a.context?.isOptional)).join(", ")}, ... ]`;break}case"Objects":{let o=i.propertySignatures.filter((a)=>Jr(a.type));if(o.length>0)return`{ ${o.map((a)=>`${jg(a.type.context?.isMutable)}${Nr(a.name)}${Bg(a.type.context?.isOptional)}: ${e(a.type)}`).join(", ")}, ... }`;break}}return e(i)});return Array.from(new Set(n)).join(" | ")}};function Qg(e,t,n,r){let i=lo(t);if(!i)return Hi(t);return qr(new uo(e,[i],n,r))}function rw(e,t,n,r){return sr(t,(i)=>Qg(e,i,n,r))}function iw(e,t,n,r,i){let o={ast:e,parser:t,input:r,out:void 0,successes:e.options?.mode==="oneOf"?[]:void 0,issues:void 0,options:i},a=aw(o,n);if(!a){if(o.out)return o.out;return d(new uo(e,o.issues??[],r,i))}return ow(a,o)}function ow(e,t){return tt(e,(n)=>{if(t.out===ne)return J(t.input);if(t.out)return t.out;return d(new uo(t.ast,t.issues??[],t.input,t.options))})}var aw=Ua()({onItem(e,t){return e.parser(t)(e.input,e.options)},step(e,t,n){if(n._tag==="Failure"){let r=lo(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]),qr(new Sg(e.ast,e.successes,e.input,e.options));if(e.out=n,e.successes)e.successes.push(e.ast.types[t]);else return Vr}}}),ey=new Zr([new Wr("Infinity"),new Wr("-Infinity"),new Wr("NaN")]);function jg(e){return e?"":"readonly "}function Bg(e){return e?"?":""}var Qu=class extends wi{_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 Qu(this.run,{...this.annotations,...e},this.aborted)}abort(){return new Qu(this.run,this.annotations,!0)}and(e,t){return new us([this,e],t)}},us=class extends wi{_tag="FilterGroup";checks;annotations;constructor(e,t=void 0){super();this.checks=e,this.annotations=t}annotate(e){return new us(this.checks,{...this.annotations,...e})}and(e,t){return new us([this,e],t)}};function ms(e,t,n=!1){return new Qu((r,i,o)=>Eg(i,e(r,i,o),r,o),t,n)}function ll(e){return ms((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 dl=Eo(il,[ll()]),sw=new At(new Zr([dl,ey]),new Et(ns(),nt((e)=>globalThis.Number.isFinite(e)?e:globalThis.String(e))));function fl(e,t){let n=new globalThis.RegExp(e),r={source:n.source,flags:n.flags};return ms((i)=>(n.lastIndex=0,n.test(i)),{expected:`a string matching the RegExp ${r.source}`,representation:{id:"effect/schema/isPattern",payload:r},toJsonSchema:()=>[{},!0],arbitraryConstraint:{patterns:[r]},...t})}var el=new WeakMap;function So(e,t){let n=Object.assign(Object.create(Object.getPrototypeOf(e)),e,t);if(Reflect.ownKeys(t).every((r)=>r==="context"||r==="encoding"))el.set(n,hs(e));return n}function hs(e){let t=el.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 el.set(e,n),n}function Bt(e,t){return e.encoding===t?e:So(e,{encoding:t})}function xo(e,t){if(e.context===t)return e;let n=hs(e);if(n.context===t&&n.encoding===e.encoding)return n;return So(e,{context:t})}function ty(e){return e.encoding?ty(e.encoding[e.encoding.length-1].to):e}function gs(e,t){if(e.checks){let n=e.checks[e.checks.length-1];return ny(e,Kc(e.checks.slice(0,-1),n.annotate(t)))}return So(e,{annotations:{...e.annotations,...t}})}function ny(e,t){if(e._tag==="Suspend"&&t)throw Error("Cannot add checks to Suspend");if(e.checks===t)return e;return So(e,{checks:t})}function Eo(e,t){return ny(e,al(e.checks,t))}function cw(e,t){let n=t(e.to);return n===e.to?e:new At(n,e.transformation)}function ry(e,t){let n=e,r=n[n.length-1],i=cw(r,t);return i===r?e:Kc(e.slice(0,e.length-1),i)}function uw(e){return(t)=>t.encoding?Bt(t,ry(t.encoding,e)):t}function lw(e,t){function n(r){if(r.encoding){let i=r.encoding[r.encoding.length-1];return t?.stopAt?.(i)?r:Bt(r,ry(r.encoding,n))}return e(r)}return Ir(n)}function dw(e,t,n){let r=new At(e,t);return Bt(n,n.encoding?[...n.encoding,r]:[r])}function Yr(e,t){let n;for(let r=0;r<e.length;r++){let i=e[r],o=t(i);if(n)n[r]=o;else if(o!==i){n=Array(e.length);for(let a=0;a<r;a++)n[a]=e[a];n[r]=o}}return n??e}function pl(e,t){let n=e.context?new Hr(e.context.isOptional,e.context.isMutable,e.context.constructorDefault,{...e.context.annotations,...t}):new Hr(!1,!1,void 0,t);return xo(e,n)}var ys=Ir((e)=>{let t=e.context?e.context.isOptional===!1?new Hr(!0,e.context.isMutable,e.context.constructorDefault,e.context.annotations):e.context:new Hr(!0,!1);return fw(xo(e,t))}),fw=uw(ys),iy=_i((e)=>ys(new Zr([e,rl])));function oy(e,t){let n=e.context?new Hr(e.context.isOptional,e.context.isMutable,t,e.context.annotations):new Hr(!1,!1,t);return xo(e,n)}function ay(e,t,n){return dw(e,n,t)}function pw(e){let t=[],n=[];function r(i){switch(i._tag){case"Literal":if(np(i.literal)&&!t.includes(i.literal))t.push(i.literal);return;case"UniqueSymbol":if(!t.includes(i.symbol))t.push(i.symbol);return;case"Never":return;case"Union":for(let o=0;o<i.types.length;o++)r(i.types[o]);return;default:n.push(i)}}return r(e),{literals:t,parameters:n}}function sy(e,t){let{literals:n,parameters:r}=pw(e);return new ds(n.map((i)=>new ol(i,t)),r.map((i)=>new Hg(i,t)))}function dr(e){return e.context?.isOptional??!1}function cy(e){return e.annotations?.[to]===!0||e._tag==="FilterGroup"&&e.checks.every(cy)}function mw(e){function t(r){if(cy(r))return[r];return r._tag==="FilterGroup"?r.checks.flatMap(t):[]}let n=e.flatMap(t);return Gc(n)?n:void 0}function hw(e){let t=!0;function n(r){if(t=t&&!r.encoding&&!Vg(r),t&&"recur"in r)r.recur(n);return r}if("recur"in e)e.recur(n);return t}var Pn=Ir((e)=>{let t=hs(e);if(t!==e){let r=Pn(t);return r===t&&e.encoding===void 0?e:xo(r,e.context)}let n="recur"in e?e.recur(Pn):e;if("encodingChecks"in n&&n.encodingChecks){let r=hw(e)?n.encodingChecks:qb(n)||Vb(n)||qg(n)&&n.typeParameters.length>0?mw(n.encodingChecks):void 0;return So(n,{encodingChecks:void 0,checks:al(n.checks,r)})}return n}),Ss=Ir((e)=>Pn(Sn(e)));function gw(e,t){let n=t,r=n.length,i=n[r-1],o=[new At(Sn(Bt(e,void 0)),n[0].transformation.flip())];for(let s=1;s<r;s++)o.unshift(new At(Sn(n[s-1].to),n[s].transformation.flip()));let a=Sn(i.to);if(a.encoding)return Bt(a,[...a.encoding,...o]);else return Bt(a,o)}var Sn=_i((e)=>{if(e.encoding)return gw(e,e.encoding);let t=hs(e);if(t!==e){let n=Sn(t);return n===t?e:xo(n,e.context)}return"flip"in e?e.flip(Sn):("recur"in e)?e.recur(Sn):e});function uy(e){switch(e._tag){case"Undefined":return!0;case"Union":return e.types.some(uy);default:return!1}}function ml(e,t){let n=t===0?ne:Pe(t);return(r,i)=>{if(r===q)return Ct;if(r===t)return n;return d(new en(e,r,i))}}function vo(e,t){return(n,r)=>{if(n===q)return Ct;if(t(n))return ne;return d(new en(e,n,r))}}var hl=lw((e)=>{switch(e._tag){default:return e;case"Number":return e.toCodecStringTree();case"Union":return e.recur(hl)}});var tl=new globalThis.RegExp(`^${Gg}$`),yw=new globalThis.RegExp(`^(?:${Gg}|Infinity|-Infinity|NaN)$`);function ly(e){return fl(tl,{expected:"a string representing a finite number",representation:{id:"effect/schema/isStringFinite",payload:null},toJsonSchema:()=>({pattern:tl.source}),...e})}var dy=Eo(lr,[ly()]),Sw=new At(dy,go),xw=new At(new Zr([dy,ey]),go),Ew="-?\\d+",x0=new globalThis.RegExp(`^${Ew}$`);var vw="Symbol\\(([\\s\\S]*)\\)",E0=new globalThis.RegExp(`^${vw}$`);function Nn(e,t,n,r,i){for(let o=0;o<e.length;o++){let a=e[o];if(a._tag==="FilterGroup"){if(n=Nn(a.checks,t,n,r,i),n&&(i.errors!=="all"||n[n.length-1].filter.aborted))return n}else{let s=a.run(t,r,i);if(s){let u=new gg(a,s,t,i);if(n)n.push(u);else n=[u];if(i.errors!=="all"||a.aborted)return n}}}return n}function fy(e){if(!qg(e))return;let t=e.annotations?.[$u];return Wn(t)?t(e.typeParameters):void 0}function bw(e){return e===null||typeof e==="string"||typeof e==="boolean"||typeof e==="number"&&globalThis.Number.isFinite(e)}function ww(e){return e===void 0||typeof e==="string"}function py(e,t){let n=new WeakMap,r=[];e:while(!0){if(typeof e!=="object"||e===null){if(!t(e))return!1}else{let i=e,o=n.get(i);if(o===!1)return!1;if(o===void 0){let a=Array.isArray(i);if(!a){let s=Object.getPrototypeOf(i);if(s!==null&&s!==Object.prototype&&Object.getPrototypeOf(s)!==null)return!1}n.set(i,!1),r.push({value:i,keys:a?i.length:Object.keys(i),index:0})}}while(r.length>0){let i=r[r.length-1],o=i.keys;if(typeof o==="number"){if(i.index<o){e=i.value[i.index++];continue e}}else if(i.index<o.length){e=i.value[o[i.index++]];continue e}n.set(i.value,!0),r.pop()}return!0}}function _w(e){return py(e,bw)}var my=new yo([],()=>(e,t,n)=>_w(e)?ne:d(new en(t,e,n)),{representation:{id:"effect/schema/Json",payload:null},expected:"JSON value",toCodecJson:()=>{return},toCodecStringTree:()=>Iw});function kw(e){return py(e,ww)}var Tw=new yo([],()=>(e,t,n)=>kw(e)?ne:d(new en(t,e,n)),{expected:"StringTree",toCodecStringTree:()=>{return}}),Iw=new At(Tw,rs());var Es=(e,t,n)=>e===ne?n(t):tt(e,n);function gy(e){if(e._tag==="Middleware")return(n,r,i)=>{let o=n===ne?e.decode(Pe(no(r)),i):e.decode(Ya(n,no),i);return hy(o)};let t=e.decode;switch(t._tag){case"Passthrough":return(n,r)=>n===ne?Pe(r):n;case"Transform":{let n=(r)=>r===q?Ct:Pe(t.transform(r));return(r,i)=>Es(r,i,n)}case"TransformOptional":{let n=(r)=>Bu(t.transform(no(r)));return(r,i)=>Es(r,i,n)}case"TransformEffect":return(n,r,i)=>Es(n,r,(o)=>o===q?Ct:t.transform(o,i));case"TransformOptionalEffect":return(n,r,i)=>Es(n,r,(o)=>hy(t.transform(no(o),i)))}}var hy=(e)=>tt(e,Bu),yy=(e,t,n,r)=>sr(r,(i)=>Zi(()=>In(i,(o)=>new yg(e,o,t,n))));function Rw(e,t){let n=gy(e.link.transformation),r;return(i,o)=>{if(i===q)return Ct;if(e.isConstructed(i))return ne;let a=(r??=t(e.link.to))(i,o);return n(a,i,o)}}function Cw(e,t){let n=e.context.constructorDefault;return(r,i)=>{if(r!==q&&r!==void 0)return t(r,i);let o=n;if(oe(o)&&o._tag==="Success"){let a=t(o[D],i);return a===ne?o:a}return tt(yy(e,r,i,o),(a)=>{let s=t(a,i);return s===ne?Pe(a):s})}}function gl(e,t){let n=t(e);return e.context?.constructorDefault===void 0?n:Cw(e,n)}function bo(e,t,n,r,i){if(e._tag==="Declaration")for(let w of e.typeParameters)t(w);let o=n?fy(e):void 0,a=o?Rw(o,t):r??e.getParser(t,n),{checks:s,encoding:u}=e,p=u?.map((w)=>gy(w.transformation)),c=e.encodingChecks;if(!u&&!s&&!c)return a;let l,g=(w,k)=>{let E=a(w,k);if(c&&!k.disableChecks)if(oe(E)){if(E._tag==="Success"){let m=E===ne?w:E[D];if(w!==q&&m!==q){let h=Nn(c,w,void 0,e,k);if(h)E=d(new ze(e,h,w,k))}}}else E=xe(E,(m)=>{if(w!==q&&m!==q){let h=Nn(c,w,void 0,e,k);if(h)return d(new ze(e,h,w,k))}return J(m)});if(s&&!k.disableChecks)if(oe(E)){if(E._tag==="Success"){let m=E===ne?w:E[D];if(m===q)return E;let h=Nn(s,m,void 0,e,k);if(h)E=d(new ze(e,h,m,k))}}else E=xe(E,(m)=>{if(m!==q){let h=Nn(s,m,void 0,e,k);if(h)return d(new ze(e,h,m,k))}return J(m)});return E},v=i===void 0?g:i(g);if(!u)return v;return(w,k)=>{let E=l??=u.map((R)=>t(R.to)),m=w,h=E[E.length-1](w,k);for(let R=u.length-1;R>=0;R--)if(h=p[R](h,m,k),R!==0){let I=E[R-1];if(h._tag==="Success")m=h[D],h=I(m,k);else h=tt(h,(A)=>{let V=I(A,k);return V===ne?Pe(A):V})}if(h._tag==="Success"){let R=h[D],I=v(R,k);return I===ne?h:I}return h=yy(e,w,k,h),tt(h,(R)=>{let I=v(R,k);return I===ne?Pe(R):I})}}var yl=Symbol(),Sy=new WeakMap,xy,bs=!1;var Ow=(e)=>bs?vs(qt,e,"parser"):qt(e).parser,Ey=(e)=>bs?vs(qt,e,"makeEffect"):qt(e).makeEffect,Pw=(e)=>gl(e,Ey);class Sl{ast;constructor(e){this.ast=e}get decodeEffect(){return this.cachedDecodeEffect??=bo(this.ast,Ow)}get parser(){return this.decodeEffect}get makeEffect(){return this.cachedMakeEffect??=bo(this.ast,Ey,Pw)}}class vy extends Sl{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")??bo(this.ast,(e)=>vs(this.resolve,e,"parser")))}get parser(){let e=this.decode;return e===void 0?this.decodeEffect:this.save("parser",Nw(e,()=>this.decodeEffect))}get makeEffect(){let e=this.operation("makeEffect");if(e!==void 0)return this.save("makeEffect",e);let t=(n)=>vs(this.resolve,n,"makeEffect");return this.save("makeEffect",bo(this.ast,t,(n)=>gl(n,t)))}}function Nw(e,t){let n;return(r,i)=>{if(r!==q)try{let o=e(r,i);if(o!==yl)return o===r?ne:Pe(o)}catch(o){return Xi(o)}return(n??=t())(r,i)}}function vs(e,t,n){let r=e(t);if(r.compiled===void 0||Object.hasOwn(r,n))return r[n];let i;return(o,a)=>(i??=r[n])(o,a)}function qt(e){let t=Sy.get(e);if(t!==void 0)return t;let n=xy===void 0?new Sl(e):new vy(e,xy(e,qt),qt);return Sy.set(e,n),n}function xl(e){let t=e.ast,n;return(r,i)=>(n??=Ty(Vw,Pn(t)))(r,i?.disableChecks?i?.parseOptions?{...i.parseOptions,disableChecks:!0}:{disableChecks:!0}:i?.parseOptions)}function El(e){let t=xl(e);return(n,r)=>{let i=cr(t(n,r));if(hn(i))return pn(i.value);return An(i.cause,"Option adapter can only return none for schema issues"),Xt()}}function vl(e){return Bw(Pn(e.ast))}function by(e){return Dw(e.ast)}function Fw(e){if(!bs){let i=Iy(_y(e));return(o)=>{let a=i(o,pr);if(hn(a))return!0;return An(a.cause,"Type guard adapter can only return false for schema issues"),!1}}let t=qt(e),n=t.is;if(n!==void 0)return(i)=>{try{return n(i,pr)}catch(o){return An(Pu(o),"Type guard adapter can only return false for schema issues"),!1}};let r=t.parser;return(i)=>{let o=cr(ky(r(i,pr),i));if(hn(o))return!0;return An(o.cause,"Type guard adapter can only return false for schema issues"),!1}}function Dw(e){let t=Pn(e),n=(r)=>(n=Fw(t),n(r));return(r)=>n(r)}function bl(e,t){let n=_y(e.ast);return t===void 0?n:(r,i)=>n(r,Uw(t,i))}function wy(e,t){return $w(bl(e,t))}var Uw=(e,t)=>t?{...e,...t}:e,ws=(e)=>{if(e===q)return d(new Ve);return J(e)};function _y(e){return Ty(qw,e)}function ky(e,t){if(e===ne)return J(t);if(!oe(e))return tt(e,ws);return e[D]===q?ws(q):e}function Ty(e,t){let n;return(r,i)=>{let o=(n??=e(t))(r,i??pr);if(o===ne)return J(r);if(!oe(o))return tt(o,ws);return o[D]===q?ws(q):o}}function Iy(e){return(t,n)=>cr(e(t,n))}function $w(e){let t=Iy(e);return(n,r)=>{let i=t(n,r);if(hn(i))return St(i.value);return je(An(i.cause,"Result adapter can only return schema issues"))}}function jw(e,t){let n=cr(e);if(hn(n))return n.value;let r=An(n.cause,t);throw Error("Schema validation failed",{cause:r})}function Bw(e){let t,n;return(r,i)=>{t??=qt(e);let o=i?.disableChecks?i.parseOptions?{...i.parseOptions,disableChecks:!0}:{disableChecks:!0}:i?.parseOptions??pr,a=t.make;if(a!==void 0&&r!==q){let u;try{u=a(r,o)}catch(p){throw An(Pu(p),"Constructor adapter can only throw schema issues"),p}if(u!==yl&&u!==q)return u}let s=(n??=t.makeEffect)(r,o);return jw(ky(s,r),"Constructor adapter can only throw schema issues")}}var qw=(e)=>qt(e).parser,Vw=(e)=>qt(e).makeEffect;var wl="~effect/Schema/Schema",Cy=Symbol(),zw={[wl]:wl,get make(){let e=vl(this);return Object.defineProperty(this,"make",{value:e,enumerable:!0}),e},get makeEffect(){let e=xl(this);return Object.defineProperty(this,"makeEffect",{value:e,enumerable:!0}),e},get makeOption(){let e=El(this);return Object.defineProperty(this,"makeOption",{value:e,enumerable:!0}),e},pipe(){return ut(this,arguments)},annotate(e){return this.rebuild(gs(this.ast,e))},annotateKey(e){return this.rebuild(pl(this.ast,e))},check(...e){return this.rebuild(Eo(this.ast,e))},rebuild(e){return _l(e,this[Cy])}};function _l(e,t){function n(){}let r=Object.setPrototypeOf(n,zw);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[Cy]=t,r.ast=e,r}var Xr=(e)=>e;var Qr="~effect/Schema/SchemaError";function Ay(e){return Z(e,Qr)&&e[Qr]===Qr}function Ww(){return(e,t,n)=>ue(new yo(e.map(fs),(r)=>t(r.map((i)=>ue(i))),n))}function Jw(e,t){return Ww()([],()=>(n,r,i)=>e(n)?J(n):d(new en(r,n,i)),t)}class _s extends Pa("SchemaError"){[Qr]=Qr;constructor(e){let t=Lr();Mr(0);try{super({issue:e})}finally{Mr(t)}}get message(){return wg(this.issue)}toString(){return`SchemaError(${this.message})`}}function Hw(e){return Ay(e)}function Yw(e){if(oe(e))return Zw(e);return sr(e,(t)=>Zi(()=>In(t,(n)=>new _s(n))))}function Zw(e){return hn(e)?e:Hi(In(e.cause,(t)=>new _s(t)))}function Xw(e,t){let n;for(let r of e.reasons){if(!Va(r)||!Hw(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 Qw(e){let t=cr(e);if(hn(t))return t.value;throw Xw(t.cause,"Sync adapter can only throw schema errors")}var pt=by;function mr(e,t){let n=bl(e,t);return(r,i)=>Yw(n(r,i))}function vt(e,t){let n=wy(e,t);return(r,i)=>zp(n(r,i),(o)=>new _s(o))}function kl(e,t){let n=mr(e,t);return(r,i)=>Qw(n(r,i))}var ue=_l;var re=Xr((e)=>ue(ys(e.ast),{schema:e}));var b=Xr((e)=>{let t=n_(e);return ue(iy(e.ast),{schema:t})});var e_=Xr((e)=>ue(Ss(e.ast),{schema:e}));function Tl(e){let t=ue(new Wr(e),{literal:e,transform(n){return t.pipe(ei(Tl(n),{decode:nt(()=>n),encode:nt(()=>e)}))}});return t}var rt=ue(as),G=ue(nl),t_=ue(rl),S=ue(lr);var ae=ue(il),U=ue(zg);function Py(e,t){return ue(e,{fields:t,mapFields(n,r){let i=n(this.fields);return Py(sl(i,r?.unsafePreserveChecks?this.ast.checks:void 0),i)}})}function y(e){return Py(sl(e,void 0),e)}function Ne(e,t){return ue(sy(e.ast,t.ast),{key:e,value:t})}function te(e,t){return ue(Zg(e.ast,t.map(fs)),{schema:e,records:t})}function Ny(e,t){return ue(e,{elements:t,mapElements(n,r){let i=n(this.elements);return Ny(cl(i,r?.unsafePreserveChecks?this.ast.checks:void 0),i)}})}function Il(e){return Ny(cl(e),e)}var C=Xr((e)=>ue(new ls(!1,[],[e.ast]),{value:e}));function Ly(e,t){return ue(e,{members:t,mapMembers(n,r){let i=n(this.members);return Ly(ps(i,this.ast.options,r?.unsafePreserveChecks?this.ast.checks:void 0),i)}})}function P(e,t){return Ly(ps(e,t,void 0),e)}function x(e){let t=e.map(Tl);return ue(ps(t,void 0,void 0),{literals:e,members:t,mapMembers(n){return P(n(this.members))},pick(n){return x(n)},transform(n){return P(t.map((r,i)=>r.transform(n[i])))}})}var n_=Xr((e)=>P([e,t_]));function hr(e){return(t)=>ue(t.ast,{schema:t,identifier:e})}function ei(e,t){return(n)=>ue(ay(n.ast,e.ast,t?Wu(t):rs()),{from:n,to:e})}function r_(e){return(t)=>ue(oy(t.ast,e),{schema:t})}function i_(e){return sr(e,(t)=>Zi(()=>In(t,(n)=>n.issue)))}function Rl(e,t){let n=t?.encodingStrategy==="omit"?Tg():po();return(r)=>re(e_(r)).pipe(ei(r,{decode:Ig(i_(e)),encode:n}))}function Oy(e){return Tl(e).pipe(r_(J(e)))}function ti(e,t){return Jw((n)=>n instanceof e,t)}function ni(){return(e,t)=>new At(e.ast,Wu(t))}var B=ms;function W(e,t){let{source:n,flags:r}=e,i=/^[dg]*uy?$/.test(r),o=r===""?`new RegExp(${Q(n)})`:`new RegExp(${Q(n)}, ${Q(r)})`;return fl(e,{toJsonSchema:()=>i?{pattern:r.endsWith("y")?`^(?:${n})`:n}:[{},!0],toCode:()=>({runtime:`Schema.isPattern(${o})`}),...t})}function o_(e){let t=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;return W(t,{expected:"a base64 encoded string",representation:{id:"effect/schema/isBase64",payload:null},toJsonSchema:()=>({pattern:t.source}),toCode:()=>({runtime:"Schema.isBase64()"}),...e})}var a_=ue(dl),tn=ll;function s_(e){let t=Ea(e.order),n=e.formatter??Q;return(r,i)=>B((o)=>t(o,r),{expected:`a value greater than ${n(r)}`,arbitraryConstraint:{order:e.order,minimum:r,exclusiveMinimum:!0},...e.annotate?.(r),...i})}function c_(e){let t=jp(e.order),n=e.formatter??Q;return(r,i)=>B((o)=>t(o,r),{expected:`a value greater than or equal to ${n(r)}`,arbitraryConstraint:{order:e.order,minimum:r},...e.annotate?.(r),...i})}function u_(e){let t=$p(e.order),n=e.formatter??Q;return(r,i)=>B((o)=>t(o,r),{expected:`a value less than or equal to ${n(r)}`,arbitraryConstraint:{order:e.order,maximum:r},...e.annotate?.(r),...i})}function Cl(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${Q(e)}`);return e}var Vt=s_({order:$r,annotate:(e)=>({representation:{id:"effect/schema/isGreaterThan",payload:{exclusiveMinimum:Cl(e)}},toJsonSchema:()=>({exclusiveMinimum:e}),toCode:()=>({runtime:`Schema.isGreaterThan(${Q(e)})`})})}),Ln=c_({order:$r,annotate:(e)=>({representation:{id:"effect/schema/isGreaterThanOrEqualTo",payload:{minimum:Cl(e)}},toJsonSchema:()=>({minimum:e}),toCode:()=>({runtime:`Schema.isGreaterThanOrEqualTo(${Q(e)})`})})});var ri=u_({order:$r,annotate:(e)=>({representation:{id:"effect/schema/isLessThanOrEqualTo",payload:{maximum:Cl(e)}},toJsonSchema:()=>({maximum:e}),toCode:()=>({runtime:`Schema.isLessThanOrEqualTo(${Q(e)})`})})});function Mn(e){return B((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 ks=ae.check(Mn());function de(e,t){return e=My(e),l_(e,Math.ceil(e/2),t)}function l_(e,t,n){return B((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})`}),[to]:!0,arbitraryConstraint:{minLength:e},...n})}function Al(e,t){return e=My(e),B((n)=>n.length<=e,{expected:`a value with a length of at most ${e}`,representation:{id:"effect/schema/isMaxLength",payload:{maxLength:e}},toJsonSchema:({type:n})=>n==="string"?e===0?{maxLength:e}:[{maxLength:e},!0]:n==="array"?{maxItems:e}:n===void 0?[{maxLength:e,maxItems:e},!0]:[{},!0],toCode:()=>({runtime:`Schema.isMaxLength(${e})`}),[to]:!0,arbitraryConstraint:{maxLength:e},...t})}function My(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${e}`);return Math.max(0,Math.floor(e))}var dL=ti(globalThis.RegExp,{representation:{id:"effect/schema/RegExp",payload:null},toCode:()=>({runtime:"Schema.RegExp",Type:"globalThis.RegExp"}),expected:"RegExp",toCodecJson:()=>ni()(y({source:S,flags:S}),ho({decode:(e,t)=>ie({try:()=>new globalThis.RegExp(e.source,e.flags),catch:()=>new Ve({expected:"valid RegExp source and flags"},e,t)}),encode:(e)=>J({source:e.source,flags:e.flags})}))}),d_=S.annotate({expected:"a string that will be decoded as a URL"}),fL=ti(globalThis.URL,{representation:{id:"effect/schema/URL",payload:null},toCode:()=>({runtime:"Schema.URL",Type:"globalThis.URL"}),expected:"URL",toCodecJson:()=>ni()(d_,Ng)});var f_=S.annotate({expected:"a string that will be decoded as JSON",contentMediaType:"application/json"});function Ol(e,t){return f_.pipe(ei(e,is(t)))}var p_=ti(globalThis.File,{representation:{id:"effect/schema/File",payload:null},toCode:()=>({runtime:"Schema.File",Type:"globalThis.File"}),expected:"File",toCodecJson:()=>ni()(y({data:S.check(o_()),type:S,name:S,lastModified:ks}),ho({decode:(e,t)=>wa(Qa(e.data),{onFailure:()=>d(new Ve({expected:"a valid Base64 string"},e.data,t)),onSuccess:(n)=>{let r=new globalThis.Uint8Array(n);return J(new globalThis.File([r],e.name,{type:e.type,lastModified:e.lastModified}))}}),encode:(e,t)=>K({try:async()=>{let n=new globalThis.Uint8Array(await e.arrayBuffer());return{data:Xa(n),type:e.type,name:e.name,lastModified:e.lastModified}},catch:()=>new Ve({expected:"a readable File"},e,t)})}))}),pL=ti(globalThis.FormData,{representation:{id:"effect/schema/FormData",payload:null},toCode:()=>({runtime:"Schema.FormData",Type:"globalThis.FormData"}),expected:"FormData",toCodecJson:()=>ni()(C(Il([S,P([y({_tag:Oy("String"),value:S}),y({_tag:Oy("File"),value:p_})])])),ho({decode:(e)=>{let t=new globalThis.FormData;for(let[n,r]of e)t.append(n,r.value);return J(t)},encode:(e)=>J(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 mL=ti(globalThis.URLSearchParams,{representation:{id:"effect/schema/URLSearchParams",payload:null},toCode:()=>({runtime:"Schema.URLSearchParams",Type:"globalThis.URLSearchParams"}),expected:"URLSearchParams",toCodecJson:()=>ni()(S.annotate({expected:"a query string that will be decoded as URLSearchParams"}),Pg({decode:(e)=>new globalThis.URLSearchParams(e),encode:(e)=>e.toString()}))});var Fy=S.annotate({expected:"a string that will be decoded as a finite number"}).pipe(ei(a_,go));var m_=S.annotate({expected:"a base64 encoded string that will be decoded as Uint8Array",format:"byte",contentEncoding:"base64"}),hL=ti(globalThis.Uint8Array,{representation:{id:"effect/schema/Uint8Array",payload:null},toCode:()=>({runtime:"Schema.Uint8Array",Type:"globalThis.Uint8Array"}),expected:"Uint8Array",toCodecJson:()=>ni()(m_,Lg)});var h_=-8640000000000000,g_=8640000000000000,gL=h_+50400000,yL=g_-50400000;var Fn=ue(gs(my,{toCode:()=>({runtime:"Schema.Json",Type:"Schema.Json"})})),ii=Ne(S,Fn);var y_={onExcessProperty:"error"};function it(e,t){return vt(e,y_)(t)}var Uy=/^0\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-(?:0|[1-9]\d*))?$/u,S_=/^0\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-(?:(?:0|[1-9]\d*)|dev\.[1-9]\d*\.[1-9]\d*))?$/u,$y=S.check(W(Uy));function x_(e){let t=vt($y)(e);return Xe(t)?t.success:void 0}function jy(e){return x_(e)!==void 0}function By(e){return typeof e==="string"&&jy(e)&&!e.includes("-")}var E_=S.check(B((e)=>By(e)?void 0:"Expected a canonical base version"));function Dy(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 v_(e){if(typeof e!=="string")return!1;let[t,n,r]=e.split("-");if(t===void 0||n===void 0||r!==void 0)return!1;if(!By(t))return!1;let[i,o,a,s]=n.split(".");return i==="dev"&&s===void 0&&Dy(o)&&Dy(a)}var b_=S.check(B((e)=>v_(e)?void 0:"Expected a development release version")),w_=S.check(W(S_));var Nl=x(["auto-reset","browser_use","computer_use","frontend","session-audit","security","sites"]),__=x(["browser_use","computer_use","sites","session-audit","auto-reset"]),Ll=y({browser_use:U,computer_use:U,sites:U,"session-audit":U.pipe(re,Rl(J(!1))),"auto-reset":U.pipe(re,Rl(J(!1)))}),k_=x(["installed","disabled","missing","uncertain"]),T_=x(["healthy","missing","disabled","uncertain"]),qy=Object.freeze(["openai-curated","openai-curated-remote"]),EL=x(qy),Ml=Object.freeze(["build-web-apps","codex-security"]),vL=x(Ml),Vy=Object.freeze(["browser","computer-use","sites"]),bL=x(Vy);var wt=Object.freeze({coding:!0,computer_use:!1,browser_use:!0,sites:!0,frontend:!0,"session-audit":!1,"auto-reset":!1,security:!0}),bt=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([{skillId:"codex-security:security-diff-scan",appliesWhen:"a bounded implemented change is ready for security review"},{skillId:"codex-security:security-scan",appliesWhen:"a repository or scoped path needs a broader security review"},{skillId:"codex-security:threat-model",appliesWhen:"security architecture or trust boundaries need analysis"}]),computer_use:Object.freeze([]),browser_use:Object.freeze([]),sites:Object.freeze([]),"session-audit":Object.freeze([{skillId:"session-audit",appliesWhen:"the session-audit capability is enabled for the current task"}]),"auto-reset":Object.freeze([{skillId:"auto-reset",appliesWhen:"the auto-reset capability is enabled and quota monitoring detects a threshold"}])}),I_=bt.frontend,R_={frontend:{name:"frontend",pluginIds:["build-web-apps@openai-curated"],defaultSelected:wt.frontend,semanticSkillIds:Object.freeze(bt.frontend.map(({skillId:e})=>e)),applicability:bt.frontend,ownership:"shared-preserve"},security:{name:"security",pluginIds:["codex-security@openai-curated"],defaultSelected:wt.security,semanticSkillIds:bt.security.map(({skillId:e})=>e),applicability:bt.security,ownership:"shared-preserve"},"session-audit":{name:"session-audit",pluginIds:[],defaultSelected:wt["session-audit"],semanticSkillIds:bt["session-audit"].map(({skillId:e})=>e),applicability:bt["session-audit"],ownership:"shared-preserve"},"auto-reset":{name:"auto-reset",pluginIds:[],defaultSelected:wt["auto-reset"],semanticSkillIds:bt["auto-reset"].map(({skillId:e})=>e),applicability:bt["auto-reset"],ownership:"shared-preserve"},computer_use:{name:"computer_use",pluginIds:["computer-use@openai-bundled"],defaultSelected:wt.computer_use,migrationKey:"computer_use",semanticSkillIds:["computer-use:computer-use"],applicability:bt.computer_use,ownership:"shared-preserve"},browser_use:{name:"browser_use",pluginIds:[],defaultSelected:wt.browser_use,migrationKey:"browser_use",semanticSkillIds:[],applicability:bt.browser_use,ownership:"shared-preserve"},sites:{name:"sites",pluginIds:["sites@openai-bundled"],defaultSelected:wt.sites,migrationKey:"sites",semanticSkillIds:[],applicability:bt.sites,ownership:"shared-preserve"}},Pl=Object.freeze(R_),C_=Object.freeze(["browser_use","computer_use","sites","session-audit","auto-reset"]),A_=Object.freeze(["frontend","security"]),O_=Object.freeze([...Pl.frontend.pluginIds,...Pl.security.pluginIds]),P_=Object.freeze(["writing-instructions","babysit-ci","dev-server","visual-loop"]),N_=Object.freeze({browser_use:wt.browser_use,computer_use:wt.computer_use,sites:wt.sites,"session-audit":wt["session-audit"],"auto-reset":wt["auto-reset"]});var Gy=x(["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"]),L_=y({identifier:Gy,label:S,requiresRootApproval:U});function nn(e){return y({identifier:x([e]),label:S,requiresRootApproval:U})}var M_=y({localRepositoryEdit:nn("local.repository.edit"),localRepositoryCheck:nn("local.repository.check"),localRepositoryLint:nn("local.repository.lint"),localRepositoryFormat:nn("local.repository.format"),localRepositoryCommit:nn("local.repository.commit"),externalRead:nn("external.read"),specialistDispatch:nn("specialist.dispatch"),versionControlServerMutation:nn("vcs.server.mutation"),versionControlServerCiTrigger:nn("vcs.server.ci-trigger"),unknownEffect:nn("unknown.effect")}),Fl={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}};Ht(Fl);var F_=x(["never","root"]),Wy=Object.values(Fl);function zy(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 Ky(e){return e.length===0?e:`${e[0]?.toUpperCase()??""}${e.slice(1)}`}var D_=Wy.filter((e)=>!e.requiresRootApproval),U_=Wy.filter((e)=>e.requiresRootApproval),$_=Object.freeze({noRootApproval:`${Ky(zy(D_))} actions do not require Root approval.`,rootApproval:`${Ky(zy(U_))} require Root approval.`});var zt=S.check(W(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),Dl=S.check(W(/^[0-9a-f]{64}$/u)),RL=zt.pipe(hr("RunId")),CL=zt.pipe(hr("ProjectId")),AL=zt.pipe(hr("TrustId")),j_=Dl.pipe(hr("Sha256Digest"));function Ul(e){let t=it(j_,e);if(Ce(t))return ia(oa("sha256 digest",t.failure));return ra(t.success)}var B_=y({run_id:zt,objective_lineage:zt,parent_run_id:b(P([zt,G]))}),q_=y({project_id:zt,trust_id:zt,trust_digest:Dl}),V_=y({project_id:zt,project_digest:Dl}),z_=S.check(W(/^state-[0-9]+\.[0-9]+$/u));var Rs=x(["low","default","high"]),Jy=x(["go","Go","plus-low","plus","plus-high","pro-5x","pro-20x"]),K_=P([Rs,Jy]);var Hy=x(["standard","fast","fast-all"]),G_=x(["low","medium","high"]),Yy="Satisfy the complete requested outcome and acceptance criteria correctly; preserve repository and runtime constraints; 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.",Ts="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.",oi="Do not modify repository source or the implementation under validation; observation, analysis, and proof artifacts only.",rn=Object.freeze({materialDecision:"A choice that changes requirements/accepted behavior, user-facing behavior, architecture/trust boundaries, security posture, persistent/data/API contracts, dependency/toolchain strategy, deployment/external effects, Assignment ownership/scope, or whose reversal would invalidate substantial accepted work.",routineDecision:"A safe reversible choice inside the Assignment that changes none of the material-decision categories.",stableSource:"Every currently planned writer for the seam/revision is terminal and no running Assignment owns an overlapping write that can invalidate dependent evidence.",schedulingIndependent:"Neither action needs the other's output to choose or execute its next action.",writeIndependent:"Write ownership does not overlap and neither Assignment depends on transient mutable state produced by the other.",independentReview:"The reviewer is not the agent whose work is being independently reviewed and does not share ownership that compromises that review.",evidenceInvalidation:"Evidence becomes stale only when a later mutation changes behavior, source/configuration, generated artifact, runtime state, or a dependency assumption established by that evidence.",compatibleWarmReuse:"Reuse is allowed only when the previous specialist is terminal; the same concrete Role.task remains valid; the follow-up fits the same or compatible ownership seam; retained context remains relevant; reuse does not violate independent review; and no conflicting writer is active.",materialVisualDiscrepancy:"A rendered discrepancy affecting acceptance criteria, hierarchy/composition, legibility, accessibility, responsiveness, interaction correctness, reference adherence, or obvious production quality."}),$l=[["Material decision",rn.materialDecision],["Routine decision",rn.routineDecision],["Stable source",rn.stableSource],["Scheduling-independent",rn.schedulingIndependent],["Write-independent",rn.writeIndependent],["Independent review",rn.independentReview],["Evidence invalidation",rn.evidenceInvalidation],["Compatible warm reuse",rn.compatibleWarmReuse],["Material visual discrepancy",rn.materialVisualDiscrepancy]].map(([e,t])=>`${e}: ${t}`).join(" "),W_="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.",J_=x([!1]),Zy=Object.freeze(["implementation","review","validation","integration","vcs"]),H_=x(["read-only","workspace-write"]),Dn=[{role:"Explorer",sharedInstruction:`Keep discovery within the assigned repository scope and return exact paths, symbols, callers, tests, and constraints. ${oi}`,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:`${W_} ${oi}`,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 projected skills appropriate to the work and keep image_generation enabled. Prefer a suitable existing project or user asset, then an online asset legally reusable for the intended use with its required attribution/license provenance, then a generated asset when no reusable asset fits or a generated asset better satisfies the design. Do not search indefinitely when generation is the better implementation choice. Return changed paths and observable rendered/interaction evidence for independent Reviewer.visual review. ${Ts}`,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. ${oi}`,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. ${oi}`,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:"Own reproduction, regression hunting, benchmark methodology and results, missing or ineffective behavioral tests, flaky tests, test architecture, and testing-related behavior defects. Repair concrete in-scope defects and prove the affected behavior. Return material test-strategy and architecture decisions to Root. Add no redundant tests; behavior expectations must come from externally meaningful contracts rather than implementation internals.",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. ${Ts} ${oi}`,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:"Own cross-cutting repository, process, configuration, and integration concerns that have no narrower specialist owner or span multiple categories. Route testing, reproduction, and benchmarks to Reviewer.testing; security and trust-boundary work to Reviewer.security; rendered UI/UX to Reviewer.visual; and implementation correctness to Reviewer.code. Repair concrete in-scope findings 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:"For an implemented change, use `codex-security:security-diff-scan`; for a broader repository scope, use `codex-security:security-scan`; for architecture or trust-boundary analysis, use `codex-security:threat-model`. Apply first-party validation and fix procedures when relevant instead of duplicating them. Hypothetical modeled threats are allowed in threat-model work but are not validated vulnerabilities. Repair validated vulnerabilities within the Assignment and prove the affected behavior. A validated introduced or worsened vulnerability blocks VCS. Return material security, product, architecture, and risk 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}}];Ht(Dn);var NL=new Map(Dn.map((e)=>[e.role,e])),Xy=Dn.flatMap((e)=>e.tasks.map((t)=>`${e.role}:${t.name}`)),Y_=Xy.map((e)=>e.replace(":",".")),jl=x(["Explorer","Librarian","Worker","Reviewer"]),Qy=x(["map","lookup","trace"]),eS=x(["lookup","research"]),tS=x(["mechanical","implementation","visual","integration","operations","validation","debugging"]),nS=x(["code","testing","visual","artifact","audit","security"]),wo=P([y({role:x(["Explorer"]),task:Qy}),y({role:x(["Librarian"]),task:eS}),y({role:x(["Worker"]),task:tS}),y({role:x(["Reviewer"]),task:nS})]),Bl=x(["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"]),rS=x(["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"]),_o=Object.freeze(Xy.map((e)=>kl(Bl)(e))),Cs=Object.freeze(Y_.map((e)=>kl(rS)(e))),Z_=`Execute only the bounded Assignment using its objective, scope, constraints, dependencies, permissions, ownership, and acceptance criteria; make routine in-scope choices autonomously. Return material decisions, scope expansion, or required user input to Root; never ask or message the user. Do not delegate, mutate Intent or Assignment lifecycle, perform Git/VCS writes, or cause consequential external effects unless the Assignment explicitly grants an allowed effect. Stay within the owned mutable seam, preserve unrelated and concurrent work, and adapt to shared-tree changes. Root owns user interaction, lifecycle, material decisions, integration acceptance, completion, Git/VCS writes, consequential external effects, final visual judgment, and the shared development server. ${$l}`;var iS=Object.freeze(["default","worker","explorer","reviewer","librarian"]);var oS=y({profile:Rs,service_tier:b(Hy)}),Is=Object.freeze(["user_interaction","intent","material_decisions","orchestration_lifecycle","integration_acceptance","completion","git_vcs","external_effects","visual_judgment","dev_server"]),X_=x([...Is]),Q_=x(["delegated","root_direct","unavailable"]),ek=x([...Is]),ql=x(["used","no_coverage","unavailable","auth_or_quota_failure","source_conflict"]),aS=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}),tk=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}),nk=/\b(?:libraries?|frameworks?|sdks?|apis?|clis?|cloud[ _-]?services?|packages?|dependencies?|technical|documentation|docs?|context7)\b/iu,rk=/\b(?:historical|history|legacy|archived?|past)\b/iu;function Vl(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 nk.test(t)&&!rk.test(t)}var ik=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:Ts,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"])}),ok=Object.freeze({interactiveCapabilitiesRemainSpecialistOwned:!0,rootMayInspectForVisualJudgment:!0,credentialEntryAndSubmissionRemainUserOwned:!0,specialistsMustNeverHandleCredentials:!0,missingAuthorizedPathIsCapabilityBlocker:!0}),ak=Object.freeze({threatModelForMaterialTrustBoundaryChanges:!0,securityDiffScanRequiredForSecuritySensitiveDiffs:!0,fullScanOnlyForAuditNewExposedSurfaceOrSystemicConcern:!0,validateSupportedFindingsBeforeBlocking:!0,introducedOrWorsenedValidatedVulnerabilityBlocksVcs:!0,preExistingUnrelatedFindingsDoNotExpandScope:!0,securityEditsInvalidateCodeReview:!0,securitySensitiveCodeReviewEditsInvalidateSecurityReview:!0,materialDecisionsRemainRootOwned:!0}),sk=Object.freeze({requiresDelegation:!0,explicitUserDirectExecutionOverridesDelegation:!1,assignmentStartAndDispatchPrecedeDelegableExecution:!0,trivialWorkRequiresDelegation:!0,preparatoryAndExploratoryWorkRequiresDelegation:!0,genericDirectWorkFallback:!1,concreteSpecialistDispatchRequired:!0,registeredSpecialistAgentTypes:Cs,roleFamiliesAreLabelsOnly:!0,forbiddenGenericAgentTypes:iS,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:Is,rootOwnedAuthority:Is,requestUserInputGates:Object.freeze(["missing_authorization_for_consequential_effect","missing_or_ambiguous_correctness_input_unresolvable_from_authorized_context"]),dependencyAwareAmbiguityInstruction:"When required information is missing, continue actions whose correctness is independent of it and do not perform speculative work whose validity depends on the answer. Ask only when missing or ambiguous information affects correctness and cannot be resolved from authorized context, or authorization for a consequential external effect is missing.",surgicalMutationRule:Yy,phaseOrder:Zy,phaseGates:Object.freeze({implementedScopeStableBeforeReview:!0,reviewerCodeAndWorkerValidationMayOverlapOnNonConflictingScopes:!0,currentValidationBeforeRootIntegration:!0,rootIntegrationBeforeVcs:!0}),initialDispatch:Object.freeze({independentAssignments:!0,substantiveIndependentConcurrency:!0,routinePostdispatchSteering:!1,waitIncludesEveryLiveBlockingSpecialist:!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,terminalReuseStateIncludes:Object.freeze(["agent_id","concrete Role.task","owned seam and write scope","terminal outcome","reusable status"])}),normalSpawnForkContext:!1,normalSpawnRequiresExplicitRegisteredAgentType:!0,normalSpawnUsesConcreteRegisteredAgentType:!0,normalSpawnModelOverride:!1,normalSpawnEffortOverride:!1,orchestrationToolNamespace:"multi_agent_v1",orchestrationToolOperations:Object.freeze(["spawn_agent","send_input","wait_agent","resume_agent","close_agent"]),orchestrationToolsDirectOnly:!0,toolSearchRemainsAvailableForDeferredCapabilities:!0,v1UsageHintText:"HolyCodex Root delegates all delegable work to exact registered HolyCodex Role.task agent types. For normal spawns use fork_context=false; do not override the selected route's model or effort. Dispatch all ready independent Assignments before waiting. Follow the HolyCodex exact wait contract. Root does not perform delegable fallback work.",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,semanticDefinitionsInstruction:$l,normalProgressMessages:!1,normalHeartbeatMessages:!1,normalIntermediateEvidence:!1,userUpdatesUsefulOrImportantOnly:!0,routinePerToolOrSubagentNarrationForbidden:!0,routineStatusOnlyChatterForbidden:!0,fixedCadenceUserUpdatesForbidden:!0,materialUserUpdateKinds:Object.freeze(["changes_a_root_decision","changes_the_expected_user_visible_outcome","user_input_is_required","authorized_progress_is_blocked","user_relevant_release_or_completion_milestone"]),outOfBoundaryRequiresNewAssignment:!0,rootWaitTool:"multi_agent_v1.wait_agent",rootWaitTimeoutMs:600000,specialistCoordinationInstruction:"Coordinate through terminal reports, not conversation. After dispatch, do not inspect, message, poll, request status from, or follow up with a running specialist. Interrupt or supersede only when changed user intent, cancellation, or Assignment invalidation makes continued work incorrect. Never sleep or busy-poll for specialist coordination. Dispatch every ready scheduling-independent Assignment before waiting. Each multi_agent_v1.wait_agent call must include every live specialist whose result blocks the next required Root decision or action and use timeout_ms=600000 exactly; terminal completion may wake it early. If the timeout expires while a blocking dependency remains live, perform ready independent work and then wait again with timeout_ms=600000. After a terminal result, prefer compatible warm reuse only when the exact predicate allows it: send_input for immediate follow-up on an open agent, close_agent with no near-term follow-up, or resume_agent then send_input for later reuse after closure. Keep Root turns for judgment, decisions, orchestration boundaries, integration, contradictions, and completion.",rootWaitRequiresExactTimeout:!0,earlySpecialistCompletionWakesWait:!0,waitIncludesEveryLiveBlockingSpecialist:!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(["agent_id","concrete Role.task","owned seam and write scope","terminal outcome","reusable status","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:aS,codeReviewRequiredForImplementation:!0,codeReviewRequiredBeforeVcs:!0,externalVerificationMustBeTerminal:!0,postVcsFlow:"discover_topology_observe_repair_repeat"});var sS=x(["blocked","completed","failed","partial"]),ck=P([x(["high"]),G]),uk=P([x(["high","max","xhigh"]),G]),cS=Fn,lk=ii,dk=y({blocked:U,changed_files:C(S),confidence:ae,context_owner:P([S,G]),material_findings:C(S),needs_more_context:U,needs_root_decision:U,needs_verification:U,relevant_files:C(S),remaining_risk:C(S),reuse_recommended:U,status:sS,suggested_followup:P([S,G]),suggested_luna_effort:uk,suggested_specialist:P([jl,G]),verification:C(S),verification_passed:U}),zl="holycodex-specialist-outcome-2",Le=S.check(de(1)),ai=y({state:ql,evidence:C(Le).check(de(1)),library:b(Le),version:b(Le)}),ko={protocol_version:x([zl]),route:wo,evidence:C(Le),context7:b(ai)},fk=y(ko),pk=y({...ko,status:x(["completed"]),summary:Le}),mk=y({...ko,status:x(["blocked"]),reason:Le,needs_root_decision:U}),hk=y({...ko,status:x(["partial"]),summary:Le,completed:C(Le),remaining:C(Le),needs_root_decision:U}),gk=y({...ko,status:x(["failed"]),error:Le}),yk=P([pk,mk,hk,gk]),As={protocol_version:x([zl]),capability:Nl,route:P([wo,G]),evidence:C(Le),context7:b(ai),data:cS},Sk=y({...As,status:x(["completed"]),summary:Le}),xk=y({...As,status:x(["blocked"]),reason:Le,needs_root_decision:U}),Ek=y({...As,status:x(["partial"]),summary:Le,completed:C(Le),remaining:C(Le),needs_root_decision:U}),vk=y({...As,status:x(["failed"]),error:Le}),bk=P([Sk,xk,Ek,vk]);var uS=C(S),lS=S.check(W(/^[a-z][a-z0-9-]*(?: [a-z][a-z0-9-]*)*$/u)),dS=x([gi]),wk=y({code:zt,message:S,details:lk}),fS=y({schema_version:dS,ok:x([!0]),command:lS,data:cS,warnings:uS}),pS=y({schema_version:dS,ok:x([!1]),command:lS,error:wk,warnings:uS}),_k=P([fS,pS]);var Os="gpt-6.1-sol",To="gpt-6-luna";function kk(e,t,n){return{key:`${e}:${t}`,role:e,task:t,model:To,effort:n}}var Tk=new Set(_o),Gl=[{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"}}];Ht(Gl);var Ik=new Map(Gl.map((e)=>[e.profile,e]));function Rk(e){let t=Ik.get(e);if(t===void 0)throw new ct("catalog_invalid","A profile has no route effort policy.",{profile:e});return Dn.flatMap((n)=>n.tasks.map((r)=>{let i=`${n.role}:${r.name}`,o=t.efforts[i];if(o===void 0)throw new ct("catalog_invalid","A route effort policy is incomplete.",{profile:e,route:i});return kk(n.role,r.name,o)}))}function Kl(e){return{name:e.name,root:{model:e.rootModel,effort:e.rootEffort},specialistModel:To,defaultServiceTier:"standard",routes:Rk(e.name)}}var Wl=[Kl({name:"low",rootModel:Os,rootEffort:"low"}),Kl({name:"default",rootModel:Os,rootEffort:"medium"}),Kl({name:"high",rootModel:Os,rootEffort:"medium"})];function Ck(e){let t=["low","default","high"];if(e.length!==t.length)throw new ct("catalog_invalid","The profile catalog has an invalid size.");for(let n=0;n<t.length;n+=1){let r=e[n],i=t[n];if(!r||r.name!==i)throw new ct("catalog_invalid","The profile catalog order is invalid.",{index:n});let o=Os,a=i==="low"?"low":"medium";if(r.root.model!==o||r.root.effort!==a||r.specialistModel!==To)throw new ct("catalog_invalid","A profile has an invalid model route.",{profile:r.name});if(r.routes.length!==_o.length)throw new ct("catalog_invalid","A profile is incomplete.",{profile:r.name});let s=new Set;for(let u of r.routes){if(s.has(u.key)||!Tk.has(u.key)||u.model!==To||`${u.role}:${u.task}`!==u.key)throw new ct("catalog_invalid","A profile contains an invalid route.",{profile:r.name});s.add(u.key)}if(s.size!==_o.length)throw new ct("catalog_invalid","A profile is missing a specialist route.",{profile:r.name})}}Ck(Wl);Ht(Wl);var mS=Wl,Ak=new Map,Ok=new Map;for(let e of mS){Ak.set(e.name,e);let t=new Map;for(let n of e.routes)t.set(n.key,n);Ok.set(e.name,t)}function Jl(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 i=Object.getOwnPropertyDescriptor(e,String(r));if(!i||!i.enumerable||!("value"in i)||!Jl(i.value,n))return!1}return Object.getOwnPropertyNames(e).every((r)=>{if(r==="length")return!0;let i=Number(r),o=Object.getOwnPropertyDescriptor(e,r);return Number.isInteger(i)&&i>=0&&i<e.length&&String(i)===r&&o!==void 0&&o.enumerable&&"value"in o})}if(Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null||Object.getOwnPropertySymbols(e).length>0)return!1;return Object.getOwnPropertyNames(e).every((r)=>{let i=Object.getOwnPropertyDescriptor(e,r);return i!==void 0&&i.enumerable&&"value"in i&&Jl(i.value,n)})}var HL=Fn.check(B((e)=>Jl(e))),YL=S.check(de(1),W(/^[^\0]+$/u));import{execFile as Nk}from"child_process";import{createHash as Lk,randomBytes as Mk}from"crypto";import{lstat as Pt,mkdir as ui,open as Us,readFile as nd,readdir as vn,realpath as Fk,rename as Dk,rm as xr,stat as Uk}from"fs/promises";import{basename as Hl,dirname as Er,isAbsolute as $k,join as T,relative as td,resolve as li}from"path";import{promisify as jk}from"util";var $s="holycodex-intent-1",rd="holycodex-plan-1",id="holycodex-assignment-1",$n="toon-4",M=S.check(B((e)=>e.trim().length>0)),Me=S.check(W(/^[a-z0-9][a-z0-9-]{0,95}$/u)),js=S.check(W(/^[a-f0-9]{64}$/u)),wS=S.check(W(/^[a-f0-9]{40}$/u)),di=ks.check(Ln(1)),Nt=S.check(B((e)=>!Number.isNaN(Date.parse(e)))),me=C(M),Bk=y({pid:ks.check(Vt(0)),token:M}),qk=120000,Vk=4294967295,Bs=y({role:x(["Explorer","Librarian","Worker","Reviewer"]),task:M}).check(B((e)=>Dn.some((t)=>t.role===e.role&&t.tasks.some((n)=>n.name===e.task)))),br=y({kind:x(["changed_path","check","repository_fact","ci","behavior","uncertainty"]),value:M,result:b(x(["passed","failed","observed","unknown"]))}),od=y({root:M,git_common_dir:M,initial_head:M,expected_head:M,expected_changes:me,expected_status_digest:js,integrated_commit:b(wS),updated_at:Nt}),fi=x(["scoping","ready","executing","verifying","reviewing","blocked","needs_root_input","complete","abandoned"]),zk=x(["scoping","ready","executing","verifying","reviewing"]),hS=y({required:U,status:x(["not_required","missing","passed","failed","accepted","rejected"]),evidence:C(br)}),vr=y({schema_version:x([$s]),toon_compatibility:x([$n]),id:Me,slug:Me,title:M,goal:M,acceptance_criteria:me,state:fi,revision:di,plan_required:U,active_plan_revision:b(di),active_plan_digest:b(js),blockers:me,resume_state:b(zk),verification:hS,review:hS,acceptance_met:U,root_readiness:U,evidence:C(br),baseline:od,created_at:Nt,updated_at:Nt}),Co=y({schema_version:x([rd]),toon_compatibility:x([$n]),intent_id:Me,revision:di,predecessor_digest:b(js),approach:M,scope:me,exclusions:me,assignments:me,dependencies:me,architecture:me,risks:me,assumptions:me,open_questions:me,verification:me,recovery:me,updated_at:Nt}),ad=x(["completed","blocked","needs_root_input","failed"]),_S=x(["pending","executing","completed","blocked","needs_root_input","failed","superseded"]),sd=y({id:Me,outcome:ad,started_at:Nt,finished_at:Nt,summary:M,evidence:C(br),context7:b(ai),blocker:b(M),remaining_risk:me}),qn=js,cd={schema_version:x([id]),toon_compatibility:x([$n]),intent_id:Me,id:Me,objective:M,owner:P([Bs,y({role:x(["Reviewer"]),task:x(["plan"])})]),scope:me,constraints:me,exclusions:me,dependencies:me,acceptance_criteria:me,status:_S,revision:di,invocations:C(sd),active_invocation_id:b(M),active_started_at:b(Nt),supersedes:b(Me),superseded_by:b(Me),supersession_reason:b(M),supersession_provenance:b(M),evidence:C(br),blocker:b(M),remaining_risk:me,created_at:Nt,updated_at:Nt},ud=y(cd),kS=y({...cd,capability:qn}),Ao=y({...cd,active_invocation_capability_verifier:b(qn),active_invocation_capability:b(qn)}),Ps=".holycodex-transaction.toon",TS="holycodex-work-state-transaction-1",gS=y({schema_version:x([TS]),state:x(["prepared","committed"]),files:C(y({path:M,previous:S,next:S})).check(de(1))}),IS=y({schema_version:x(["holycodex-intent-0"]),id:Me,slug:Me,title:M,goal:M,acceptance_criteria:me,state:fi,revision:di,baseline:od,created_at:Nt,updated_at:Nt});class _ extends Error{code;details;constructor(e,t,n={}){super(t);this.name="IntentStoreError",this.code=e,this.details=n}}var qs=y({title:M,goal:M,acceptanceCriteria:C(M).check(de(1)),planRequired:b(U),verificationRequired:b(U),reviewRequired:b(U)}),RS=y({approach:M,scope:b(C(M)),exclusions:b(C(M)),assignments:b(C(M)),dependencies:b(C(M)),architecture:b(C(M)),risks:b(C(M)),assumptions:b(C(M)),openQuestions:b(C(M)),verification:b(C(M)),recovery:b(C(M))}),Vs=y({id:b(M),objective:M,owner:Bs,scope:C(M).check(de(1)),constraints:b(C(M)),exclusions:b(C(M)),dependencies:b(C(M)),acceptanceCriteria:C(M).check(de(1))}),zs=y({scope:C(M).check(de(1))}),Ks=y({scope:b(C(M).check(de(1)))}),Gs=y({replacementId:Me,replacementRevision:b(di),reason:M,provenance:M}),Ws=y({commit:wS}),No=y({invocationId:b(M),capability:b(qn),outcome:ad,startedAt:b(M),summary:M,scope:b(C(M).check(de(1))),evidence:b(C(br)),context7:b(ai),blocker:b(M),remainingRisk:b(C(M))}),Kk=y({invocationId:M,startedAt:Nt,capability:qn,interruptionReason:M}),Js=y({evidence:b(C(br)),verification:b(x(["passed","failed"])),review:b(x(["accepted","rejected"])),acceptanceMet:b(U),rootReadiness:b(U),clearBlockers:b(U)}),Lo=jk(Nk);class Hs{repositoryRoot;stateRoot;#e;diagnose(e){let t=this;return f(function*(){yield*t.#s();let n=yield*O(()=>vn(t.stateRoot)).pipe(F(()=>!0,(m)=>f(function*(){if(H(m,"ENOENT"))return yield*d(new _("not_found","Intent was not found.",{reference:e}));return yield*d(se(m))}))),r=[];for(let m of n.sort()){let h=T(t.stateRoot,m);if(!(yield*Ro(h))||!(yield*ci(T(h,"intent.toon"))))continue;let R;if((yield*f(function*(){return R=yield*nT(T(h,"intent.toon")),{kind:"none"}}).pipe(j((A)=>d(A))).pipe(F(()=>!0,(A)=>f(function*(){if(Oo(A)){if(m===e||A.code!=="not_found"&&(yield*rT(T(h,"intent.toon"),e)))return yield*d(A);return{kind:"continue"}}return yield*d(A)})))).kind==="continue")continue;if([R.id,R.slug,m].includes(e))r.push({directory:h,intent:R})}if(r.length!==1)return yield*d(new _(r.length?"current_ambiguous":"not_found",r.length?"Intent reference is ambiguous.":"Intent was not found.",{reference:e}));let{directory:i,intent:o}=r[0],a=[],s=(m,h,R)=>{a.push({code:m,subject:h,repair:R})},u=T(i,Ps);{let m=yield*f(function*(){let h=yield*O(()=>Pt(u));if(h.isSymbolicLink()||!h.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.");return{kind:"none"}}).pipe(j((h)=>d(h))).pipe(F(()=>!0,(h)=>f(function*(){if(!H(h,"ENOENT")&&!H(h,"ENOTDIR"))return yield*d(se(h));return{kind:"none"}})))}let p=T(i,"plan.toon"),c,l=!1;{let m=yield*f(function*(){return c=yield*tT(p,Co),{kind:"none"}}).pipe(j((h)=>d(h))).pipe(F(()=>!0,(h)=>f(function*(){if(!Oo(h))return yield*d(h);return l=!0,s("plan_unreadable","plan","Repair the canonical Plan record before continuing."),{kind:"none"}})))}if(c!==void 0){let m=Kt(`${Ue(c)}
|
|
30
|
+
`);if(c.intent_id!==o.id||o.active_plan_revision!==c.revision||o.active_plan_digest!==m)s("plan_provenance_mismatch","plan","Reconcile the canonical Plan and Intent provenance.")}else if(!l&&(o.active_plan_revision!==void 0||o.active_plan_digest!==void 0))s("stale_plan_reference","intent","Restore or reconcile the referenced Plan.");let g=T(i,"assignments"),v=[];{let m=yield*f(function*(){if(yield*Ql(g,!0))v=(yield*O(()=>vn(g))).filter((h)=>h.endsWith(".toon")).sort();return{kind:"none"}}).pipe(j((h)=>d(h))).pipe(F(()=>!0,(h)=>f(function*(){if(!Oo(h))return yield*d(h);return s("assignment_directory_invalid","assignments","Restore the Assignments directory as a real repository-local directory."),{kind:"none"}})))}let w=[];for(let m of v){let h;if((yield*f(function*(){return h=yield*Sr(T(g,m),Ao),{kind:"none"}}).pipe(j((I)=>d(I))).pipe(F(()=>!0,(I)=>f(function*(){if(!Oo(I))return yield*d(I);return s("assignment_unreadable",m,"Repair this Assignment record before continuing."),{kind:"continue"};return{kind:"none"}})))).kind==="continue")continue;if(h.intent_id!==o.id||m!==`${h.id}.toon`){s("assignment_identity_mismatch",m,"Reconcile the Assignment identity and path.");continue}w.push(h)}let k=new Map(w.map((m)=>[m.id,m]));for(let m of w){let h=`assignment:${m.id}`,R=m.active_invocation_id,I=R!==void 0,A=I||m.active_started_at!==void 0||m.active_invocation_capability!==void 0||m.active_invocation_capability_verifier!==void 0;if(m.status==="executing"&&!I)s("missing_active_invocation",h,"Reconcile the executing Assignment's invocation.");if(m.status!=="executing"&&A)s("orphaned_active_invocation",h,"Reconcile the active invocation and Assignment status.");if(I&&m.active_started_at===void 0)s("missing_invocation_start",h,"Reconcile the active invocation start time.");let V=new Set;for(let Y of m.invocations){if(V.has(Y.id))s("duplicate_invocation_id",h,"Reconcile duplicate invocation records.");V.add(Y.id)}if(R!==void 0&&V.has(R))s("active_invocation_reused",h,"Reconcile the active invocation identity.");if(m.status==="superseded"&&m.superseded_by===void 0)s("missing_replacement",h,"Record or reconcile the replacement Assignment.");if(m.superseded_by!==void 0){let Y=k.get(m.superseded_by);if(m.superseded_by===m.id||Y?.supersedes!==m.id||m.status!=="superseded")s("stale_supersession",h,"Reconcile both ends of the supersession relation.");else if(m.supersession_reason===void 0||m.supersession_provenance===void 0||Y.supersession_reason===void 0||Y.supersession_provenance===void 0)s("supersession_metadata_missing",h,"Record the reason and provenance on both Assignments.");else if(m.supersession_reason!==Y.supersession_reason||m.supersession_provenance!==Y.supersession_provenance)s("supersession_metadata_mismatch",h,"Reconcile the reason and provenance on both Assignments.")}if(m.supersedes!==void 0&&(m.supersedes===m.id||k.get(m.supersedes)?.superseded_by!==m.id))s("stale_predecessor",h,"Reconcile the predecessor Assignment reference.");for(let Y of m.dependencies)if(Y===m.id)s("self_dependency",h,"Remove the Assignment's dependency on itself.");else if(Y.startsWith("assignment-")&&!k.has(Y))s("stale_dependency",h,`Reconcile missing dependency ${Y}.`);else if(k.get(Y)?.status==="superseded")s("superseded_dependency",h,`Reconcile dependency ${Y} with its replacement Assignment.`);let z=m.invocations.at(-1);if(m.status==="completed"){if(z?.outcome!=="completed"||z.evidence.length===0&&z.context7===void 0)s("completion_evidence_missing",h,"Reconcile the completed invocation result and its evidence.")}else if(["blocked","needs_root_input","failed"].includes(m.status)&&z?.outcome!==m.status)s("assignment_result_mismatch",h,"Reconcile the status with its latest result.");if(["blocked","needs_root_input"].includes(m.status)&&m.blocker===void 0)s("assignment_blocker_missing",h,"Record the Assignment's current blocker.");if(m.status==="pending"&&m.invocations.length>0)s("pending_assignment_has_history",h,"Reconcile pending status with its results.");if(!["completed","superseded"].includes(m.status))s("assignment_unresolved",h,o.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 m of c.assignments)if(m.startsWith("assignment-")&&!k.has(m))s("stale_plan_assignment","plan",`Reconcile missing Assignment ${m}.`);else if(k.get(m)?.status==="superseded")s("superseded_plan_assignment","plan",`Reconcile Plan reference ${m} with its replacement Assignment.`)}let E=iT(w);for(let m of E)s("dependency_cycle",`assignment:${m}`,"Remove the cyclic Assignment dependency before continuing.");if(o.state==="complete"&&w.some((m)=>!["completed","superseded"].includes(m.status)))s("terminal_intent_with_unresolved_work","intent","Reconcile terminal state and unfinished Assignments.");if(o.state==="complete"&&w.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"||!SS(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.")}{let m=yield*f(function*(){return yield*t.#i(o,w.filter((h)=>h.status==="executing").flatMap((h)=>h.scope)),{kind:"none"}}).pipe(j((h)=>d(h))).pipe(F(()=>!0,(h)=>f(function*(){if(!(h instanceof _)||h.code!=="repository_drift")return yield*d(h);return s("repository_drift","repository","Reconcile the recorded baseline with the current repository state."),{kind:"none"}})))}return a.sort((m,h)=>Xl(m.subject,h.subject)||Xl(m.code,h.code)||Xl(m.repair,h.repair)),{intent_id:o.id,issues:a}})}#a;constructor(e,t={}){this.repositoryRoot=li(e),this.stateRoot=T(this.repositoryRoot,".holycodex"),this.#e=t.now??(()=>new Date);let n=t.repositorySnapshot;this.#a=n===void 0?()=>Gk(this.repositoryRoot):()=>Ka(()=>{let r=n();return sg(r)?r:O(()=>Promise.resolve(r))})}recover(){let e=this;return f(function*(){if(yield*e.#s(),!(yield*Ls(e.stateRoot)))return[];return yield*yr(T(e.stateRoot,".intent-store"),()=>f(function*(){let t=yield*e.#u(e.stateRoot),n=yield*e.#h();return[...t,...n].sort()}))})}#u(e,t=!1){let n=this;return f(function*(){let r;{let o=yield*f(function*(){return r=t?yield*O(()=>vn(e,{recursive:!0})):yield*O(()=>vn(e)),{kind:"none"}}).pipe(j((a)=>d(a))).pipe(F(()=>!0,(a)=>f(function*(){if(H(a,"ENOENT"))return{kind:"return",value:[]};return yield*d(se(a))})));if(o.kind==="return")return o.value}let i=[];for(let o of r){let a=Hl(o);if(!a.startsWith(".holycodex-write-")||!a.endsWith(".tmp"))continue;let s=T(e,o);yield*Bn(s),yield*O(()=>xr(s,{force:!0})),i.push(td(n.stateRoot,s).replaceAll("\\","/"))}return i.sort()})}#h(){let e=this;return f(function*(){let t;{let r=yield*f(function*(){return t=yield*O(()=>vn(e.stateRoot)),{kind:"none"}}).pipe(j((i)=>d(i))).pipe(F(()=>!0,(i)=>f(function*(){if(H(i,"ENOENT"))return{kind:"return",value:[]};return yield*d(se(i))})));if(r.kind==="return")return r.value}let n=[];for(let r of t){if(r===".intent-store")continue;let i=T(e.stateRoot,r);if(!(yield*Ro(i)))continue;yield*yr(T(i,".intent-store"),()=>f(function*(){n.push(...yield*e.#l(i))}))}return n.sort()})}#l(e){let t=this;return f(function*(){let n=[],r=T(e,Ps);if(yield*t.#f(e))n.push(td(t.stateRoot,r).replaceAll("\\","/"));return n.push(...yield*t.#u(e,!0)),n})}#f(e){let t=this;return f(function*(){let n=T(e,Ps);yield*Bn(n);let r;{let c=yield*f(function*(){return r=yield*O(()=>Pt(n)),{kind:"none"}}).pipe(j((l)=>d(l))).pipe(F(()=>!0,(l)=>f(function*(){if(H(l,"ENOENT"))return{kind:"return",value:!1};return yield*d(se(l))})));if(c.kind==="return")return c.value}if(r.isSymbolicLink()||!r.isFile())return yield*d(new _("schema_invalid","The work-state transaction journal must be a regular file.",{path:n}));let i=yield*Sr(n,gS),o=i.files.filter((c)=>jn(c.path)==="intent.toon"),a=i.files.filter((c)=>{let l=jn(c.path);return l!==void 0&&/^assignments\/[a-z0-9][a-z0-9-]{0,95}\.toon$/u.test(l)});if(i.files.length<2||o.length!==1||a.length<1||o.length+a.length!==i.files.length)return yield*d(new _("schema_invalid","The work-state transaction must pair one or more Assignments with their Intent.",{path:n}));let s=new Set,u=yield*cg(i.files,(c)=>f(function*(){let l=jn(c.path);if(l===void 0)return yield*d(new _("schema_invalid","The work-state transaction contains an invalid target path.",{path:n,target:c.path}));let g=vS(e,c.path);if(s.has(g))return yield*d(new _("schema_invalid","The work-state transaction has duplicate targets.",{path:n,target:c.path}));s.add(g);let v=i.state==="committed"?c.next:c.previous,w=l==="intent.toon"?yield*bS(v,vr,g):yield*bS(v,Ao,g);return{canonical:l,target:g,contents:v,record:w}})),p=u.find((c)=>c.canonical==="intent.toon")?.record?.id;if(p===void 0)return yield*d(new _("schema_invalid","The work-state transaction has no Intent.",{path:n}));for(let c of u)if(yield*Bn(c.target),c.canonical!=="intent.toon"){let l=c.canonical.slice(12,-5);ed(c.record,p,l,c.target)}for(let c of u)yield*Po(c.target,c.contents);return yield*O(()=>xr(n,{force:!0})),yield*Ds(e),!0})}#s(){let e=this;return f(function*(){{let t=yield*f(function*(){let n=yield*O(()=>Pt(e.stateRoot));if(n.isSymbolicLink()||!n.isDirectory())return yield*d(new _("schema_invalid","Repository-local work state must be a real directory.",{path:e.stateRoot}));return{kind:"none"}}).pipe(j((n)=>d(n))).pipe(F(()=>!0,(n)=>f(function*(){if(H(n,"ENOENT"))return{kind:"return",value:void 0};return yield*d(se(n))})));if(t.kind==="return")return t.value}})}createIntent(e){let t=this;return f(function*(){let n=ee(qs,e);if(!n.title.trim()||!n.goal.trim()||n.acceptanceCriteria.length===0)return yield*d(at("Intent title, goal, and acceptance criteria are required."));return yield*t.recover(),yield*O(()=>ui(t.stateRoot,{recursive:!0})),yield*yr(T(t.stateRoot,".intent-store"),()=>f(function*(){let r=yield*t.#a(),i=Zk(n.title),o=Kt([r.root,n.title.trim(),n.goal.trim()].join("\x00")).slice(0,10),a=`${i}-${o}`,s=1;while(yield*Ls(T(t.stateRoot,a)))s+=1,a=`${i}-${o}-${String(s).padStart(2,"0")}`;let u=`intent-${o}${s===1?"":`-${String(s).padStart(2,"0")}`}`,p=t.#e().toISOString(),c=ee(vr,{schema_version:$s,toon_compatibility:$n,id:u,slug:i,title:n.title.trim(),goal:n.goal.trim(),acceptance_criteria:[...n.acceptanceCriteria],state:"scoping",revision:1,plan_required:n.planRequired??!1,blockers:[],verification:Ms(n.verificationRequired??!0),review:Ms(n.reviewRequired??!0),acceptance_met:!1,root_readiness:!1,evidence:[],baseline:Yl(r,p),created_at:p,updated_at:p}),l=T(t.stateRoot,a);return yield*O(()=>ui(T(l,"assignments"),{recursive:!0})),yield*ot(T(l,"intent.toon"),c),yield*Po(T(t.stateRoot,"current"),`${a}
|
|
31
|
+
`),c}))})}listIntents(){let e=this;return f(function*(){if(yield*e.#s(),!(yield*Ls(e.stateRoot)))return[];return yield*yr(T(e.stateRoot,".intent-store"),()=>f(function*(){yield*e.#u(e.stateRoot);let t;{let r=yield*f(function*(){return t=yield*O(()=>vn(e.stateRoot)),{kind:"none"}}).pipe(j((i)=>d(i))).pipe(F(()=>!0,(i)=>f(function*(){if(H(i,"ENOENT"))return{kind:"return",value:[]};return yield*d(se(i))})));if(r.kind==="return")return r.value}let n=[];for(let r of t.sort()){if(r===".intent-store")continue;let i=T(e.stateRoot,r);if(!(yield*Ro(i)))continue;yield*yr(T(i,".intent-store"),()=>f(function*(){yield*e.#l(i);let o=T(i,"intent.toon");if(yield*ci(o))n.push(yield*e.#t(o))}))}return n.sort((r,i)=>r.id.localeCompare(i.id))}))})}readIntent(e){let t=this;return f(function*(){let n=yield*t.#n(e);return yield*t.#r(n,()=>f(function*(){return yield*t.#t(T(n,"intent.toon"))}))})}currentIntent(){let e=this;return f(function*(){yield*e.#s(),yield*e.recover();let t=T(e.stateRoot,"current"),n=yield*O(()=>Pt(t)).pipe(F(()=>!0,(o)=>f(function*(){if(H(o,"ENOENT"))return;return yield*d(se(o))})));if(n?.isSymbolicLink()||n&&!n.isFile())return yield*d(new _("schema_invalid","The current Intent pointer must be a regular file."));let r=n?(yield*O(()=>nd(t,"utf8"))).trim():"";if(n&&!r)return yield*d(new _("schema_invalid","The current Intent pointer must select a work-state directory."));if(r){let o=li(e.stateRoot,r);if(!NS(e.stateRoot,o))return yield*d(new _("schema_invalid","The current Intent pointer escapes repository-local state.",{directory:r}));if(!(yield*Ro(o)))return yield*d(new _("schema_invalid","The current Intent pointer does not select a work-state directory.",{directory:r}));return yield*e.#r(o,()=>f(function*(){return yield*e.#t(T(o,"intent.toon"))}))}let i=(yield*e.listIntents()).filter((o)=>o.state!=="complete"&&o.state!=="abandoned");if(i.length===1)return i[0];return yield*d(new _(i.length?"current_ambiguous":"not_found",i.length?"Multiple active Intents require explicit selection.":"No current Intent exists.",{intent_ids:i.map((o)=>o.id)}))})}selectCurrent(e){let t=this;return f(function*(){let n=yield*t.#n(e),r=yield*t.#t(T(n,"intent.toon"));return yield*yr(T(t.stateRoot,".intent-store"),()=>f(function*(){return yield*Po(T(t.stateRoot,"current"),`${Hl(n)}
|
|
32
|
+
`)})),r})}transitionIntent(e,t,n,r){let i=this;return f(function*(){let o=ee(fi,t),a=r===void 0?void 0:ee(M,r);if(!Number.isSafeInteger(n)||n<1)return yield*d(at("Intent revision must be a positive integer."));let s=yield*i.#n(e);return yield*i.#r(s,()=>f(function*(){let u=yield*i.#t(T(s,"intent.toon"));if(mt(u.revision,n),o==="complete")return yield*d(new _("invalid_transition","Use the predicate-checked complete operation."));if(o==="abandoned")return yield*i.#m(s,u);return yield*i.#g(s,u,o,a)}))})}completeIntent(e,t){let n=this;return f(function*(){let r=yield*n.#n(e);return yield*n.#r(r,()=>f(function*(){let i=yield*n.#t(T(r,"intent.toon"));if(mt(i.revision,t),En(i),yield*n.#i(i),i.active_plan_revision!==void 0)yield*n.readPlan(e);let o=yield*n.#c(r,i),a=[];if(i.state!=="reviewing")a.push("intent_not_reviewing");if(i.blockers.length)a.push("global_blockers_unresolved");if(o.length===0)a.push("assignment_required");if(o.some((u)=>u.status!=="completed"&&u.status!=="superseded"))a.push("assignments_unresolved");if(i.verification.required&&i.verification.status!=="passed")a.push("verification_unresolved");if(i.review.required&&i.review.status!=="accepted")a.push("review_unresolved");if(!i.acceptance_met)a.push("acceptance_criteria_unmet");if(!i.root_readiness)a.push("root_readiness_missing");if(a.length)return{completed:!1,reasons:a};let s=xn(i,n.#e,{state:"complete"});return yield*ot(T(r,"intent.toon"),s),s}))})}abandonIntent(e,t){let n=this;return f(function*(){let r=yield*n.#n(e);return yield*n.#r(r,()=>f(function*(){let i=yield*n.#t(T(r,"intent.toon"));return mt(i.revision,t),yield*n.#m(r,i)}))})}recordIntentEvidence(e,t,n){let r=this;return f(function*(){let i=ee(Js,n),o=yield*r.#n(e);return yield*r.#r(o,()=>f(function*(){let a=yield*r.#t(T(o,"intent.toon"));if(mt(a.revision,t),En(a),i.verification!==void 0||i.review!==void 0)yield*r.#i(a);if(i.verification!==void 0&&a.state!=="verifying")return yield*d(new _("invalid_transition","Verification evidence is only accepted while the Intent is verifying.",{state:a.state}));let s=[...a.verification.evidence,...i.evidence??[]];if(i.verification==="passed"&&!SS(s))return yield*d(new _("invalid_input","Verification cannot pass without meaningful successful check or behavioral evidence.",{required_evidence:["check","behavior","ci"]}));if(i.review!==void 0&&a.state!=="reviewing")return yield*d(new _("invalid_transition","Review evidence is only accepted while the Intent is reviewing.",{state:a.state}));let u=[...a.evidence,...i.evidence??[]],p=i.verification===void 0?a.verification:{...a.verification,status:i.verification,evidence:[...a.verification.evidence,...i.evidence??[]]},c=i.review===void 0?a.review:{...a.review,status:i.review,evidence:[...a.review.evidence,...i.evidence??[]]},l=i.review==="rejected"&&a.state==="reviewing"?"executing":a.state,g=xn(a,r.#e,{state:l,evidence:u,verification:p,review:c,...i.acceptanceMet===void 0?{}:{acceptance_met:i.acceptanceMet},...i.rootReadiness===void 0?{}:{root_readiness:i.rootReadiness},...i.clearBlockers?{blockers:[]}:{}});return yield*ot(T(o,"intent.toon"),g),g}))})}recordVcsIntegration(e,t,n){let r=this;return f(function*(){let i=ee(Ws,n),o=yield*r.#n(e);return yield*r.#r(o,()=>f(function*(){let a=yield*r.#t(T(o,"intent.toon"));if(mt(a.revision,t),En(a),a.state!=="reviewing")return yield*d(new _("invalid_transition","VCS integration is only accepted after review while the Intent is reviewing.",{state:a.state}));if(a.review.required&&a.review.status!=="accepted")return yield*d(new _("not_ready","VCS integration requires accepted review evidence.",{review_status:a.review.status}));let s=yield*r.#a();if(s.root!==a.baseline.root||s.gitCommonDir!==a.baseline.git_common_dir)return yield*d(new _("repository_drift","VCS integration repository identity does not match the Intent baseline.",{expected_root:a.baseline.root,actual_root:s.root}));if(s.head!==i.commit)return yield*d(new _("repository_drift","VCS integration requires the requested commit to be the current HEAD.",{expected_head:i.commit,actual_head:s.head}));if(s.changedPaths.length)return yield*d(new _("repository_drift","VCS integration requires a clean worktree.",{changed_paths:[...s.changedPaths].sort()}));let u=yield*Wk(r.repositoryRoot,i.commit);if(u.parents[0]!==a.baseline.expected_head)return yield*d(new _("repository_drift","VCS integration commit parent does not match the recorded baseline HEAD.",{expected_parent:a.baseline.expected_head,actual_parents:u.parents}));let p=yield*Jk(r.repositoryRoot,a.baseline.expected_head,i.commit),c=[...new Set(Zl(a.baseline.expected_changes,p))].sort();if(p.join("\x00")!==c.join("\x00"))return yield*d(new _("repository_drift","VCS integration commit tree does not match the recorded expected change set.",{expected_changes:c,actual_changes:p}));let l=r.#e().toISOString(),g={kind:"repository_fact",value:`Root VCS integration recorded at ${i.commit}; ${String(p.length)} expected path(s) committed.`,result:"observed"},v=xn(a,r.#e,{baseline:Yl(s,l,a.baseline.initial_head,i.commit),evidence:[...a.evidence,g]});return yield*ot(T(o,"intent.toon"),v),v}))})}readPlan(e){let t=this;return f(function*(){let n=yield*t.#n(e),r=T(n,"plan.toon");if(!(yield*ci(r)))return;let i=yield*Sr(r,Co),o=yield*t.#t(T(n,"intent.toon")),a=Kt(`${Ue(i)}
|
|
33
|
+
`);if(i.intent_id!==o.id||o.active_plan_revision!==i.revision||o.active_plan_digest!==a)return yield*d(new _("schema_invalid","Canonical Plan provenance does not match its Intent.",{intent_id:o.id,plan_revision:i.revision}));return i})}revisePlan(e,t,n,r){let i=this;return f(function*(){let o=ee(RS,t);if(!o.approach.trim())return yield*d(at("Plan approach is required."));let a=yield*i.#n(e);return yield*i.#r(a,()=>f(function*(){let s=yield*i.#t(T(a,"intent.toon"));mt(s.revision,n),En(s),yield*i.#i(s);let u=T(a,"plan.toon"),p=(yield*ci(u))?yield*Sr(u,Co):void 0;if(p===void 0&&r!==void 0)mt(0,r);if(p!==void 0)mt(p.revision,r);let c,l;if(p){let k=`${Ue(p)}
|
|
34
|
+
`;l=Kt(k),c=yield*uT(a),yield*oT(c,k)}let g=ee(Co,{schema_version:rd,toon_compatibility:$n,intent_id:s.id,revision:(p?.revision??0)+1,...l?{predecessor_digest:l}:{},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:i.#e().toISOString()});yield*ot(u,g);let v=Kt(`${Ue(g)}
|
|
35
|
+
`),w=xn(s,i.#e,{active_plan_revision:g.revision,active_plan_digest:v,verification:si(s.verification),review:si(s.review),acceptance_met:!1,root_readiness:!1});return yield*ot(T(a,"intent.toon"),w),{intent:w,plan:g,...c?{archived:Hl(c)}:{}}}))})}createAssignment(e,t,n){let r=this;return f(function*(){let i=ee(Vs,t);if(!i.objective.trim()||i.scope.length===0||i.acceptanceCriteria.length===0)return yield*d(at("Assignment objective, scope, and acceptance criteria are required."));let o=Fs(i.scope),a=yield*r.#n(e);return yield*r.#r(a,()=>f(function*(){let s=yield*r.#t(T(a,"intent.toon"));if(mt(s.revision,n),En(s),yield*r.#i(s,o),i.owner.role==="Worker"&&i.owner.task==="operations"&&s.baseline.integrated_commit!==s.baseline.expected_head)return yield*d(new _("not_ready","Worker.operations requires a successfully integrated exact commit.",{expected_head:s.baseline.expected_head}));let u=i.id??`assignment-${Kt([s.id,i.objective,...o].join("\x00")).slice(0,10)}`;if(!/^[a-z0-9][a-z0-9-]{0,95}$/u.test(u))return yield*d(at("Assignment id is invalid."));let p=T(a,"assignments",`${u}.toon`);if(yield*Ls(p))return yield*d(new _("already_exists","Assignment already exists.",{id:u}));let c=r.#e().toISOString(),l=ee(ud,{schema_version:id,toon_compatibility:$n,intent_id:s.id,id:u,objective:i.objective.trim(),owner:i.owner,scope:o,constraints:[...i.constraints??[]],exclusions:[...i.exclusions??[]],dependencies:[...i.dependencies??[]],acceptance_criteria:[...i.acceptanceCriteria],status:"pending",revision:1,invocations:[],evidence:[],remaining_risk:[],created_at:c,updated_at:c});return yield*O(()=>ui(Er(p),{recursive:!0})),yield*ot(p,l),l}))})}reviseAssignmentScope(e,t,n,r){let i=this;return f(function*(){let o=ee(zs,n),a=Fs(o.scope),s=ee(Me,t),u=yield*i.#n(e);return yield*i.#r(u,()=>f(function*(){let p=yield*i.#t(T(u,"intent.toon"));En(p);let c=yield*i.#o(u,p,s);if(mt(c.revision,r),c.status==="completed"||c.status==="superseded")return yield*d(new _("invalid_transition","A completed or superseded Assignment cannot have its scope revised."));let l=Io(c,i.#e,{scope:a});return yield*ot(T(u,"assignments",`${s}.toon`),l),gr(l)}))})}supersedeAssignment(e,t,n,r){let i=this;return f(function*(){let o=ee(Gs,r),a=ee(Me,t),s=yield*i.#n(e);return yield*i.#r(s,()=>f(function*(){let u=yield*i.#t(T(s,"intent.toon"));if(En(u),u.acceptance_met||u.root_readiness||u.review.status==="accepted")return yield*d(new _("invalid_transition","Accepted Intent evidence cannot be superseded.",{intent_id:u.id}));let p=yield*i.#o(s,u,a);mt(p.revision,n);let c=yield*i.#o(s,u,o.replacementId);if(o.replacementRevision!==void 0)mt(c.revision,o.replacementRevision);if(c.id===p.id)return yield*d(at("An Assignment cannot supersede itself."));if(p.status==="completed"||p.status==="superseded")return yield*d(new _("invalid_transition","Only unfinished, non-superseded Assignments may be replaced.",{assignment_id:p.id,status:p.status}));if(p.status==="executing")return yield*d(new _("invalid_transition","An executing Assignment must record its active invocation before supersession.",{assignment_id:p.id}));if(p.superseded_by!==void 0)return yield*d(new _("invalid_transition","An Assignment with an existing replacement cannot be superseded again.",{assignment_id:p.id,replacement_id:p.superseded_by}));if(c.status==="completed"||c.status==="executing"||c.status==="superseded")return yield*d(new _("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*d(new _("invalid_transition","An Assignment already participating in a supersession cannot be reused.",{assignment_id:c.id}));if(!p.scope.some((E)=>c.scope.some((m)=>Un(E,m)||Un(m,E))))return yield*d(at("A supersession replacement must overlap the predecessor bounded scope."));let g=yield*i.#c(s,u);yield*i.#i(u,[...p.scope,...c.scope,...g.filter((E)=>E.status==="executing").flatMap((E)=>E.scope)]);let v=Io(p,i.#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:o.reason.trim(),supersession_provenance:o.provenance.trim()}),w=Io(c,i.#e,{supersedes:p.id,supersession_reason:o.reason.trim(),supersession_provenance:o.provenance.trim()}),k=xn(u,i.#e,{state:u.blockers.length===0&&["blocked","needs_root_input","verifying","reviewing"].includes(u.state)?"executing":u.state,blockers:[...u.blockers],...u.blockers.length===0?{resume_state:void 0}:{},verification:si(u.verification),review:si(u.review),acceptance_met:!1,root_readiness:!1,evidence:[...u.evidence,{kind:"behavior",value:`Assignment ${p.id} superseded by ${c.id}: ${o.reason.trim()} (${o.provenance.trim()})`,result:"observed"}]});return yield*i.#p(s,[{path:`assignments/${p.id}.toon`,previous:`${Ue(p)}
|
|
36
|
+
`,next:`${Ue(v)}
|
|
37
|
+
`},{path:`assignments/${c.id}.toon`,previous:`${Ue(c)}
|
|
38
|
+
`,next:`${Ue(w)}
|
|
39
|
+
`},{path:"intent.toon",previous:`${Ue(u)}
|
|
40
|
+
`,next:`${Ue(k)}
|
|
41
|
+
`}]),{assignment:gr(v),replacement:gr(w),intent:k}}))})}readAssignment(e,t){let n=this;return f(function*(){let r=ee(Me,t),i=yield*n.#n(e);return yield*n.#r(i,()=>f(function*(){let o=yield*n.#t(T(i,"intent.toon"));return gr(yield*n.#o(i,o,r))}))})}isLegacyExecutingAssignment(e,t){let n=this;return f(function*(){let r=ee(Me,t),i=yield*n.#n(e);return yield*n.#r(i,()=>f(function*(){let o=yield*n.#t(T(i,"intent.toon")),a=yield*n.#o(i,o,r);return a.status==="executing"&&a.active_invocation_capability_verifier===void 0&&a.active_invocation_capability===void 0}))})}#o(e,t,n){let r=this;return f(function*(){let i=T(e,"assignments");yield*Ql(i,!0);let o=T(i,`${n}.toon`);if(!(yield*ci(o)))return yield*d(new _("not_found","Assignment was not found.",{assignment_id:n}));let a=yield*Sr(o,Ao);return ed(a,t.id,n,o),a})}listAssignments(e){let t=this;return f(function*(){let n=yield*t.#n(e);return yield*t.#r(n,()=>f(function*(){return(yield*t.#c(n,yield*t.#t(T(n,"intent.toon")))).map(gr)}))})}#c(e,t){let n=this;return f(function*(){let r=T(e,"assignments");if(!(yield*Ql(r,!0)))return[];let i;{let a=yield*f(function*(){return i=yield*O(()=>vn(r)),{kind:"none"}}).pipe(j((s)=>d(s))).pipe(F(()=>!0,(s)=>f(function*(){if(H(s,"ENOENT"))return{kind:"return",value:[]};return yield*d(se(s))})));if(a.kind==="return")return a.value}return yield*za(i.filter((a)=>a.endsWith(".toon")).sort().map((a)=>f(function*(){let s=T(r,a),u=yield*Sr(s,Ao),p=a.slice(0,-5);return ed(u,t.id,p,s),u})))})}startAssignment(e,t,n,r={}){let i=this;return f(function*(){let o=ee(Ks,r),a=ee(Me,t),s=yield*i.#n(e);return yield*i.#r(s,()=>f(function*(){let u=yield*i.#t(T(s,"intent.toon"));En(u);let p=yield*i.#o(s,u,a);if(mt(p.revision,n),!Xe(vt(Bs)(p.owner)))return yield*d(at("This Assignment owner is retired; supersede it with a current route."));let c=ES(p.scope,o.scope);if(yield*i.#i(u,c),p.status==="completed")return yield*d(new _("invalid_transition","A completed Assignment cannot be restarted."));if(p.status==="superseded")return yield*d(new _("invalid_transition","A superseded Assignment cannot be restarted.",{assignment_id:p.id}));if(p.status==="executing")return yield*d(new _("invalid_transition","Assignment is already executing; record its active invocation result first.",{assignment_id:p.id,...p.active_invocation_id?{invocation_id:p.active_invocation_id}:{}}));let l=i.#e().toISOString(),g=xS(p),v=Yk(),w=Io(p,i.#e,{status:"executing",scope:c,blocker:void 0,active_invocation_id:g,active_started_at:l,active_invocation_capability_verifier:Kt(v),active_invocation_capability:void 0});return yield*ot(T(s,"assignments",`${a}.toon`),w),ee(kS,{...gr(w),capability:v})}))})}recordAssignmentResult(e,t,n,r){let i=this;return f(function*(){return yield*i.#d(e,t,n,r,!1)})}recordSpecialistAssignmentResult(e,t,n,r){let i=this;return f(function*(){if(ee(No,r).capability===void 0)return yield*d(at("Specialist Assignment results require an active invocation capability."));return yield*i.#d(e,t,n,r,!0)})}recoverInterruptedAssignment(e,t,n,r){let i=this;return f(function*(){let o=ee(Kk,r),a=o.interruptionReason.trim(),s={kind:"behavior",value:`Interrupted invocation ${o.invocationId} started at ${o.startedAt} recovered as failed: ${a}`,result:"failed"};return yield*i.#d(e,t,n,{invocationId:o.invocationId,capability:o.capability,outcome:"failed",startedAt:o.startedAt,summary:`Interrupted invocation recovered as failed: ${a}`,evidence:[s]},!0,{invocationId:o.invocationId,startedAt:o.startedAt})})}#d(e,t,n,r,i,o){let a=this;return f(function*(){let s=ee(No,r),u=ee(Me,t),p=yield*a.#n(e);return yield*a.#r(p,()=>f(function*(){let c=yield*a.#t(T(p,"intent.toon"));if(En(c),o!==void 0&&e!==c.id)return yield*d(at("Interruption recovery requires the exact Intent ID reference."));let l=yield*a.#o(p,c,u);if(mt(l.revision,n),l.status!=="executing")return yield*d(new _("invalid_transition",`Assignment result requires an executing Assignment; current status is ${l.status}.`,{assignment_id:l.id,status:l.status}));if(o===void 0&&!i&&s.capability===void 0&&(l.active_invocation_capability_verifier!==void 0||l.active_invocation_capability!==void 0))return yield*d(new _("invalid_transition","This Assignment invocation requires its active capability to record a result.",{assignment_id:l.id}));if(o!==void 0){if(l.active_invocation_id!==o.invocationId||l.active_started_at!==o.startedAt)return yield*d(new _("invalid_transition","Interruption recovery does not match the active invocation identity and start time.",{assignment_id:l.id,expected_invocation_id:l.active_invocation_id,expected_started_at:l.active_started_at}))}if(l.active_invocation_id!==void 0&&s.invocationId!==void 0&&l.active_invocation_id!==s.invocationId)return yield*d(new _("invalid_transition","Assignment result does not match the active invocation.",{assignment_id:l.id,expected_invocation_id:l.active_invocation_id,actual_invocation_id:s.invocationId}));if(i&&(l.active_invocation_id===void 0||s.invocationId===void 0))return yield*d(new _("invalid_transition",o===void 0?"Specialist Assignment results require the active invocation identity.":"Interruption recovery requires the active invocation identity.",{assignment_id:l.id}));if(i&&l.active_invocation_capability_verifier===void 0&&l.active_invocation_capability===void 0)return yield*d(new _("invalid_transition",o===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:l.id}));if(s.capability!==void 0&&(l.active_invocation_capability_verifier!==void 0?Kt(s.capability)!==l.active_invocation_capability_verifier:l.active_invocation_capability!==s.capability))return yield*d(new _("invalid_transition","Assignment result capability does not match the active invocation.",{assignment_id:l.id}));if((s.outcome==="blocked"||s.outcome==="needs_root_input")&&!s.blocker?.trim())return yield*d(at("Blocked results require a local blocker."));if(o===void 0&&Vl({role:l.owner.role,task:l.owner.task,objective:l.objective,scope:l.scope,constraints:l.constraints,exclusions:l.exclusions,dependencies:l.dependencies,acceptanceCriteria:l.acceptance_criteria})&&s.context7===void 0)return yield*d(new _("invalid_input","This Librarian Assignment result requires typed Context7 evidence.",{assignment_id:l.id,required_evidence:"context7"}));let g=ES(l.scope,s.scope),v=yield*a.#a(),w=Zl(c.baseline.expected_changes,v.changedPaths),k=[...s.evidence??[]],E=new Set(k.filter((le)=>le.kind==="changed_path").map((le)=>le.value)),m=[...E].filter((le)=>!g.some((hi)=>Un(le,hi)));if(m.length)return yield*d(new _("repository_drift","Assignment evidence declares paths outside its bounded scope.",{assignment_id:l.id,out_of_scope_paths:m.sort()}));let R=(yield*a.#c(p,c)).filter((le)=>le.id!==l.id&&le.status==="executing"),I=v.changedPaths.filter((le)=>R.some((hi)=>hi.scope.some((gx)=>Un(le,gx)))),A=new Set(I),V=new Set([...w,...E,...I]),z=v.changedPaths.filter((le)=>!V.has(le)),Y=new Set(w),Ee=v.changedPaths.filter((le)=>g.some((hi)=>Un(le,hi))&&!Y.has(le)&&!E.has(le)&&!A.has(le)),_t=v.root!==c.baseline.root||v.gitCommonDir!==c.baseline.git_common_dir,Ge=yS(v.statusDigest)!==c.baseline.expected_status_digest,We=v.head!==c.baseline.expected_head||Ge||[...new Set(w)].sort().join("\x00")!==[...new Set(v.changedPaths)].sort().join("\x00"),Mt=[...E].some((le)=>v.changedPaths.includes(le)),Je=I.length>0;if(o===void 0&&(_t||z.length||Ee.length||Ge&&!Mt&&!Je||v.head!==c.baseline.expected_head&&!Mt&&!Je))return yield*d(new _("repository_drift","Repository state changed outside the recorded Assignment result.",{expected_head:c.baseline.expected_head,actual_head:v.head,unexpected_paths:[...new Set([...z,...Ee])].sort(),concurrent_assignments:R.map((le)=>le.id).sort()}));let ac=a.#e().toISOString(),sc=l.active_invocation_id??s.invocationId??xS(l);if(l.invocations.some((le)=>le.id===sc))return yield*d(new _("already_exists","Assignment invocation already exists.",{invocation_id:sc}));let fx=ee(sd,{id:sc,outcome:s.outcome,started_at:l.active_started_at??s.startedAt??ac,finished_at:ac,summary:s.summary,evidence:k,...s.context7===void 0?{}:{context7:s.context7},...s.blocker?{blocker:s.blocker}:{},remaining_risk:[...s.remainingRisk??[]]}),xf=Io(l,a.#e,{status:s.outcome,scope:g,invocations:[...l.invocations,fx],active_invocation_id:void 0,active_started_at:void 0,active_invocation_capability_verifier:void 0,active_invocation_capability:void 0,evidence:[...l.evidence,...k],blocker:s.blocker,remaining_risk:[...s.remainingRisk??[]]}),Ef=l.owner.role==="Worker"&&l.owner.task==="operations",vf=c.baseline.integrated_commit!==void 0&&c.baseline.integrated_commit===c.baseline.expected_head&&v.head===c.baseline.expected_head&&v.changedPaths.length===0,px=Ef&&s.outcome==="failed",mx=Ef&&s.outcome==="completed"&&vf&&c.state==="reviewing"&&(!c.verification.required||c.verification.status==="passed")&&(!c.review.required||c.review.status==="accepted"),hx=We||s.outcome==="failed",bf=xn(c,a.#e,{baseline:o===void 0?Yl(v,ac,c.baseline.initial_head,vf?c.baseline.integrated_commit:void 0):c.baseline,...mx||!hx?{}:{state:px?"executing":c.state,verification:si(c.verification),review:si(c.review),acceptance_met:!1,root_readiness:!1}});return yield*a.#y(p,u,l,xf,c,bf),{assignment:gr(xf),intent:bf}}))})}#g(e,t,n,r){let i=this;return f(function*(){let o=t.state;if(n==="blocked"||n==="needs_root_input"){if(["complete","abandoned","blocked","needs_root_input"].includes(o))return yield*d(Ns(o,n));if(!r?.trim())return yield*d(at("A blocker or required input is required."));let s=xn(t,i.#e,{state:n,blockers:[r.trim()],resume_state:o});return yield*ot(T(e,"intent.toon"),s),s}if(o==="blocked"||o==="needs_root_input"){if(n!==t.resume_state||t.blockers.length)return yield*d(Ns(o,n))}else if(!{scoping:["ready"],ready:["executing"],executing:["verifying"],verifying:["reviewing","executing"],reviewing:["executing"]}[o]?.includes(n))return yield*d(Ns(o,n));if(n==="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:yield*i.readPlan(t.id))?.open_questions.length)s.push("material_open_questions");if(s.length)return yield*d(new _("not_ready","Intent readiness predicates failed.",{reasons:s}))}if(n==="executing"&&o==="ready")yield*i.#i(t);if(n==="reviewing"&&t.verification.required&&t.verification.status!=="passed")return yield*d(new _("invalid_transition","Verification must pass before review."));if(n==="reviewing")yield*i.#i(t);let a=xn(t,i.#e,{state:n,resume_state:void 0});return yield*ot(T(e,"intent.toon"),a),a})}#r(e,t){let n=this;return f(function*(){return yield*yr(T(e,".intent-store"),()=>f(function*(){return yield*n.#l(e),yield*t()}))})}#y(e,t,n,r,i,o){let a=this;return f(function*(){yield*a.#p(e,[{path:`assignments/${t}.toon`,previous:`${Ue(n)}
|
|
42
|
+
`,next:`${Ue(r)}
|
|
43
|
+
`},{path:"intent.toon",previous:`${Ue(i)}
|
|
44
|
+
`,next:`${Ue(o)}
|
|
45
|
+
`}])})}#p(e,t){let n=this;return f(function*(){let r=T(e,Ps),i=ee(gS,{schema_version:TS,state:"prepared",files:t.map((a)=>({...a}))}),o=i.files.map((a)=>vS(e,a.path));yield*ot(r,i);{let a=yield*f(function*(){for(let[s,u]of o.entries())yield*Po(u,i.files[s].next);return yield*ot(r,{...i,state:"committed"}),{kind:"none"}}).pipe(j((s)=>d(s))).pipe(F(()=>!0,(s)=>f(function*(){{let u=yield*f(function*(){return yield*n.#f(e),{kind:"none"}}).pipe(j((p)=>d(p))).pipe(F(()=>!0,(p)=>f(function*(){return yield*d(se(p))})))}return yield*d(s)})))}yield*O(()=>xr(r,{force:!0})),yield*Ds(e)})}#m(e,t){let n=this;return f(function*(){if(t.state==="complete"||t.state==="abandoned")return yield*d(Ns(t.state,"abandoned"));let r=xn(t,n.#e,{state:"abandoned",blockers:[]});return yield*ot(T(e,"intent.toon"),r),r})}#i(e,t){let n=this;return f(function*(){let r=yield*n.#a(),i=[...Zl(e.baseline.expected_changes,r.changedPaths)].sort(),o=[...r.changedPaths].sort(),a=new Set(t===void 0?[]:o.filter((u)=>t.some((p)=>Un(u,p)))),s=[...new Set([...i,...a])].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")||yS(r.statusDigest)!==e.baseline.expected_status_digest&&a.size===0)return yield*d(new _("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}))})}#n(e){let t=this;return f(function*(){yield*t.#s();let n;{let i=yield*f(function*(){return n=yield*O(()=>vn(t.stateRoot)),{kind:"none"}}).pipe(j((o)=>d(o))).pipe(F(()=>!0,(o)=>f(function*(){if(H(o,"ENOENT"))return yield*d(new _("not_found","Intent was not found.",{reference:e}));return yield*d(se(o))})))}let r=[];for(let i of n.sort()){let o=T(t.stateRoot,i);if(!(yield*Ro(o)))continue;let a=T(o,"intent.toon");if(!(yield*ci(a)))continue;let s=yield*t.#t(a);if(s.id===e||s.slug===e||i===e)r.push(o)}if(r.length===1)return r[0];if(r.length>1)return yield*d(new _("current_ambiguous","Intent reference is ambiguous.",{reference:e}));return yield*d(new _("not_found","Intent was not found.",{reference:e}))})}#t(e){let t=this;return f(function*(){let n=yield*Ys(e),r=it(vr,n);if(Xe(r))return r.success;let i=it(IS,n);if(Ce(i))return yield*d(new _("schema_invalid","Persisted Intent failed schema validation.",{path:e,error:String(r.failure)}));let o=CS(i.success);return yield*ot(e,o),o})}}function Gk(e){return f(function*(){let t=yield*O(()=>Fk(e)),n=(...p)=>f(function*(){{let c=yield*f(function*(){return{kind:"return",value:(yield*O(()=>Lo("git",["-C",t,...p],{encoding:"utf8"}))).stdout.trimEnd()}}).pipe(j((l)=>d(l))).pipe(F(()=>!0,(l)=>f(function*(){return yield*d(new _("io_failure","Repository identity requires an accessible Git worktree.",{message:l instanceof Error?l.message:String(l)}))})));if(c.kind==="return")return c.value}}),r=yield*n("rev-parse","--git-common-dir"),i=(yield*Hk(t,"rev-parse","--verify","HEAD"))??"unborn",o=yield*n("status","--porcelain=v1","-z","--untracked-files=all"),a=yield*n("status","--porcelain=v1","--untracked-files=all"),s=o.split("\x00"),u=[];for(let p=0;p<s.length;p+=1){let c=s[p];if(!c)continue;if(u.push(c.slice(3)),c.slice(0,2).includes("R")||c.slice(0,2).includes("C"))p+=1}return u.sort(),{root:t,gitCommonDir:li(t,r),head:i,changedPaths:u,statusDigest:Kt(a)}})}function Wk(e,t){return f(function*(){{let n=yield*f(function*(){let r=(yield*O(()=>Lo("git",["-C",e,"show","-s","--format=%H%n%P",t],{encoding:"utf8"}))).stdout.trim(),[i,o=""]=r.split(`
|
|
46
|
+
`);if(i!==t)return yield*d(Error(`Resolved commit ${i??""} does not match requested ${t}.`));return{kind:"return",value:{hash:i,parents:o?o.split(/\s+/u):[]}}}).pipe(j((r)=>d(r))).pipe(F(()=>!0,(r)=>f(function*(){return yield*d(new _("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 Jk(e,t,n){return f(function*(){{let r=yield*f(function*(){return{kind:"return",value:(yield*O(()=>Lo("git",["-C",e,"diff","--name-only","-z","--no-ext-diff",t,n],{encoding:"utf8"}))).stdout.split("\x00").filter(Boolean).sort()}}).pipe(j((i)=>d(i))).pipe(F(()=>!0,(i)=>f(function*(){return yield*d(new _("repository_drift","VCS integration commit tree could not be inspected.",{parent:t,commit:n,message:i instanceof Error?i.message:String(i)}))})));if(r.kind==="return")return r.value}})}function Hk(e,...t){return f(function*(){{let n=yield*f(function*(){return{kind:"return",value:(yield*O(()=>Lo("git",["-C",e,...t],{encoding:"utf8"}))).stdout.trim()}}).pipe(j((r)=>d(r))).pipe(F(()=>!0,(r)=>f(function*(){return{kind:"return",value:void 0}})));if(n.kind==="return")return n.value}})}function CS(e){return ee(vr,{...e,schema_version:$s,toon_compatibility:$n,plan_required:!1,blockers:[],verification:Ms(!0),review:Ms(!0),acceptance_met:!1,root_readiness:!1,evidence:[]})}function Ms(e){return{required:e,status:e?"missing":"not_required",evidence:[]}}function si(e){return{...e,status:e.required?"missing":"not_required"}}function Yl(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:Kt(e.statusDigest),...r===void 0?{}:{integrated_commit:r},updated_at:t}}function yS(e){return/^[a-f0-9]{64}$/u.test(e)?e:Kt(e)}function SS(e){return e.some((t)=>["check","behavior","ci"].includes(t.kind)&&["passed","observed"].includes(t.result??""))}function Yk(){return Mk(32).toString("hex")}function xS(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 xn(e,t,n){return ee(vr,AS({...e,...n,revision:e.revision+1,updated_at:t().toISOString()}))}function Io(e,t,n){return ee(Ao,AS({...e,...n,revision:e.revision+1,updated_at:t().toISOString()}))}function gr(e){let{active_invocation_capability_verifier:t,active_invocation_capability:n,...r}=e;return ee(ud,r)}function AS(e){let t={...e};for(let[n,r]of Object.entries(t))if(r===void 0)delete t[n];return t}function Zk(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=jn(n);if(r===void 0)throw at("Assignment scope must contain canonical repository-relative paths.");return r});return[...new Set(t)].sort()}function ES(e,t){let n=Fs(e);if(t===void 0)return n;let r=Fs(t);if(n.some((o)=>!r.includes(o)))throw at("Assignment scope expansion must preserve the existing scope.");if(r.filter((o)=>!n.some((a)=>Xk(o,a))).length)throw at("Assignment scope expansion exceeds the declared component authority.");return r}function Xk(e,t){if(Un(e,t))return!0;let n=jn(t);if(n===void 0||n===".")return!1;let r=n.split("/"),i=r.at(-1);if(i===void 0||!i.includes("."))return!1;let o=r.slice(0,-1).join("/")||".";return e!==o&&Un(e,o)}function Un(e,t){let n=jn(e),r=jn(t);if(n===void 0||r===void 0)return!1;return r==="."||n===r||n.startsWith(`${r}/`)}function jn(e){let t=e.replaceAll("\\","/");if(!t||t.startsWith("/")||/^[a-z]:/iu.test(t))return;let n=t.split("/");if(n.some((i)=>i===".."))return;let r=n.filter((i)=>i!==""&&i!==".");return r.length===0?".":r.join("/")}function vS(e,t){let n=jn(t);if(n===void 0||n!=="intent.toon"&&!/^assignments\/[a-z0-9][a-z0-9-]{0,95}\.toon$/u.test(n))throw new _("schema_invalid","The work-state transaction target is outside the supported Intent records.",{path:t});let r=li(e,n);if(!NS(li(e),r))throw new _("schema_invalid","The work-state transaction target escapes the Intent directory.",{path:t});return r}function Zl(e,t){let n=new Set(t);return e.map((r)=>{if(n.has(r))return r;let i=eT(r);return i!==void 0&&n.has(i)?i:r})}var Qk={a:7,b:8,t:9,n:10,v:11,f:12,r:13,"\\":92,'"':34};function eT(e){if(e.length<2||e[0]!=='"'||e[e.length-1]!=='"')return;let t=[],n=new TextEncoder,r=e.slice(1,-1);for(let o=0;o<r.length;){let a=r.codePointAt(o);if(a===void 0)return;if(a!==92){if(a===34||a<32||a===127)return;let c=String.fromCodePoint(a);t.push(...n.encode(c)),o+=c.length;continue}let s=r[o+1];if(s===void 0)return;let u=Qk[s];if(u!==void 0){t.push(u),o+=2;continue}if(s<"0"||s>"7")return;let p=o+2;while(p<r.length&&p<o+4&&r[p]>="0"&&r[p]<="7")p+=1;t.push(Number.parseInt(r.slice(o+1,p),8)),o=p}let i=Vp(()=>new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(Uint8Array.from(t)));return Xe(i)?i.success:void 0}function Kt(e){return Lk("sha256").update(e).digest("hex")}function mt(e,t){if(t===void 0||e!==t)throw new _("stale_write","Persisted revision changed before mutation.",{expected_revision:t,actual_revision:e})}function at(e){return new _("invalid_input",e)}function En(e){if(e.state==="complete"||e.state==="abandoned")throw new _("invalid_transition","Terminal Intents cannot be mutated.",{state:e.state})}function Ns(e,t){return new _("invalid_transition",`Intent cannot transition from ${e} to ${t}.`,{source:e,target:t})}function ee(e,t){let n=it(e,t);if(Ce(n))throw new _("schema_invalid","Value failed Effect Schema validation.",{error:String(n.failure)});return n.success}function Ys(e){return f(function*(){let t;{let n=yield*f(function*(){let r=yield*O(()=>Pt(e));if(r.isSymbolicLink()||!r.isFile())return yield*d(new _("schema_invalid","Persistent work state must be a regular file.",{path:e}));return t=yield*O(()=>nd(e,"utf8")),{kind:"none"}}).pipe(j((r)=>d(r))).pipe(F(()=>!0,(r)=>f(function*(){if(H(r,"ENOENT"))return yield*d(new _("not_found","Persistent work state was not found.",{path:e}));return yield*d(se(r))})))}return yield*OS(t,e)})}function Sr(e,t){return f(function*(){return ee(t,yield*Ys(e))})}function tT(e,t){return f(function*(){let n;{let r=yield*f(function*(){return n=yield*O(()=>Pt(e)),{kind:"none"}}).pipe(j((i)=>d(i))).pipe(F(()=>!0,(i)=>f(function*(){if(H(i,"ENOENT")||H(i,"ENOTDIR"))return{kind:"return",value:void 0};return yield*d(se(i))})));if(r.kind==="return")return r.value}if(n.isSymbolicLink()||!n.isFile())return yield*d(new _("schema_invalid","Persistent work state must be a regular file.",{path:e}));return yield*Sr(e,t)})}function nT(e){return f(function*(){let t=yield*Ys(e),n=it(vr,t);if(Xe(n))return n.success;let r=it(IS,t);if(Ce(r))return yield*d(new _("schema_invalid","Persisted Intent failed schema validation.",{path:e,error:String(n.failure)}));return CS(r.success)})}function rT(e,t){return f(function*(){let n;{let i=yield*f(function*(){return n=yield*Ys(e),{kind:"none"}}).pipe(j((o)=>d(o))).pipe(F(()=>!0,(o)=>f(function*(){if(Oo(o))return{kind:"return",value:!1};return yield*d(o)})));if(i.kind==="return")return i.value}if(typeof n!=="object"||n===null||Array.isArray(n))return!1;let r=n;return r.id===t||r.slug===t})}function Oo(e){return e instanceof _&&["malformed_toon","schema_invalid","not_found"].includes(e.code)}function iT(e){let t=new Map(e.map((a)=>[a.id,a])),n=new Set,r=[],i=new Set,o=(a)=>{let s=r.indexOf(a);if(s>=0){for(let u of r.slice(s))i.add(u);return}if(n.has(a))return;r.push(a);for(let u of t.get(a)?.dependencies??[])if(u!==a&&t.has(u))o(u);r.pop(),n.add(a)};for(let a of[...t.keys()].sort())o(a);return[...i].sort()}function Xl(e,t){return e<t?-1:e>t?1:0}function bS(e,t,n){return OS(e,n).pipe(xe((r)=>ie({try:()=>ee(t,r),catch:(i)=>i})))}function OS(e,t){return ie({try:()=>Zf(e,{strict:!0}),catch:(n)=>new _("malformed_toon","Persistent work state is malformed TOON.",{path:t,message:n instanceof Error?n.message:String(n)})})}function ot(e,t){return f(function*(){yield*Po(e,`${Ue(t)}
|
|
47
|
+
`)})}function Po(e,t){return f(function*(){yield*Bn(e),yield*O(()=>ui(Er(e),{recursive:!0})),yield*Bn(e);let n=T(Er(e),`.holycodex-write-${process.pid}-${crypto.randomUUID()}.tmp`);{let r=yield*f(function*(){let i=yield*O(()=>Us(n,"wx",384));{let o=yield*f(function*(){return yield*O(()=>i.writeFile(t,"utf8")),yield*O(()=>i.sync()),{kind:"none"}}).pipe(j((a)=>d(a))).pipe(xt(f(function*(){return yield*O(()=>i.close()),{kind:"none"}}).pipe(Rn)))}return yield*O(()=>Dk(n,e)),yield*Ds(Er(e)),{kind:"none"}}).pipe(j((i)=>d(i))).pipe(F(()=>!0,(i)=>f(function*(){return yield*O(()=>xr(n,{force:!0})),yield*d(se(i));return{kind:"none"}})))}})}function oT(e,t){return f(function*(){yield*Bn(e);{let n=yield*f(function*(){let r=yield*O(()=>Us(e,"wx",256));{let i=yield*f(function*(){return yield*O(()=>r.writeFile(t,"utf8")),yield*O(()=>r.sync()),{kind:"none"}}).pipe(j((o)=>d(o))).pipe(xt(f(function*(){return yield*O(()=>r.close()),{kind:"none"}}).pipe(Rn)))}return yield*Ds(Er(e)),{kind:"none"}}).pipe(j((r)=>d(r))).pipe(F(()=>!0,(r)=>f(function*(){if(H(r,"EEXIST"))return yield*d(new _("archive_conflict","Archived plans are immutable.",{path:e}));return yield*d(se(r))})))}})}function Ds(e){return f(function*(){if(process.platform==="win32")return;{let t=yield*f(function*(){let n=yield*O(()=>Us(e,"r"));{let r=yield*f(function*(){return yield*O(()=>n.sync()),{kind:"none"}}).pipe(j((i)=>d(i))).pipe(xt(f(function*(){return yield*O(()=>n.close()),{kind:"none"}}).pipe(Rn)))}return{kind:"none"}}).pipe(j((n)=>d(n))).pipe(F(()=>!0,(n)=>f(function*(){if(H(n,"EINVAL")||H(n,"ENOSYS")||H(n,"ENOTSUP")||H(n,"EOPNOTSUPP")||H(n,"EISDIR"))return{kind:"return",value:void 0};return yield*d(n)})));if(t.kind==="return")return t.value}})}function yr(e,t){return f(function*(){let n=Er(e);yield*Bn(e),yield*O(()=>ui(n,{recursive:!0}));let r=!1;for(let s=0;s<200;s+=1){let u=yield*f(function*(){return yield*O(()=>ui(e)),r=!0,{kind:"break"};return{kind:"none"}}).pipe(j((p)=>d(p))).pipe(F(()=>!0,(p)=>f(function*(){if(!H(p,"EEXIST"))return yield*d(se(p));if((yield*f(function*(){let l=yield*O(()=>Pt(e));if(l.isSymbolicLink()||!l.isDirectory())return yield*d(new _("schema_invalid","The work-state lock must be a real directory.",{path:e}));let g=yield*PS(e);if(g.kind==="owned"&&!(yield*aT(g.owner.pid)))return yield*O(()=>xr(e,{recursive:!0,force:!0})),{kind:"continue"};if(g.kind==="missing"&&Date.now()-l.mtimeMs>qk)return yield*O(()=>xr(e,{recursive:!0,force:!0})),{kind:"continue"};return{kind:"none"}}).pipe(j((l)=>d(l))).pipe(F(()=>!0,(l)=>f(function*(){if(!H(l,"ENOENT"))return yield*d(se(l));return{kind:"none"}})))).kind==="continue")return{kind:"continue"};return yield*Wa(Math.min(5+s,50)),{kind:"none"}})));if(u.kind==="break")break;if(u.kind==="continue")continue}if(!r)return yield*d(new _("stale_write","Another mutation is still in progress.",{lock:e}));let i=T(e,".owner"),o=crypto.randomUUID(),a;{let s=yield*f(function*(){return yield*Bn(i),a=yield*O(()=>Us(i,"wx",384)),yield*O(()=>a.writeFile(`${JSON.stringify({pid:process.pid,token:o})}
|
|
48
|
+
`,"utf8")),yield*O(()=>a.sync()),{kind:"none"}}).pipe(j((u)=>d(u))).pipe(F(()=>!0,(u)=>f(function*(){if(a!==void 0){let p=yield*f(function*(){return yield*O(()=>a.close()),{kind:"none"}}).pipe(j((c)=>d(c))).pipe(F(()=>!0,(c)=>f(function*(){return{kind:"none"}})))}if(H(u,"EEXIST"))return yield*d(new _("stale_write","Another mutation is still in progress.",{lock:e}));return yield*d(se(u))})))}if(a===void 0)return yield*d(se(Error("The work-state lock owner was not opened.")));{let s=yield*f(function*(){return{kind:"return",value:yield*t()}}).pipe(j((u)=>d(u))).pipe(xt(f(function*(){{let u=yield*f(function*(){return yield*O(()=>a.close()),{kind:"none"}}).pipe(j((p)=>d(p))).pipe(xt(f(function*(){return yield*cT(e,o),{kind:"none"}}).pipe(Rn)))}return{kind:"none"}}).pipe(Rn)));if(s.kind==="return")return s.value}})}function PS(e){return f(function*(){let t=T(e,".owner");{let n=yield*f(function*(){let r=yield*O(()=>Pt(t));if(r.isSymbolicLink()||!r.isFile())return{kind:"return",value:{kind:"unknown"}};let i=yield*O(()=>nd(t,"utf8")),o;{let s=yield*f(function*(){return o=JSON.parse(i),{kind:"none"}}).pipe(j((u)=>d(u))).pipe(F(()=>!0,(u)=>f(function*(){return{kind:"return",value:{kind:"unknown"}}})));if(s.kind==="return")return{kind:"return",value:s.value}}let a=it(Bk,o);return{kind:"return",value:Xe(a)?{kind:"owned",owner:a.success}:{kind:"unknown"}}}).pipe(j((r)=>d(r))).pipe(F(()=>!0,(r)=>f(function*(){if(H(r,"ENOENT"))return{kind:"return",value:{kind:"missing"}};if(H(r,"EPERM")||H(r,"EACCES"))return{kind:"return",value:{kind:"unknown"}};return yield*d(se(r))})));if(n.kind==="return")return n.value}})}function aT(e){return f(function*(){if(e===process.pid)return!0;if(process.platform==="win32")return yield*sT(e);if(!["aix","android","darwin","freebsd","haiku","linux","openbsd","sunos","win32"].includes(process.platform))return!0;{let n=yield*f(function*(){return process.kill(e,0),{kind:"return",value:!0};return{kind:"none"}}).pipe(j((r)=>d(r))).pipe(F(()=>!0,(r)=>f(function*(){return{kind:"return",value:H(r,"EPERM")}})));if(n.kind==="return")return n.value}})}function sT(e){return f(function*(){if(!Number.isSafeInteger(e)||e>Vk)return!1;{let t=yield*f(function*(){let{stdout:n}=yield*O(()=>Lo("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(j((n)=>d(n))).pipe(F(()=>!0,(n)=>f(function*(){return{kind:"return",value:!0}})));if(t.kind==="return")return t.value}})}function cT(e,t){return f(function*(){let n=yield*PS(e);if(n.kind!=="owned"||n.owner.token!==t)return;yield*O(()=>xr(e,{recursive:!0,force:!0}))})}function uT(e){return f(function*(){let t=(yield*O(()=>vn(e))).map((n)=>/^plan\.old-(\d{3})\.toon$/u.exec(n)?.[1]).filter((n)=>n!==void 0).map(Number);return T(e,`plan.old-${String((t.length?Math.max(...t):0)+1).padStart(3,"0")}.toon`)})}function Ls(e){return f(function*(){{let t=yield*f(function*(){return yield*O(()=>Uk(e)),{kind:"return",value:!0};return{kind:"none"}}).pipe(j((n)=>d(n))).pipe(F(()=>!0,(n)=>f(function*(){if(H(n,"ENOENT"))return{kind:"return",value:!1};return yield*d(se(n))})));if(t.kind==="return")return t.value}})}function ci(e){return f(function*(){{let t=yield*f(function*(){let n=yield*O(()=>Pt(e));return{kind:"return",value:n.isFile()&&!n.isSymbolicLink()}}).pipe(j((n)=>d(n))).pipe(F(()=>!0,(n)=>f(function*(){if(H(n,"ENOENT")||H(n,"ENOTDIR"))return{kind:"return",value:!1};return yield*d(se(n))})));if(t.kind==="return")return t.value}})}function Ql(e,t){return f(function*(){{let n=yield*f(function*(){let r=yield*O(()=>Pt(e));if(r.isSymbolicLink()||!r.isDirectory())return yield*d(new _("schema_invalid","Persistent work-state directories must be real directories.",{path:e}));return{kind:"return",value:!0}}).pipe(j((r)=>d(r))).pipe(F(()=>!0,(r)=>f(function*(){if(H(r,"ENOENT")&&t)return{kind:"return",value:!1};return yield*d(se(r))})));if(n.kind==="return")return n.value}})}function Ro(e){return f(function*(){{let t=yield*f(function*(){let n=yield*O(()=>Pt(e));return{kind:"return",value:n.isDirectory()&&!n.isSymbolicLink()}}).pipe(j((n)=>d(n))).pipe(F(()=>!0,(n)=>f(function*(){if(H(n,"ENOENT")||H(n,"ENOTDIR"))return{kind:"return",value:!1};return yield*d(se(n))})));if(t.kind==="return")return t.value}})}function ed(e,t,n,r){if(e.intent_id!==t||e.id!==n)throw new _("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 Bn(e){return f(function*(){let t=li(e);while(!0){{let r=yield*f(function*(){if((yield*O(()=>Pt(t))).isSymbolicLink())return yield*d(new _("schema_invalid","Persistent work state must not contain symbolic links.",{path:t}));return{kind:"none"}}).pipe(j((i)=>d(i))).pipe(F(()=>!0,(i)=>f(function*(){if(!H(i,"ENOENT"))return yield*d(se(i));return{kind:"none"}})))}let n=Er(t);if(n===t)break;t=n}})}function H(e,t){return typeof e==="object"&&e!==null&&"code"in e&&e.code===t}function se(e){return e instanceof _?e:new _("io_failure","Persistent work-state I/O failed.",{message:e instanceof Error?e.message:String(e)})}function NS(e,t){let n=td(e,t);return n===""||!n.startsWith(`..${lT()}`)&&n!==".."&&!$k(n)}function lT(){return process.platform==="win32"?"\\":"/"}function O(e){return K({try:e,catch:(t)=>t})}var fd=gi;var Mo=1048576,pd=65536;function Zs(e){if(typeof e!=="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}var Ie=Fn,fe=ii,mF=S.check(W(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),bn=S.check(B((e)=>e.length>0&&e.length<=4096)),hT=ae.check(B((e)=>Number.isFinite(e)&&e>=0));function gT(e){switch(e){case"invalid_external_data":case"manifest_invalid":case"empty_output_directory":return"validation";case"discovery_failed":return"identity";case"protocol_mismatch":case"method_unsupported":case"server_request_unsupported":case"unexpected_response":return"protocol";case"invalid_transport_line":case"transport_closed":case"transport_failure":return"transport";case"approval_required":case"permission_denied":return"approval";case"cancellation":return"interruption";case"timeout":return"timeout";case"turn_failed":return"turn";case"closed":return"closed";case"server_error":return"server"}}class L extends Error{code;kind;details;retryable;constructor(e,t,n={},r){super(t,r?.cause===void 0?void 0:{cause:r.cause});this.name="CodexError",this.code=e,this.kind=gT(e),this.details=n,this.retryable=r?.retryable??!1,Object.freeze(this.details),Object.freeze(this)}}function Gt(e,t=512){let n="";for(let r of e){let i=r.codePointAt(0)??0;n+=i<=8||i===11||i===12||i>=14&&i<=31||i===127?" ":r}return n.replace(/\s+/gu," ").trim().slice(0,t)}function wr(e,t=0){if(t>3)return"[truncated]";if(e===null||typeof e==="boolean")return e;if(typeof e==="string")return Gt(e,256);if(typeof e==="number")return Number.isFinite(e)?e:null;if(Array.isArray(e))return e.slice(0,32).map((n)=>wr(n,t+1));if(Zs(e)){let n={};for(let[r,i]of Object.entries(e).slice(0,32)){let o=Gt(r,96);if(o.length>0)n[o]=wr(i,t+1)}return n}return"[redacted]"}function MS(e){let t=wr(e);return Zs(t)?t:{value:t}}function Fo(e,t,n){return new L("invalid_external_data",`Invalid ${e}.`,{field:e,received:wr(t)},n===void 0?void 0:{cause:n})}function Lt(e,t,n){let r=it(e,t);if(Ce(r))throw Fo(n,t,String(r.failure));return r.success}function Xs(e,t){return Xe(it(e,t))}var md=["initialize","thread/start","thread/resume","thread/read","thread/list","thread/fork","thread/unsubscribe","turn/start","turn/steer","turn/interrupt","model/list","modelProvider/capabilities/read","config/read","permissionProfile/list","account/rateLimits/read","account/rateLimitResetCredit/consume"];var Do=["item/commandExecution/requestApproval","item/fileChange/requestApproval","applyPatchApproval","execCommandApproval"],Uo=["item/permissions/requestApproval"],hd=["mcpServer/elicitation/request"],gd=["item/tool/call"],yd={method:"initialized"},Sd="turn/completed";import{dirname as NF,isAbsolute as wT,join as LF,relative as MF,resolve as FF,sep as DF}from"path";var yT={clientInfo:{name:"holycodex",title:null,version:fd},capabilities:null},ST=new Set(md);class qo{transport;maxLineBytes;requestTimeoutMs;signal;notificationListeners=new Set;serverRequestHandlers=new Set;pending=new Map;serverRequestWork=new Set;serverRequestTasks=new Set;nextRequestId=1;readerFiber;initializeEffect;transportCloseEffect;initializeAttempted=!1;initialized=!1;closed=!1;constructor(e,t={}){if(this.transport=e,this.maxLineBytes=t.maxLineBytes??Mo,this.requestTimeoutMs=t.requestTimeoutMs,this.signal=t.signal,!Number.isSafeInteger(this.maxLineBytes)||this.maxLineBytes<1)throw new L("invalid_external_data","The maximum line size is invalid.");if(this.requestTimeoutMs!==void 0&&(!Number.isSafeInteger(this.requestTimeoutMs)||this.requestTimeoutMs<1))throw new L("invalid_external_data","The request timeout is invalid.");if(t.onNotification)this.notificationListeners.add(t.onNotification);if(t.onServerRequest)this.serverRequestHandlers.add(t.onServerRequest);if(this.signal?.aborted)this.close();else if(this.signal)this.signal.addEventListener("abort",()=>void this.close(),{once:!0})}get isInitialized(){return this.initialized}onNotification(e){return this.notificationListeners.add(e),()=>this.notificationListeners.delete(e)}onServerRequest(e){return this.serverRequestHandlers.add(e),()=>this.serverRequestHandlers.delete(e)}initialize(e=yT){if(this.initializeEffect)return Oe(this.initializeEffect);if(this.initializeAttempted)return Oe(d(new L("invalid_external_data","The App Server initialize handshake was already attempted.")));let t=ie({try:()=>{this.ensureOpen();let n=Lt(Bo,e,"initialize parameters");return this.initializeAttempted=!0,this.performInitializeEffect(n)},catch:(n)=>wn(n,"The initialize handshake failed.")}).pipe(Ga);return this.initializeEffect=Cn(Qi(t)),Oe(this.initializeEffect)}startThread(e={}){return this.action("thread/start",Rd,e,Vo)}resumeThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/resume",zo,t,bd)}readThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/read",Cd,t,Td)}listThreads(e={}){return this.action("thread/list",Od,e,Id)}forkThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/fork",Ad,t,wd)}unsubscribeThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/unsubscribe",_d,t,kd)}startTurn(e){return this.action("turn/start",Pd,e,Ld)}steerTurn(e){return this.action("turn/steer",Nd,e,Md)}interruptTurn(e,t){let n=typeof e==="string"?{threadId:e,turnId:t??""}:e;return this.action("turn/interrupt",Fd,n,Dd)}listModels(e={}){return this.action("model/list",$d,e,jd)}readModelProviderCapabilities(e={}){return this.action("modelProvider/capabilities/read",Bd,e,qd)}readConfig(e={}){return this.action("config/read",Wd,e,Jd)}listPermissionProfiles(e={}){return this.action("permissionProfile/list",Hd,e,Yd)}readAccountRateLimits(e={}){return this.action("account/rateLimits/read",Vd,e,zd)}consumeAccountRateLimitResetCredit(e){return this.action("account/rateLimitResetCredit/consume",Kd,e,Gd)}call(e,t={}){return Oe(ie({try:()=>this.callEffect(e,t),catch:(n)=>wn(n,"The App Server method failed.")}).pipe(Ga))}callEffect(e,t){if(e==="initialize")return zr(K({try:()=>this.initialize(Lt(Bo,t,"initialize parameters")),catch:(r)=>wn(r,"The initialize handshake failed.")}),(r)=>Lt(Ie,r,"initialize result"));let n=Lt(jo,{id:1,method:e,params:t},"App Server method");if(!ST.has(n.method))throw new L("method_unsupported",`Unsupported App Server method: ${e}.`,{method:e});return this.requestEffect(n.method,n.params===void 0?{}:n.params)}close(){return Oe(this.closeWithErrorEffect(new L("closed","The App Server client is closed.")))}performInitializeEffect(e){let t=f({self:this},function*(){let n=yield*this.decodeEffect(Bo,e,"initialize parameters"),r=yield*this.decodeEffect(Ie,n,"initialize parameters"),i=yield*this.requestEffect("initialize",r),o=yield*this.decodeEffect(Ed,i,"initialize result"),a=yield*this.decodeEffect(vd,yd,"initialized notification");return yield*this.transportWriteEffect(JSON.stringify(a)),this.initialized=!0,o});return F(t,()=>!0,(n)=>f({self:this},function*(){let r=wn(n,"The initialize handshake failed.");return yield*this.closeWithErrorEffect(r),yield*d(r)}))}action(e,t,n,r){return Oe(ie({try:()=>this.actionEffect(e,t,n,r),catch:(i)=>wn(i,`The ${e} action failed.`)}).pipe(Ga))}actionEffect(e,t,n,r){return f({self:this},function*(){let i=yield*this.decodeEffect(t,n,`${e} parameters`),o=yield*this.decodeEffect(Ie,i,`${e} parameters`),a=yield*this.requestEffect(e,o);return yield*this.decodeEffect(r,a,`${e} result`)})}decodeEffect(e,t,n){return ie({try:()=>Lt(e,t,n),catch:(r)=>wn(r,`Invalid ${n}.`)})}requestEffect(e,t){if(this.closed)return d(new L("closed","The App Server client is closed."));if(e!=="initialize"&&!this.initialized)return d(new L("invalid_external_data",`The ${e} action requires an initialized App Server client.`));this.startReader();let n=this.nextRequestId;return this.nextRequestId+=1,xe(this.decodeEffect(jo,{id:n,method:e,params:t},`${e} request`),(r)=>ug((i,o)=>{let a=!1,s,u,p=()=>c(new L("cancellation",`The ${e} request was cancelled.`,{method:e})),c=(v)=>{if(a)return;if(a=!0,this.pending.delete(n),s!==void 0)clearTimeout(s);u?.(),i(d(v))};if(this.requestTimeoutMs!==void 0)s=setTimeout(()=>c(new L("timeout",`The ${e} request timed out.`,{method:e})),this.requestTimeoutMs);if(this.signal){if(this.signal.addEventListener("abort",p,{once:!0}),u=()=>this.signal?.removeEventListener("abort",p),this.signal.aborted)p()}let l={method:e,resume:i,...s===void 0?{}:{timer:s},...u===void 0?{}:{removeAbortListener:u}};this.pending.set(n,l),o.addEventListener("abort",p,{once:!0});let g=this.transportWriteEffect(JSON.stringify(r)).pipe(F(()=>!0,(v)=>dt(()=>c(v))));return Kr(g),dt(()=>{if(s!==void 0)clearTimeout(s);u?.(),o.removeEventListener("abort",p),this.pending.delete(n)})}))}transportWriteEffect(e){return K({try:()=>this.transport.writeLine(e),catch:(t)=>wn(t,"The App Server request could not be written.")})}startReader(){if(!this.readerFiber){let e=this.readLoopEffect().pipe(F(()=>!0,(t)=>this.handleReaderFailureEffect(t)));this.readerFiber=Kr(e)}}readLoopEffect(){return f({self:this},function*(){while(!this.closed){let e=yield*K({try:()=>this.transport.readLine(),catch:(t)=>wn(t,"The App Server stdout could not be read.")});if(e===null){if(!this.closed)return yield*d(new L("transport_closed","The App Server transport closed."));return}if(new TextEncoder().encode(e).byteLength>this.maxLineBytes)return yield*d(new L("invalid_transport_line","An App Server line exceeded the limit."));yield*ie({try:()=>this.handleLine(e),catch:(t)=>wn(t,"The App Server emitted an invalid message.")})}})}handleReaderFailureEffect(e){let t=e instanceof L?e:new L("transport_failure","The App Server transport failed.",{},{cause:e});return this.closeWithErrorEffect(t)}handleLine(e){let t=Cn(ie({try:()=>JSON.parse(e),catch:(o)=>new L("invalid_transport_line","The App Server emitted invalid JSON.",{},{cause:o})})),n=this.tryDecode($o,t);if(n!==void 0){this.handleResponse(n);return}let r=this.tryDecode(jo,t);if(r!==void 0){this.handleServerRequest(r);return}let i=this.tryDecode(xd,t);if(i!==void 0){this.handleNotification(i);return}throw Fo("JSON-RPC message",t)}tryDecode(e,t){return Xs(e,t)?Lt(e,t,"JSON-RPC message"):void 0}handleResponse(e){let t=this.pending.get(e.id);if(!t)throw new L("unexpected_response","The App Server returned an unknown request id.",{id:e.id});if(this.pending.delete(e.id),"error"in e){let n=e.error.code===-32001,r=ET(t.method);this.resumePending(t,d(new L(r,`The App Server rejected ${t.method}: ${Gt(e.error.message)}.`,{method:t.method,serverCode:e.error.code,retryable:n,...e.error.data===void 0?{}:{data:wr(e.error.data)}},{retryable:n})));return}this.resumePending(t,J(e.result))}resumePending(e,t){if(e.timer!==void 0)clearTimeout(e.timer);e.removeAbortListener?.(),e.resume(t)}handleServerRequest(e){let t=e.params??{},n=Lt(Zd,{...e,params:t,category:FS(e.method)},"server request");this.emitNotification({kind:"server_request",method:e.method,params:t});let r=[...this.serverRequestHandlers];if(r.length===0){this.trackServerRequestTask(this.writeServerErrorEffect(e.id,-32601,`No handler for ${e.method}.`));return}let i=r[0];if(i===void 0){this.trackServerRequestTask(this.writeServerErrorEffect(e.id,-32601,`No handler for ${e.method}.`));return}let o={active:!0};this.serverRequestWork.add(o);let a=Ja({onFailure:(s)=>this.writeServerErrorEffect(e.id,-32000,Gt(String(s))),onSuccess:(s)=>this.writeValidatedServerResultEffect(e.id,s)})(K({try:()=>Promise.resolve(i(n)),catch:(s)=>s}));this.completeServerRequest(o,a)}writeValidatedServerResultEffect(e,t){return Xs(Qs,t)?this.writeServerResultEffect(e,Lt(Qs,t,"server response")):this.writeServerErrorEffect(e,-32000,"Invalid server response.")}completeServerRequest(e,t){if(!e.active)return;e.active=!1,this.serverRequestWork.delete(e),this.trackServerRequestTask(t)}trackServerRequestTask(e){let t=et(e);this.serverRequestTasks.add(t),Kr(xt(t,dt(()=>this.serverRequestTasks.delete(t))))}writeServerResultEffect(e,t){return xe(this.decodeEffect($o,{id:e,result:t},"server response"),(n)=>this.transportWriteEffect(JSON.stringify(n)))}writeServerErrorEffect(e,t,n){return xe(this.decodeEffect($o,{id:e,error:{code:t,message:xT(n)}},"server error response"),(r)=>this.transportWriteEffect(JSON.stringify(r)))}handleNotification(e){let t=e.params;if(e.method===Sd){let n=Lt(Ud,t,"turn/completed notification");this.emitNotification({kind:"turn_completed",method:e.method,params:n});return}if(e.method.includes("agent")||e.method.includes("subagent")){this.emitNotification({kind:"multi_agent",method:e.method,...t===void 0?{}:{params:t}});return}this.emitNotification({kind:"unknown",method:e.method,metadata:MS({params:wr(t)})})}emitNotification(e){for(let t of this.notificationListeners)Cn(et(ie({try:()=>t(e),catch:()=>{return}})))}rejectPending(e){for(let t of this.pending.values())this.resumePending(t,d(e));this.pending.clear()}closeWithErrorEffect(e){if(this.transportCloseEffect===void 0){this.closed=!0,this.rejectPending(e);for(let t of this.serverRequestWork)t.active=!1;this.serverRequestWork.clear(),this.serverRequestTasks.clear(),this.transportCloseEffect=Cn(Qi(et(K({try:()=>this.transport.close(),catch:()=>{return}}))))}return this.transportCloseEffect}ensureOpen(){if(this.closed)throw new L("closed","The App Server client is closed.")}}function xT(e){let t=Gt(e);return t.length>0?t:"server request failed"}function wn(e,t){return e instanceof L?e:new L("transport_failure",t,{},{cause:e})}function ET(e){if(Uo.some((t)=>t===e))return"permission_denied";if(Do.some((t)=>t===e))return"approval_required";if(e==="turn/interrupt")return"cancellation";if(e.startsWith("turn/"))return"turn_failed";return"server_error"}import{isAbsolute as bT}from"path";var DS=Jm;function ec(e=process.env){let t=["PATH","HOME","USER","CODEX_HOME","TMPDIR","TEMP","TMP","LANG","LC_ALL"],n={};for(let r of t){let i=e[r];if(i!==void 0&&i.length>0)n[r]=i}return n}function Xd(e,t){return Oe($S(e,t))}function $S(e,t){return f(function*(){let n=yield*ie({try:()=>e.getReader(),catch:(a)=>new L("transport_failure","A subprocess stream could not be read.",{},{cause:a})}),r=[],i=0,o=f(function*(){while(!0){let u=yield*K({try:()=>n.read(),catch:(p)=>new L("transport_failure","A subprocess stream could not be read.",{},{cause:p})});if(u.done)break;if(i+=u.value.byteLength,i>t)return yield*d(new L("invalid_transport_line","A subprocess stream exceeded its limit."));r.push(u.value)}let a=new Uint8Array(i),s=0;for(let u of r)a.set(u,s),s+=u.byteLength;return a});return yield*xt(o,dt(()=>n.releaseLock()))})}function tc(e,t){return Cn(ie({try:()=>new TextDecoder("utf-8",{fatal:!0}).decode(e),catch:(n)=>new L("invalid_transport_line",`Invalid UTF-8 in ${t}.`,{},{cause:n})}))}function nc(e){return Gt(e.replace(/Bearer\s+[^\s]+/giu,"Bearer [redacted]").replace(/((?:api[_-]?key|authorization|cookie|password|secret|token)\s*[:=]\s*)[^\s,;]+/giu,"$1[redacted]"),512)}class Ko{process;stdin;stdoutReader;stderrStream;maxLineBytes;maxDiagnosticBytes;lineDecoder=new TextDecoder("utf-8",{fatal:!0});stderrDiagnostics=[];stdoutBuffer=new Uint8Array(0);stderrFiber;closeEffect;closed=!1;constructor(e){if(!bT(e.executablePath))throw new L("discovery_failed","The Codex executable path must be absolute.");if(this.maxLineBytes=e.maxLineBytes??Mo,this.maxDiagnosticBytes=e.maxDiagnosticBytes??pd,this.maxLineBytes<1||this.maxDiagnosticBytes<1)throw new L("invalid_external_data","The transport bounds are invalid.");if(this.process=Bun.spawn([e.executablePath,"app-server"],{...e.cwd===void 0?{}:{cwd:e.cwd},env:ec(e.environment),stdin:"pipe",stdout:"pipe",stderr:"pipe"}),!(this.process.stdout instanceof ReadableStream)||!(this.process.stderr instanceof ReadableStream))throw new L("transport_failure","The Codex App Server did not expose stdio pipes.");if(typeof this.process.stdin==="number"||this.process.stdin===void 0)throw new L("transport_failure","The Codex App Server did not expose stdin.");if(this.stdin=this.process.stdin,this.stdoutReader=this.process.stdout,this.stderrStream=this.process.stderr,this.stderrFiber=Kr(this.collectStderrEffect()),e.signal)if(e.signal.aborted)this.close();else e.signal.addEventListener("abort",()=>void this.close(),{once:!0})}get diagnostics(){return[...this.stderrDiagnostics]}readLine(){return Oe(this.readLineEffect())}readLineEffect(){if(this.closed&&this.stdoutBuffer.byteLength===0)return J(null);return f({self:this},function*(){let e=yield*ie({try:()=>this.stdoutReader.getReader(),catch:(n)=>new L("transport_failure","The App Server stdout could not be read.",{},{cause:n})}),t=f({self:this},function*(){while(!0){let n=this.stdoutBuffer.indexOf(10);if(n>=0){if(n>this.maxLineBytes)return yield*et(K({try:()=>this.close(),catch:()=>{return}})),yield*d(new L("invalid_transport_line","The App Server emitted an overlong line."));let o=this.stdoutBuffer.slice(0,n);this.stdoutBuffer=this.stdoutBuffer.slice(n+1);let a=o.at(-1)===13?o.slice(0,-1):o;return yield*US(a,this.lineDecoder)}if(this.stdoutBuffer.byteLength>this.maxLineBytes)return yield*et(K({try:()=>this.close(),catch:()=>{return}})),yield*d(new L("invalid_transport_line","The App Server emitted an overlong line."));let r=yield*K({try:()=>e.read(),catch:(o)=>new L("transport_failure","The App Server stdout could not be read.",{},{cause:o})});if(r.done){if(this.stdoutBuffer.byteLength===0)return null;if(this.stdoutBuffer.byteLength>this.maxLineBytes)return yield*et(K({try:()=>this.close(),catch:()=>{return}})),yield*d(new L("invalid_transport_line","The App Server emitted an overlong line."));let o=this.stdoutBuffer;return this.stdoutBuffer=new Uint8Array(0),yield*US(o,this.lineDecoder)}let i=new Uint8Array(this.stdoutBuffer.byteLength+r.value.byteLength);i.set(this.stdoutBuffer,0),i.set(r.value,this.stdoutBuffer.byteLength),this.stdoutBuffer=i}});return yield*xt(t,dt(()=>e.releaseLock()))})}writeLine(e){return Oe(this.writeLineEffect(e))}writeLineEffect(e){if(this.closed)return d(new L("closed","The App Server transport is closed."));if(new TextEncoder().encode(e).byteLength>this.maxLineBytes)return d(new L("invalid_transport_line","The App Server request exceeded the line limit."));return f({self:this},function*(){yield*K({try:()=>Promise.resolve(this.stdin.write(`${e}
|
|
49
|
+
`)),catch:(t)=>new L("transport_failure","The App Server stdin could not be written.",{},{cause:t})}),yield*K({try:()=>Promise.resolve(this.stdin.flush()),catch:(t)=>new L("transport_failure","The App Server stdin could not be written.",{},{cause:t})})})}close(){if(this.closeEffect===void 0){if(this.closed)return Promise.resolve();this.closed=!0,this.closeEffect=Cn(Qi(this.closeTransportEffect()))}return Oe(this.closeEffect)}closeTransportEffect(){return f({self:this},function*(){yield*et(K({try:()=>Promise.resolve(this.stdin.end()),catch:()=>{return}})),yield*et(ie({try:()=>this.process.kill(),catch:()=>{return}})),yield*fg(et(K({try:()=>this.process.exited,catch:()=>{return}})),Wa(1000)),yield*et(DS(this.stderrFiber))})}collectStderrEffect(){return f({self:this},function*(){let e=yield*ar($S(this.stderrStream,this.maxDiagnosticBytes));if(Lu(e)){this.stderrDiagnostics.push("[stderr unavailable]");return}let t=yield*ie({try:()=>tc(e.value,"Codex stderr"),catch:(n)=>n instanceof L?n:new L("transport_failure","Codex stderr could not be decoded.",{},{cause:n})});for(let n of t.split(/\r?\n/u).slice(0,128)){let r=nc(n);if(r.length>0)this.stderrDiagnostics.push(r)}}).pipe(Rn)}}function US(e,t){return ie({try:()=>t.decode(e),catch:(n)=>new L("invalid_transport_line","The App Server emitted invalid UTF-8.",{},{cause:n})})}var jS="openai-curated",Qd="https://github.com/openai/plugins.git";var tf=S.check(W(/^[a-z][a-z0-9._-]{1,63}$/u)),rc=P([S,te(y({url:S}),[Ne(S,rt)])]),qF=P([x([Qd]),te(y({url:x([Qd])}),[Ne(S,rt)])]),VF=te(y({name:x([jS]),plugins:C(rt),source:b(rc),repository:b(rc),repo:b(rc),url:b(rc)}),[Ne(S,rt)]),zF=S.check(B((e)=>{if(e.length===0||wT(e)||/^[A-Za-z]:[\\/]/u.test(e))return!1;let t=e.replaceAll("\\","/");return!t.startsWith("/")&&!/^[A-Za-z][A-Za-z0-9+.-]*:/u.test(t)&&t.split("/").every((n)=>n.length===0||n==="."||n!=="..")})),_T=P([S,te(y({path:b(S)}),[Ne(S,rt)])]),KF=te(y({name:tf,source:b(_T),path:b(S)}),[Ne(S,rt)]),kT=S.check(W(/^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][A-Za-z0-9.-]+)?$/u)),Go=C(S),nf=S.check(W(/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u)),TT=y({name:tf,version:kT,description:bn,author:b(Ie),license:b(bn),homepage:b(bn),repository:b(bn),keywords:b(Go),skills:b(Go),commands:b(Go),hooks:b(Go),assets:b(Go),official:b(U)});var IT=y({id:tf,selected:x([!0])});var ef=te(y({pluginId:nf,installed:U,enabled:U,name:b(P([S,G])),marketplaceName:b(P([S,G])),version:b(P([S,G]))}),[Ne(S,rt)]),RT=y({installed:C(ef),available:C(ef)});var CT=te(y({sourceType:S,source:S}),[Ne(S,rt)]),AT=te(y({name:S,root:S,marketplaceSource:b(CT)}),[Ne(S,rt)]),GF=te(y({marketplaces:C(AT)}),[Ne(S,rt)]);var OT=[...Cs,"Reviewer.plan"];var rf=ii;var qS=["model","model_catalog_json","model_reasoning_effort","service_tier","agents.enabled","agents.default.config_file","agents.worker.config_file","agents.explorer.config_file","agents.librarian.config_file","agents.reviewer.config_file","agents.max_concurrent_threads_per_session","agents.max_depth","web_search","approval_policy","approvals_reviewer","default_permissions","model_verbosity","developer_instructions","include_collaboration_mode_instructions","tools.experimental_request_user_input.enabled","tools.update_plan.enabled","suppress_unstable_features_warning","features.multi_agent","features.default_mode_request_user_input","features.goals","features.image_generation","features.memories","features.request_permissions_tool","features.skill_search","features.sleep_tool","features.multi_agent_v2.enabled","features.multi_agent_v2.usage_hint_text","features.agent_message_board","features.code_mode.enabled","features.code_mode.direct_only_tool_namespaces","features.context_management.experimental_mode"],of=["model_auto_compact_token_limit","features.context_management","features.multi_agent_v2","sandbox_workspace_write.network_access","permissions.holycodex.extends","permissions.holycodex.network.enabled"];var VS=S.check(B(PT));function PT(e){if(qS.includes(e))return!0;if(/^agents\.(?:explorer|librarian|worker|reviewer)\.config_file$/u.test(e))return!0;return OT.some((t)=>e===`agents."${t}".config_file`)}var zS=P([VS,x(of)]);var NT=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u,pi=S.check(W(NT)),LT=P([pi,x([":workspace",":read-only",":danger-full-access"])]),MT=ae.check(B((e)=>Number.isSafeInteger(e)&&e>=0)),FT=S.check(W(/^[a-f0-9]{64}$/u)),DT=S.check(B(VT)),KS=S.check(B(zT)),GS=S.check(B((e)=>e.length>0&&e.length<=2000)),UT=S.check(W(/^[A-Za-z0-9_-]{1,64}$/u)),WS=C(UT),$T=P([y({kind:x(["enum"]),value:LT}),y({kind:x(["text"]),value:GS}),y({kind:x(["string_array"]),value:WS}),y({kind:x(["number"]),value:MT}),y({kind:x(["boolean"]),value:U}),y({kind:x(["relative_path"]),value:DT}),y({kind:x(["absolute_path"]),value:KS}),y({kind:x(["digest"]),value:FT})]),ic=$T.check(B((e)=>cf(e,["kind","value"]))),af=P([ic,y({kind:x(["absent"])})]),jT=y({owner:x(["holycodex"]),schema:pi,installId:pi,keyPath:zS,originalValue:af,lastManagedValue:ic}),sf=jT.check(B((e)=>cf(e,["owner","schema","installId","keyPath","originalValue","lastManagedValue"])&&BS(e.keyPath,e.lastManagedValue)&&(e.originalValue.kind==="absent"||BS(e.keyPath,e.originalValue)))),BT=y({owner:x(["holycodex"]),schema:pi,installId:pi,managed:Ne(S,sf)}),JS=BT.check(B((e)=>cf(e,["owner","schema","installId","managed"])&&Object.entries(e.managed).every(([t,n])=>pt(zS)(t)&&n.keyPath===t)));function qT(e){return pt(pi)(e)}function cf(e,t){let n=new Set(t);return Object.keys(e).every((r)=>n.has(r))}function BS(e,t){switch(KT(e)){case"number":return t.kind==="number";case"boolean":return t.kind==="boolean";case"relative_path":return t.kind==="relative_path";case"absolute_path":return t.kind==="absolute_path"&&pt(KS)(t.value);case"digest":return t.kind==="digest";case"string_array":return t.kind==="string_array"&&pt(WS)(t.value);case"text":return t.kind==="text"&&pt(GS)(t.value);case"enum":if(t.kind!=="enum")return!1;if(e==="model")return t.value==="gpt-6-astra"||t.value==="gpt-6.1-sol"||t.value==="gpt-6-sol"||t.value==="gpt-6-luna"||t.value==="gpt-5.6-terra"||t.value==="gpt-5.6-sol"||t.value==="gpt-5.6-luna";if(e==="model_reasoning_effort")return t.value==="low"||t.value==="medium"||t.value==="high"||t.value==="max";if(e==="service_tier")return t.value==="default"||t.value==="fast";if(e==="approval_policy")return t.value==="on-request"||t.value==="never";if(e==="approvals_reviewer")return t.value==="auto_review"||t.value==="user";if(e==="default_permissions")return t.value===":danger-full-access"||t.value===":workspace"||t.value===":read-only"||t.value==="holycodex";if(e==="permissions.holycodex.extends")return t.value===":workspace"||t.value===":read-only"||qT(t.value);if(e==="web_search")return t.value==="live"||t.value==="cached"||t.value==="indexed"||t.value==="disabled";return t.value==="low"||t.value==="medium"||t.value==="high"}}function VT(e){if(e.length===0||e.includes("\x00")||/^[\\/]|^[A-Za-z]:[\\/]/u.test(e))return!1;let t=e.replaceAll("\\","/").split("/");return t.some((n)=>n!==".")&&t.every((n)=>n.length>0&&n!=="..")}function zT(e){return e.length>0&&e.length<=1024&&!e.includes("\x00")&&/^(?:[A-Za-z]:[\\/]|\\\\|\/)/u.test(e)}function KT(e){if(e==="developer_instructions")return"digest";if(e==="model_catalog_json")return"absolute_path";if(e.endsWith(".config_file"))return"relative_path";if(e==="agents.max_concurrent_threads_per_session"||e==="agents.max_depth")return"number";if(e==="permissions.holycodex.extends")return"enum";if(e==="features.multi_agent_v2.usage_hint_text")return"text";if(e==="features.code_mode.direct_only_tool_namespaces")return"string_array";if(e==="model_auto_compact_token_limit")return"number";if(e==="suppress_unstable_features_warning"||e==="include_collaboration_mode_instructions"||e==="tools.experimental_request_user_input.enabled"||e==="tools.update_plan.enabled"||e==="agents.enabled"||e==="features.multi_agent"||e==="features.default_mode_request_user_input"||e==="features.goals"||e==="features.image_generation"||e==="features.memories"||e==="features.request_permissions_tool"||e==="features.skill_search"||e==="features.sleep_tool"||e==="features.multi_agent_v2.enabled"||e==="features.agent_message_board"||e==="features.code_mode.enabled"||e==="features.context_management.experimental_mode"||e==="permissions.holycodex.network.enabled"||of.includes(e))return"boolean";return"enum"}var HS=S.check(W(/^[A-Za-z][A-Za-z0-9_./:-]{0,127}$/u)),Re=[Ne(S,Ie)],GT=S.check(W(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),df=S.check(de(1)),mi=P([S.check(de(1)),ae.check(B((e)=>Number.isSafeInteger(e)))]),YS=y({code:ae.check(B((e)=>Number.isSafeInteger(e))),message:S,data:b(Ie)}),$o=P([y({id:mi,result:Ie}),y({id:mi,error:YS})]),WT=y({id:mi,error:YS});var xd=y({method:HS,params:b(Ie)}),jo=y({id:mi,method:HS,params:b(Ie),trace:b(Ie)}),on=ae.check(tn(),Ln(0)),JT=y({inputTokens:re(on),cachedInputTokens:re(on),outputTokens:re(on),reasoningOutputTokens:re(on),totalTokens:re(on)}).check(B((e)=>Object.values(e).some((t)=>t!==void 0))),HT=y({input_tokens:re(on),cached_input_tokens:re(on),output_tokens:re(on),reasoning_output_tokens:re(on),total_tokens:re(on)}).check(B((e)=>Object.values(e).some((t)=>t!==void 0))),ZS=P([JT,HT]);var Bo=y({clientInfo:y({name:bn,version:bn,title:P([bn,G])}),capabilities:P([y({experimentalApi:U,requestAttestation:U,mcpServerOpenaiFormElicitation:b(U),optOutNotificationMethods:b(P([C(S),G])),extensions:b(fe)}),G])}),Ed=te(y({userAgent:S,codexHome:S,platformFamily:S,platformOs:S,serverInfo:re(fe),capabilities:re(fe),protocolVersion:re(S)}),Re),vd=y({method:x(["initialized"])}),Wo=te(y({id:GT}),Re),Vo=P([te(y({thread:Wo,id:re(S)}),Re),te(y({id:S}),Re)]),bd=Vo,wd=Vo,_d=te(y({threadId:df}),Re),kd=te(y({status:x(["notLoaded","notSubscribed","unsubscribed"])}),Re),Td=te(y({thread:Wo}),Re),Id=fe.check(B((e)=>Array.isArray(e.data)&&e.threads===void 0&&pt(C(Wo))(e.data)||Array.isArray(e.threads)&&e.data===void 0&&pt(C(Wo))(e.threads))),Rd=fe,zo=te(y({threadId:df}),Re),Cd=zo,Ad=zo,Od=fe,XS=te(y({id:df,status:re(S),usage:re(ZS),error:re(Ie)}),Re),Pd=fe.check(B((e)=>typeof e.threadId==="string"&&e.threadId.length>0&&(Array.isArray(e.input)&&pt(C(Ie))(e.input)||typeof e.prompt==="string"&&e.prompt.length>0))),Nd=fe.check(B((e)=>typeof e.threadId==="string"&&e.threadId.length>0&&typeof e.expectedTurnId==="string"&&e.expectedTurnId.length>0&&Array.isArray(e.input)&&pt(C(Ie))(e.input))),Ld=fe.check(B((e)=>e.turn!==void 0&&pt(XS)(e.turn)||typeof e.turnId==="string"&&e.turnId.length>0||typeof e.id==="string"&&e.id.length>0)),Md=fe.check(B((e)=>typeof e.turnId==="string"&&e.turnId.length>0)),Fd=fe.check(B((e)=>typeof e.threadId==="string"&&e.threadId.length>0&&typeof e.turnId==="string"&&e.turnId.length>0)),Dd=fe,Ud=fe.check(B((e)=>typeof e.threadId==="string"&&e.threadId.length>0&&(e.turn!==void 0&&pt(XS)(e.turn)||typeof e.turnId==="string"&&e.turnId.length>0))),$d=fe,YT=te(y({reasoningEffort:S}),Re),ZT=te(y({id:S}),Re),XT=te(y({id:S,model:S,supportedReasoningEfforts:re(C(YT)),serviceTiers:re(C(ZT)),defaultServiceTier:re(P([S,G])),multiAgentVersion:re(P([x(["disabled","v1","v2"]),G]))}),Re),jd=te(y({data:C(XT)}),Re),Bd=fe,qd=fe,Vd=y({supportsLunaReserve:b(U),excludeResetCreditDetails:b(U)}),uf=y({usedPercent:ae.check(tn(),Ln(0),ri(100)),windowDurationMins:P([ae.check(tn(),Vt(0)),G]),resetsAt:P([ae.check(tn()),G])}),lf=te(y({primary:P([uf,G]),secondary:P([uf,G])}),Re),QS=y({id:S.check(de(1)),resetType:x(["codexRateLimits","unknown"]),status:x(["available","redeeming","redeemed","unknown"]),grantedAt:ae.check(tn()),expiresAt:P([ae.check(tn()),G]),title:P([S,G]),description:P([S,G])}),zd=te(y({rateLimits:lf,rateLimitsByLimitId:P([Ne(S,lf),G]),rateLimitResetCredits:P([te(y({availableCount:ae.check(Mn(),Ln(0)),credits:P([C(QS),G])}),Re),G])}),Re),Kd=y({idempotencyKey:S.check(de(1)),creditId:b(P([S.check(de(1)),G]))}),Gd=y({outcome:x(["reset","nothingToReset","noCredit","alreadyRedeemed"])}),Wd=y({includeLayers:b(U),cwd:b(P([S,G]))}),Jd=y({config:rf,origins:fe,layers:P([C(fe),G])}),Hd=fe,Yd=fe,Zd=te(y({id:mi,method:S,params:fe,category:x(["approval","dynamic_tool","elicitation","other","permissions"])}),Re),Qs=Ie,rD=te(y({kind:x(["multi_agent","turn_completed","server_request","unknown"]),method:S,params:re(Ie),metadata:re(fe)}),Re);function FS(e){if(Uo.some((t)=>t===e))return"permissions";if(Do.some((t)=>t===e))return"approval";if(hd.some((t)=>t===e))return"elicitation";if(gd.some((t)=>t===e))return"dynamic_tool";return"other"}var QT=P([x(["stable","experimental","disabled"]),U]),iD=Ne(S,QT);import{lstat as sD,mkdir as cD,readFile as eI,readdir as uD,realpath as tI,stat as nI}from"fs/promises";import{delimiter as rI,isAbsolute as dD,join as fD,relative as pD,resolve as ex}from"path";var iI=30000;function oI(e){return f(function*(){let t=[];if(e.executablePath!==void 0)t.push(ex(e.cwd??process.cwd(),e.executablePath));else{let n=e.pathValue??e.environment?.PATH??process.env.PATH??"",r=process.platform==="win32"?["codex.exe","codex.cmd","codex"]:["codex"];for(let i of n.split(rI).filter((o)=>o.length>0))for(let o of r)t.push(ex(i,o))}for(let n of t){let r=yield*F(K({try:()=>nI(n),catch:(i)=>i}),()=>!0,(i)=>e.executablePath!==void 0?d(new L("discovery_failed","The explicit Codex executable was not found.",{path:n},{cause:i})):J(void 0));if(r===void 0)continue;if(!r.isFile())continue;if(process.platform!=="win32"&&(r.mode&73)===0)continue;return yield*K({try:()=>tI(n),catch:(i)=>new L("discovery_failed","The explicit Codex executable could not be resolved.",{path:n},{cause:i})})}return yield*d(new L("discovery_failed","No Codex executable was found on the allowlisted PATH."))})}function aI(e,t){let n=Bun.spawn([e,"--version"],{env:t,stdin:"ignore",stdout:"pipe",stderr:"pipe"});if(!(n.stdout instanceof ReadableStream)||!(n.stderr instanceof ReadableStream))return d(new L("discovery_failed","The Codex version command did not expose output pipes."));return f(function*(){let[r,i,o]=yield*cI(za([K({try:()=>Xd(n.stdout,16384),catch:(s)=>s}),K({try:()=>Xd(n.stderr,16384),catch:(s)=>s}),K({try:()=>n.exited,catch:(s)=>s})],{concurrency:"unbounded"}),()=>n.kill(),"The Codex version command timed out."),a=Gt(tc(r,"Codex version output"));if(o!==0||a.length===0){let s=nc(tc(i,"Codex version diagnostics"));return yield*d(new L("discovery_failed","The Codex executable did not provide a version.",{exitCode:o,diagnostics:s}))}return a}).pipe(gn((r)=>r instanceof L?r:new L("discovery_failed","The Codex version command failed.",{},{cause:r})),xt(dt(()=>n.kill())))}function sI(e){return f(function*(){let t=yield*K({try:()=>eI(e),catch:(o)=>o}),n=yield*K({try:()=>crypto.subtle.digest("SHA-256",t),catch:(o)=>o}),r=[...new Uint8Array(n)].map((o)=>o.toString(16).padStart(2,"0")).join(""),i=Ul(r);if(!i.ok)return yield*d(new L("discovery_failed","The Codex executable digest was invalid."));return i.value})}function ff(e={}){return Oe(f(function*(){let t=yield*oI(e),n=ec(e.environment),r=e.versionRunner?yield*K({try:()=>e.versionRunner(t,n),catch:(i)=>i}).pipe(zr(Gt)):yield*aI(t,n);if(r.length===0)return yield*d(new L("discovery_failed","The Codex version output was empty."));return{path:t,version:r,sha256:yield*sI(t)}}))}var yD=y({exitCode:ae.check(B((e)=>Number.isSafeInteger(e))),stdout:S.check(Al(1048576)),stderr:S.check(Al(1048576))});function cI(e,t,n){return e.pipe(dg(iI),gn((r)=>r instanceof L?r:r!==null&&typeof r==="object"&&("_tag"in r)&&r._tag==="TimeoutError"?new L("timeout",n):r),Ha(()=>dt(t)))}var uI="packages/codex/generated",lI=/^codex-cli \d+\.\d+\.\d+$/u,dI=/^codex-app-server-\d+\.\d+\.\d+$/u,fI=4194304;var pf=S.check(W(/^[a-f0-9]{64}$/u)).pipe(hr("Sha256Digest")),pI=ae.check(Mn(),Vt(0),ri(fI)),vD=y({schema_version:x(["holycodex-generated-v2"]),artifact_root:x([uI]),codex_cli_version:S.check(W(lI)),codex_cli_digest:pf,protocol_epoch:S.check(W(dI)),generator:y({command:Il([x(["app-server"]),x(["generate-ts"])]),supported_surface:x(["codex app-server generators"])}),typescript_root:x(["typescript"]),files:y({count:ae.check(Mn(),Vt(0)),digest:pf})}),bD=y({path:S.check(de(1)),size:pI,sha256:pf}),wD=S.pipe(ei(rt,is()));var SI=y({owner:x(["holycodex"]),schema:S.check(W(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),installId:S.check(W(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u))});function xI(){return f(function*(){let e=yield*K({try:()=>ff(),catch:(r)=>r}),t=yield*ie({try:()=>new Ko({executablePath:e.path}),catch:(r)=>r}),n=new qo(t,{requestTimeoutMs:30000});return yield*K({try:()=>n.initialize(),catch:(r)=>r}).pipe(Ha(()=>K({try:()=>n.close(),catch:(r)=>r}).pipe(et))),{readAccountRateLimits:()=>n.readAccountRateLimits(),consumeAccountRateLimitResetCredit:(r)=>n.consumeAccountRateLimitResetCredit(r),close:()=>n.close()}})}function mf(e,t){let n=e===void 0?xI():J(e);return pg(n,t,(r)=>K({try:()=>r.close(),catch:(i)=>i}).pipe(et))}var tx=y({usedPercent:ae.check(tn(),Ln(0),ri(100)),windowDurationMins:P([ae.check(tn(),Vt(0)),G])}),EI=y({primary:P([tx,G]),secondary:P([tx,G])}),rx=y({snapshot:EI,permission:b(x(["notRequested","granted","refused"]))});function hf(e){let t=[e.snapshot.primary,e.snapshot.secondary].filter((s)=>s!==null),n=t.find((s)=>s.windowDurationMins===300),r=t.find((s)=>s.windowDurationMins===10080),i=e.permission??"notRequested",o=nx(r?.usedPercent),a=nx(n?.usedPercent);if(n!==void 0){let s=100-n.usedPercent,u=s<15||o!==null&&o<7,p=s<20||o!==null&&o<15;if(u)return Wt(!0,o,a,"resetAuthorized","A five-hour or weekly remaining quota is below its no-permission threshold.");if(r===void 0&&!p)return Wt(!0,o,a,"insufficientEvidence","The current snapshot does not contain a weekly usage window needed to rule out its threshold.");if(!p)return Wt(!0,o,a,"doNotReset","Neither remaining quota is below its permission threshold.");if(i==="granted")return Wt(!0,o,a,"resetAuthorized","Permission was granted at the current permission threshold.");return Wt(!0,o,a,"requestPermission",i==="refused"?"Permission was refused and neither quota has reached the lower no-permission threshold.":"A remaining quota is below its permission threshold.")}if(r===void 0)return Wt(null,null,null,"insufficientEvidence","The current snapshot does not contain a weekly usage window.");if(t.some((s)=>s.windowDurationMins!==10080))return Wt(null,o,null,"insufficientEvidence","A present usage window has an unknown or non-weekly duration, so a weekly-only plan cannot be inferred.");if(o!==null&&o<5)return Wt(!1,o,null,"resetAuthorized","Weekly remaining quota is below the no-permission threshold.");if(o!==null&&o>=10)return Wt(!1,o,null,"doNotReset","Weekly remaining quota is not below the permission threshold.");if(i==="granted")return Wt(!1,o,null,"resetAuthorized","Permission was granted at the weekly permission threshold.");return Wt(!1,o,null,"requestPermission",i==="refused"?"Permission was refused and weekly remaining quota has not reached the lower no-permission threshold.":"Weekly remaining quota is below its permission threshold.")}function ix(e,t="notRequested"){let n=e.rateLimitsByLimitId?.codex??e.rateLimits,r=hf({snapshot:{primary:n.primary,secondary:n.secondary},permission:t}),i=e.rateLimitResetCredits,o=i!==null&&i.availableCount>0&&i.credits!==null?i.credits.find((a)=>a.resetType==="codexRateLimits"&&a.status==="available"):void 0;return{policy:r,availableCreditCount:i?.availableCount??null,eligibleCreditId:o?.id??null}}function nx(e){return e===void 0?null:100-e}function Wt(e,t,n,r,i){return{hasFiveHourLimit:e,weeklyRemainingPercent:t,fiveHourRemainingPercent:n,decision:r,reason:i}}var ox={state:`Usage: holycodex-agent state diagnose --intent <ref> [--repo <path>]
|
|
36
50
|
|
|
37
51
|
Read-only diagnosis of one Intent, its active Plan, Assignments, and repository baseline.
|
|
52
|
+
`,"auto-reset":`Usage: holycodex-agent auto-reset evaluate --input <json>
|
|
53
|
+
|
|
54
|
+
Read-only decision adapter for the banked reset thresholds. Input contains one current snapshot
|
|
55
|
+
with primary and secondary usage windows (including explicit nulls), plus optional permission state.
|
|
56
|
+
Output identifies a five-hour window only from a 300-minute bucket and reports whether Root must
|
|
57
|
+
request permission, may use an authorized reset, must not reset, or lacks quota evidence. This
|
|
58
|
+
command never consumes a reset credit.
|
|
59
|
+
`,"auto-reset evaluate":`Usage: holycodex-agent auto-reset evaluate --input <json>
|
|
60
|
+
|
|
61
|
+
Input: {"snapshot":{"primary":window|null,"secondary":window|null},"permission"?:"notRequested"|"granted"|"refused"}.
|
|
62
|
+
Each window has usedPercent and windowDurationMins. Output includes detected five-hour limit,
|
|
63
|
+
weekly/five-hour remaining percentages, decision, and reason. Read-only; no reset is performed.
|
|
64
|
+
`,"auto-reset read":`Usage: holycodex-agent auto-reset read [--authorization granted|refused]
|
|
65
|
+
|
|
66
|
+
Reads fresh account rate limits through the local Codex App Server RPC, selects the Codex usage
|
|
67
|
+
snapshot, and reports the threshold decision and whether a known available Codex reset credit exists.
|
|
68
|
+
No reset is consumed. Only Root should run this account capability.
|
|
69
|
+
`,"auto-reset consume":`Usage: holycodex-agent auto-reset consume --idempotency-key <key> [--authorization granted|refused]
|
|
70
|
+
|
|
71
|
+
Reads fresh account rate limits and verifies the threshold and an available Codex reset credit before
|
|
72
|
+
calling the banked reset-credit RPC. At ask-permission thresholds, pass --authorization granted only
|
|
73
|
+
after the user explicitly authorizes it. A lower no-permission threshold applies even after refusal.
|
|
74
|
+
Only Root should run this consequential action. Retries for one logical attempt must reuse its key.
|
|
38
75
|
`,"state diagnose":`Usage: holycodex-agent state diagnose --intent <ref> [--repo <path>]
|
|
39
76
|
|
|
40
77
|
Output: intent_id and deterministic issues with code, subject, and repair guidance.
|
|
@@ -133,7 +170,7 @@ for legacy executing records with neither a persisted verifier nor a raw capabil
|
|
|
133
170
|
The operation atomically persists the Assignment and Intent revisions and returns both current
|
|
134
171
|
records. Worker evidence
|
|
135
172
|
cannot set Root gates; actual repository evolution or failure invalidates prior gates.
|
|
136
|
-
`};function
|
|
173
|
+
`};function gf(e){return ox[e.slice(0,2).join(" ")]??ox[e[0]??""]??`Usage: holycodex-agent <intent|assignment|state|auto-reset> <command> [options]
|
|
137
174
|
|
|
138
175
|
Deterministic model-facing work-state API. JSON responses use holycodex-agent-response-1.
|
|
139
176
|
Updates to existing records require --revision and are atomic. No command prompts or emits ANSI.
|
|
@@ -142,8 +179,9 @@ Commands:
|
|
|
142
179
|
intent create, list, current, read, select, transition, evidence, integrate, complete, abandon
|
|
143
180
|
assignment create, list, read, revise, supersede, start, recover, result
|
|
144
181
|
state diagnose
|
|
182
|
+
auto-reset read current quota/reset evidence, evaluate thresholds, consume an authorized credit
|
|
145
183
|
|
|
146
184
|
Use -h or --help at any command depth. Failures are classified and exit nonzero.
|
|
147
|
-
`}function
|
|
148
|
-
`)),0}).pipe(
|
|
149
|
-
`),
|
|
185
|
+
`}function yf(e){return e.includes("-h")||e.includes("--help")||e.length===0}var sx="holycodex-agent-response-1",wI=C(S),_I=S.check(de(1)),kI=x(["granted","refused"]),TI=y({owner:x(["holycodex"]),optional_selections:Ll}),II=y({format_version:x([1]),record:rt}),RI=Fy.check(Mn(),Vt(0)),CI=y({invocationId:S,startedAt:S,capability:qn,interruptionReason:S});function AI(e=Bun.argv.slice(2),t={cwd:process.cwd(),writeStdout:(n)=>process.stdout.write(n),writeStderr:(n)=>process.stderr.write(n)}){let n=f(function*(){let r=yield*Sf(wI,e);if(r[0]==="plan")return yield*d(new Ke("invalid_usage","Planning commands were removed. Use --help."));let i=r.filter((u)=>!u.startsWith("-")).slice(0,2);if(yf(r))return yield*dt(()=>t.writeStdout(gf(i))),0;let o=yield*PI(r),a=new Hs(o.options.repo??t.cwd??process.cwd()),s=yield*OI(a,o.command,o.subcommand,o.options,t);return yield*dt(()=>t.writeStdout(`${JSON.stringify({schema_version:sx,ok:!0,operation:`${o.command}.${o.subcommand}`,data:s})}
|
|
186
|
+
`)),0}).pipe(Ja({onFailure:(r)=>{let i=MI(r);return dt(()=>(t.writeStderr(`${JSON.stringify({schema_version:sx,ok:!1,error:i})}
|
|
187
|
+
`),i.code==="invalid_usage"||i.code==="invalid_input"?2:i.code==="completion_refused"?3:1))},onSuccess:J}));return Oe(n)}function OI(e,t,n,r,i){return f(function*(){let o=r.intent;if(t==="intent"){if(n==="create"){let a=yield*an(qs,yield*Fe(r,"input"));if(a.planRequired)return yield*d(new Ke("invalid_input","New Intents cannot require a Plan."));return yield*e.createIntent(a)}if(n==="list")return yield*e.listIntents();if(n==="current")return yield*e.currentIntent();if(n==="read")return yield*e.readIntent(yield*De(o,"intent"));if(n==="select")return yield*e.selectCurrent(yield*De(o,"intent"));if(n==="transition")return yield*e.transitionIntent(yield*De(o,"intent"),yield*Sf(fi,yield*Fe(r,"state")),yield*Jt(r),r.blocker);if(n==="evidence")return yield*e.recordIntentEvidence(yield*De(o,"intent"),yield*Jt(r),yield*an(Js,yield*Fe(r,"input")));if(n==="integrate")return yield*e.recordVcsIntegration(yield*De(o,"intent"),yield*Jt(r),yield*an(Ws,yield*Fe(r,"input")));if(n==="abandon")return yield*e.abandonIntent(yield*De(o,"intent"),yield*Jt(r));if(n==="complete"){let a=yield*e.completeIntent(yield*De(o,"intent"),yield*Jt(r));if("completed"in a&&!a.completed)return yield*d(new Ke("completion_refused","Intent completion predicates failed.",{reasons:a.reasons}));return a}}if(t==="assignment"){if(n==="create")return yield*e.createAssignment(yield*De(o,"intent"),yield*an(Vs,yield*Fe(r,"input")),yield*Jt(r));if(n==="revise")return yield*e.reviseAssignmentScope(yield*De(o,"intent"),yield*Fe(r,"assignment"),yield*an(zs,yield*Fe(r,"input")),yield*Jt(r));if(n==="supersede")return yield*e.supersedeAssignment(yield*De(o,"intent"),yield*Fe(r,"assignment"),yield*Jt(r),yield*an(Gs,yield*Fe(r,"input")));if(n==="list")return yield*e.listAssignments(yield*De(o,"intent"));if(n==="read")return yield*e.readAssignment(yield*De(o,"intent"),yield*Fe(r,"assignment"));if(n==="start"){let a=r.input,s=a===void 0?{}:yield*an(Ks,a);return yield*e.startAssignment(yield*De(o,"intent"),yield*Fe(r,"assignment"),yield*Jt(r),s)}if(n==="recover")return yield*e.recoverInterruptedAssignment(yield*De(o,"intent"),yield*Fe(r,"assignment"),yield*Jt(r),yield*an(CI,yield*Fe(r,"input")));if(n==="result"){let a=yield*an(No,yield*Fe(r,"input")),s=yield*De(o,"intent"),u=yield*Fe(r,"assignment"),p=yield*Jt(r);if(a.capability===void 0&&(yield*e.isLegacyExecutingAssignment(s,u)))return yield*e.recordAssignmentResult(s,u,p,a);return yield*e.recordSpecialistAssignmentResult(s,u,p,a)}}if(t==="state"&&n==="diagnose")return yield*e.diagnose(yield*De(o,"intent"));if(t==="auto-reset"){if(n==="evaluate"){let a=yield*an(rx,yield*Fe(r,"input"));return hf(a)}if(n==="read"){yield*cx(i.codexHome);let a=yield*dx(r.authorization);return yield*mf(i.autoResetAccountClient,(s)=>f(function*(){let u=yield*ux(s,a);return lx(u)}))}if(n==="consume"){yield*cx(i.codexHome);let a=yield*dx(r.authorization),s=yield*Fe(r,"idempotency-key");return yield*mf(i.autoResetAccountClient,(u)=>f(function*(){let p=yield*ux(u,a),c=lx(p),l=p.eligibleCreditId;if(p.policy.decision!=="resetAuthorized"||l===null)return{...c,outcome:"notConsumed"};let g=yield*K({try:()=>u.consumeAccountRateLimitResetCredit({idempotencyKey:s,creditId:l}),catch:(v)=>v});return{...c,outcome:g.outcome}}))}}return yield*d(new Ke("invalid_usage","Unknown command. Use --help."))})}function cx(e){let t=e??process.env.CODEX_HOME??ax(bI(),".codex"),n=ax(t,"holycodex","active.toml");return K({try:()=>vI(n,"utf8"),catch:()=>oc()}).pipe(xe((r)=>ie({try:()=>r.trimStart().startsWith("{")?JSON.parse(r):Bun.TOML.parse(r),catch:()=>oc()}).pipe(xe((i)=>{let o=vt(II)(i),a=Xe(o)?o.success.record:i;return mr(TI)(a).pipe(gn(()=>oc()),xe((s)=>s.optional_selections["auto-reset"]?Mu:d(oc())))}))))}function oc(){return new Ke("capability_disabled","Auto reset is disabled for this HolyCodex installation. Enable it in the install options first.")}function ux(e,t){return K({try:()=>e.readAccountRateLimits(),catch:(n)=>n}).pipe(zr((n)=>ix(n,t)))}function lx(e){return{...e.policy,availableCreditCount:e.availableCreditCount,hasSelectableCodexCredit:e.eligibleCreditId!==null}}function PI(e){return f(function*(){let t=e[0],n=e[1];if(!t||!n||t.startsWith("-")||n.startsWith("-"))return yield*d(new Ke("invalid_usage","A command and subcommand are required. Use --help."));let r={},i=NI(t,n);for(let o=2;o<e.length;o+=2){let a=e[o],s=e[o+1];if(!a?.startsWith("--")||s===void 0||s.startsWith("--"))return yield*d(new Ke("invalid_usage","Options require --name value pairs."));let u=a.slice(2);if(r[u]!==void 0)return yield*d(new Ke("invalid_usage",`Duplicate option --${u}.`));if(!i.has(u))return yield*d(new Ke("invalid_usage",`Unknown option --${u}.`));r[u]=s}return{command:t,subcommand:n,options:r}})}function NI(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"],"auto-reset evaluate":["input"],"auto-reset read":["authorization"],"auto-reset consume":["authorization","idempotency-key"]};return new Set([...n,...r[`${e} ${t}`]??[]])}class Ke extends Error{code;details;constructor(e,t,n={}){super(t);this.code=e,this.details=n}}function an(e,t){return Sf(Ol(e),t)}function Sf(e,t){return mr(e,{onExcessProperty:"error"})(t).pipe(gn((n)=>new Ke("invalid_input","Input failed Effect Schema validation.",{issue:String(n)})))}function Fe(e,t){return De(e[t],t)}function De(e,t){if(e===void 0)return d(new Ke("invalid_usage",`Missing --${t}.`));return mr(_I)(e).pipe(gn(()=>new Ke("invalid_input",`--${t} must not be empty.`)))}function Jt(e){return LI(e.revision,"revision")}function LI(e,t){return mr(RI)(e).pipe(gn(()=>new Ke("invalid_input",`--${t} must be a positive integer.`)))}function dx(e){if(e===void 0)return J("notRequested");return mr(kI)(e).pipe(gn(()=>new Ke("invalid_input","--authorization must be granted or refused.")))}function MI(e){if(e instanceof _||e instanceof Ke)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 AI();export{gf as agentHelp,yf as agentHelpRequested,AI as runAgentBinary};
|