@visa/cli 5.0.0-rc.411 → 5.0.0-rc.412

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.
@@ -55,7 +55,7 @@ ${c}
55
55
  }`,m;try{m=new d(...o,p)(...s)}catch(b){throw new Oe(`this schema (generated code failed to evaluate: ${b.message})`)}return t?.debug&&(m.code=u),m}function ae(e,t){for(let[i,n]of e.constants)if(n===t)return i;let r=`c${e.constantCounter++}`;return e.constants.set(r,t),r}function ce(e){return`v${e.varCounter++}`}function QT(e,t){let r=e._zod.run({value:t,issues:[]},{});if(r&&typeof r.then=="function")return ke.INVALID;let i=r;return i.issues.length===0?i.value:ke.INVALID}function mt(e,t,r,i,n=!0){let a=e.content.length,o=t.constants.size,s=t.constantCounter,c=t.varCounter;try{return Ue(e,t,r,i,n)}catch(u){if(!(u instanceof Oe)||!u.islandable)throw u;if(e.content.length=a,t.constants.size>o){let d=Array.from(t.constants.keys()).slice(o);for(let p of d)t.constants.delete(p)}return t.constantCounter=s,t.varCounter=c,eA(e,t,r,i)}}function eA(e,t,r,i){let n=ae(t,r),a=ae(t,QT),o=ce(t);return e.write(`const ${o} = ${a}(${n}, ${i});`),e.write(`if (${o} === INVALID) return INVALID;`),o}var tA=new Set(["max_size","min_size","size_equals","max_length","min_length","length_equals"]);function nA(e,t,r,i){let n=r._zod.def.checks;if(!n||n.length===0)return i;let a=i;for(let o of n){let s=o._zod.def;if(s.when&&!tA.has(s.check))throw new Oe('check with a custom "when" condition');switch(s.check){case"greater_than":rA(e,t,s,a);break;case"less_than":iA(e,t,s,a);break;case"multiple_of":aA(e,t,s,a);break;case"number_format":Lg(e,s,a);break;case"min_length":{let c=gi(s.minimum,"min_length"),u=Wu(e,t,a,`${a}.length >= ${c} && ${a}.length < ${s.minimum*2}`);e.write(`if (${u} < ${c}) return INVALID;`);break}case"max_length":{let c=gi(s.maximum,"max_length"),u=Wu(e,t,a,`${a}.length > ${c}`);e.write(`if (${u} > ${c}) return INVALID;`);break}case"length_equals":{let c=gi(s.length,"length_equals"),u=Wu(e,t,a,`${a}.length >= ${c} && ${a}.length <= ${s.length*2}`);e.write(`if (${u} !== ${c}) return INVALID;`);break}case"min_size":e.write(`if (${a}.size < ${gi(s.minimum,"min_size")}) return INVALID;`);break;case"max_size":e.write(`if (${a}.size > ${gi(s.maximum,"max_size")}) return INVALID;`);break;case"size_equals":e.write(`if (${a}.size !== ${gi(s.size,"size_equals")}) return INVALID;`);break;case"string_format":a=Zg(e,t,s,a);break;case"custom":a=lA(e,t,o,a);break;case"bigint_format":oA(e,s,a);break;case"mime_type":sA(e,t,s,a);break;case"property":cA(e,t,s,a);break;case"overwrite":{let c=ce(t);uA(e,t,o,a,c),a=c;break}default:throw new Oe(`check type ${s.check}`)}}return a}function Wu(e,t,r,i){let n=ae(t,st.codePointLength),a=ce(t);return e.write(`const ${a} = typeof ${r} === "string" && ${i} ? ${n}(${r}) : ${r}.length;`),a}function gi(e,t){if(typeof e!="number"||!Number.isFinite(e))throw new Oe(`${t} bound of type ${typeof e}`);return`${e}`}function Ug(e,t){if(typeof t=="bigint")return`${t}n`;if(typeof t=="number"){if(Number.isNaN(t))throw new Oe("comparison check with NaN bound");return`${t}`}if(t instanceof Date){if(Number.isNaN(t.getTime()))throw new Oe("comparison check with Invalid Date bound");return ae(e,t)}throw new Oe(`comparison check bound of type ${typeof t}`)}function rA(e,t,r,i){let n=r.inclusive?"<":"<=";e.write(`if (${i} ${n} ${Ug(t,r.value)}) return INVALID;`)}function iA(e,t,r,i){let n=r.inclusive?">":">=";e.write(`if (${i} ${n} ${Ug(t,r.value)}) return INVALID;`)}function aA(e,t,r,i){if(typeof r.value=="bigint"){if(r.value===BigInt(0))throw new Oe("multiple_of check with a zero divisor");e.write(`if (${i} % ${r.value}n !== 0n) return INVALID;`)}else{let n=ae(t,st.floatSafeRemainder);e.write(`if (${n}(${i}, ${gi(r.value,"multiple_of")}) !== 0) return INVALID;`)}}function Lg(e,t,r){let i=t.format;switch(i){case"safeint":e.write(`if (!Number.isSafeInteger(${r})) return INVALID;`);break;case"int32":e.write(`if (!Number.isInteger(${r}) || ${r} < -2147483648 || ${r} > 2147483647) return INVALID;`);break;case"uint32":e.write(`if (!Number.isInteger(${r}) || ${r} < 0 || ${r} > 4294967295) return INVALID;`);break;case"float32":e.write(`if (!Number.isFinite(${r}) || ${r} < -3.4028234663852886e38 || ${r} > 3.4028234663852886e38) return INVALID;`);break;case"float64":e.write(`if (!Number.isFinite(${r})) return INVALID;`);break;default:throw new Oe(`number format ${i}`)}}function oA(e,t,r){let i=t.format;if(i)switch(i){case"int64":e.write(`if (${r} < -9223372036854775808n || ${r} > 9223372036854775807n) return INVALID;`);break;case"uint64":e.write(`if (${r} < 0n || ${r} > 18446744073709551615n) return INVALID;`);break;default:throw new Oe(`bigint format ${i}`)}}function sA(e,t,r,i){let n=r.mime;if(n&&n.length>0){let a=ae(t,new Set(n));e.write(`if (!${a}.has(${i}.type)) return INVALID;`)}}function cA(e,t,r,i){let n=`${i}[${JSON.stringify(r.property)}]`;Ue(e,t,r.schema,n)}function uA(e,t,r,i,n){let a=r._zod.def.tx;if(!a)throw new Oe("overwrite check without a transform function");if(vi(a))throw new $r("z.compile: async overwrite transforms are not supported");let o=ae(t,a);e.write(`const ${n} = ${o}(${i});`)}function Yu(){throw new JT.$ZodAsyncError}function Hu(e){this.issues.push(e)}function lA(e,t,r,i){let n=r._zod.def;if(n.fn){if(vi(n.fn))throw new $r("z.compile: async .refine() predicates are not supported");let a=ae(t,n.fn),o=ae(t,Yu),s=ce(t);return e.write(`const ${s} = ${a}(${i});`),e.write(`if (${s} instanceof Promise) ${o}();`),e.write(`if (!${s}) return INVALID;`),i}if(r._zod.check){if(vi(r._zod.check))throw new $r("z.compile: async .superRefine() / check functions are not supported");let a=r._zod.check,s=ae(t,u=>{let d={value:u,issues:[],addIssue:Hu};return a(d)instanceof Promise&&Yu(),d.issues.length===0?d.value:ke.INVALID}),c=ce(t);return e.write(`const ${c} = ${s}(${i});`),e.write(`if (${c} === INVALID) return INVALID;`),c}throw new Oe("custom check without a predicate or check function")}var dA=new Set(["cidrv4","cuid","cuid2","date","datetime","duration","e164","email","emoji","ends_with","guid","includes","ipv4","ksuid","lowercase","mac","nanoid","regex","starts_with","time","ulid","uppercase","uuid","xid"]);function Zg(e,t,r,i){let n=r.format;if(n==="base64"){let c=ae(t,Kt.isValidBase64);return e.write(`if (!${c}(${i})) return INVALID;`),i}if(n==="base64url"){let c=ae(t,Kt.isValidBase64URL);return e.write(`if (!${c}(${i})) return INVALID;`),i}if(n==="jwt"){let c=ae(t,Kt.isValidJWT),u=ae(t,r.alg??null);return e.write(`if (!${c}(${i}, ${u})) return INVALID;`),i}if(n==="ipv6"){let c=ae(t,Kt.isValidIPv6);return e.write(`if (!${c}(${i})) return INVALID;`),i}if(n==="cidrv6"){let c=ae(t,Kt.isValidCIDRv6);return e.write(`if (!${c}(${i})) return INVALID;`),i}if(n==="credit_card"){let c=ae(t,Kt.isValidCreditCard);return e.write(`if (!${c}(${i})) return INVALID;`),i}let a=r;if(n==="url"||n==="httpurl"||a.normalize||a.hostname!==void 0||a.protocol!==void 0){let c=ae(t,Kt.parseURLObject),u=ae(t,r),d=ce(t),p=ce(t);if(e.write(`const ${d} = ${i}.trim();`),e.write(`const ${p} = ${c}(${d}, ${u});`),e.write(`if (typeof ${p} === "number") return INVALID;`),a.hostname!==void 0){let y=ae(t,Kt.urlHostnameOk);e.write(`if (!${y}(${p}, ${u}.hostname)) return INVALID;`)}if(a.protocol!==void 0){let y=ae(t,Kt.urlProtocolOk);e.write(`if (!${y}(${p}, ${u}.protocol)) return INVALID;`)}let m=ce(t),b=a.normalize?`${p}.href`:`${ae(t,Kt.stripTabAndNewline)}(${d})`;return e.write(`const ${m} = ${b};`),m}let o=r.fn;if(o){if(vi(o))throw new Oe(`async string format ${n}`);let c=ae(t,o);return e.write(`if (!${c}(${i})) return INVALID;`),i}if(dA.has(n)&&r.pattern){let c=ae(t,r.pattern);return e.write(`${c}.lastIndex = 0;`),e.write(`if (!${c}.test(${i})) return INVALID;`),i}let s=r.format;switch(s){case"regex":throw new Oe("regex format without a pattern");case"lowercase":e.write(`if (${i} !== ${i}.toLowerCase()) return INVALID;`);break;case"uppercase":e.write(`if (${i} !== ${i}.toUpperCase()) return INVALID;`);break;case"includes":e.write(`if (!${i}.includes(${st.esc(r.includes)})) return INVALID;`);break;case"starts_with":{let c=r.prefix;e.write(`if (${i}.slice(0, ${c.length}) !== ${st.esc(c)}) return INVALID;`);break}case"ends_with":{let c=r.suffix;e.write(`if (${i}.slice(-${c.length}) !== ${st.esc(c)}) return INVALID;`);break}default:throw new Oe(`string format ${s}`)}return i}function Ue(e,t,r,i,n=!0){let a=r._zod.def,o=a.type;if(a.coerce)throw new Oe(`coercion (z.coerce.${o}())`);let s=n||!!a.checks?.length,c;switch(o){case"string":c=fA(e,t,r,i);break;case"number":c=pA(e,r,i);break;case"boolean":c=mA(e,i);break;case"bigint":c=gA(e,r,i);break;case"symbol":c=_A(e,i);break;case"undefined":c=hA(e,i);break;case"null":c=vA(e,i);break;case"any":case"unknown":c=i;break;case"never":e.write("return INVALID;"),c=i;break;case"void":c=yA(e,i);break;case"nan":c=bA(e,i);break;case"date":c=wA(e,i);break;case"object":c=SA(e,t,r,i,s);break;case"optional":c=$A(e,t,r,i,s);break;case"nullable":c=EA(e,t,r,i,s);break;case"array":c=PA(e,t,r,i,s);break;case"literal":c=zA(e,t,r,i);break;case"enum":c=TA(e,t,r,i);break;case"readonly":{let u=Cg(e,t,r,i),d=ce(t);e.write(`const ${d} = Object.freeze(${u});`),c=d;break}case"success":Cg(e,t,r,i),c="true";break;case"default":case"prefault":c=AA(e,t,r,i);break;case"nonoptional":c=jA(e,t,r,i);break;case"tuple":c=kA(e,t,r,i);break;case"union":c=NA(e,t,r,i);break;case"intersection":c=DA(e,t,r,i);break;case"record":c=MA(e,t,r,i);break;case"map":c=UA(e,t,r,i);break;case"set":c=LA(e,t,r,i);break;case"file":c=ZA(e,i);break;case"template_literal":c=qA(e,t,r,i);break;case"lazy":c=FA(e,t,r,i);break;case"pipe":c=VA(e,t,r,i);break;case"custom":c=BA(e,t,r,i);break;case"transform":c=WA(e,t,r,i);break;case"catch":c=JA(e,t,r,i);break;default:throw new Oe(`schema type ${o}`)}return c===null?null:nA(e,t,r,c)}function fA(e,t,r,i){e.write(`if (typeof ${i} !== "string") return INVALID;`);let n=r._zod.def;return n.format===void 0?i:Zg(e,t,n,i)}function pA(e,t,r){e.write(`if (typeof ${r} !== "number" || !Number.isFinite(${r})) return INVALID;`);let i=t._zod.def;return i.check==="number_format"&&i.format&&Lg(e,{format:i.format},r),r}function mA(e,t){return e.write(`if (typeof ${t} !== "boolean") return INVALID;`),t}function gA(e,t,r){e.write(`if (typeof ${r} !== "bigint") return INVALID;`);let i=t._zod.def;if(i.format)switch(i.format){case"int64":e.write(`if (${r} < -9223372036854775808n || ${r} > 9223372036854775807n) return INVALID;`);break;case"uint64":e.write(`if (${r} < 0n || ${r} > 18446744073709551615n) return INVALID;`);break}return r}function _A(e,t){return e.write(`if (typeof ${t} !== "symbol") return INVALID;`),t}function hA(e,t){return e.write(`if (${t} !== undefined) return INVALID;`),t}function vA(e,t){return e.write(`if (${t} !== null) return INVALID;`),t}function yA(e,t){return e.write(`if (${t} !== undefined) return INVALID;`),t}function bA(e,t){return e.write(`if (typeof ${t} !== "number" || !Number.isNaN(${t})) return INVALID;`),t}function wA(e,t){return e.write(`if (!(${t} instanceof Date) || Number.isNaN(${t}.getTime())) return INVALID;`),t}function SA(e,t,r,i,n=!0){let a=r._zod.def;e.write(`if (typeof ${i} !== "object" || ${i} === null || Array.isArray(${i})) return INVALID;`);let o=a.shape,s=Object.keys(o),c=Object.getOwnPropertySymbols(o),u=c.length?[...s,...c]:s,d=C=>typeof C=="symbol"?ae(t,C):st.esc(C),p=C=>typeof C=="symbol"?`[${d(C)}]`:st.esc(C),m=o;if(s.includes("__proto__"))throw new Oe('object shape key "__proto__"');let b=new Map;for(let C of u){let Z=m[C],oe=d(C),ve=ce(t);if(e.write(`const ${ve} = ${i}[${oe}];`),Z._zod.optin!==void 0){let me=ce(t);e.write(`let ${me} = (() => {`),e.indented(Pe=>{let ft=mt(Pe,t,Z,ve);Pe.write(`return ${ft};`)}),e.write("})();"),Z._zod.optout==="optional"?(e.write(`if (${me} === INVALID) {`),e.indented(Pe=>{Pe.write(`if (${oe} in ${i}) return INVALID;`),Pe.write(`${me} = undefined;`)}),e.write("}")):e.write(`if (${me} === INVALID) return INVALID;`),b.set(C,me)}else{IA(Z)&&e.write(`if (!(${oe} in ${i})) return INVALID;`);let me=mt(e,t,Z,ve,n);me!==null&&b.set(C,me)}}let y=a.catchall,O="none";if(y){let C=y._zod.def.type;if(C==="never"){let Z=s.map(oe=>`k !== ${st.esc(oe)}`).join(" && ")||"true";e.write(`for (const k in ${i}) {`),e.indented(oe=>{oe.write(`if (${Z}) return INVALID;`)}),e.write("}")}else(C==="unknown"||C==="any")&&!y._zod.def.checks?.length?O="passthrough":O="schema"}let z=ce(t),re=u.some(C=>hi(m[C])||Ku(m[C]));if(!n){if(O==="schema"){let C=s.length>0?ae(t,new Set(s)):null;e.write(`for (const k in ${i}) {`),e.indented(Z=>{Z.write('if (k === "__proto__") continue;'),C&&Z.write(`if (${C}.has(k)) continue;`);let oe=ce(t);Z.write(`const ${oe} = ${i}[k];`),mt(Z,t,y,oe,!1)}),e.write("}")}return null}if(re){e.write(`const ${z} = {};`);for(let C of u){let Z=d(C),oe=b.get(C);Ku(m[C])?e.write(`if (${Z} in ${i}) ${z}[${Z}] = ${oe};`):hi(m[C])?e.write(`if (${oe} !== undefined || ${Z} in ${i}) ${z}[${Z}] = ${oe};`):e.write(`${z}[${Z}] = ${oe};`)}}else{let C=u.map(Z=>`${p(Z)}: ${b.get(Z)}`).join(", ");e.write(`const ${z} = { ${C} };`)}if(O!=="none"){let C=s.length>0?ae(t,new Set(s)):null;e.write(`for (const k in ${i}) {`),e.indented(Z=>{if(Z.write('if (k === "__proto__") continue;'),C&&Z.write(`if (${C}.has(k)) continue;`),O==="passthrough")Z.write(`${z}[k] = ${i}[k];`);else{let oe=ce(t);Z.write(`const ${oe} = ${i}[k];`);let ve=mt(Z,t,y,oe);Z.write(`${z}[k] = ${ve};`)}}),e.write("}")}return z}function $A(e,t,r,i,n=!0){let a=r._zod.def;if(OA(r))return Ue(e,t,a.innerType,i,n);if(a.innerType._zod.optin==="defaulted"){let s=ce(t),c=ce(t);return e.write(`let ${s};`),e.write(`if (${i} === undefined) {`),e.indented(u=>{u.write(`const ${c} = (() => {`),u.indented(d=>{let p=Ue(d,t,a.innerType,i);d.write(`return ${p};`)}),u.write("})();"),u.write(`if (${c} !== INVALID) ${s} = ${c};`)}),e.write("} else {"),e.indented(u=>{let d=Ue(u,t,a.innerType,i);u.write(`${s} = ${d};`)}),e.write("}"),s}let o=n?ce(t):null;return o&&e.write(`let ${o};`),e.write(`if (${i} !== undefined) {`),e.indented(s=>{let c=Ue(s,t,a.innerType,i,n);o&&c!==null&&s.write(`${o} = ${c};`)}),e.write("}"),o}function OA(e){return e._zod.traits?.has("$ZodExactOptional")===!0}function IA(e){return e._zod.optin===void 0&&_i(e)}function _i(e){if(e._zod.def.coerce)return!0;let t=e._zod.def;switch(t.type){case"any":case"unknown":case"undefined":case"void":case"default":case"prefault":case"transform":case"custom":case"lazy":return!0;case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"never":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":return!1;case"nonoptional":return t.innerType?_i(t.innerType):!1;case"literal":return!!t.values?.includes(void 0);case"enum":return!!e._zod.values?.has(void 0);case"optional":case"nullable":case"readonly":case"success":return t.innerType?_i(t.innerType):!0;case"catch":return!0;case"union":return t.options?t.options.some(_i):!0;case"intersection":return!t.left||!t.right?!0:_i(t.left)&&_i(t.right);case"pipe":return t.in?_i(t.in):!0;default:return!0}}function Ku(e){return e._zod.optin==="optional"&&e._zod.optout==="optional"}function hi(e){let t=e._zod.def;switch(t.type){case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":case"never":case"success":return!1;case"literal":return!!t.values?.includes(void 0);case"enum":return!!e._zod.values?.has(void 0);case"optional":return!0;case"nullable":case"readonly":case"nonoptional":return t.innerType?hi(t.innerType):!0;case"union":return t.options?t.options.some(hi):!0;case"intersection":return!t.left||!t.right||hi(t.left)||hi(t.right);case"pipe":return t.out?hi(t.out):!0;default:return!0}}function EA(e,t,r,i,n=!0){let a=r._zod.def,o=n?ce(t):null;return o&&e.write(`let ${o} = null;`),e.write(`if (${i} !== null) {`),e.indented(s=>{let c=Ue(s,t,a.innerType,i,n);o&&c!==null&&s.write(`${o} = ${c};`)}),e.write("}"),o}function PA(e,t,r,i,n=!0){let a=r._zod.def;e.write(`if (!Array.isArray(${i})) return INVALID;`);let o=n?ce(t):null,s=ce(t),c=ce(t);return o&&e.write(`const ${o} = new Array(${i}.length);`),e.write(`for (let ${s} = 0; ${s} < ${i}.length; ${s}++) {`),e.indented(u=>{u.write(`const ${c} = ${i}[${s}];`);let d=mt(u,t,a.element,c,n);o&&d!==null&&u.write(`${o}[${s}] = ${d};`)}),e.write("}"),o}function zA(e,t,r,i){let a=r._zod.def.values;if(a.length!==1){let s=ae(t,new Set(a));return e.write(`if (!${s}.has(${i})) return INVALID;`),i}let o=a[0];if(typeof o=="number"&&Number.isNaN(o)){let s=ae(t,new Set(a));return e.write(`if (!${s}.has(${i})) return INVALID;`),i}if(typeof o=="string")e.write(`if (${i} !== ${st.esc(o)}) return INVALID;`);else if(typeof o=="number"||typeof o=="boolean")e.write(`if (${i} !== ${o}) return INVALID;`);else if(o===null)e.write(`if (${i} !== null) return INVALID;`);else if(o===void 0)e.write(`if (${i} !== undefined) return INVALID;`);else if(typeof o=="bigint")e.write(`if (${i} !== ${o}n) return INVALID;`);else throw new Oe(`literal type ${typeof o}`);return i}function TA(e,t,r,i){let n=r._zod.values;if(!n)throw new Oe("enum schema without enumerated values");let a=ae(t,n);return e.write(`if (!${a}.has(${i})) return INVALID;`),i}function Cg(e,t,r,i){let n=r._zod.def;return Ue(e,t,n.innerType,i)}function AA(e,t,r,i){let n=r._zod.def,o=Object.getOwnPropertyDescriptor(r._zod.def,"defaultValue")?()=>r._zod.def.defaultValue:void 0;if(r._zod.def.type==="prefault"){if(!o)return Ue(e,t,n.innerType,i);let c=ae(t,o),u=ce(t);return e.write(`let ${u} = ${i};`),e.write(`if (${i} === undefined) ${u} = ${c}();`),Ue(e,t,n.innerType,u)}let s=ce(t);if(o){let c=ae(t,o),u=ae(t,st.shallowClone);e.write(`let ${s};`),e.write(`if (${i} === undefined) {`),e.indented(d=>{d.write(`${s} = ${u}(${c}());`)}),e.write("} else {"),e.indented(d=>{let p=Ue(d,t,n.innerType,i);d.write(`${s} = ${p} === undefined ? ${u}(${c}()) : ${p};`)}),e.write("}")}else e.write(`let ${s};`),e.write(`if (${i} !== undefined) {`),e.indented(c=>{let u=Ue(c,t,n.innerType,i);c.write(`${s} = ${u};`)}),e.write("}");return s}function jA(e,t,r,i){let n=r._zod.def,a=Ue(e,t,n.innerType,i),o=ce(t);return e.write(`const ${o} = ${a};`),e.write(`if (${o} === undefined) return INVALID;`),o}function kA(e,t,r,i){let n=r._zod.def,a=n.items,o=n.rest;e.write(`if (!Array.isArray(${i})) return INVALID;`);let s=Dg(a,"optin"),c=Dg(a,"optout");o?e.write(`if (${i}.length < ${s}) return INVALID;`):e.write(`if (${i}.length < ${s} || ${i}.length > ${a.length}) return INVALID;`);let u=ce(t);e.write(`const ${u} = [];`);for(let d=0;d<a.length;d++){let p=a[d];if(d>=c)e.write(`if (${u}.length === ${d}) {`),e.indented(m=>{m.write(`if (${d} < ${i}.length) {`),m.indented(b=>{let y=ce(t);b.write(`const ${y} = ${i}[${d}];`);let O=mt(b,t,p,y);b.write(`${u}[${d}] = ${O};`)}),m.write("} else {"),m.indented(b=>{if(Ku(p)){b.write(`${u}.length = ${d};`);return}let y=ce(t),O=ce(t);b.write(`const ${y} = undefined;`),b.write(`const ${O} = (() => {`),b.indented(z=>{let re=mt(z,t,p,y);z.write(`return ${re};`)}),b.write("})();"),b.write(`if (${O} === INVALID || ${O} === undefined) ${u}.length = ${d};`),b.write(`else ${u}[${d}] = ${O};`)}),m.write("}")}),e.write("}");else{let m=ce(t);e.write(`const ${m} = ${i}[${d}];`);let b=mt(e,t,p,m);e.write(`${u}[${d}] = ${b};`)}}if(o){let d=ce(t),p=ce(t);e.write(`for (let ${d} = ${a.length}; ${d} < ${i}.length; ${d}++) {`),e.indented(m=>{m.write(`const ${p} = ${i}[${d}];`);let b=mt(m,t,o,p);m.write(`${u}[${d}] = ${b};`)}),e.write("}")}return u}function Dg(e,t){for(let r=e.length-1;r>=0;r--)if(!(t==="optin"?e[r]._zod.optin!==void 0:e[r]._zod.optout==="optional"))return r+1;return 0}function NA(e,t,r,i){let n=r._zod.def,a=n.options;if(n.discriminator)return RA(e,t,n,i);if(n.inclusive===!1)throw new Oe("exclusive unions (z.xor)");if(a.length===0)return e.write("return INVALID;"),i;if(a.length===1)return Ue(e,t,a[0],i);if(a.every(c=>c._zod.def.type==="literal"&&!c._zod.def.checks?.length)){let c=new Set(a.flatMap(d=>d._zod.def.values)),u=ae(t,c);return e.write(`if (!${u}.has(${i})) return INVALID;`),i}let s=ce(t);e.write(`let ${s};`);for(let c=0;c<a.length;c++){let u=a[c];c===0?e.write(`${s} = (() => {`):e.write(`if (${s} === INVALID) ${s} = (() => {`),e.indented(d=>{let p=Ue(d,t,u,i);d.write(`return ${p};`)}),e.write("})();")}return e.write(`if (${s} === INVALID) return INVALID;`),s}function RA(e,t,r,i){if(r.unionFallback)throw new Oe("discriminated union with unionFallback");if(r.options.length===0)return e.write("return INVALID;"),i;let n=ce(t),a=ce(t);e.write(`const ${n} = ${i}?.[${st.esc(r.discriminator)}];`),e.write(`let ${a};`);let o=!0,s=new Set;for(let c of r.options){let u=c._zod.propValues?.[r.discriminator];if(!u||u.size===0)throw new Oe("discriminated union option without static discriminator values");for(let m of u){if(s.has(m))throw new Oe(`duplicate discriminator value ${String(m)}`);s.add(m)}let d=Array.from(u,m=>CA(t,n,m)),p=o?"if":"else if";e.write(`${p} (${d.join(" || ")}) {`),e.indented(m=>{let b=Ue(m,t,c,i);m.write(`${a} = ${b};`)}),e.write("}"),o=!1}return e.write("else { return INVALID; }"),a}function CA(e,t,r){if(typeof r=="string")return`${t} === ${st.esc(r)}`;if(typeof r=="number")return Number.isNaN(r)?`Number.isNaN(${t})`:`${t} === ${r}`;if(typeof r=="boolean")return`${t} === ${r}`;if(r===null)return`${t} === null`;if(r===void 0)return`${t} === undefined`;if(typeof r=="bigint")return`${t} === ${r}n`;if(typeof r=="symbol"){let i=ae(e,r);return`${t} === ${i}`}throw new Oe(`literal discriminator value ${String(r)}`)}function DA(e,t,r,i){let n=r._zod.def,a=mt(e,t,n.left,i),o=mt(e,t,n.right,i),s=ae(t,Kt.mergeValues),c=ce(t);return e.write(`const ${c} = ${s}(${a}, ${o});`),e.write(`if (!${c}.valid) return INVALID;`),`${c}.data`}function MA(e,t,r,i){let n=r._zod.def,a=ae(t,st.isPlainObject);e.write(`if (!${a}(${i})) return INVALID;`);let o=ce(t),s=ce(t),c=ce(t);e.write(`const ${o} = {};`);let u=n,d=u.partial?void 0:n.keyType._zod.values;if(d){let y=[];for(let z of d){if(!(typeof z=="string"||typeof z=="number"||typeof z=="symbol"))throw new Oe(`record key value ${String(z)}`);let re=typeof z=="number"?z.toString():z;if(re==="__proto__")throw new Oe('record key "__proto__"');y.push(re);let C=ae(t,z),Z=Ue(e,t,n.keyType,C),oe=ce(t);e.write(`const ${oe} = ${i}[${xA(t,re)}];`);let ve=mt(e,t,n.valueType,oe);e.write(`${o}[${Z}] = ${ve};`)}let O=ae(t,new Set(y));return e.write(`for (const ${s} in ${i}) {`),e.indented(z=>{z.write(`if (${O}.has(${s})) continue;`),u.mode==="loose"?z.write(`if (${s} !== "__proto__") ${o}[${s}] = ${i}[${s}];`):z.write("return INVALID;")}),e.write("}"),o}let p=n.keyType._zod.def;if(!(p.type==="string"&&p.format===void 0&&!p.coerce&&(p.checks?.length??0)===0)){let y=n.mode==="loose",O=ae(t,qs(n.keyType)),z=ae(t,YT.number),re=ae(t,Object.prototype.propertyIsEnumerable),C=ce(t);return e.write(`for (const ${s} of Reflect.ownKeys(${i})) {`),e.indented(Z=>{Z.write(`if (${s} === "__proto__") continue;`),Z.write(`if (!${re}.call(${i}, ${s})) continue;`),Z.write(`let ${C} = ${O}(${s});`),Z.write(`if (${C} === INVALID && typeof ${s} === "string" && ${z}.test(${s})) ${C} = ${O}(Number(${s}));`),y?Z.write(`if (${C} === INVALID) { ${o}[${s}] = ${i}[${s}]; continue; }`):Z.write(`if (${C} === INVALID) return INVALID;`),Z.write(`if (${C} === "__proto__") continue;`);let oe=ce(t);Z.write(`const ${oe} = ${i}[${s}];`);let ve=mt(Z,t,n.valueType,oe);Z.write(`${o}[${C}] = ${ve};`)}),e.write("}"),o}let b=ae(t,Object.prototype.propertyIsEnumerable);return e.write(`for (const ${s} of Reflect.ownKeys(${i})) {`),e.indented(y=>{y.write(`if (${s} === "__proto__") continue;`),y.write(`if (!${b}.call(${i}, ${s})) continue;`),y.write(`if (typeof ${s} !== "string") return INVALID;`),y.write(`const ${c} = ${i}[${s}];`);let O=mt(y,t,n.valueType,c);y.write(`${o}[${s}] = ${O};`)}),e.write("}"),o}function xA(e,t){return typeof t=="string"?st.esc(t):ae(e,t)}function UA(e,t,r,i){let n=r._zod.def;e.write(`if (!(${i} instanceof Map)) return INVALID;`);let a=ce(t),o=ce(t),s=ce(t);return e.write(`const ${a} = new Map();`),e.write(`for (const [${o}, ${s}] of ${i}) {`),e.indented(c=>{let u=Ue(c,t,n.keyType,o),d=Ue(c,t,n.valueType,s);c.write(`${a}.set(${u}, ${d});`)}),e.write("}"),a}function LA(e,t,r,i){let n=r._zod.def;e.write(`if (!(${i} instanceof Set)) return INVALID;`);let a=ce(t),o=ce(t);return e.write(`const ${a} = new Set();`),e.write(`for (const ${o} of ${i}) {`),e.indented(s=>{let c=Ue(s,t,n.valueType,o);s.write(`${a}.add(${c});`)}),e.write("}"),a}function ZA(e,t){return e.write(`if (!(${t} instanceof File)) return INVALID;`),t}function qA(e,t,r,i){e.write(`if (typeof ${i} !== "string") return INVALID;`);let n=r._zod.pattern;if(n){let a=ae(t,n);e.write(`${a}.lastIndex = 0;`),e.write(`if (!${a}.test(${i})) return INVALID;`)}return i}function FA(e,t,r,i){let n=r._zod.def,a=ae(t,n.getter),o=ae(t,{parser:null});e.write(`if (!${o}.parser) {`),e.indented(c=>{c.write(`const inner = ${a}();`),c.write(`${o}.parser = function(input) {`),c.indented(u=>{u.write("const result = inner._zod.run({ value: input, issues: [] }, {});"),u.write("return result.issues.length === 0 ? result.value : INVALID;")}),c.write("};")}),e.write("}");let s=ce(t);return e.write(`const ${s} = ${o}.parser(${i});`),e.write(`if (${s} === INVALID) return INVALID;`),s}function VA(e,t,r,i){let n=r._zod.def,a=Ue(e,t,n.in,i);if(n.transform){if(vi(n.transform))throw new $r("z.compile: async transforms in pipes are not supported");let o=n.transform,c=ae(t,d=>{let p={value:d,issues:[],addIssue:Hu},m=o(d,p);return m instanceof Promise?ke.INVALID:p.issues.length===0?m:ke.INVALID}),u=ce(t);return e.write(`const ${u} = ${c}(${a});`),e.write(`if (${u} === INVALID) return INVALID;`),Ue(e,t,n.out,u)}else return Ue(e,t,n.out,a)}function vi(e){return typeof e=="function"&&(e.constructor.name==="AsyncFunction"||e[Symbol.toStringTag]==="AsyncFunction")}function BA(e,t,r,i){let n=r._zod.def;if(n.fn){if(vi(n.fn))throw new $r("z.compile: async custom predicates are not supported");let a=ae(t,n.fn),o=ae(t,Yu),s=ce(t);e.write(`const ${s} = ${a}(${i});`),e.write(`if (${s} instanceof Promise) ${o}();`),e.write(`if (!${s}) return INVALID;`)}else throw new Oe("custom schema without a predicate function");return i}function GA(e,t,r){let i=e._zod.run({value:r,issues:[]},{});if(i&&typeof i.then=="function")return ke.INVALID;let n=i;return n.issues.length===0?n.value:t()}function JA(e,t,r,i){let n=r._zod.def;if(!n.catchValue[st.CONSTANT_CATCH])throw new Oe("catch with a callback (only a constant catch value compiles)",!1);let a=ce(t);e.write(`let ${a} = (() => {`),e.indented(u=>{let d=mt(u,t,n.innerType,i);u.write(`return ${d};`)}),e.write("})();");let o=ae(t,n.innerType),s=ae(t,n.catchValue),c=ae(t,GA);return e.write(`if (${a} === INVALID) {`),e.indented(u=>{u.write(`${a} = ${c}(${o}, ${s}, ${i});`),u.write(`if (${a} === INVALID) return INVALID;`)}),e.write("}"),a}function WA(e,t,r,i){let n=r._zod.def;if(n.transform){if(vi(n.transform))throw new $r("z.compile: async transforms are not supported");let a=n.transform,s=ae(t,u=>{let d={value:u,issues:[],addIssue:Hu},p=a(u,d);return p instanceof Promise?ke.INVALID:d.issues.length===0?p:ke.INVALID}),c=ce(t);return e.write(`const ${c} = ${s}(${i});`),e.write(`if (${c} === INVALID) return INVALID;`),c}return i}});var Gg=P(T=>{"use strict";var YA=T&&T.__createBinding||(Object.create?(function(e,t,r,i){i===void 0&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);(!n||("get"in n?!t.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}):(function(e,t,r,i){i===void 0&&(i=r),e[i]=t[r]})),KA=T&&T.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),Bs=T&&T.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&YA(t,e,r);return KA(t,e),t};Object.defineProperty(T,"__esModule",{value:!0});T.TimePrecision=void 0;T._string=HA;T._coercedString=XA;T._email=QA;T._guid=e0;T._uuid=t0;T._uuidv4=n0;T._uuidv6=r0;T._uuidv7=i0;T._url=a0;T._emoji=o0;T._nanoid=s0;T._cuid=c0;T._cuid2=u0;T._ulid=l0;T._xid=d0;T._ksuid=f0;T._ipv4=p0;T._ipv6=m0;T._mac=g0;T._cidrv4=_0;T._cidrv6=h0;T._base64=v0;T._base64url=y0;T._e164=b0;T._creditCard=w0;T._jwt=S0;T._isoDateTime=$0;T._isoDate=O0;T._isoTime=I0;T._isoDuration=E0;T._number=P0;T._coercedNumber=z0;T._int=T0;T._float32=A0;T._float64=j0;T._int32=k0;T._uint32=N0;T._boolean=R0;T._coercedBoolean=C0;T._bigint=D0;T._coercedBigint=M0;T._int64=x0;T._uint64=U0;T._symbol=L0;T._undefined=Z0;T._null=q0;T._any=F0;T._unknown=V0;T._never=B0;T._void=G0;T._date=J0;T._coercedDate=W0;T._nan=Y0;T._lt=Fg;T._lte=Pa;T._max=Pa;T._lte=Pa;T._max=Pa;T._gt=Vg;T._gte=za;T._min=za;T._gte=za;T._min=za;T._positive=K0;T._negative=H0;T._nonpositive=X0;T._nonnegative=Q0;T._multipleOf=ej;T._maxSize=tj;T._minSize=nj;T._size=rj;T._maxLength=ij;T._minLength=aj;T._length=oj;T._regex=sj;T._lowercase=cj;T._uppercase=uj;T._includes=lj;T._startsWith=dj;T._endsWith=fj;T._property=pj;T._properties=mj;T._mime=gj;T._overwrite=Hi;T._normalize=_j;T._trim=hj;T._toLowerCase=vj;T._toUpperCase=yj;T._slugify=bj;T._array=wj;T._union=Sj;T._xor=$j;T._discriminatedUnion=Oj;T._intersection=Ij;T._tuple=Ej;T._record=Pj;T._map=zj;T._set=Tj;T._enum=Aj;T._nativeEnum=jj;T._literal=kj;T._file=Nj;T._transform=Rj;T._optional=Cj;T._nullable=Dj;T._default=Mj;T._nonoptional=xj;T._success=Uj;T._catch=Lj;T._pipe=Zj;T._readonly=qj;T._templateLiteral=Fj;T._lazy=Vj;T._promise=Bj;T._custom=Gj;T._refine=Jj;T._superRefine=Wj;T._check=Bg;T.describe=Yj;T.meta=Kj;T._stringbool=Hj;T._stringFormat=Xj;var Le=Bs(wo()),Vs=Bs(Ea()),Fs=Bs(Oa()),x=Bs(B());function HA(e,t){return new e({type:"string",...x.normalizeParams(t)})}function XA(e,t){return new e({type:"string",coerce:!0,...x.normalizeParams(t)})}function QA(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...x.normalizeParams(t)})}function e0(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...x.normalizeParams(t)})}function t0(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...x.normalizeParams(t)})}function n0(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...x.normalizeParams(t)})}function r0(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...x.normalizeParams(t)})}function i0(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...x.normalizeParams(t)})}function a0(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...x.normalizeParams(t)})}function o0(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...x.normalizeParams(t)})}function s0(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...x.normalizeParams(t)})}function c0(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...x.normalizeParams(t)})}function u0(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...x.normalizeParams(t)})}function l0(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...x.normalizeParams(t)})}function d0(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...x.normalizeParams(t)})}function f0(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...x.normalizeParams(t)})}function p0(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...x.normalizeParams(t)})}function m0(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...x.normalizeParams(t)})}function g0(e,t){return new e({type:"string",format:"mac",check:"string_format",abort:!1,...x.normalizeParams(t)})}function _0(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...x.normalizeParams(t)})}function h0(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...x.normalizeParams(t)})}function v0(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...x.normalizeParams(t)})}function y0(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...x.normalizeParams(t)})}function b0(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...x.normalizeParams(t)})}function w0(e,t){return new e({type:"string",format:"credit_card",check:"string_format",abort:!1,...x.normalizeParams(t)})}function S0(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...x.normalizeParams(t)})}T.TimePrecision={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function $0(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...x.normalizeParams(t)})}function O0(e,t){return new e({type:"string",format:"date",check:"string_format",...x.normalizeParams(t)})}function I0(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...x.normalizeParams(t)})}function E0(e,t){return new e({type:"string",format:"duration",check:"string_format",...x.normalizeParams(t)})}function P0(e,t){return new e({type:"number",checks:[],...x.normalizeParams(t)})}function z0(e,t){return new e({type:"number",coerce:!0,checks:[],...x.normalizeParams(t)})}function T0(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...x.normalizeParams(t)})}function A0(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...x.normalizeParams(t)})}function j0(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...x.normalizeParams(t)})}function k0(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...x.normalizeParams(t)})}function N0(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...x.normalizeParams(t)})}function R0(e,t){return new e({type:"boolean",...x.normalizeParams(t)})}function C0(e,t){return new e({type:"boolean",coerce:!0,...x.normalizeParams(t)})}function D0(e,t){return new e({type:"bigint",...x.normalizeParams(t)})}function M0(e,t){return new e({type:"bigint",coerce:!0,...x.normalizeParams(t)})}function x0(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...x.normalizeParams(t)})}function U0(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...x.normalizeParams(t)})}function L0(e,t){return new e({type:"symbol",...x.normalizeParams(t)})}function Z0(e,t){return new e({type:"undefined",...x.normalizeParams(t)})}function q0(e,t){return new e({type:"null",...x.normalizeParams(t)})}function F0(e){return new e({type:"any"})}function V0(e){return new e({type:"unknown"})}function B0(e,t){return new e({type:"never",...x.normalizeParams(t)})}function G0(e,t){return new e({type:"void",...x.normalizeParams(t)})}function J0(e,t){return new e({type:"date",...x.normalizeParams(t)})}function W0(e,t){return new e({type:"date",coerce:!0,...x.normalizeParams(t)})}function Y0(e,t){return new e({type:"nan",...x.normalizeParams(t)})}function Fg(e,t){return new Le.$ZodCheckLessThan({check:"less_than",...x.normalizeParams(t),value:e,inclusive:!1})}function Pa(e,t){return new Le.$ZodCheckLessThan({check:"less_than",...x.normalizeParams(t),value:e,inclusive:!0})}function Vg(e,t){return new Le.$ZodCheckGreaterThan({check:"greater_than",...x.normalizeParams(t),value:e,inclusive:!1})}function za(e,t){return new Le.$ZodCheckGreaterThan({check:"greater_than",...x.normalizeParams(t),value:e,inclusive:!0})}function K0(e){return Vg(0,e)}function H0(e){return Fg(0,e)}function X0(e){return Pa(0,e)}function Q0(e){return za(0,e)}function ej(e,t){return new Le.$ZodCheckMultipleOf({check:"multiple_of",...x.normalizeParams(t),value:e})}function tj(e,t){return new Le.$ZodCheckMaxSize({check:"max_size",...x.normalizeParams(t),maximum:e})}function nj(e,t){return new Le.$ZodCheckMinSize({check:"min_size",...x.normalizeParams(t),minimum:e})}function rj(e,t){return new Le.$ZodCheckSizeEquals({check:"size_equals",...x.normalizeParams(t),size:e})}function ij(e,t){return new Le.$ZodCheckMaxLength({check:"max_length",...x.normalizeParams(t),maximum:e})}function aj(e,t){return new Le.$ZodCheckMinLength({check:"min_length",...x.normalizeParams(t),minimum:e})}function oj(e,t){return new Le.$ZodCheckLengthEquals({check:"length_equals",...x.normalizeParams(t),length:e})}function sj(e,t){return new Le.$ZodCheckRegex({check:"string_format",format:"regex",...x.normalizeParams(t),pattern:e})}function cj(e){return new Le.$ZodCheckLowerCase({check:"string_format",format:"lowercase",...x.normalizeParams(e)})}function uj(e){return new Le.$ZodCheckUpperCase({check:"string_format",format:"uppercase",...x.normalizeParams(e)})}function lj(e,t){return new Le.$ZodCheckIncludes({check:"string_format",format:"includes",...x.normalizeParams(t),includes:e})}function dj(e,t){return new Le.$ZodCheckStartsWith({check:"string_format",format:"starts_with",...x.normalizeParams(t),prefix:e})}function fj(e,t){return new Le.$ZodCheckEndsWith({check:"string_format",format:"ends_with",...x.normalizeParams(t),suffix:e})}function pj(e,t,r){return new Le.$ZodCheckProperty({check:"property",property:e,schema:t,...x.normalizeParams(r)})}function mj(e){return Object.entries(e).map(([t,r])=>new Le.$ZodCheckProperty({check:"property",property:t,schema:r}))}function gj(e,t){return new Le.$ZodCheckMimeType({check:"mime_type",mime:e,...x.normalizeParams(t)})}function Hi(e){return new Le.$ZodCheckOverwrite({check:"overwrite",tx:e})}function _j(e){return Hi(t=>t.normalize(e))}function hj(){return Hi(e=>e.trim())}function vj(){return Hi(e=>e.toLowerCase())}function yj(){return Hi(e=>e.toUpperCase())}function bj(){return Hi(e=>x.slugify(e))}function wj(e,t,r){return new e({type:"array",element:t,...x.normalizeParams(r)})}function Sj(e,t,r){return new e({type:"union",options:t,...x.normalizeParams(r)})}function $j(e,t,r){return new e({type:"union",options:t,inclusive:!1,...x.normalizeParams(r)})}function Oj(e,t,r,i){return new e({type:"union",options:r,discriminator:t,...x.normalizeParams(i)})}function Ij(e,t,r){return new e({type:"intersection",left:t,right:r})}function Ej(e,t,r,i){let n=r instanceof Fs.$ZodType,a=n?i:r,o=n?r:null;return new e({type:"tuple",items:t,rest:o,...x.normalizeParams(a)})}function Pj(e,t,r,i){return new e({type:"record",keyType:t,valueType:r,...x.normalizeParams(i)})}function zj(e,t,r,i){return new e({type:"map",keyType:t,valueType:r,...x.normalizeParams(i)})}function Tj(e,t,r){return new e({type:"set",valueType:t,...x.normalizeParams(r)})}function Aj(e,t,r){let i=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new e({type:"enum",entries:i,...x.normalizeParams(r)})}function jj(e,t,r){return new e({type:"enum",entries:t,...x.normalizeParams(r)})}function kj(e,t,r){return new e({type:"literal",values:Array.isArray(t)?t:[t],...x.normalizeParams(r)})}function Nj(e,t){return new e({type:"file",...x.normalizeParams(t)})}function Rj(e,t){return new e({type:"transform",transform:t})}function Cj(e,t){return new e({type:"optional",innerType:t})}function Dj(e,t){return new e({type:"nullable",innerType:t})}function Mj(e,t,r){return new e({type:"default",innerType:t,get defaultValue(){return typeof r=="function"?r():x.shallowClone(r)}})}function xj(e,t,r){return new e({type:"nonoptional",innerType:t,...x.normalizeParams(r)})}function Uj(e,t){return new e({type:"success",innerType:t})}function Lj(e,t,r){return new e({type:"catch",innerType:t,catchValue:typeof r=="function"?r:x.constantCatch(r)})}function Zj(e,t,r){return new e({type:"pipe",in:t,out:r})}function qj(e,t){return new e({type:"readonly",innerType:t})}function Fj(e,t,r){return new e({type:"template_literal",parts:t,...x.normalizeParams(r)})}function Vj(e,t){return new e({type:"lazy",getter:t})}function Bj(e,t){return new e({type:"promise",innerType:t})}function Gj(e,t,r){let i=x.normalizeParams(r);return i.abort??(i.abort=!0),new e({type:"custom",check:"custom",fn:t,...i})}function Jj(e,t,r){return new e({type:"custom",check:"custom",fn:t,...x.normalizeParams(r)})}function Wj(e,t){let r=Bg(i=>(i.addIssue=n=>{if(typeof n=="string")i.issues.push(x.issue(n,i.value,r._zod.def));else{let a=n;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),"input"in a||(a.input=i.value),a.inst??(a.inst=r),a.continue??(a.continue=!r._zod.def.abort),i.issues.push(x.issue(a))}},e(i.value,i)),t);return r}function Bg(e,t){let r=new Le.$ZodCheck({check:"custom",...x.normalizeParams(t)});return r._zod.check=e,r}function Yj(e){let t=new Le.$ZodCheck({check:"describe"});return t._zod.onattach=[r=>{let i=Vs.globalRegistry.get(r)??{};Vs.globalRegistry.add(r,{...i,description:e})}],t._zod.check=()=>{},t}function Kj(e){let t=new Le.$ZodCheck({check:"meta"});return t._zod.onattach=[r=>{let i=Vs.globalRegistry.get(r)??{};Vs.globalRegistry.add(r,{...i,...e})}],t._zod.check=()=>{},t}function Hj(e,t){let r=x.normalizeParams(t),i=r.truthy??["true","1","yes","on","y","enabled"],n=r.falsy??["false","0","no","off","n","disabled"];r.case!=="sensitive"&&(i=i.map(b=>typeof b=="string"?b.toLowerCase():b),n=n.map(b=>typeof b=="string"?b.toLowerCase():b));let a=new Set(i),o=new Set(n),s=e.Codec??Fs.$ZodCodec,c=e.Boolean??Fs.$ZodBoolean,u=e.String??Fs.$ZodString,d=new u({type:"string",error:r.error}),p=new c({type:"boolean",error:r.error}),m=new s({type:"pipe",in:d,out:p,transform:((b,y)=>{let O=b;return r.case!=="sensitive"&&(O=O.toLowerCase()),a.has(O)?!0:o.has(O)?!1:(y.issues.push({code:"invalid_value",expected:"stringbool",values:[...a,...o],input:y.value,inst:m,continue:!1}),{})}),reverseTransform:((b,y)=>b===!0?i[0]||"true":n[0]||"false"),error:r.error});return m._zod.bag.truthy=i,m._zod.bag.falsy=n,m._zod.bag.case=r.case??"insensitive",m}function Xj(e,t,r,i={}){let n=x.normalizeParams(i),a={check:"string_format",type:"string",format:t,fn:typeof r=="function"?r:s=>r.test(s),...n};return r instanceof RegExp&&(a.pattern=r),new e(a)}});var Aa=P(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.createStandardJSONSchemaMethod=kt.createToJSONSchemaMethod=void 0;kt.initializeContext=el;kt.handleUnrepresentable=ek;kt.process=Gs;kt.extractDefs=tl;kt.finalize=nl;var Qj=Ea(),Qu=B();function Ta(e,...t){for(let r of t)for(let i of Reflect.ownKeys(r))Object.prototype.propertyIsEnumerable.call(r,i)&&(0,Qu.assignProp)(e,i,r[i]);return e}function el(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??Qj.globalRegistry,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??"ref",reused:e?.reused??"inline",intersections:[],deferred:[],external:e?.external??void 0}}function ek(e,t,r,i,n){let a=typeof t.unrepresentable=="function"?t.unrepresentable({zodSchema:e,path:i.path,message:n}):t.unrepresentable;if(a==="any")return!1;if(a===void 0||a==="throw")throw new Error(n);return Object.assign(r,a),!0}function Gs(e,t,r={path:[],schemaPath:[]}){var i;let n=e._zod.def,a=t.seen.get(e);if(a)return a.count++,r.schemaPath.includes(e)&&(a.cycle=r.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,o),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let d={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,d);else{let m=o.schema,b=t.processors[n.type];if(!b)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${n.type}`);b(e,t,m,d)}let p=e._zod.parent;p&&(o.ref||(o.ref=p),Gs(p,t,d),t.seen.get(p).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Ta(o.schema,c),t.io==="input"&&gt(e)&&(delete o.schema.examples,delete o.schema.default),t.io==="input"&&"_prefault"in o.schema&&((i=o.schema).default??(i.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function Jg(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function tl(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");if(e.external&&e.sharedDefsExtractedFor===e.external)return;let i=new Map;for(let o of e.seen.entries()){let s=e.metadataRegistry.get(o[0])?.id;if(s){let c=i.get(s);if(c&&c!==o[0])throw new Error(`Duplicate schema id "${s}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);i.set(s,o[0])}}let n=o=>{let s=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let p=e.external.registry.get(o[0])?.id,m=e.external.uri??(y=>y);if(p)return{ref:m(p)};let b=o[1].defId??o[1].schema.id??`schema${e.counter++}`;return o[1].defId=b,{defId:b,ref:`${m("__shared")}#/${s}/${Jg(b)}`}}let c="#",u=`${c}/${s}/`;if(o[1]===r&&!o[1].schema.id)return{ref:c};let d=o[1].schema.id??`__schema${e.counter++}`;return{defId:d,ref:u+Jg(d)}},a=o=>{if(o[1].schema.$ref)return;let s=o[1],{ref:c,defId:u}=n(o);s.def={...s.schema},u&&(s.defId=u);let d=s.schema;for(let p in d)delete d[p];d.$ref=c};if(e.cycles==="throw")for(let o of e.seen.entries()){let s=o[1];if(s.cycle)throw new Error(`Cycle detected: #/${s.cycle?.join("/")}/<root>
56
56
 
57
57
  Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let o of e.seen.entries()){let s=o[1];if(t===o[0]){a(o);continue}if(e.external){let u=e.external.registry.get(o[0])?.id;if(t!==o[0]&&u){a(o);continue}}if(e.metadataRegistry.get(o[0])?.id){a(o);continue}if(s.cycle){a(o);continue}if(s.count>1&&e.reused==="ref"){a(o);continue}}e.external&&(e.sharedDefsExtractedFor=e.external)}function Kg(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let r=[];for(let i of t){if(!i||typeof i!="object")return;Kg(i);let n=Object.keys(i);if(n.length!==1||n[0]!=="type")return;let a=i.type;for(let o of Array.isArray(a)?a:[a]){if(typeof o!="string")return;r.includes(o)||r.push(o)}}delete e.anyOf,e.type=r.length===1?r[0]:r}var Hg=new Set(["type","properties","required","additionalProperties"]),Wg=["oneOf","anyOf"];function Yg(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!="object"||t===null?null:Object.keys(t).length?t:null}function Xu(e){let t=[];for(let a of e){if(typeof a!="object"||a.type!=="object")return null;for(let o in a)if(!Hg.has(o))return null;t.push(a)}let r={},i=new Set;for(let a of t){for(let o in a.properties){if(Object.prototype.hasOwnProperty.call(r,o))continue;let s=[];for(let u of t){let d=u.properties?.[o]??Yg(u);d!=null&&(s.some(p=>JSON.stringify(p)===JSON.stringify(d))||s.push(d))}let c=s.length===1?s[0]:Xu(s)??{allOf:s};(0,Qu.assignProp)(r,o,c)}for(let o of a.required??[])i.add(o)}let n={type:"object",properties:r};if(i.size&&(n.required=[...i]),t.every(a=>a.additionalProperties===!1))n.additionalProperties=!1;else{let a=[];for(let o of t){let s=Yg(o);s&&!a.some(c=>JSON.stringify(c)===JSON.stringify(s))&&a.push(s)}a.length===1?n.additionalProperties=a[0]:a.length>1&&(n.additionalProperties={allOf:a})}return n}function tk(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let n of Hg)if(n in e)return;let r=t.filter(n=>Wg.some(a=>Array.isArray(n[a]))),i=null;if(!r.length)i=Xu(t);else{let n=r[0],a=Wg.find(c=>Array.isArray(n[c]));if(Object.keys(n).length!==1)return;let o=t.filter(c=>c!==n),s=n[a].map(c=>Xu([...o,c]));if(s.some(c=>!c))return;i={[a]:s}}i&&(delete e.allOf,Ta(e,i))}function nl(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let i=s=>{let c=e.seen.get(s);if(c.ref===null)return;let u=c.def??c.schema,d={...u},p=c.ref;if(c.ref=null,p){i(p);let b=e.seen.get(p),y=b.schema;if(y.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(y)):Ta(u,y),Ta(u,d),s._zod.parent===p)for(let z in u)z==="$ref"||z==="allOf"||z in d||delete u[z];if(y.$ref&&b.def)for(let z in u)z==="$ref"||z==="allOf"||z in b.def&&JSON.stringify(u[z])===JSON.stringify(b.def[z])&&delete u[z]}let m=s._zod.parent;if(m&&m!==p){i(m);let b=e.seen.get(m);if(b?.schema.$ref&&(u.$ref=b.schema.$ref,b.def))for(let y in u)y==="$ref"||y==="allOf"||y in b.def&&JSON.stringify(u[y])===JSON.stringify(b.def[y])&&delete u[y]}e.override({zodSchema:s,jsonSchema:u,path:c.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let s of[...e.seen.entries()].reverse())i(s[0]);if(e.target!=="openapi-3.0")for(let s of e.seen.entries())Kg(s[1].def??s[1].schema);for(let s of e.deferred)s();if(e.intersections.length){let s=new Map;for(let c of e.seen.values())for(let u of[c.schema,c.def]){let d=u?.allOf;if(!Array.isArray(d))continue;let p=s.get(d);p?p.push(u):s.set(d,[u])}for(let c of e.intersections)for(let u of s.get(c)??[])tk(u)}}let n={};if(e.target==="draft-2020-12"?n.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?n.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?n.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let s=e.external.registry.get(t)?.id;if(!s)throw new Error("Schema is missing an `id` property");n.$id=e.external.uri(s)}Ta(n,r.defId?r.schema:r.def??r.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&n.id===a&&delete n.id;let o=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let s of e.seen.entries()){let c=s[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,(0,Qu.assignProp)(o,c.defId,c.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(o).length>0&&(e.target==="draft-2020-12"?n.$defs=o:n.definitions=o);try{let s=JSON.parse(JSON.stringify(n));return Object.defineProperty(s,"~standard",{value:{...t["~standard"],jsonSchema:{input:(0,kt.createStandardJSONSchemaMethod)(t,"input",e.processors),output:(0,kt.createStandardJSONSchemaMethod)(t,"output",e.processors)}},enumerable:!1,writable:!1}),s}catch{throw new Error("Error converting schema to JSON.")}}function gt(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let i=e._zod.def;if(i.type==="transform")return!0;if(i.type==="array")return gt(i.element,r);if(i.type==="set")return gt(i.valueType,r);if(i.type==="lazy")return gt(i.getter(),r);if(i.type==="promise"||i.type==="optional"||i.type==="nonoptional"||i.type==="nullable"||i.type==="readonly"||i.type==="default"||i.type==="prefault"||i.type==="catch")return gt(i.innerType,r);if(i.type==="intersection")return gt(i.left,r)||gt(i.right,r);if(i.type==="record"||i.type==="map")return gt(i.keyType,r)||gt(i.valueType,r);if(i.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:gt(i.in,r)||gt(i.out,r);if(i.type==="object"){for(let n in i.shape)if(gt(i.shape[n],r))return!0;return!1}if(i.type==="union"){for(let n of i.options)if(gt(n,r))return!0;return!1}if(i.type==="tuple"){for(let n of i.items)if(gt(n,r))return!0;return!!(i.rest&&gt(i.rest,r))}return!1}var nk=(e,t={})=>r=>{let i=el({...r,processors:t});return Gs(e,i),tl(i,e),nl(i,e)};kt.createToJSONSchemaMethod=nk;var rk=(e,t,r={})=>i=>{let{libraryOptions:n,target:a}=i??{},o=el({...n??{},target:a,io:t,processors:r});return Gs(e,o),tl(o,e),nl(o,e)};kt.createStandardJSONSchemaMethod=rk});var ka=P(j=>{"use strict";var ik=j&&j.__createBinding||(Object.create?(function(e,t,r,i){i===void 0&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);(!n||("get"in n?!t.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}):(function(e,t,r,i){i===void 0&&(i=r),e[i]=t[r]})),ak=j&&j.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),ok=j&&j.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&ik(t,e,r);return ak(t,e),t};Object.defineProperty(j,"__esModule",{value:!0});j.allProcessors=j.lazyProcessor=j.optionalProcessor=j.promiseProcessor=j.readonlyProcessor=j.pipeProcessor=j.catchProcessor=j.prefaultProcessor=j.defaultProcessor=j.nonoptionalProcessor=j.nullableProcessor=j.recordProcessor=j.tupleProcessor=j.intersectionProcessor=j.unionProcessor=j.objectProcessor=j.arrayProcessor=j.setProcessor=j.mapProcessor=j.transformProcessor=j.functionProcessor=j.customProcessor=j.successProcessor=j.fileProcessor=j.templateLiteralProcessor=j.nanProcessor=j.literalProcessor=j.enumProcessor=j.dateProcessor=j.unknownProcessor=j.anyProcessor=j.neverProcessor=j.voidProcessor=j.undefinedProcessor=j.nullProcessor=j.symbolProcessor=j.bigintProcessor=j.booleanProcessor=j.numberProcessor=j.stringProcessor=void 0;j.toJSONSchema=Wk;var Xg=ok(Gi()),le=Aa(),Js=B(),sk={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},ck=(e,t,r,i)=>{let n=r;n.type="string";let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:u,laxFormat:d}=e._zod.bag;if(typeof a=="number"&&(n.minLength=a),typeof o=="number"&&(n.maxLength=o),s&&(n.format=sk[s]??s,n.format===""&&delete n.format,(s==="time"||d)&&delete n.format),u&&(n.contentEncoding=u),c&&c.size>0){let p=[...c];p.length===1?n.pattern=p[0].source:p.length>1&&(n.allOf=[...p.map(m=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:m.source}))])}};j.stringProcessor=ck;var uk=(e,t,r,i)=>{let n=r,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:d}=e._zod.bag;typeof s=="string"&&s.includes("int")?n.type="integer":n.type="number";let p=typeof d=="number"&&d>=(a??Number.NEGATIVE_INFINITY),m=typeof u=="number"&&u<=(o??Number.POSITIVE_INFINITY),b=t.target==="draft-04"||t.target==="openapi-3.0";p?b?(n.minimum=d,n.exclusiveMinimum=!0):n.exclusiveMinimum=d:typeof a=="number"&&(n.minimum=a),m?b?(n.maximum=u,n.exclusiveMaximum=!0):n.exclusiveMaximum=u:typeof o=="number"&&(n.maximum=o),typeof c=="number"&&(Number.isFinite(c)&&c!==0?n.multipleOf=Math.abs(c):(0,le.handleUnrepresentable)(e,t,n,i,`A multipleOf divisor of ${c} cannot be represented in JSON Schema`))};j.numberProcessor=uk;var lk=(e,t,r,i)=>{r.type="boolean"};j.booleanProcessor=lk;var dk=(e,t,r,i)=>{(0,le.handleUnrepresentable)(e,t,r,i,"BigInt cannot be represented in JSON Schema")};j.bigintProcessor=dk;var fk=(e,t,r,i)=>{(0,le.handleUnrepresentable)(e,t,r,i,"Symbols cannot be represented in JSON Schema")};j.symbolProcessor=fk;var pk=(e,t,r,i)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"};j.nullProcessor=pk;var mk=(e,t,r,i)=>{(0,le.handleUnrepresentable)(e,t,r,i,"Undefined cannot be represented in JSON Schema")};j.undefinedProcessor=mk;var gk=(e,t,r,i)=>{(0,le.handleUnrepresentable)(e,t,r,i,"Void cannot be represented in JSON Schema")};j.voidProcessor=gk;var _k=(e,t,r,i)=>{r.not={}};j.neverProcessor=_k;var hk=(e,t,r,i)=>{};j.anyProcessor=hk;var vk=(e,t,r,i)=>{};j.unknownProcessor=vk;var yk=(e,t,r,i)=>{(0,le.handleUnrepresentable)(e,t,r,i,"Date cannot be represented in JSON Schema")};j.dateProcessor=yk;var bk=(e,t,r,i)=>{let n=e._zod.def,a=(0,Js.getEnumValues)(n.entries);if(a.length===0){r.not={};return}a.every(o=>typeof o=="number")&&(r.type="number"),a.every(o=>typeof o=="string")&&(r.type="string"),r.enum=a};j.enumProcessor=bk;var wk=(e,t,r,i)=>{let n=e._zod.def;if(n.values.length===0){r.not={};return}let a=[];for(let o of n.values)if(o===void 0){if((0,le.handleUnrepresentable)(e,t,r,i,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof o=="bigint"){if((0,le.handleUnrepresentable)(e,t,r,i,"BigInt literals cannot be represented in JSON Schema"))return;a.push(Number(o))}else a.push(o);if(a.length!==0)if(a.length===1){let o=a[0];r.type=o===null?"null":typeof o,t.target==="draft-04"||t.target==="openapi-3.0"?r.enum=[o]:r.const=o}else a.every(o=>typeof o=="number")&&(r.type="number"),a.every(o=>typeof o=="string")&&(r.type="string"),a.every(o=>typeof o=="boolean")&&(r.type="boolean"),a.every(o=>o===null)&&(r.type="null"),r.enum=a};j.literalProcessor=wk;var Sk=(e,t,r,i)=>{(0,le.handleUnrepresentable)(e,t,r,i,"NaN cannot be represented in JSON Schema")};j.nanProcessor=Sk;var $k=(e,t,r,i)=>{let n=r,a=e._zod.pattern;if(!a)throw new Error("Pattern not found in template literal");n.type="string",n.pattern=a.source};j.templateLiteralProcessor=$k;var Ok=(e,t,r,i)=>{let n=r,a={type:"string",format:"binary",contentEncoding:"binary"},{minimum:o,maximum:s,mime:c}=e._zod.bag;o!==void 0&&(a.minLength=o),s!==void 0&&(a.maxLength=s),c?c.length===1?(a.contentMediaType=c[0],Object.assign(n,a)):(Object.assign(n,a),n.anyOf=c.map(u=>({contentMediaType:u}))):Object.assign(n,a)};j.fileProcessor=Ok;var Ik=(e,t,r,i)=>{r.type="boolean"};j.successProcessor=Ik;var Ek=(e,t,r,i)=>{(0,le.handleUnrepresentable)(e,t,r,i,"Custom types cannot be represented in JSON Schema")};j.customProcessor=Ek;var Pk=(e,t,r,i)=>{(0,le.handleUnrepresentable)(e,t,r,i,"Function types cannot be represented in JSON Schema")};j.functionProcessor=Pk;var zk=(e,t,r,i)=>{(0,le.handleUnrepresentable)(e,t,r,i,"Transforms cannot be represented in JSON Schema")};j.transformProcessor=zk;var Tk=(e,t,r,i)=>{(0,le.handleUnrepresentable)(e,t,r,i,"Map cannot be represented in JSON Schema")};j.mapProcessor=Tk;var Ak=(e,t,r,i)=>{(0,le.handleUnrepresentable)(e,t,r,i,"Set cannot be represented in JSON Schema")};j.setProcessor=Ak;var jk=(e,t,r,i)=>{let n=r,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o=="number"&&(n.minItems=o),typeof s=="number"&&(n.maxItems=s),n.type="array",n.items=(0,le.process)(a.element,t,{...i,path:[...i.path,"items"]})};j.arrayProcessor=jk;function ja(e){let t=e._zod.def;return t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform")?ja(t.out):t.type==="catch"?ja(t.innerType):e._zod.optin}var kk=(e,t,r,i)=>{let n=r,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&(0,le.handleUnrepresentable)(e,t,n,i,"Symbol keys cannot be represented in JSON Schema"))return;n.type="object",n.properties={};for(let d in o)(0,Js.assignProp)(n.properties,d,(0,le.process)(o[d],t,{...i,path:[...i.path,"properties",d]}));let c=new Set(Object.keys(o)),u=new Set([...c].filter(d=>{let p=a.shape[d];return t.io==="input"?ja(p)===void 0:p._zod.optout===void 0}));u.size>0&&(n.required=Array.from(u)),a.catchall?._zod.def.type==="never"?n.additionalProperties=!1:a.catchall?a.catchall&&(n.additionalProperties=(0,le.process)(a.catchall,t,{...i,path:[...i.path,"additionalProperties"]})):t.io==="output"&&(n.additionalProperties=!1)};j.objectProcessor=kk;var Nk=(e,t,r,i)=>{let n=e._zod.def,a=n.inclusive===!1,o=n.options.map((s,c)=>(0,le.process)(s,t,{...i,path:[...i.path,a?"oneOf":"anyOf",c]}));a?r.oneOf=o:r.anyOf=o};j.unionProcessor=Nk;var Rk=(e,t,r,i)=>{let n=e._zod.def,a=(0,le.process)(n.left,t,{...i,path:[...i.path,"allOf",0]}),o=(0,le.process)(n.right,t,{...i,path:[...i.path,"allOf",1]}),s=u=>"allOf"in u&&Object.keys(u).length===1,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];r.allOf=c,t.intersections.push(c)};j.intersectionProcessor=Rk;var Ck=(e,t,r,i)=>{let n=r,a=e._zod.def;n.type="array";let o=t.target==="draft-2020-12"?"prefixItems":"items",s=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",c=a.items.map((O,z)=>(0,le.process)(O,t,{...i,path:[...i.path,o,z]})),u=a.rest?(0,le.process)(a.rest,t,{...i,path:[...i.path,s,...t.target==="openapi-3.0"?[a.items.length]:[]]}):null,d=a.items.length;for(;d>0;){let O=a.items[d-1];if(!(t.io==="input"?ja(O)!==void 0:O._zod.optout==="optional"))break;d--}let p=a.items.length,m=!a.rest;t.target==="draft-2020-12"?(n.prefixItems=c,m?n.items=!1:u&&(n.items=u),d>0&&(n.minItems=d),m&&(n.maxItems=p)):t.target==="openapi-3.0"?(n.items={anyOf:c},u&&n.items.anyOf.push(u),d>0&&(n.minItems=d),m&&(n.maxItems=p)):(n.items=c,m?n.additionalItems=!1:u&&(n.additionalItems=u),d>0&&(n.minItems=d),m&&(n.maxItems=p));let{minimum:b,maximum:y}=e._zod.bag;typeof b=="number"&&(n.minItems=b),typeof y=="number"&&(n.maxItems=y)};j.tupleProcessor=Ck;function rl(e,t,r){if(t.$ref){if(r.has(t))return t;r.add(t);let y=e.get(t)?.def;if(!y)return t;let O=rl(e,y,r);return O===y?t:O}for(let y of["anyOf","oneOf"]){let O=t[y];if(!Array.isArray(O))continue;let z=O.map(re=>rl(e,re,r));z.some((re,C)=>re!==O[C])&&(t={...t,[y]:z})}let i=Array.isArray(t.type)?t.type:[t.type],n=!i.includes("string")&&i.some(y=>y==="number"||y==="integer"),a=t.enum??(t.const!==void 0?[t.const]:void 0);if(!n&&!a?.some(y=>typeof y=="number"))return t;let{minimum:o,maximum:s,exclusiveMinimum:c,exclusiveMaximum:u,multipleOf:d,format:p,id:m,...b}=t;return b.enum?b.enum=b.enum.map(y=>typeof y=="number"?String(y):y):typeof b.const=="number"&&(b.const=String(b.const)),n&&(b.type="string",a||(b.pattern=(i.includes("number")?Xg.number:Xg.integer).source)),b}var il=new WeakMap;function Dk(e){let t=new Map;for(let i of e.seen.values())i.def&&!t.has(i.schema)&&t.set(i.schema,i);let r=new Map;for(let i of il.get(e)??[]){let n=e.seen.get(i),a=(n?.def??n?.schema)?.propertyNames;if(!a||a===!0||r.has(a))continue;let o=rl(t,a,new Set);o!==a&&r.set(a,o)}if(r.size)for(let i of e.seen.values())for(let n of[i.schema,i.def]){let a=n&&r.get(n.propertyNames);a&&(n.propertyNames=a)}}var Mk=(e,t,r,i)=>{let n=r,a=e._zod.def;n.type="object";let o=a.keyType,c=o._zod.bag?.patterns;if(a.mode==="loose"&&c&&c.size>0){let p=(0,le.process)(a.valueType,t,{...i,path:[...i.path,"patternProperties","*"]});n.patternProperties={};for(let m of c)(0,Js.assignProp)(n.patternProperties,m.source,p)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){n.propertyNames=(0,le.process)(a.keyType,t,{...i,path:[...i.path,"propertyNames"]});let p=il.get(t);p||(p=[],il.set(t,p),t.deferred.push(()=>Dk(t))),p.push(e)}n.additionalProperties=(0,le.process)(a.valueType,t,{...i,path:[...i.path,"additionalProperties"]})}let u=o._zod.values,d=t.io==="input"&&ja(a.valueType)!==void 0;if(u&&!a.partial&&!d){let p=[...u].filter(m=>typeof m=="string"||typeof m=="number");p.length>0&&(n.required=p.map(String))}};j.recordProcessor=Mk;var xk=(e,t,r,i)=>{let n=e._zod.def,a=(0,le.process)(n.innerType,t,i),o=t.seen.get(e);t.target==="openapi-3.0"?(o.ref=n.innerType,r.nullable=!0):r.anyOf=[a,{type:"null"}]};j.nullableProcessor=xk;var Uk=(e,t,r,i)=>{let n=e._zod.def;(0,le.process)(n.innerType,t,i);let a=t.seen.get(e);a.ref=n.innerType};j.nonoptionalProcessor=Uk;var al=Symbol();function Qg(e,t,r,i,n){let a=!1,o=JSON.stringify(e,(s,c)=>typeof c!="bigint"?c:(a=!0,null));return a?((0,le.handleUnrepresentable)(t,r,i,n,"BigInt defaults cannot be represented in JSON Schema"),al):JSON.parse(o)}var Lk=(e,t,r,i)=>{let n=e._zod.def;(0,le.process)(n.innerType,t,i);let a=t.seen.get(e);a.ref=n.innerType;let o=Qg(n.defaultValue,e,t,r,i);o!==al&&(r.default=o)};j.defaultProcessor=Lk;var Zk=(e,t,r,i)=>{let n=e._zod.def;(0,le.process)(n.innerType,t,i);let a=t.seen.get(e);if(a.ref=n.innerType,t.io!=="input")return;let o=Qg(n.defaultValue,e,t,r,i);o!==al&&(r._prefault=o)};j.prefaultProcessor=Zk;var qk=(e,t,r,i)=>{let n=e._zod.def;(0,le.process)(n.innerType,t,i);let a=t.seen.get(e);a.ref=n.innerType;let o;try{o=n.catchValue(void 0)}catch{(0,le.handleUnrepresentable)(e,t,r,i,"Dynamic catch values are not supported in JSON Schema");return}r.default=o};j.catchProcessor=qk;var Fk=(e,t,r,i)=>{let n=e._zod.def,a=n.in._zod.traits.has("$ZodTransform"),o=t.io==="input"?a?n.out:n.in:n.out;(0,le.process)(o,t,i);let s=t.seen.get(e);s.ref=o};j.pipeProcessor=Fk;var Vk=(e,t,r,i)=>{let n=e._zod.def;(0,le.process)(n.innerType,t,i);let a=t.seen.get(e);a.ref=n.innerType,r.readOnly=!0};j.readonlyProcessor=Vk;var Bk=(e,t,r,i)=>{let n=e._zod.def;(0,le.process)(n.innerType,t,i);let a=t.seen.get(e);a.ref=n.innerType};j.promiseProcessor=Bk;var Gk=(e,t,r,i)=>{let n=e._zod.def;(0,le.process)(n.innerType,t,i);let a=t.seen.get(e);a.ref=n.innerType};j.optionalProcessor=Gk;var Jk=(e,t,r,i)=>{let n=e._zod.innerType;(0,le.process)(n,t,i);let a=t.seen.get(e);a.ref=n};j.lazyProcessor=Jk;j.allProcessors={string:j.stringProcessor,number:j.numberProcessor,boolean:j.booleanProcessor,bigint:j.bigintProcessor,symbol:j.symbolProcessor,null:j.nullProcessor,undefined:j.undefinedProcessor,void:j.voidProcessor,never:j.neverProcessor,any:j.anyProcessor,unknown:j.unknownProcessor,date:j.dateProcessor,enum:j.enumProcessor,literal:j.literalProcessor,nan:j.nanProcessor,template_literal:j.templateLiteralProcessor,file:j.fileProcessor,success:j.successProcessor,custom:j.customProcessor,function:j.functionProcessor,transform:j.transformProcessor,map:j.mapProcessor,set:j.setProcessor,array:j.arrayProcessor,object:j.objectProcessor,union:j.unionProcessor,intersection:j.intersectionProcessor,tuple:j.tupleProcessor,record:j.recordProcessor,nullable:j.nullableProcessor,nonoptional:j.nonoptionalProcessor,default:j.defaultProcessor,prefault:j.prefaultProcessor,catch:j.catchProcessor,pipe:j.pipeProcessor,readonly:j.readonlyProcessor,promise:j.promiseProcessor,optional:j.optionalProcessor,lazy:j.lazyProcessor};function Wk(e,t){if("_idmap"in e){let i=e,n=(0,le.initializeContext)({...t,processors:j.allProcessors}),a={};for(let c of i._idmap.entries()){let[u,d]=c;(0,le.process)(d,n)}let o={},s={registry:i,uri:t?.uri,defs:a};n.external=s;for(let c of i._idmap.entries()){let[u,d]=c;(0,le.extractDefs)(n,d),(0,Js.assignProp)(o,u,(0,le.finalize)(n,d))}if(Object.keys(a).length>0){let c=n.target==="draft-2020-12"?"$defs":"definitions";o.__shared={[c]:a}}return{schemas:o}}let r=(0,le.initializeContext)({...t,processors:j.allProcessors});return(0,le.process)(e,r),(0,le.extractDefs)(r,e),(0,le.finalize)(r,e)}});var e_=P(Ys=>{"use strict";Object.defineProperty(Ys,"__esModule",{value:!0});Ys.JSONSchemaGenerator=void 0;var Yk=ka(),Ws=Aa(),ol=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(t){this.ctx.counter=t}get seen(){return this.ctx.seen}constructor(t){let r=t?.target??"draft-2020-12";r==="draft-4"&&(r="draft-04"),r==="draft-7"&&(r="draft-07"),this.ctx=(0,Ws.initializeContext)({processors:Yk.allProcessors,target:r,...t?.metadata&&{metadata:t.metadata},...t?.unrepresentable&&{unrepresentable:t.unrepresentable},...t?.override&&{override:t.override},...t?.io&&{io:t.io}})}process(t,r={path:[],schemaPath:[]}){return(0,Ws.process)(t,this.ctx,r)}emit(t,r){r&&(r.cycles&&(this.ctx.cycles=r.cycles),r.reused&&(this.ctx.reused=r.reused),r.external&&(this.ctx.external=r.external)),this.ctx.sharedDefsExtractedFor=void 0,this.ctx.sharedEmitDoneFor=void 0,(0,Ws.extractDefs)(this.ctx,t);let i=(0,Ws.finalize)(this.ctx,t),{"~standard":n,...a}=i;return a}};Ys.JSONSchemaGenerator=ol});var n_=P(t_=>{"use strict";Object.defineProperty(t_,"__esModule",{value:!0})});var Ot=P(be=>{"use strict";var r_=be&&be.__createBinding||(Object.create?(function(e,t,r,i){i===void 0&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);(!n||("get"in n?!t.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}):(function(e,t,r,i){i===void 0&&(i=r),e[i]=t[r]})),Kk=be&&be.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),xt=be&&be.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&r_(t,e,r)},Ks=be&&be.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&r_(t,e,r);return Kk(t,e),t};Object.defineProperty(be,"__esModule",{value:!0});be.JSONSchema=be.JSONSchemaGenerator=be.toJSONSchema=be.locales=be.regexes=be.toZod=be.util=void 0;xt(Vr(),be);xt(Tu(),be);xt(Pu(),be);xt(Oa(),be);xt(Fu(),be);xt(wo(),be);xt(Du(),be);be.util=Ks(B());var Hk=B();Object.defineProperty(be,"toZod",{enumerable:!0,get:function(){return Hk.toZod}});be.regexes=Ks(Gi());be.locales=Ks(Ju());xt(Ea(),be);xt($o(),be);xt(qg(),be);xt(Gg(),be);xt(Aa(),be);var Xk=ka();Object.defineProperty(be,"toJSONSchema",{enumerable:!0,get:function(){return Xk.toJSONSchema}});var Qk=e_();Object.defineProperty(be,"JSONSchemaGenerator",{enumerable:!0,get:function(){return Qk.JSONSchemaGenerator}});be.JSONSchema=Ks(n_())});var Hs=P(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.slugify=Q.toUpperCase=Q.toLowerCase=Q.trim=Q.normalize=Q.overwrite=Q.mime=Q.properties=Q.property=Q.endsWith=Q.startsWith=Q.includes=Q.uppercase=Q.lowercase=Q.regex=Q.length=Q.minLength=Q.maxLength=Q.size=Q.minSize=Q.maxSize=Q.multipleOf=Q.nonnegative=Q.nonpositive=Q.negative=Q.positive=Q.gte=Q.gt=Q.lte=Q.lt=void 0;var ze=Ot();Object.defineProperty(Q,"lt",{enumerable:!0,get:function(){return ze._lt}});Object.defineProperty(Q,"lte",{enumerable:!0,get:function(){return ze._lte}});Object.defineProperty(Q,"gt",{enumerable:!0,get:function(){return ze._gt}});Object.defineProperty(Q,"gte",{enumerable:!0,get:function(){return ze._gte}});Object.defineProperty(Q,"positive",{enumerable:!0,get:function(){return ze._positive}});Object.defineProperty(Q,"negative",{enumerable:!0,get:function(){return ze._negative}});Object.defineProperty(Q,"nonpositive",{enumerable:!0,get:function(){return ze._nonpositive}});Object.defineProperty(Q,"nonnegative",{enumerable:!0,get:function(){return ze._nonnegative}});Object.defineProperty(Q,"multipleOf",{enumerable:!0,get:function(){return ze._multipleOf}});Object.defineProperty(Q,"maxSize",{enumerable:!0,get:function(){return ze._maxSize}});Object.defineProperty(Q,"minSize",{enumerable:!0,get:function(){return ze._minSize}});Object.defineProperty(Q,"size",{enumerable:!0,get:function(){return ze._size}});Object.defineProperty(Q,"maxLength",{enumerable:!0,get:function(){return ze._maxLength}});Object.defineProperty(Q,"minLength",{enumerable:!0,get:function(){return ze._minLength}});Object.defineProperty(Q,"length",{enumerable:!0,get:function(){return ze._length}});Object.defineProperty(Q,"regex",{enumerable:!0,get:function(){return ze._regex}});Object.defineProperty(Q,"lowercase",{enumerable:!0,get:function(){return ze._lowercase}});Object.defineProperty(Q,"uppercase",{enumerable:!0,get:function(){return ze._uppercase}});Object.defineProperty(Q,"includes",{enumerable:!0,get:function(){return ze._includes}});Object.defineProperty(Q,"startsWith",{enumerable:!0,get:function(){return ze._startsWith}});Object.defineProperty(Q,"endsWith",{enumerable:!0,get:function(){return ze._endsWith}});Object.defineProperty(Q,"property",{enumerable:!0,get:function(){return ze._property}});Object.defineProperty(Q,"properties",{enumerable:!0,get:function(){return ze._properties}});Object.defineProperty(Q,"mime",{enumerable:!0,get:function(){return ze._mime}});Object.defineProperty(Q,"overwrite",{enumerable:!0,get:function(){return ze._overwrite}});Object.defineProperty(Q,"normalize",{enumerable:!0,get:function(){return ze._normalize}});Object.defineProperty(Q,"trim",{enumerable:!0,get:function(){return ze._trim}});Object.defineProperty(Q,"toLowerCase",{enumerable:!0,get:function(){return ze._toLowerCase}});Object.defineProperty(Q,"toUpperCase",{enumerable:!0,get:function(){return ze._toUpperCase}});Object.defineProperty(Q,"slugify",{enumerable:!0,get:function(){return ze._slugify}})});var sl=P(Ut=>{"use strict";var eN=Ut&&Ut.__createBinding||(Object.create?(function(e,t,r,i){i===void 0&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);(!n||("get"in n?!t.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}):(function(e,t,r,i){i===void 0&&(i=r),e[i]=t[r]})),tN=Ut&&Ut.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),o_=Ut&&Ut.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&eN(t,e,r);return tN(t,e),t};Object.defineProperty(Ut,"__esModule",{value:!0});Ut.ZodRealError=Ut.ZodError=void 0;var Qs=o_(Ot()),nN=Ot(),i_=o_(B()),a_=new WeakSet([Object.prototype,Error.prototype]);function Xs(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let i=r(this);return Object.defineProperty(this,t,{value:i,configurable:!0,writable:!0}),i},set(i){Object.defineProperty(this,t,{value:i,configurable:!0,writable:!0})}})}var s_=(e,t)=>{nN.$ZodError.init(e,t),e.name="ZodError";let r=Object.getPrototypeOf(e);a_.has(r)||(a_.add(r),Xs(r,"format",i=>n=>Qs.formatError(i,n)),Xs(r,"flatten",i=>n=>Qs.flattenError(i,n)),Xs(r,"addIssue",i=>n=>{i.issues.push(n),i.message=JSON.stringify(i.issues,i_.jsonStringifyReplacer,2)}),Xs(r,"addIssues",i=>n=>{i.issues.push(...n),i.message=JSON.stringify(i.issues,i_.jsonStringifyReplacer,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))};Ut.ZodError=Qs.$constructor("ZodError",s_);Ut.ZodRealError=Qs.$constructor("ZodError",s_,void 0,{Parent:Error})});var cl=P(we=>{"use strict";var rN=we&&we.__createBinding||(Object.create?(function(e,t,r,i){i===void 0&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);(!n||("get"in n?!t.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}):(function(e,t,r,i){i===void 0&&(i=r),e[i]=t[r]})),iN=we&&we.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),aN=we&&we.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&rN(t,e,r);return iN(t,e),t};Object.defineProperty(we,"__esModule",{value:!0});we.safeDecodeAsync=we.safeEncodeAsync=we.safeDecode=we.safeEncode=we.decodeAsync=we.encodeAsync=we.decode=we.encode=we.validateAsync=we.validate=we.safeParseAsync=we.safeParse=we.parseAsync=we.parse=void 0;var Lt=aN(Ot()),Zt=sl();we.parse=Lt._parse(Zt.ZodRealError);we.parseAsync=Lt._parseAsync(Zt.ZodRealError);we.safeParse=Lt._safeParse(Zt.ZodRealError);we.safeParseAsync=Lt._safeParseAsync(Zt.ZodRealError);var c_=Ot();Object.defineProperty(we,"validate",{enumerable:!0,get:function(){return c_.validate}});Object.defineProperty(we,"validateAsync",{enumerable:!0,get:function(){return c_.validateAsync}});we.encode=Lt._encode(Zt.ZodRealError);we.decode=Lt._decode(Zt.ZodRealError);we.encodeAsync=Lt._encodeAsync(Zt.ZodRealError);we.decodeAsync=Lt._decodeAsync(Zt.ZodRealError);we.safeEncode=Lt._safeEncode(Zt.ZodRealError);we.safeDecode=Lt._safeDecode(Zt.ZodRealError);we.safeEncodeAsync=Lt._safeEncodeAsync(Zt.ZodRealError);we.safeDecodeAsync=Lt._safeDecodeAsync(Zt.ZodRealError)});var Br=P(f=>{"use strict";var oN=f&&f.__createBinding||(Object.create?(function(e,t,r,i){i===void 0&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);(!n||("get"in n?!t.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}):(function(e,t,r,i){i===void 0&&(i=r),e[i]=t[r]})),sN=f&&f.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),rc=f&&f.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&oN(t,e,r);return sN(t,e),t},cN=f&&f.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(f,"__esModule",{value:!0});f.ZodTuple=f.ZodIntersection=f.ZodDiscriminatedUnion=f.ZodXor=f.ZodUnion=f.ZodObject=f.ZodArray=f.ZodDate=f.ZodVoid=f.ZodNever=f.ZodUnknown=f.ZodAny=f.ZodNull=f.ZodUndefined=f.ZodSymbol=f.ZodBigIntFormat=f.ZodBigInt=f.ZodBoolean=f.ZodNumberFormat=f.ZodNumber=f.ZodCustomStringFormat=f.ZodJWT=f.ZodCreditCard=f.ZodE164=f.ZodBase64URL=f.ZodBase64=f.ZodCIDRv6=f.ZodCIDRv4=f.ZodIPv6=f.ZodMAC=f.ZodIPv4=f.ZodKSUID=f.ZodXID=f.ZodULID=f.ZodCUID2=f.ZodCUID=f.ZodNanoID=f.ZodEmoji=f.ZodURL=f.ZodUUID=f.ZodGUID=f.ZodEmail=f.ZodISODuration=f.ZodISOTime=f.ZodISODate=f.ZodISODateTime=f.ZodStringFormat=f.ZodString=f._ZodString=f.ZodType=void 0;f.stringbool=f.meta=f.describe=f.ZodCustom=f.ZodFunction=f.ZodPromise=f.ZodLazy=f.ZodTemplateLiteral=f.ZodReadonly=f.ZodPreprocess=f.ZodCodec=f.ZodPipe=f.ZodNaN=f.ZodCatch=f.ZodSuccess=f.ZodNonOptional=f.ZodPrefault=f.ZodDefault=f.ZodNullable=f.ZodExactOptional=f.ZodOptional=f.ZodTransform=f.ZodFile=f.ZodLiteral=f.ZodEnum=f.ZodSet=f.ZodMap=f.ZodRecord=void 0;f.string=ec;f.email=dN;f.guid=fN;f.uuid=pN;f.uuidv4=mN;f.uuidv6=gN;f.uuidv7=_N;f.url=hN;f.httpUrl=vN;f.emoji=yN;f.nanoid=bN;f.cuid=wN;f.cuid2=SN;f.ulid=$N;f.xid=ON;f.ksuid=IN;f.ipv4=EN;f.mac=PN;f.ipv6=zN;f.cidrv4=TN;f.cidrv6=AN;f.base64=jN;f.base64url=kN;f.e164=NN;f.creditCard=RN;f.jwt=CN;f.stringFormat=DN;f.hostname=MN;f.hex=xN;f.hash=UN;f.number=u_;f.int=ll;f.float32=LN;f.float64=ZN;f.int32=qN;f.uint32=FN;f.boolean=l_;f.bigint=VN;f.int64=BN;f.uint64=GN;f.symbol=JN;f.undefined=WN;f.null=d_;f.any=YN;f.unknown=Xi;f.never=fl;f.void=KN;f.date=HN;f.array=ic;f.keyof=XN;f.object=QN;f.strictObject=eR;f.looseObject=tR;f.union=pl;f.xor=nR;f.discriminatedUnion=rR;f.intersection=f_;f.tuple=p_;f.record=m_;f.partialRecord=iR;f.looseRecord=aR;f.map=oR;f.set=sR;f.enum=ml;f.nativeEnum=cR;f.literal=uR;f.file=lR;f.transform=gl;f.optional=tc;f.exactOptional=g_;f.nullable=nc;f.nullish=dR;f._default=__;f.prefault=h_;f.nonoptional=v_;f.success=fR;f.catch=y_;f.nan=pR;f.pipe=dl;f.codec=mR;f.invertCodec=gR;f.readonly=b_;f.templateLiteral=_R;f.lazy=w_;f.promise=hR;f._function=ac;f.function=ac;f._function=ac;f.function=ac;f.check=vR;f.custom=yR;f.refine=S_;f.superRefine=$_;f.instanceof=bR;f.json=SR;f.preprocess=$R;var g=rc(Ot()),he=Ot(),ge=rc(ka()),ul=Aa(),uN=cN(Vu()),pe=rc(Hs()),qt=rc(cl());function lN(){g.globalConfig.localeError||g.config((0,uN.default)())}function yi(){g.globalConfig.memoizer||g.config({memoizer:g.memoizer()})}f.ZodType=g.$constructor("ZodType",(e,t)=>(lN(),g.$ZodType.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(he.util.mergeDefs(t,{checks:[...t.checks??[],...e.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return g.clone(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(S_(e,t))},superRefine(e,t){return this.check($_(e,t))},overwrite(e){return this.check(pe.overwrite(e))},optional(){return tc(this)},exactOptional(){return g_(this)},nullable(){return nc(this)},nullish(){return tc(nc(this))},nonoptional(e){return v_(this,e)},array(){return ic(this)},or(e){return pl([this,e])},and(e){return f_(this,e)},transform(e){return dl(this,gl(e))},default(e){return __(this,e)},prefault(e){return h_(this,e)},catch(e){return y_(this,e)},pipe(e){return dl(this,e)},readonly(){return b_(this)},describe(e){let t=this.clone();return g.globalRegistry.add(t,{description:e}),t},meta(...e){if(e.length===0)return g.globalRegistry.get(this);let t=this.clone();return g.globalRegistry.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return he.util.hide(this,"~standard",{...g.standardProps(this),jsonSchema:{input:(0,ul.createStandardJSONSchemaMethod)(this,"input"),output:(0,ul.createStandardJSONSchemaMethod)(this,"output")}})},set"~standard"(e){he.util.own(this,"~standard",e)},parse:function e(t,r){return qt.parse(this,t,r,{callee:e})},parseAsync:async function e(t,r){return await qt.parseAsync(this,t,r,{callee:e})},safeParse(e,t){return qt.safeParse(this,e,t)},async safeParseAsync(e,t){return qt.safeParseAsync(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){he.util.own(this,"spa",e)},encode:function e(t,r){return qt.encode(this,t,r,{callee:e})},decode:function e(t,r){return qt.decode(this,t,r,{callee:e})},encodeAsync:async function e(t,r){return await qt.encodeAsync(this,t,r,{callee:e})},decodeAsync:async function e(t,r){return await qt.decodeAsync(this,t,r,{callee:e})},safeEncode(e,t){return qt.safeEncode(this,e,t)},safeDecode(e,t){return qt.safeDecode(this,e,t)},async safeEncodeAsync(e,t){return qt.safeEncodeAsync(this,e,t)},async safeDecodeAsync(e,t){return qt.safeDecodeAsync(this,e,t)},toJSONSchema(e){return(0,ul.createToJSONSchemaMethod)(this,{})(e)},get description(){return g.globalRegistry.get(this)?.description},get _def(){return this._zod.def}});f._ZodString=g.$constructor("_ZodString",(e,t)=>{g.$ZodString.init(e,t),f.ZodType.init(e,t),e._zod.processJSONSchema=(i,n,a)=>ge.stringProcessor(e,i,n,a);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null},{regex(...e){return this.check(pe.regex(...e))},includes(...e){return this.check(pe.includes(...e))},startsWith(...e){return this.check(pe.startsWith(...e))},endsWith(...e){return this.check(pe.endsWith(...e))},min(...e){return this.check(pe.minLength(...e))},max(...e){return this.check(pe.maxLength(...e))},length(...e){return this.check(pe.length(...e))},nonempty(...e){return this.check(pe.minLength(1,...e))},lowercase(e){return this.check(pe.lowercase(e))},uppercase(e){return this.check(pe.uppercase(e))},trim(){return this.check(pe.trim())},normalize(...e){return this.check(pe.normalize(...e))},toLowerCase(){return this.check(pe.toLowerCase())},toUpperCase(){return this.check(pe.toUpperCase())},slugify(){return this.check(pe.slugify())}});f.ZodString=g.$constructor("ZodString",(e,t)=>{g.$ZodString.init(e,t),f._ZodString.init(e,t)},{email(e){return this.check(g._email(f.ZodEmail,e))},url(e){return this.check(g._url(f.ZodURL,e))},jwt(e){return this.check(g._jwt(f.ZodJWT,e))},emoji(e){return this.check(g._emoji(f.ZodEmoji,e))},guid(e){return this.check(g._guid(f.ZodGUID,e))},uuid(e){return this.check(g._uuid(f.ZodUUID,e))},uuidv4(e){return this.check(g._uuidv4(f.ZodUUID,e))},uuidv6(e){return this.check(g._uuidv6(f.ZodUUID,e))},uuidv7(e){return this.check(g._uuidv7(f.ZodUUID,e))},nanoid(e){return this.check(g._nanoid(f.ZodNanoID,e))},cuid(e){return this.check(g._cuid(f.ZodCUID,e))},cuid2(e){return this.check(g._cuid2(f.ZodCUID2,e))},ulid(e){return this.check(g._ulid(f.ZodULID,e))},base64(e){return this.check(g._base64(f.ZodBase64,e))},base64url(e){return this.check(g._base64url(f.ZodBase64URL,e))},xid(e){return this.check(g._xid(f.ZodXID,e))},ksuid(e){return this.check(g._ksuid(f.ZodKSUID,e))},ipv4(e){return this.check(g._ipv4(f.ZodIPv4,e))},ipv6(e){return this.check(g._ipv6(f.ZodIPv6,e))},cidrv4(e){return this.check(g._cidrv4(f.ZodCIDRv4,e))},cidrv6(e){return this.check(g._cidrv6(f.ZodCIDRv6,e))},e164(e){return this.check(g._e164(f.ZodE164,e))},datetime(e){return this.check(g._isoDateTime(f.ZodISODateTime,e))},date(e){return this.check(g._isoDate(f.ZodISODate,e))},time(e){return this.check(g._isoTime(f.ZodISOTime,e))},duration(e){return this.check(g._isoDuration(f.ZodISODuration,e))}});function ec(e){return g._string(f.ZodString,e)}f.ZodStringFormat=g.$constructor("ZodStringFormat",(e,t)=>{g.$ZodStringFormat.init(e,t),f._ZodString.init(e,t)});f.ZodISODateTime=g.$constructor("ZodISODateTime",(e,t)=>{g.$ZodISODateTime.init(e,t),f.ZodStringFormat.init(e,t)});f.ZodISODate=g.$constructor("ZodISODate",(e,t)=>{g.$ZodISODate.init(e,t),f.ZodStringFormat.init(e,t)});f.ZodISOTime=g.$constructor("ZodISOTime",(e,t)=>{g.$ZodISOTime.init(e,t),f.ZodStringFormat.init(e,t)});f.ZodISODuration=g.$constructor("ZodISODuration",(e,t)=>{g.$ZodISODuration.init(e,t),f.ZodStringFormat.init(e,t)});f.ZodEmail=g.$constructor("ZodEmail",(e,t)=>{g.$ZodEmail.init(e,t),f.ZodStringFormat.init(e,t)});function dN(e){return g._email(f.ZodEmail,e)}f.ZodGUID=g.$constructor("ZodGUID",(e,t)=>{g.$ZodGUID.init(e,t),f.ZodStringFormat.init(e,t)});function fN(e){return g._guid(f.ZodGUID,e)}f.ZodUUID=g.$constructor("ZodUUID",(e,t)=>{g.$ZodUUID.init(e,t),f.ZodStringFormat.init(e,t)});function pN(e){return g._uuid(f.ZodUUID,e)}function mN(e){return g._uuidv4(f.ZodUUID,e)}function gN(e){return g._uuidv6(f.ZodUUID,e)}function _N(e){return g._uuidv7(f.ZodUUID,e)}f.ZodURL=g.$constructor("ZodURL",(e,t)=>{g.$ZodURL.init(e,t),f.ZodStringFormat.init(e,t)});function hN(e){return g._url(f.ZodURL,e)}function vN(e){return g._url(f.ZodURL,{protocol:g.regexes.httpProtocol,hostname:g.regexes.domain,...he.util.normalizeParams(e)})}f.ZodEmoji=g.$constructor("ZodEmoji",(e,t)=>{g.$ZodEmoji.init(e,t),f.ZodStringFormat.init(e,t)});function yN(e){return g._emoji(f.ZodEmoji,e)}f.ZodNanoID=g.$constructor("ZodNanoID",(e,t)=>{g.$ZodNanoID.init(e,t),f.ZodStringFormat.init(e,t)});function bN(e){return g._nanoid(f.ZodNanoID,e)}f.ZodCUID=g.$constructor("ZodCUID",(e,t)=>{g.$ZodCUID.init(e,t),f.ZodStringFormat.init(e,t)});function wN(e){return g._cuid(f.ZodCUID,e)}f.ZodCUID2=g.$constructor("ZodCUID2",(e,t)=>{g.$ZodCUID2.init(e,t),f.ZodStringFormat.init(e,t)});function SN(e){return g._cuid2(f.ZodCUID2,e)}f.ZodULID=g.$constructor("ZodULID",(e,t)=>{g.$ZodULID.init(e,t),f.ZodStringFormat.init(e,t)});function $N(e){return g._ulid(f.ZodULID,e)}f.ZodXID=g.$constructor("ZodXID",(e,t)=>{g.$ZodXID.init(e,t),f.ZodStringFormat.init(e,t)});function ON(e){return g._xid(f.ZodXID,e)}f.ZodKSUID=g.$constructor("ZodKSUID",(e,t)=>{g.$ZodKSUID.init(e,t),f.ZodStringFormat.init(e,t)});function IN(e){return g._ksuid(f.ZodKSUID,e)}f.ZodIPv4=g.$constructor("ZodIPv4",(e,t)=>{g.$ZodIPv4.init(e,t),f.ZodStringFormat.init(e,t)});function EN(e){return g._ipv4(f.ZodIPv4,e)}f.ZodMAC=g.$constructor("ZodMAC",(e,t)=>{g.$ZodMAC.init(e,t),f.ZodStringFormat.init(e,t)});function PN(e){return g._mac(f.ZodMAC,e)}f.ZodIPv6=g.$constructor("ZodIPv6",(e,t)=>{g.$ZodIPv6.init(e,t),f.ZodStringFormat.init(e,t)});function zN(e){return g._ipv6(f.ZodIPv6,e)}f.ZodCIDRv4=g.$constructor("ZodCIDRv4",(e,t)=>{g.$ZodCIDRv4.init(e,t),f.ZodStringFormat.init(e,t)});function TN(e){return g._cidrv4(f.ZodCIDRv4,e)}f.ZodCIDRv6=g.$constructor("ZodCIDRv6",(e,t)=>{g.$ZodCIDRv6.init(e,t),f.ZodStringFormat.init(e,t)});function AN(e){return g._cidrv6(f.ZodCIDRv6,e)}f.ZodBase64=g.$constructor("ZodBase64",(e,t)=>{g.$ZodBase64.init(e,t),f.ZodStringFormat.init(e,t)});function jN(e){return g._base64(f.ZodBase64,e)}f.ZodBase64URL=g.$constructor("ZodBase64URL",(e,t)=>{g.$ZodBase64URL.init(e,t),f.ZodStringFormat.init(e,t)});function kN(e){return g._base64url(f.ZodBase64URL,e)}f.ZodE164=g.$constructor("ZodE164",(e,t)=>{g.$ZodE164.init(e,t),f.ZodStringFormat.init(e,t)});function NN(e){return g._e164(f.ZodE164,e)}f.ZodCreditCard=g.$constructor("ZodCreditCard",(e,t)=>{g.$ZodCreditCard.init(e,t),f.ZodStringFormat.init(e,t)});function RN(e){return g._creditCard(f.ZodCreditCard,e)}f.ZodJWT=g.$constructor("ZodJWT",(e,t)=>{g.$ZodJWT.init(e,t),f.ZodStringFormat.init(e,t)});function CN(e){return g._jwt(f.ZodJWT,e)}f.ZodCustomStringFormat=g.$constructor("ZodCustomStringFormat",(e,t)=>{g.$ZodCustomStringFormat.init(e,t),f.ZodStringFormat.init(e,t)});function DN(e,t,r={}){return g._stringFormat(f.ZodCustomStringFormat,e,t,r)}function MN(e){return g._stringFormat(f.ZodCustomStringFormat,"hostname",g.regexes.hostname,e)}function xN(e){return g._stringFormat(f.ZodCustomStringFormat,"hex",g.regexes.hex,e)}function UN(e,t){let r=t?.enc??"hex",i=`${e}_${r}`,n=g.regexes[i];if(!n)throw new Error(`Unrecognized hash format: ${i}`);return g._stringFormat(f.ZodCustomStringFormat,i,n,t)}f.ZodNumber=g.$constructor("ZodNumber",(e,t)=>{g.$ZodNumber.init(e,t),f.ZodType.init(e,t),e._zod.processJSONSchema=(i,n,a)=>ge.numberProcessor(e,i,n,a);let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null},{gt(e,t){return this.check(pe.gt(e,t))},gte(e,t){return this.check(pe.gte(e,t))},min(e,t){return this.check(pe.gte(e,t))},lt(e,t){return this.check(pe.lt(e,t))},lte(e,t){return this.check(pe.lte(e,t))},max(e,t){return this.check(pe.lte(e,t))},int(e){return this.check(ll(e))},safe(e){return this.check(ll(e))},positive(e){return this.check(pe.gt(0,e))},nonnegative(e){return this.check(pe.gte(0,e))},negative(e){return this.check(pe.lt(0,e))},nonpositive(e){return this.check(pe.lte(0,e))},multipleOf(e,t){return this.check(pe.multipleOf(e,t))},step(e,t){return this.check(pe.multipleOf(e,t))},finite(){return this}});function u_(e){return g._number(f.ZodNumber,e)}f.ZodNumberFormat=g.$constructor("ZodNumberFormat",(e,t)=>{g.$ZodNumberFormat.init(e,t),f.ZodNumber.init(e,t)});function ll(e){return g._int(f.ZodNumberFormat,e)}function LN(e){return g._float32(f.ZodNumberFormat,e)}function ZN(e){return g._float64(f.ZodNumberFormat,e)}function qN(e){return g._int32(f.ZodNumberFormat,e)}function FN(e){return g._uint32(f.ZodNumberFormat,e)}f.ZodBoolean=g.$constructor("ZodBoolean",(e,t)=>{g.$ZodBoolean.init(e,t),f.ZodType.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ge.booleanProcessor(e,r,i,n)});function l_(e){return g._boolean(f.ZodBoolean,e)}f.ZodBigInt=g.$constructor("ZodBigInt",(e,t)=>{g.$ZodBigInt.init(e,t),f.ZodType.init(e,t),e._zod.processJSONSchema=(i,n,a)=>ge.bigintProcessor(e,i,n,a);let r=e._zod.bag;e.minValue=r.minimum??null,e.maxValue=r.maximum??null,e.format=r.format??null},{gte(e,t){return this.check(pe.gte(e,t))},min(e,t){return this.check(pe.gte(e,t))},gt(e,t){return this.check(pe.gt(e,t))},lt(e,t){return this.check(pe.lt(e,t))},lte(e,t){return this.check(pe.lte(e,t))},max(e,t){return this.check(pe.lte(e,t))},positive(e){return this.check(pe.gt(BigInt(0),e))},negative(e){return this.check(pe.lt(BigInt(0),e))},nonpositive(e){return this.check(pe.lte(BigInt(0),e))},nonnegative(e){return this.check(pe.gte(BigInt(0),e))},multipleOf(e,t){return this.check(pe.multipleOf(e,t))}});function VN(e){return g._bigint(f.ZodBigInt,e)}f.ZodBigIntFormat=g.$constructor("ZodBigIntFormat",(e,t)=>{g.$ZodBigIntFormat.init(e,t),f.ZodBigInt.init(e,t)});function BN(e){return g._int64(f.ZodBigIntFormat,e)}function GN(e){return g._uint64(f.ZodBigIntFormat,e)}f.ZodSymbol=g.$constructor("ZodSymbol",(e,t)=>{g.$ZodSymbol.init(e,t),f.ZodType.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ge.symbolProcessor(e,r,i,n)});function JN(e){return g._symbol(f.ZodSymbol,e)}f.ZodUndefined=g.$constructor("ZodUndefined",(e,t)=>{g.$ZodUndefined.init(e,t),f.ZodType.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ge.undefinedProcessor(e,r,i,n)});function WN(e){return g._undefined(f.ZodUndefined,e)}f.ZodNull=g.$constructor("ZodNull",(e,t)=>{g.$ZodNull.init(e,t),f.ZodType.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ge.nullProcessor(e,r,i,n)});function d_(e){return g._null(f.ZodNull,e)}f.ZodAny=g.$constructor("ZodAny",(e,t)=>{g.$ZodAny.init(e,t),f.ZodType.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ge.anyProcessor(e,r,i,n)});function YN(){return g._any(f.ZodAny)}f.ZodUnknown=g.$constructor("ZodUnknown",(e,t)=>{g.$ZodUnknown.init(e,t),f.ZodType.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ge.unknownProcessor(e,r,i,n)});function Xi(){return g._unknown(f.ZodUnknown)}f.ZodNever=g.$constructor("ZodNever",(e,t)=>{g.$ZodNever.init(e,t),f.ZodType.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ge.neverProcessor(e,r,i,n)});function fl(e){return g._never(f.ZodNever,e)}f.ZodVoid=g.$constructor("ZodVoid",(e,t)=>{g.$ZodVoid.init(e,t),f.ZodType.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ge.voidProcessor(e,r,i,n)});function KN(e){return g._void(f.ZodVoid,e)}f.ZodDate=g.$constructor("ZodDate",(e,t)=>{g.$ZodDate.init(e,t),f.ZodType.init(e,t),e._zod.processJSONSchema=(i,n,a)=>ge.dateProcessor(e,i,n,a),e.min=(i,n)=>e.check(pe.gte(i,n)),e.max=(i,n)=>e.check(pe.lte(i,n));let r=e._zod.bag;e.minDate=r.minimum?new Date(r.minimum):null,e.maxDate=r.maximum?new Date(r.maximum):null});function HN(e){return g._date(f.ZodDate,e)}f.ZodArray=g.$constructor("ZodArray",(e,t)=>{yi(),g.$ZodArray.init(e,t),f.ZodType.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ge.arrayProcessor(e,r,i,n),e.element=t.element},{min(e,t){return this.check(pe.minLength(e,t))},nonempty(e){return this.check(pe.minLength(1,e))},max(e,t){return this.check(pe.maxLength(e,t))},length(e,t){return this.check(pe.length(e,t))},unwrap(){return this.element}});function ic(e,t){return g._array(f.ZodArray,e,t)}function XN(e){let t=e._zod.def.shape;return ml(Object.keys(t))}f.ZodObject=g.$constructor("ZodObject",(e,t)=>{yi(),g.$ZodObjectJIT.init(e,t),f.ZodType.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ge.objectProcessor(e,r,i,n),he.util.installLazyProp(e,"shape",r=>r._zod.def.shape,!1)},{keyof(){return ml(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:Xi()})},loose(){return this.clone({...this._zod.def,catchall:Xi()})},strict(){return this.clone({...this._zod.def,catchall:fl()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return he.util.extend(this,e)},safeExtend(e){return he.util.safeExtend(this,e)},merge(e){return he.util.merge(this,e)},pick(e){return he.util.pick(this,e)},omit(e){return he.util.omit(this,e)},partial(...e){return he.util.partial(f.ZodOptional,this,e[0])},exactPartial(...e){return he.util.partial(f.ZodExactOptional,this,e[0],"exactPartial")},required(...e){return he.util.required(f.ZodNonOptional,this,e[0])}});function QN(e,t){let r={type:"object",shape:e??{},...he.util.normalizeParams(t)};return new f.ZodObject(r)}function eR(e,t){return new f.ZodObject({type:"object",shape:e,catchall:fl(),...he.util.normalizeParams(t)})}function tR(e,t){return new f.ZodObject({type:"object",shape:e,catchall:Xi(),...he.util.normalizeParams(t)})}f.ZodUnion=g.$constructor("ZodUnion",(e,t)=>{g.$ZodUnion.init(e,t),f.ZodType.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ge.unionProcessor(e,r,i,n),e.options=t.options});function pl(e,t){return new f.ZodUnion({type:"union",options:e,...he.util.normalizeParams(t)})}f.ZodXor=g.$constructor("ZodXor",(e,t)=>{f.ZodUnion.init(e,t),g.$ZodXor.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ge.unionProcessor(e,r,i,n),e.options=t.options});function nR(e,t){return new f.ZodXor({type:"union",options:e,inclusive:!1,...he.util.normalizeParams(t)})}f.ZodDiscriminatedUnion=g.$constructor("ZodDiscriminatedUnion",(e,t)=>{f.ZodUnion.init(e,t),g.$ZodDiscriminatedUnion.init(e,t)});function rR(e,t,r){return new f.ZodDiscriminatedUnion({type:"union",options:t,discriminator:e,...he.util.normalizeParams(r)})}f.ZodIntersection=g.$constructor("ZodIntersection",(e,t)=>{g.$ZodIntersection.init(e,t),f.ZodType.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ge.intersectionProcessor(e,r,i,n)});function f_(e,t){return new f.ZodIntersection({type:"intersection",left:e,right:t})}f.ZodTuple=g.$constructor("ZodTuple",(e,t)=>{yi(),g.$ZodTuple.init(e,t),f.ZodType.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ge.tupleProcessor(e,r,i,n)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...e,items:e.items.map(t=>new f.ZodOptional({type:"optional",innerType:t}))})}});function p_(e,t,r){let i=t instanceof g.$ZodType,n=i?r:t,a=i?t:null;return new f.ZodTuple({type:"tuple",items:e,rest:a,...he.util.normalizeParams(n)})}f.ZodRecord=g.$constructor("ZodRecord",(e,t)=>{yi(),g.$ZodRecord.init(e,t),f.ZodType.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ge.recordProcessor(e,r,i,n),e.keyType=t.keyType,e.valueType=t.valueType});function m_(e,t,r){return!t||!t._zod?new f.ZodRecord({type:"record",keyType:ec(),valueType:e,...he.util.normalizeParams(t)}):new f.ZodRecord({type:"record",keyType:e,valueType:t,...he.util.normalizeParams(r)})}function iR(e,t,r){return new f.ZodRecord({type:"record",keyType:e,valueType:t,...he.util.normalizeParams(r),partial:!0})}function aR(e,t,r){return new f.ZodRecord({type:"record",keyType:e,valueType:t,mode:"loose",...he.util.normalizeParams(r)})}f.ZodMap=g.$constructor("ZodMap",(e,t)=>{yi(),g.$ZodMap.init(e,t),f.ZodType.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ge.mapProcessor(e,r,i,n),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...r)=>e.check(g._minSize(...r)),e.nonempty=r=>e.check(g._minSize(1,r)),e.max=(...r)=>e.check(g._maxSize(...r)),e.size=(...r)=>e.check(g._size(...r))});function oR(e,t,r){return new f.ZodMap({type:"map",keyType:e,valueType:t,...he.util.normalizeParams(r)})}f.ZodSet=g.$constructor("ZodSet",(e,t)=>{yi(),g.$ZodSet.init(e,t),f.ZodType.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ge.setProcessor(e,r,i,n),e.min=(...r)=>e.check(g._minSize(...r)),e.nonempty=r=>e.check(g._minSize(1,r)),e.max=(...r)=>e.check(g._maxSize(...r)),e.size=(...r)=>e.check(g._size(...r))});function sR(e,t){return new f.ZodSet({type:"set",valueType:e,...he.util.normalizeParams(t)})}f.ZodEnum=g.$constructor("ZodEnum",(e,t)=>{g.$ZodEnum.init(e,t),f.ZodType.init(e,t),e._zod.processJSONSchema=(i,n,a)=>ge.enumProcessor(e,i,n,a),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(i,n)=>{let a={};for(let o of i)if(r.has(o))a[o]=t.entries[o];else throw new Error(`Key ${o} not found in enum`);return new f.ZodEnum({...t,checks:[],...he.util.normalizeParams(n),entries:a})},e.exclude=(i,n)=>{let a={...t.entries};for(let o of i)if(r.has(o))delete a[o];else throw new Error(`Key ${o} not found in enum`);return new f.ZodEnum({...t,checks:[],...he.util.normalizeParams(n),entries:a})}});function ml(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(i=>[i,i])):e;return new f.ZodEnum({type:"enum",entries:r,...he.util.normalizeParams(t)})}function cR(e,t){return new f.ZodEnum({type:"enum",entries:e,...he.util.normalizeParams(t)})}f.ZodLiteral=g.$constructor("ZodLiteral",(e,t)=>{g.$ZodLiteral.init(e,t),f.ZodType.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ge.literalProcessor(e,r,i,n),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function uR(e,t){return new f.ZodLiteral({type:"literal",values:Array.isArray(e)?e:[e],...he.util.normalizeParams(t)})}f.ZodFile=g.$constructor("ZodFile",(e,t)=>{g.$ZodFile.init(e,t),f.ZodType.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ge.fileProcessor(e,r,i,n),e.min=(r,i)=>e.check(g._minSize(r,i)),e.max=(r,i)=>e.check(g._maxSize(r,i)),e.mime=(r,i)=>e.check(g._mime(Array.isArray(r)?r:[r],i))});function lR(e){return g._file(f.ZodFile,e)}f.ZodTransform=g.$constructor("ZodTransform",(e,t)=>{yi(),g.$ZodTransform.init(e,t),f.ZodType.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ge.transformProcessor(e,r,i,n),e._zod.parse=(r,i)=>{if(i.direction==="backward")throw new g.$ZodEncodeError(e.constructor.name);r.addIssue=a=>{if(typeof a=="string")r.issues.push(he.util.issue(a,r.value,t));else{let o=a;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),"input"in o||(o.input=r.value),o.inst??(o.inst=e),r.issues.push(he.util.issue(o))}};let n=t.transform(r.value,r);return n instanceof Promise?n.then(a=>(r.value=a,r)):(r.value=n,r)}});function gl(e){return new f.ZodTransform({type:"transform",transform:e})}f.ZodOptional=g.$constructor("ZodOptional",(e,t)=>{g.$ZodOptional.init(e,t),f.ZodType.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ge.optionalProcessor(e,r,i,n),e.unwrap=()=>e._zod.def.innerType});function tc(e){return new f.ZodOptional({type:"optional",innerType:e})}f.ZodExactOptional=g.$constructor("ZodExactOptional",(e,t)=>{g.$ZodExactOptional.init(e,t),f.ZodType.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ge.optionalProcessor(e,r,i,n),e.unwrap=()=>e._zod.def.innerType});function g_(e){return new f.ZodExactOptional({type:"optional",innerType:e})}f.ZodNullable=g.$constructor("ZodNullable",(e,t)=>{g.$ZodNullable.init(e,t),f.ZodType.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ge.nullableProcessor(e,r,i,n),e.unwrap=()=>e._zod.def.innerType});function nc(e){return new f.ZodNullable({type:"nullable",innerType:e})}function dR(e){return tc(nc(e))}f.ZodDefault=g.$constructor("ZodDefault",(e,t)=>{g.$ZodDefault.init(e,t),f.ZodType.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ge.defaultProcessor(e,r,i,n),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function __(e,t){return new f.ZodDefault({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():he.util.shallowClone(t)}})}f.ZodPrefault=g.$constructor("ZodPrefault",(e,t)=>{g.$ZodPrefault.init(e,t),f.ZodType.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ge.prefaultProcessor(e,r,i,n),e.unwrap=()=>e._zod.def.innerType});function h_(e,t){return new f.ZodPrefault({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():he.util.shallowClone(t)}})}f.ZodNonOptional=g.$constructor("ZodNonOptional",(e,t)=>{g.$ZodNonOptional.init(e,t),f.ZodType.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ge.nonoptionalProcessor(e,r,i,n),e.unwrap=()=>e._zod.def.innerType});function v_(e,t){return new f.ZodNonOptional({type:"nonoptional",innerType:e,...he.util.normalizeParams(t)})}f.ZodSuccess=g.$constructor("ZodSuccess",(e,t)=>{g.$ZodSuccess.init(e,t),f.ZodType.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ge.successProcessor(e,r,i,n),e.unwrap=()=>e._zod.def.innerType});function fR(e){return new f.ZodSuccess({type:"success",innerType:e})}f.ZodCatch=g.$constructor("ZodCatch",(e,t)=>{g.$ZodCatch.init(e,t),f.ZodType.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ge.catchProcessor(e,r,i,n),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function y_(e,t){return new f.ZodCatch({type:"catch",innerType:e,catchValue:typeof t=="function"?t:g.util.constantCatch(t)})}f.ZodNaN=g.$constructor("ZodNaN",(e,t)=>{g.$ZodNaN.init(e,t),f.ZodType.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ge.nanProcessor(e,r,i,n)});function pR(e){return g._nan(f.ZodNaN,e)}f.ZodPipe=g.$constructor("ZodPipe",(e,t)=>{g.$ZodPipe.init(e,t),f.ZodType.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ge.pipeProcessor(e,r,i,n),e.in=t.in,e.out=t.out});function dl(e,t){return new f.ZodPipe({type:"pipe",in:e,out:t})}f.ZodCodec=g.$constructor("ZodCodec",(e,t)=>{f.ZodPipe.init(e,t),g.$ZodCodec.init(e,t)});function mR(e,t,r){return new f.ZodCodec({type:"pipe",in:e,out:t,transform:r.decode,reverseTransform:r.encode})}function gR(e){let t=e._zod.def;return new f.ZodCodec({type:"pipe",in:t.out,out:t.in,transform:t.reverseTransform,reverseTransform:t.transform})}f.ZodPreprocess=g.$constructor("ZodPreprocess",(e,t)=>{f.ZodPipe.init(e,t),g.$ZodPreprocess.init(e,t)});f.ZodReadonly=g.$constructor("ZodReadonly",(e,t)=>{g.$ZodReadonly.init(e,t),f.ZodType.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ge.readonlyProcessor(e,r,i,n),e.unwrap=()=>e._zod.def.innerType});function b_(e){return new f.ZodReadonly({type:"readonly",innerType:e})}f.ZodTemplateLiteral=g.$constructor("ZodTemplateLiteral",(e,t)=>{g.$ZodTemplateLiteral.init(e,t),f.ZodType.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ge.templateLiteralProcessor(e,r,i,n)});function _R(e,t){return new f.ZodTemplateLiteral({type:"template_literal",parts:e,...he.util.normalizeParams(t)})}f.ZodLazy=g.$constructor("ZodLazy",(e,t)=>{g.$ZodLazy.init(e,t),f.ZodType.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ge.lazyProcessor(e,r,i,n),e.unwrap=()=>e._zod.def.getter()});function w_(e){return new f.ZodLazy({type:"lazy",getter:e})}f.ZodPromise=g.$constructor("ZodPromise",(e,t)=>{g.$ZodPromise.init(e,t),f.ZodType.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ge.promiseProcessor(e,r,i,n),e.unwrap=()=>e._zod.def.innerType});function hR(e){return new f.ZodPromise({type:"promise",innerType:e})}f.ZodFunction=g.$constructor("ZodFunction",(e,t)=>{g.$ZodFunction.init(e,t),f.ZodType.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ge.functionProcessor(e,r,i,n)});function ac(e){return new f.ZodFunction({type:"function",input:Array.isArray(e?.input)?p_(e?.input):e?.input??ic(Xi()),output:e?.output??Xi()})}f.ZodCustom=g.$constructor("ZodCustom",(e,t)=>{g.$ZodCustom.init(e,t),f.ZodType.init(e,t),e._zod.processJSONSchema=(r,i,n)=>ge.customProcessor(e,r,i,n)});function vR(e){let t=new g.$ZodCheck({check:"custom"});return t._zod.check=e,t}function yR(e,t){return g._custom(f.ZodCustom,e??(()=>!0),t)}function S_(e,t={}){return g._refine(f.ZodCustom,e,t)}function $_(e,t){return g._superRefine(e,t)}f.describe=g.describe;f.meta=g.meta;function bR(e,t={}){let r=new f.ZodCustom({type:"custom",check:"custom",fn:i=>i instanceof e,abort:!0,...he.util.normalizeParams(t)});return r._zod.bag.Class=e,r._zod.check=i=>{i.value instanceof e||i.issues.push({code:"invalid_type",expected:e.name,input:i.value,inst:r,path:[...r._zod.def.path??[]]})},r}var wR=(...e)=>g._stringbool({Codec:f.ZodCodec,Boolean:f.ZodBoolean,String:f.ZodString},...e);f.stringbool=wR;function SR(e){let t=w_(()=>pl([ec(e),u_(),l_(),d_(),ic(t),m_(ec(),t)]));return t}function $R(e,t){return new f.ZodPreprocess({type:"pipe",in:gl(e),out:t})}});var P_=P(tt=>{"use strict";var OR=tt&&tt.__createBinding||(Object.create?(function(e,t,r,i){i===void 0&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);(!n||("get"in n?!t.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}):(function(e,t,r,i){i===void 0&&(i=r),e[i]=t[r]})),IR=tt&&tt.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),ER=tt&&tt.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&OR(t,e,r);return IR(t,e),t};Object.defineProperty(tt,"__esModule",{value:!0});tt.ZodFirstPartyTypeKind=tt.config=tt.$brand=tt.ZodIssueCode=void 0;tt.setErrorMap=PR;tt.getErrorMap=zR;var I_=ER(Ot());tt.ZodIssueCode={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};var E_=Ot();Object.defineProperty(tt,"$brand",{enumerable:!0,get:function(){return E_.$brand}});Object.defineProperty(tt,"config",{enumerable:!0,get:function(){return E_.config}});function PR(e){I_.config({customError:e})}function zR(){return I_.config().customError}var O_;O_||(tt.ZodFirstPartyTypeKind=O_={})});var uc=P(Xe=>{"use strict";var TR=Xe&&Xe.__createBinding||(Object.create?(function(e,t,r,i){i===void 0&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);(!n||("get"in n?!t.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}):(function(e,t,r,i){i===void 0&&(i=r),e[i]=t[r]})),AR=Xe&&Xe.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),jR=Xe&&Xe.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&TR(t,e,r);return AR(t,e),t};Object.defineProperty(Xe,"__esModule",{value:!0});Xe.ZodISOTime=Xe.ZodISODuration=Xe.ZodISODateTime=Xe.ZodISODate=void 0;Xe.datetime=kR;Xe.date=NR;Xe.time=RR;Xe.duration=CR;var oc=jR(Ot()),sc=Br(),cc=Br();Object.defineProperty(Xe,"ZodISODate",{enumerable:!0,get:function(){return cc.ZodISODate}});Object.defineProperty(Xe,"ZodISODateTime",{enumerable:!0,get:function(){return cc.ZodISODateTime}});Object.defineProperty(Xe,"ZodISODuration",{enumerable:!0,get:function(){return cc.ZodISODuration}});Object.defineProperty(Xe,"ZodISOTime",{enumerable:!0,get:function(){return cc.ZodISOTime}});function kR(e){return oc._isoDateTime(sc.ZodISODateTime,e)}function NR(e){return oc._isoDate(sc.ZodISODate,e)}function RR(e){return oc._isoTime(sc.ZodISOTime,e)}function CR(e){return oc._isoDuration(sc.ZodISODuration,e)}});var j_=P(Or=>{"use strict";var DR=Or&&Or.__createBinding||(Object.create?(function(e,t,r,i){i===void 0&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);(!n||("get"in n?!t.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}):(function(e,t,r,i){i===void 0&&(i=r),e[i]=t[r]})),MR=Or&&Or.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),hl=Or&&Or.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&DR(t,e,r);return MR(t,e),t};Object.defineProperty(Or,"__esModule",{value:!0});Or.fromJSONSchema=WR;var xR=Ea(),_l=B(),UR=hl(Hs()),LR=hl(uc()),ZR=hl(Br()),Y={...ZR,...UR,iso:LR},qR=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function FR(e,t){let r=e.$schema;return r==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":r==="http://json-schema.org/draft-07/schema#"?"draft-7":r==="http://json-schema.org/draft-04/schema#"?"draft-4":t??"draft-2020-12"}function z_(e,t){return e.map((r,i)=>i<t?r:r.optional())}function VR(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function BR(e,t){if(!e.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let r=e.slice(1).split("/").filter(Boolean);if(r.length===0)return t.rootSchema;let i=t.version==="draft-2020-12"?"$defs":"definitions";if(r[0]===i){let n=r[1]===void 0?void 0:VR(r[1]);if(!n||!t.defs[n])throw new Error(`Reference not found: ${e}`);return t.defs[n]}throw new Error(`Reference not found: ${e}`)}function GR(e,t){return Y.transform(i=>i).check(i=>{let n=i.value;if(!(typeof n!="object"||n===null||Array.isArray(n)))for(let a of Object.getOwnPropertyNames(n)){let o=t.safeParse(a);o.success||i.issues.push({code:"invalid_key",origin:"record",issues:o.error.issues,input:a,path:[a],continue:!0})}}).pipe(e)}function T_(e,t){if(e!==!1)return e===void 0||e===!0?Y.any():It(e,t)}var JR=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function A_(e,t){if(e.not!==void 0){if(typeof e.not=="object"&&Object.keys(e.not).length===0)return Y.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(e.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(e.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(e.if!==void 0||e.then!==void 0||e.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(e.dependentSchemas!==void 0||e.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(e.$ref){let n=e.$ref;if(t.refs.has(n))return t.refs.get(n);if(t.processing.has(n))return Y.lazy(()=>{if(!t.refs.has(n))throw new Error(`Circular reference not resolved: ${n}`);return t.refs.get(n)});t.processing.add(n);let a=BR(n,t),o=It(a,t);return t.refs.set(n,o),t.processing.delete(n),o}if(e.enum!==void 0){let n=e.enum;if(t.version==="openapi-3.0"&&e.nullable===!0&&n.length===1&&n[0]===null)return Y.null();if(n.length===0)return Y.never();if(n.length===1)return Y.literal(n[0]);if(n.every(o=>typeof o=="string"))return Y.enum(n);let a=n.map(o=>Y.literal(o));return a.length<2?a[0]:Y.union([a[0],a[1],...a.slice(2)])}if(e.const!==void 0)return Y.literal(e.const);let r=e.type;if(Array.isArray(r)){let n=r.map(a=>{let o={...e,type:a};return A_(o,t)});return n.length===0?Y.never():n.length===1?n[0]:Y.union(n)}if(!r)return Y.any();let i;switch(r){case"string":{let n=Y.string();if(e.format){let a=e.format;a==="email"?n=n.check(Y.email()):a==="uri"||a==="uri-reference"?n=n.check(Y.url()):a==="uuid"||a==="guid"?n=n.check(Y.uuid()):a==="date-time"?n=n.check(Y.iso.datetime({offset:!0})):a==="date"?n=n.check(Y.iso.date()):a==="time"?n=n.check(Y.regex(JR)):a==="duration"?n=n.check(Y.iso.duration()):a==="hostname"?n=n.check(Y.hostname()):a==="ipv4"?n=n.check(Y.ipv4()):a==="ipv6"?n=n.check(Y.ipv6()):a==="mac"?n=n.check(Y.mac()):a==="cidr"?n=n.check(Y.cidrv4()):a==="cidr-v6"?n=n.check(Y.cidrv6()):a==="base64"?n=n.check(Y.base64()):a==="base64url"?n=n.check(Y.base64url()):a==="e164"?n=n.check(Y.e164()):a==="credit_card"?n=n.check(Y.creditCard()):a==="jwt"?n=n.check(Y.jwt()):a==="emoji"?n=n.check(Y.emoji()):a==="nanoid"?n=n.check(Y.nanoid()):a==="cuid"?n=n.check(Y.cuid()):a==="cuid2"?n=n.check(Y.cuid2()):a==="ulid"?n=n.check(Y.ulid()):a==="xid"?n=n.check(Y.xid()):a==="ksuid"&&(n=n.check(Y.ksuid()))}typeof e.minLength=="number"&&(n=n.min(e.minLength)),typeof e.maxLength=="number"&&(n=n.max(e.maxLength)),e.pattern&&(n=n.regex(new RegExp(e.pattern))),i=n;break}case"number":case"integer":{let n=r==="integer"?Y.number().int():Y.number();typeof e.minimum=="number"&&e.exclusiveMinimum!==!0&&(n=n.min(e.minimum)),typeof e.maximum=="number"&&e.exclusiveMaximum!==!0&&(n=n.max(e.maximum)),typeof e.exclusiveMinimum=="number"?n=n.gt(e.exclusiveMinimum):e.exclusiveMinimum===!0&&typeof e.minimum=="number"&&(n=n.gt(e.minimum)),typeof e.exclusiveMaximum=="number"?n=n.lt(e.exclusiveMaximum):e.exclusiveMaximum===!0&&typeof e.maximum=="number"&&(n=n.lt(e.maximum)),typeof e.multipleOf=="number"&&(n=n.multipleOf(e.multipleOf)),i=n;break}case"boolean":{i=Y.boolean();break}case"null":{i=Y.null();break}case"object":{let n={},a=e.properties||{},o=new Set(e.required||[]),s=typeof e.additionalProperties=="object"?It(e.additionalProperties,t):void 0;for(let[c,u]of Object.entries(a)){let d=It(u,t);(0,_l.assignProp)(n,c,o.has(c)?d:d.optional())}if(e.patternProperties){let c=e.patternProperties,u=Object.keys(c),d=[];for(let m of u){let b=It(c[m],t),y=Y.string().regex(new RegExp(m));d.push(Y.looseRecord(y,b))}let p=[];if(Object.keys(n).length>0&&p.push(Y.object(n).passthrough()),p.push(...d),p.length===0)i=Y.object({}).passthrough();else if(p.length===1)i=p[0];else{let m=Y.intersection(p[0],p[1]);for(let b=2;b<p.length;b++)m=Y.intersection(m,p[b]);i=m}if(e.additionalProperties===!1){let m=Object.keys(n),b=u.map(O=>new RegExp(O)),y=i;i=i.check(O=>{if(!(0,_l.isPlainObject)(O.value))return;let z=[];for(let re of Object.keys(O.value))m.includes(re)||b.some(C=>C.test(re))||z.push(re);z.length&&O.issues.push({code:"unrecognized_keys",keys:z,input:O.value,inst:y})})}}else{let c=Y.object(n);e.additionalProperties===!1?i=c.strict():s?i=c.catchall(s):i=c.passthrough()}if(e.propertyNames!==void 0&&e.propertyNames!==!0){let c=typeof e.propertyNames=="object"&&e.propertyNames.type===void 0?{type:"string",...e.propertyNames}:e.propertyNames;i=GR(i,It(c,t))}break}case"array":{let n=e.prefixItems,a=e.items;if(n&&Array.isArray(n)){let o=typeof e.minItems=="number"?e.minItems:0,s=n.map(p=>It(p,t)),c=z_(s,o),u=Array.isArray(a)?void 0:T_(a,t),d=Y.tuple(c);i=u?d.rest(u):d,typeof e.minItems=="number"&&(i=i.check(Y.minLength(e.minItems))),typeof e.maxItems=="number"&&(i=i.check(Y.maxLength(e.maxItems)))}else if(Array.isArray(a)){let o=typeof e.minItems=="number"?e.minItems:0,s=a.map(p=>It(p,t)),c=z_(s,o),u=T_(e.additionalItems,t),d=Y.tuple(c);i=u?d.rest(u):d,typeof e.minItems=="number"&&(i=i.check(Y.minLength(e.minItems))),typeof e.maxItems=="number"&&(i=i.check(Y.maxLength(e.maxItems)))}else if(a!==void 0){let o=It(a,t),s=Y.array(o);typeof e.minItems=="number"&&(s=s.min(e.minItems)),typeof e.maxItems=="number"&&(s=s.max(e.maxItems)),i=s}else i=Y.array(Y.any());break}default:throw new Error(`Unsupported type: ${r}`)}return i}function It(e,t){if(typeof e=="boolean")return e?Y.any():Y.never();let r=A_(e,t),i=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){let s=e.anyOf.map(u=>It(u,t)),c=Y.union(s);r=i?Y.intersection(r,c):c}if(e.oneOf&&Array.isArray(e.oneOf)){let s=e.oneOf.map(u=>It(u,t)),c=Y.xor(s);r=i?Y.intersection(r,c):c}if(e.allOf&&Array.isArray(e.allOf))if(e.allOf.length===0)r=i?r:Y.any();else{let s=i?r:It(e.allOf[0],t),c=i?0:1;for(let u=c;u<e.allOf.length;u++)s=Y.intersection(s,It(e.allOf[u],t));r=s}e.nullable===!0&&t.version==="openapi-3.0"&&(r=Y.nullable(r)),e.readOnly===!0&&(r=Y.readonly(r)),e.default!==void 0&&(r=r.default(e.default));let n={},a=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let s of a)s in e&&(n[s]=e[s]);let o=["contentEncoding","contentMediaType","contentSchema"];for(let s of o)s in e&&(n[s]=e[s]);e.propertyNames!==void 0&&e.type==="object"&&e.$ref===void 0&&(n.propertyNames=e.propertyNames);for(let s of Object.keys(e))qR.has(s)||(0,_l.assignProp)(n,s,e[s]);return Object.keys(n).length>0&&t.registry.add(r,n),e.description&&(r=r.describe(e.description)),r}function WR(e,t){if(typeof e=="boolean")return e?Y.any():Y.never();let r;try{r=JSON.parse(JSON.stringify(e))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let i=FR(r,t?.defaultTarget),n=r.$defs||r.definitions||{},a={version:i,defs:n,refs:new Map,processing:new Set,rootSchema:r,registry:t?.registry??xR.globalRegistry};return It(r,a)}});var vl=P(Ir=>{"use strict";var YR=Ir&&Ir.__createBinding||(Object.create?(function(e,t,r,i){i===void 0&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);(!n||("get"in n?!t.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}):(function(e,t,r,i){i===void 0&&(i=r),e[i]=t[r]})),KR=Ir&&Ir.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),HR=Ir&&Ir.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&YR(t,e,r);return KR(t,e),t};Object.defineProperty(Ir,"__esModule",{value:!0});Ir.visit=QR;var XR=HR(Oa()),Ht=B(),k_=Symbol("z.visit/resolving");function QR(e,t){let r=typeof t=="function"?t:(o,s)=>{let c=t[o._zod.def.type];return c?c(o,s):o},i=new Map;function n(o){let s=i.get(o);if(s===k_)return new XR.$ZodLazy({type:"lazy",getter:()=>i.get(o)});if(s!==void 0)return s;i.set(o,k_);let c=a(o),u=r(c,c!==o);return i.set(o,u),u}function a(o){let s=o._zod.def,c=s.type;switch(c){case"object":{let u=s.shape,d=Object.keys(u),p=!1,m={};for(let y of d){let O=n(u[y]);O!==u[y]&&(p=!0),m[y]=O}let b=s.catchall;return s.catchall&&(b=n(s.catchall),b!==s.catchall&&(p=!0)),p?(0,Ht.clone)(o,{...s,shape:m,catchall:b}):o}case"array":{let u=n(s.element);return u===s.element?o:(0,Ht.clone)(o,{...s,element:u})}case"tuple":{let u=s.items,d=!1,p=[];for(let b of u){let y=n(b);y!==b&&(d=!0),p.push(y)}let m=s.rest;return s.rest&&(m=n(s.rest),m!==s.rest&&(d=!0)),d?(0,Ht.clone)(o,{...s,items:p,rest:m}):o}case"record":case"map":{let u=n(s.keyType),d=n(s.valueType);return u===s.keyType&&d===s.valueType?o:(0,Ht.clone)(o,{...s,keyType:u,valueType:d})}case"set":{let u=n(s.valueType);return u===s.valueType?o:(0,Ht.clone)(o,{...s,valueType:u})}case"union":{let u=s.options,d=!1,p=[];for(let m of u){let b=n(m);b!==m&&(d=!0),p.push(b)}return d?(0,Ht.clone)(o,{...s,options:p}):o}case"intersection":{let u=n(s.left),d=n(s.right);return u===s.left&&d===s.right?o:(0,Ht.clone)(o,{...s,left:u,right:d})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{let u=n(s.innerType);return u===s.innerType?o:(0,Ht.clone)(o,{...s,innerType:u})}case"pipe":{let u=n(s.in),d=n(s.out);return u===s.in&&d===s.out?o:(0,Ht.clone)(o,{...s,in:u,out:d})}case"function":{let u=n(s.input),d=n(s.output);return u===s.input&&d===s.output?o:(0,Ht.clone)(o,{...s,input:u,output:d})}case"lazy":{let u=s.getter,{_cachedInner:d,...p}=s;return(0,Ht.clone)(o,{...p,getter:()=>n(u())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return o;default:return o}}return n(e)}});var N_=P(Er=>{"use strict";var eC=Er&&Er.__createBinding||(Object.create?(function(e,t,r,i){i===void 0&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);(!n||("get"in n?!t.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}):(function(e,t,r,i){i===void 0&&(i=r),e[i]=t[r]})),tC=Er&&Er.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),nC=Er&&Er.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&eC(t,e,r);return tC(t,e),t};Object.defineProperty(Er,"__esModule",{value:!0});Er.deepPartial=aC;var rC=vl(),iC=nC(Br());function aC(e){return(0,rC.visit)(e,{object:t=>t.partial(),union:t=>{let r=t._zod.def;return r.discriminator===void 0?t:iC.union(r.options)}})}});var M_=P(dr=>{"use strict";var oC=dr&&dr.__createBinding||(Object.create?(function(e,t,r,i){i===void 0&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);(!n||("get"in n?!t.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}):(function(e,t,r,i){i===void 0&&(i=r),e[i]=t[r]})),sC=dr&&dr.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),cC=dr&&dr.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&oC(t,e,r);return sC(t,e),t};Object.defineProperty(dr,"__esModule",{value:!0});dr.input=fC;dr.output=pC;var R_=B(),C_=vl(),uC=cC(Br());function lC(e,t){if(!t?.length)return e;let r=e._zod.def;return(0,R_.clone)(e,(0,R_.mergeDefs)(r,{checks:[...r.checks??[],...t]}),{parent:!0})}function D_(e){return lC(e.out,e.checks)}function dC(e){return e.in._zod.traits.has("$ZodTransform")?D_(e):e.in}function fC(e){return(0,C_.visit)(e,{pipe:t=>dC(t._zod.def),default:(t,r)=>r?uC.optional(t._zod.def.innerType):t,catch:(t,r)=>r?t._zod.def.innerType:t})}function pC(e){return(0,C_.visit)(e,{pipe:t=>D_(t._zod.def),prefault:(t,r)=>r?t._zod.def.innerType:t})}});var U_=P(Nt=>{"use strict";var mC=Nt&&Nt.__createBinding||(Object.create?(function(e,t,r,i){i===void 0&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);(!n||("get"in n?!t.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}):(function(e,t,r,i){i===void 0&&(i=r),e[i]=t[r]})),gC=Nt&&Nt.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),x_=Nt&&Nt.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&mC(t,e,r);return gC(t,e),t};Object.defineProperty(Nt,"__esModule",{value:!0});Nt.string=_C;Nt.number=hC;Nt.boolean=vC;Nt.bigint=yC;Nt.date=bC;var Na=x_(Ot()),Ra=x_(Br());function _C(e){return Na._coercedString(Ra.ZodString,e)}function hC(e){return Na._coercedNumber(Ra.ZodNumber,e)}function vC(e){return Na._coercedBoolean(Ra.ZodBoolean,e)}function yC(e){return Na._coercedBigint(Ra.ZodBigInt,e)}function bC(e){return Na._coercedDate(Ra.ZodDate,e)}});var yl=P(F=>{"use strict";var L_=F&&F.__createBinding||(Object.create?(function(e,t,r,i){i===void 0&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);(!n||("get"in n?!t.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}):(function(e,t,r,i){i===void 0&&(i=r),e[i]=t[r]})),wC=F&&F.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),lc=F&&F.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&L_(t,e,r);return wC(t,e),t},Ca=F&&F.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&L_(t,e,r)};Object.defineProperty(F,"__esModule",{value:!0});F.coerce=F.iso=F.ZodISODuration=F.ZodISOTime=F.ZodISODate=F.ZodISODateTime=F.locales=F.output=F.input=F.deepPartial=F.fromJSONSchema=F.toJSONSchema=F.getDiscriminatedOption=F.ZodCompileUnsupportedError=F.ZodCompileAsyncError=F.compile=F.toZod=F.NEVER=F.util=F.TimePrecision=F.flattenError=F.formatError=F.prettifyError=F.treeifyError=F.regexes=F.clone=F.$brand=F.$input=F.$output=F.memoizer=F.config=F.registry=F.globalRegistry=F.core=void 0;F.core=lc(Ot());Ca(Br(),F);Ca(Hs(),F);Ca(sl(),F);Ca(cl(),F);Ca(P_(),F);var We=Ot();Object.defineProperty(F,"globalRegistry",{enumerable:!0,get:function(){return We.globalRegistry}});Object.defineProperty(F,"registry",{enumerable:!0,get:function(){return We.registry}});Object.defineProperty(F,"config",{enumerable:!0,get:function(){return We.config}});Object.defineProperty(F,"memoizer",{enumerable:!0,get:function(){return We.memoizer}});Object.defineProperty(F,"$output",{enumerable:!0,get:function(){return We.$output}});Object.defineProperty(F,"$input",{enumerable:!0,get:function(){return We.$input}});Object.defineProperty(F,"$brand",{enumerable:!0,get:function(){return We.$brand}});Object.defineProperty(F,"clone",{enumerable:!0,get:function(){return We.clone}});Object.defineProperty(F,"regexes",{enumerable:!0,get:function(){return We.regexes}});Object.defineProperty(F,"treeifyError",{enumerable:!0,get:function(){return We.treeifyError}});Object.defineProperty(F,"prettifyError",{enumerable:!0,get:function(){return We.prettifyError}});Object.defineProperty(F,"formatError",{enumerable:!0,get:function(){return We.formatError}});Object.defineProperty(F,"flattenError",{enumerable:!0,get:function(){return We.flattenError}});Object.defineProperty(F,"TimePrecision",{enumerable:!0,get:function(){return We.TimePrecision}});Object.defineProperty(F,"util",{enumerable:!0,get:function(){return We.util}});Object.defineProperty(F,"NEVER",{enumerable:!0,get:function(){return We.NEVER}});Object.defineProperty(F,"toZod",{enumerable:!0,get:function(){return We.toZod}});Object.defineProperty(F,"compile",{enumerable:!0,get:function(){return We.compile}});Object.defineProperty(F,"ZodCompileAsyncError",{enumerable:!0,get:function(){return We.ZodCompileAsyncError}});Object.defineProperty(F,"ZodCompileUnsupportedError",{enumerable:!0,get:function(){return We.ZodCompileUnsupportedError}});Object.defineProperty(F,"getDiscriminatedOption",{enumerable:!0,get:function(){return We.getDiscriminatedOption}});var SC=ka();Object.defineProperty(F,"toJSONSchema",{enumerable:!0,get:function(){return SC.toJSONSchema}});var $C=j_();Object.defineProperty(F,"fromJSONSchema",{enumerable:!0,get:function(){return $C.fromJSONSchema}});var OC=N_();Object.defineProperty(F,"deepPartial",{enumerable:!0,get:function(){return OC.deepPartial}});var Z_=M_();Object.defineProperty(F,"input",{enumerable:!0,get:function(){return Z_.input}});Object.defineProperty(F,"output",{enumerable:!0,get:function(){return Z_.output}});F.locales=lc(Ju());var dc=uc();Object.defineProperty(F,"ZodISODateTime",{enumerable:!0,get:function(){return dc.ZodISODateTime}});Object.defineProperty(F,"ZodISODate",{enumerable:!0,get:function(){return dc.ZodISODate}});Object.defineProperty(F,"ZodISOTime",{enumerable:!0,get:function(){return dc.ZodISOTime}});Object.defineProperty(F,"ZodISODuration",{enumerable:!0,get:function(){return dc.ZodISODuration}});F.iso=lc(uc());F.coerce=lc(U_())});var ct=P(_t=>{"use strict";var q_=_t&&_t.__createBinding||(Object.create?(function(e,t,r,i){i===void 0&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);(!n||("get"in n?!t.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}):(function(e,t,r,i){i===void 0&&(i=r),e[i]=t[r]})),IC=_t&&_t.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),EC=_t&&_t.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&q_(t,e,r);return IC(t,e),t},PC=_t&&_t.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&q_(t,e,r)};Object.defineProperty(_t,"__esModule",{value:!0});_t.default=_t.z=void 0;var F_=EC(yl());_t.z=F_;_t.default=F_;PC(yl(),_t)});var Et=P(Qi=>{"use strict";Object.defineProperty(Qi,"__esModule",{value:!0});Qi.apiMetadata=void 0;Qi.apiMetadataOf=TC;var zC=ct(),bl=class extends zC.z.core.$ZodRegistry{owners=new Map;add(t,r){if(r.id!==void 0){if(this.owners.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this.owners.set(r.id,t)}return super.add(t,r)}remove(t){let r=this.get(t)?.id;return r!==void 0&&this.owners.get(r)===t&&this.owners.delete(r),super.remove(t)}clear(){return this.owners.clear(),super.clear()}};Qi.apiMetadata=new bl;function TC(e){return Qi.apiMetadata.get(e)}});var Sl=P(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.FINANCIAL_RUNTIME_PATH_PREFIX=ut.FINANCIAL_RUNTIME_ROUTES=void 0;ut.isFinancialRuntimeRequestId=AC;ut.financialRuntimeRoutePath=jC;ut.financialRuntimeRoute=wl;ut.financialRuntimeBodyMismatch=kC;ut.nativeAgentFinancialRuntimeAction=NC;function AC(e){return typeof e=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)}var fc=["requestId","operationId","agentId","runtimeId","connectorKeyId","grantId","grantVersion","intentHash","issuedAtSec","identitySlip","connectorProof","leaseConnectorProof","signingInput"];ut.FINANCIAL_RUNTIME_ROUTES={"device-context":{fields:["requestId","agentId"],id:"requestId",clients:"auth",variants:[["requestId","agentId","runtimeId"]]},"device-handoff-create":{fields:["requestId","proposal","ceremony"],id:"requestId",clients:"auth",variants:[["requestId","proposal","requestPop"]]},"device-handoff-read":{fields:["requestId","proposal"],id:"requestId",clients:"both"},"device-handoff-proof":{fields:["requestId","proposal","childPop"],id:"requestId",clients:"auth"},"device-handoff-prepare":{fields:["requestId","proposal","ownerSession"],id:"requestId",clients:"web",variants:[["requestId","proposal","ownerSession","instrumentId"],["requestId","proposal","ownerSession","instrumentId","certificateExpiresAt"]]},"device-handoff-signatures":{fields:["requestId","proposal","ownerSession","certificate","delegation"],id:"requestId",clients:"web",variants:[["requestId","proposal","ownerSession","certificate"]]},"device-handoff-activate":{fields:["requestId","proposal","ownerSession"],id:"requestId",clients:"web"},"device-prepare":{fields:["ownerSession","requestId","associationId","runtimeId","publicJwk"],id:"requestId",clients:"web"},"device-activate":{fields:["ownerSession","requestId","certificate","delegation","childPop"],id:"requestId",clients:"web"},"device-renew-prepare":{fields:["ownerSession","agentId"],id:"agentId",clients:"web"},"device-renew-activate":{fields:["ownerSession","requestId","certificate","delegation"],id:"requestId",clients:"web"},lookup:{fields:["ownerSession","agentId"],id:"agentId",clients:"web"},pause:{fields:["ownerSession","agentId"],id:"agentId",clients:"web"},resume:{fields:["ownerSession","agentId"],id:"agentId",clients:"web"},"revoke-agent":{fields:["ownerSession","agentId"],id:"agentId",clients:"web"},"teardown-claim":{fields:["ownerSession","requestId"],id:"requestId",clients:"web"},"teardown-confirm":{fields:["ownerSession","requestId","teardownIds"],id:"requestId",clients:"web"},history:{fields:["ownerSession","agentId"],id:"agentId",clients:"web"},prepare:{fields:["ownerSession","requestId","associationId","custody"],id:"requestId",clients:"web",variants:[["ownerSession","requestId","associationId","custody","runtimeId"]]},"tempo-pay":{fields:["requestId","runtimeId","requestPop","request","intent"],variants:[["requestId","runtimeId","requestPop","request","intent","ownerApproval"],["requestId","runtimeId","requestPop","request","intent","purchaseKey"],["requestId","runtimeId","requestPop","request","intent","ownerApproval","purchaseKey"],["requestId","runtimeId","requestPop","request","intent","merchantUrl"],["requestId","runtimeId","requestPop","request","intent","ownerApproval","merchantUrl"],["requestId","runtimeId","requestPop","request","intent","purchaseKey","merchantUrl"],["requestId","runtimeId","requestPop","request","intent","ownerApproval","purchaseKey","merchantUrl"]],id:"requestId",clients:"auth"},"tempo-history":{fields:["requestId","runtimeId","requestPop","limit"],id:"requestId",clients:"auth"},"tempo-report":{fields:["requestId","runtimeId","requestPop","outcome","txHash"],id:"requestId",clients:"auth"},"tempo-attempt":{fields:["requestId","runtimeId","requestPop","attemptRequestId"],id:"requestId",clients:"auth"},"tempo-context":{nativeAgentOperation:"agent.financialRuntime.context",fields:["requestId","agentId","runtimeId"],id:"requestId",clients:"auth"},"atum-sign":{fields:["requestId","runtimeId","requestPop","request","intent"],variants:[["requestId","runtimeId","requestPop","request","intent","ownerApproval"]],id:"requestId",clients:"auth",nativeAgentOperation:"agent.financialRuntime.sign"},"atum-operation":{fields:["requestId","runtimeId","requestPop","operationRequestId"],id:"requestId",clients:"auth",nativeAgentOperation:"agent.financialRuntime.operation"},"atum-confirm":{fields:["requestId","runtimeId","requestPop","operationRequestId","transactionHash"],id:"requestId",clients:"auth",nativeAgentOperation:"agent.financialRuntime.confirm"},"atum-settle":{fields:["requestId","runtimeId","requestPop","settlement"],id:"requestId",clients:"auth",nativeAgentOperation:"agent.financialRuntime.settle"},"tempo-wallets":{fields:["ownerSession"],id:"correlation",clients:"web",variants:[["ownerSession","keysOnly"]]},"tempo-status":{fields:["ownerSession","agentId"],id:"agentId",clients:"web"},"tempo-disable":{fields:["ownerSession","agentId"],id:"agentId",clients:"web"},"tempo-retire-ungranted":{fields:["ownerSession","agentId"],id:"agentId",clients:"web"},"tempo-cleanup-confirm":{fields:["ownerSession","requestId","accessKeyAddress"],id:"requestId",clients:"web"},"tempo-limit-confirm":{fields:["ownerSession","requestId","agentId","txHash"],id:"requestId",clients:"web"},"tempo-limit-intent":{fields:["ownerSession","requestId","agentId","txHash","raw"],id:"requestId",clients:"web"},"tempo-enroll-prepare":{fields:["ownerSession","requestId","agentId","accessKeyAddress"],id:"requestId",clients:"web"},"tempo-enroll-finish":{fields:["ownerSession","requestId","agentId","accountAddress","accessKeyAddress","accessKeyPublicKey","turnkeyPrivateKeyId","tokenAddress","limitMicros","periodSeconds","expiresAtSeconds","authorizationTxHash"],id:"requestId",clients:"web"},"tempo-hosted-autonomous":{fields:[...fc,"terms","request"],variants:[[...fc,"terms","request","hostedTap"]],id:"requestId",clients:"none"},"tempo-hosted-context":{fields:["requestId","agentId","runtimeId"],variants:[["requestId","agentId","runtimeId","terms"]],id:"requestId",clients:"none"},"tempo-hosted-prepare":{fields:["requestId","operationId","agentId","runtimeId","terms","request"],id:"requestId",clients:"none"},"tempo-hosted-status":{fields:["requestId","agentId","runtimeId"],id:"requestId",clients:"none"},"tempo-hosted-approved":{fields:["requestId","operationId","agentId","runtimeId","terms","request","ownerApproval"],variants:[[...fc,"terms","request","ownerApproval","hostedTap"]],id:"requestId",clients:"none"},"card-hosted-context":{fields:["requestId","agentId","runtimeId"],id:"requestId",clients:"none"},"card-hosted-presence":{fields:[...fc],id:"requestId",clients:"none"},"card-hosted-status":{fields:["ownerSession","agentId"],id:"agentId",clients:"web"},"card-hosted-setup":{fields:["ownerSession","requestId","agentId","instrumentId","certificateExpiresAt"],variants:[["ownerSession","requestId","agentId","instrumentId","certificateExpiresAt","signerRequestId"]],id:"requestId",clients:"web"},"card-hosted-activate":{fields:["ownerSession","requestId","certificate"],id:"requestId",clients:"web"},"tempo-connector-autonomy":{fields:["ownerSession","requestId","agentId","statement"],id:"requestId",clients:"web"}};ut.FINANCIAL_RUNTIME_PATH_PREFIX="/v1/financial-runtime/";function jC(e){return ut.FINANCIAL_RUNTIME_PATH_PREFIX+e}function wl(e){return Object.hasOwn(ut.FINANCIAL_RUNTIME_ROUTES,e)?ut.FINANCIAL_RUNTIME_ROUTES[e]:null}function kC(e,t){let r=wl(e);if(!r)return`unknown financial-runtime action "${e}"`;if(!t||typeof t!="object"||Array.isArray(t))return`financial-runtime "${e}" body must be an object`;let i=Object.keys(t).sort(),n=[...r.fields].sort();if([n,...(r.variants??[]).map(c=>[...c].sort())].some(c=>c.join(",")===i.join(",")))return null;let o=n.filter(c=>!i.includes(c)),s=i.filter(c=>!n.includes(c));return`financial-runtime "${e}" body`+(o.length?` is missing ${o.join(", ")}`:"")+(o.length&&s.length?" and":"")+(s.length?` carries unexpected ${s.join(", ")}`:"")}function NC(e){if(!e.startsWith(ut.FINANCIAL_RUNTIME_PATH_PREFIX))return null;let t=e.slice(ut.FINANCIAL_RUNTIME_PATH_PREFIX.length);return wl(t)?.nativeAgentOperation?t:null}});var Pr=P(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.AGENT_AUTH=ht.CSRF_HEADER=ht.FAMILY_PREFIX=ht.PRODUCT_FAMILIES=void 0;ht.defineOperations=RC;ht.openApiPath=CC;ht.pathParams=DC;ht.operationPathMatchesFamily=MC;var V_=Sl();ht.PRODUCT_FAMILIES=["owner","agent"];ht.FAMILY_PREFIX={owner:"/owner/v1/",agent:"/agent/v1/",admin:"/admin/v1/",mcp:"/mcp",oauth:"/oauth/","well-known":"/.well-known/",public:"/"};ht.CSRF_HEADER="X-CSRF-Token";ht.AGENT_AUTH=["agent_signature","agent_token","oauth_token","app_token"];function RC(e){return e}function CC(e){return e.replace(/:([A-Za-z][A-Za-z0-9_]*)/g,"{$1}")}function DC(e){return[...e.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)].map(t=>t[1])}function MC(e){if(e.path.startsWith(ht.FAMILY_PREFIX[e.family]))return!0;let t=(0,V_.nativeAgentFinancialRuntimeAction)(e.path);return e.family==="agent"&&e.method==="POST"&&t!==null&&(0,V_.financialRuntimeRoute)(t)?.nativeAgentOperation===e.id}});var Rt=P(E=>{"use strict";Object.defineProperty(E,"__esModule",{value:!0});E.OwnerStatusWordSchema=E.OWNER_STATUS_WORDS=E.PaymentMoney=E.PaymentFacts=E.EVIDENCE_QUALITY=E.Attempt=E.ProviderEvidence=E.ATTEMPT_CLOSED_EVIDENCE=E.ATTEMPT_STATES=E.ATTEMPT_KINDS=E.PAYMENT_TERMINAL_STATES=E.PAYMENT_STATES=E.Operation=E.OwnerAction=E.WithdrawalTerms=E.TokenRef=E.OperationStep=E.OPERATION_TERMINAL_STATES=E.OPERATION_STEP_STATES=E.OPERATION_STATES=E.FINANCIAL_OPERATION_KINDS=E.OPERATION_STEP_ACTIONS=E.DEVICE_APPROVER_ACTIONS=E.OPERATION_KINDS=E.Readiness=E.Continuation=E.RetryOrExpiry=E.ACTORS=E.CapabilitySchema=E.CAPABILITIES=E.ReadinessLevelSchema=E.READINESS_LADDER=E.PageQuery=E.Page=E.Surface=E.SURFACES=E.Rail=E.RAILS=E.Amount=E.Asset=E.ASSETS=E.Micros=E.Timestamp=E.Id=void 0;E.ownerStatusWord=UC;var L=ct(),se=Et();E.Id=L.z.string().min(1).max(128).regex(/^[A-Za-z0-9][A-Za-z0-9._:-]*$/).clone().register(se.apiMetadata,{id:"Id",description:"An opaque identifier: 1\u2013128 ASCII characters, starting alphanumeric, then alphanumeric or . _ : -"});E.Timestamp=L.z.iso.datetime({offset:!1}).clone().register(se.apiMetadata,{id:"Timestamp",description:"An RFC 3339 timestamp in UTC, with the `Z` designator."});E.Micros=L.z.string().regex(/^(0|[1-9][0-9]{0,24})$/).clone().register(se.apiMetadata,{id:"Micros",description:"Integer micros (10\u207B\u2076 of one unit of the asset) as a decimal string."});E.ASSETS=["USD","OUSD","USDC.e"];E.Asset=L.z.enum(E.ASSETS).clone().register(se.apiMetadata,{id:"Asset",description:"USD is the card rail; OUSD and USDC.e are Tempo stablecoins."});E.Amount=L.z.object({micros:E.Micros,asset:E.Asset}).clone().register(se.apiMetadata,{id:"Amount",description:"An exact amount of one asset."});E.RAILS=["tempo","card"];E.Rail=L.z.enum(E.RAILS).clone().register(se.apiMetadata,{id:"Rail",description:'How money moves. A field on payments, approvals and grants, never a path. tempo = Tempo MPP from the owner wallet (owner-facing copy says "wallet"); card = a VIC network credential minted from the owner\u2019s enrolled card.'});E.SURFACES=["laptop","hosted"];E.Surface=L.z.enum(E.SURFACES).clone().register(se.apiMetadata,{id:"Surface",description:"Where the agent runs. laptop = the Visa CLI and its stdio MCP on a computer the owner controls; hosted = a remote connector (OAuth) or REST app."});E.Page=L.z.object({next_cursor:L.z.string().nullable()}).clone().register(se.apiMetadata,{id:"Page",description:"Cursor pagination. `next_cursor` is null on the last page."});E.PageQuery=L.z.object({cursor:L.z.string().optional(),limit:L.z.coerce.number().int().min(1).max(100).optional()});E.READINESS_LADDER=["supported","configured","authorized","funded","ready"];E.ReadinessLevelSchema=L.z.enum(E.READINESS_LADDER).clone().register(se.apiMetadata,{id:"ReadinessLevel",description:"supported: this deployment and host can offer it. configured: its prerequisites exist. authorized: the owner granted it to this agent. funded: money is there to use it. ready: this exact operation can proceed. A rung that does not apply to a capability (identity has no funding) is passed through."});E.CAPABILITIES=["identity","tempo","card","tap","hosted_connection"];E.CapabilitySchema=L.z.enum(E.CAPABILITIES).clone().register(se.apiMetadata,{id:"Capability"});E.ACTORS=["agent","owner","server","operator"];E.RetryOrExpiry=L.z.discriminatedUnion("kind",[L.z.object({kind:L.z.literal("retry"),after_seconds:L.z.number().int().min(0),until:E.Timestamp.nullable()}),L.z.object({kind:L.z.literal("expires"),at:E.Timestamp}),L.z.object({kind:L.z.literal("none")})]).clone().register(se.apiMetadata,{id:"RetryOrExpiry",description:"retry: the actor may repeat the same request (same identifiers) after the delay, until the deadline. expires: the step lapses at `at`. none: no timing rule (for example a terminal state)."});E.Continuation=L.z.object({actor:L.z.enum(E.ACTORS),next_action:L.z.string().regex(/^[a-z][a-z0-9_]*$/).clone().register(se.apiMetadata,{description:"A stable machine code for the next step, for example `approve_payment`."}),message:L.z.string().clone().register(se.apiMetadata,{description:"One plain sentence for the actor."}),url:L.z.url().nullable().clone().register(se.apiMetadata,{description:"Where the owner acts, when the actor is the owner."}),retry_or_expiry:E.RetryOrExpiry}).clone().register(se.apiMetadata,{id:"Continuation",description:"What happens next and who does it. Every non-terminal answer carries one; the server decides it and clients only display it."});E.Readiness=L.z.discriminatedUnion("status",[L.z.object({status:L.z.literal("ready"),capability:E.CapabilitySchema,reached:L.z.literal("ready"),continuation:L.z.null()}),L.z.object({status:L.z.literal("incomplete"),capability:E.CapabilitySchema,reached:L.z.enum(["supported","configured","authorized","funded"]).clone().register(se.apiMetadata,{description:"The highest rung reached so far."}),continuation:E.Continuation.clone().register(se.apiMetadata,{description:"Required: who climbs the next rung, and how."})}),L.z.object({status:L.z.literal("unsupported"),capability:E.CapabilitySchema,reached:L.z.null(),continuation:L.z.null()})]).clone().register(se.apiMetadata,{id:"Readiness",description:"ready: nothing left to do. incomplete: a continuation is always given. unsupported: not offered on this deployment or host."});E.OPERATION_KINDS=["wallet_enable","setup","renewal","revocation_teardown","account_closure","account_recovery","provider_cleanup","withdrawal","telemetry_deletion","chain_limit"];E.DEVICE_APPROVER_ACTIONS=["create_device_approver_guard","create_device_approver_user","create_tempo_signer_guard","create_tempo_signer_user","create_device_approver_policy","update_device_approver_policy"];E.OPERATION_STEP_ACTIONS=["revoke_wallet_key","withdraw_tap_entry","remove_custody_user","remove_device_approver","end_card_mandate","remove_card_instrument","end_connector_tokens","delete_provider_data","delete_telemetry","sign_withdrawal","broadcast_withdrawal","sign_key_authorization","sign_tap_enrollment","sign_hosted_identity","sign_chain_limit","sign_renewal","create_owner_wallet","create_owner_identity_root",...E.DEVICE_APPROVER_ACTIONS];E.FINANCIAL_OPERATION_KINDS=["withdrawal"];E.OPERATION_STATES=["pending","running","needs_owner_action","succeeded","failed","cancelled"];E.OPERATION_STEP_STATES=["pending","running","done","failed","skipped"];E.OPERATION_TERMINAL_STATES=["succeeded","failed","cancelled"];E.OperationStep=L.z.object({action:L.z.enum(E.OPERATION_STEP_ACTIONS),state:L.z.enum(E.OPERATION_STEP_STATES),effect:L.z.enum(["removal","owner_signed"]).clone().register(se.apiMetadata,{description:"removal: revoke or delete only. owner_signed: needs the owner\u2019s signature."}),executor:L.z.enum(["server","owner"]).clone().register(se.apiMetadata,{description:"server: a removal-only step the server finishes under a narrow delegated permission (revoke, delete). owner: a step that needs the owner\u2019s own signature (P3)."}),external_refs:L.z.array(L.z.object({system:L.z.string(),ref:L.z.string()})).clone().register(se.apiMetadata,{description:"Transaction hashes and provider ids."}),completed_at:E.Timestamp.nullable(),evidence:L.z.string().nullable().clone().register(se.apiMetadata,{description:"Verified completion evidence; telemetry alone never counts."})}).clone().register(se.apiMetadata,{id:"OperationStep"});E.TokenRef=L.z.discriminatedUnion("kind",[L.z.object({kind:L.z.literal("supported"),asset:L.z.enum(["OUSD","USDC.e"])}),L.z.object({kind:L.z.literal("other"),contract_address:L.z.string().regex(/^0x[0-9a-fA-F]{40}$/).clone().register(se.apiMetadata,{description:"Any other token the wallet holds (unsupported or sent by mistake)."})})]).clone().register(se.apiMetadata,{id:"TokenRef"});E.WithdrawalTerms=L.z.object({chain_id:L.z.number().int(),to_address:L.z.string().regex(/^0x[0-9a-fA-F]{40}$/),token:E.TokenRef,amount_base_units:L.z.string().regex(/^(0|[1-9][0-9]{0,77})$/).clone().register(se.apiMetadata,{description:"Exact amount in the token\u2019s own base units, so sub-micro dust is representable."})}).clone().register(se.apiMetadata,{id:"WithdrawalTerms",description:"The immutable terms of one withdrawal, fixed when the operation is recorded (before any signature or broadcast)."});E.OwnerAction=L.z.object({action:L.z.enum(["sign_withdrawal","sign_key_authorization","sign_tap_enrollment","sign_hosted_identity","sign_chain_limit","sign_renewal","create_owner_wallet","create_owner_identity_root","revoke_wallet_key","remove_custody_user","remove_device_approver",...E.DEVICE_APPROVER_ACTIONS,"revoke_wallet_key","remove_custody_user","remove_device_approver"]),challenge_id:E.Id.clone().register(se.apiMetadata,{description:"Fetch or renew it with owner.operations.challenge."}),expires_at:E.Timestamp}).clone().register(se.apiMetadata,{id:"OwnerAction",description:"The owner signature an operation is waiting for."});E.Operation=L.z.object({id:E.Id,kind:L.z.enum(E.OPERATION_KINDS),state:L.z.enum(E.OPERATION_STATES),steps:L.z.array(E.OperationStep),withdrawal:E.WithdrawalTerms.nullable().clone().register(se.apiMetadata,{description:"Set for kind withdrawal: its immutable terms."}),owner_action:E.OwnerAction.nullable().clone().register(se.apiMetadata,{description:"Set while state is needs_owner_action."}),needs_attention:L.z.boolean().clone().register(se.apiMetadata,{description:"Stuck, overdue or unsafe: shown to the owner and in the operator view."}),created_at:E.Timestamp,updated_at:E.Timestamp,continuation:E.Continuation.nullable()}).clone().register(se.apiMetadata,{id:"Operation",description:"Durable multi-step work. Recorded before any external effect, so status and recovery follow the owner across browsers and devices. Spending shutdown never stops withdrawals, export, reconciliation or cleanup."});E.PAYMENT_STATES=["proposed","awaiting_owner","authorized","submitted","unknown","issued","settled","released","refused","declined","expired","failed"];E.PAYMENT_TERMINAL_STATES=["issued","settled","released","refused","declined","expired","failed"];E.ATTEMPT_KINDS=["quote","approval","execution"];E.ATTEMPT_STATES=["open","approved","declined","admitted","credential_issued","signed","submitted","settled","superseded","expired","refused","failed","unknown"];E.ATTEMPT_CLOSED_EVIDENCE=["expired_unsigned","expired_on_chain","provider_void","declined","refused_before_signing","superseded_quote","settled"];E.ProviderEvidence=L.z.object({provider:L.z.literal("turnkey"),organization_id:L.z.string(),activity_id:L.z.string(),fingerprint:L.z.string(),status:L.z.string().clone().register(se.apiMetadata,{description:"The provider\u2019s own activity status, as last read by the server."}),observed_at:E.Timestamp}).clone().register(se.apiMetadata,{id:"ProviderEvidence",description:"The durable locator of the provider signing activity for one execution attempt. Recorded when the activity is created and re-read, never trusted from the client."});E.Attempt=L.z.object({id:E.Id,kind:L.z.enum(E.ATTEMPT_KINDS),state:L.z.enum(E.ATTEMPT_STATES),terms:L.z.object({amount:E.Amount,funding_max:E.Amount.clone().register(se.apiMetadata,{description:"The most of the funding asset it may consume (a swap\u2019s maxIn)."}),fee_ceiling:E.Amount,merchant:L.z.string(),expires_at:E.Timestamp.clone().register(se.apiMetadata,{description:"Quote validity or the charge\u2019s valid-before."})}).clone().register(se.apiMetadata,{description:"The exact terms this attempt binds (its terms_hash). Changed terms need fresh consent."}),terms_hash:L.z.string(),wire_request_id:L.z.uuid().nullable().clone().register(se.apiMetadata,{description:"Execution attempts: the client-chosen execution id (unique), used as the PoP nonce."}),signing_hash:L.z.string().nullable().clone().register(se.apiMetadata,{description:"The chain signing payload hash: one charge, one attempt (unique)."}),network_ref:L.z.string().nullable().clone().register(se.apiMetadata,{description:"Transaction hash once known."}),provider_evidence:E.ProviderEvidence.nullable(),admission_expires_at:E.Timestamp.nullable().clone().register(se.apiMetadata,{description:"A signed admission is honoured by SlipGate for at most 60 seconds after issue."}),closed_evidence:L.z.enum(E.ATTEMPT_CLOSED_EVIDENCE).nullable(),created_at:E.Timestamp}).clone().register(se.apiMetadata,{id:"Attempt",description:"One quote, approval or execution of a purchase. A replacement quote stays on the same purchase. Another execution requires the previous one closed with evidence that it can no longer execute. An explicit decline is terminal."});E.EVIDENCE_QUALITY=["proven","conservative_max"];E.PaymentFacts=L.z.object({credential_issued_at:E.Timestamp.nullable(),submission_reported_at:E.Timestamp.nullable(),funds_settled_at:E.Timestamp.nullable(),settlement:L.z.object({kind:L.z.literal("merchant_held"),network_ref:L.z.string().regex(/^0x[0-9a-f]{64}$/)}).strict().nullable().clone().register(se.apiMetadata,{description:"Independently reconciled receive-policy hold: the recorded debit left the wallet but did not reach the merchant. Recovery eligibility depends on the merchant settings; this is never an unpaid retry or a claim authorization. Null means no retained proof of this cause, not delivery."}),delivery:L.z.enum(["none","delivered","unavailable"]).clone().register(se.apiMetadata,{description:'Merchant delivery, separate from money. `unavailable` is "paid, result unavailable": Visa stores no request or result content, so recovery runs between the agent and the merchant.'})}).clone().register(se.apiMetadata,{id:"PaymentFacts"});E.PaymentMoney=L.z.object({authorized:E.Amount.nullable().clone().register(se.apiMetadata,{description:"What the owner (or their grant) authorized."}),may_still_owe:E.Amount.nullable().clone().register(se.apiMetadata,{description:"Reserved exposure still unresolved."}),moved:E.Amount.nullable().clone().register(se.apiMetadata,{description:"What actually left the funding source, where known."}),received:E.Amount.nullable().clone().register(se.apiMetadata,{description:"Refunds or reversals received back."}),fees:E.Amount.nullable(),evidence_quality:L.z.enum(E.EVIDENCE_QUALITY).clone().register(se.apiMetadata,{description:"proven, or a conservative maximum (as with a swap\u2019s maxIn)."})}).clone().register(se.apiMetadata,{id:"PaymentMoney"});E.OWNER_STATUS_WORDS=["Pending","Settling","Completed","Card issued","Cancelled","Failed","Needs attention"];E.OwnerStatusWordSchema=L.z.enum(E.OWNER_STATUS_WORDS).clone().register(se.apiMetadata,{id:"OwnerStatusWord",description:"The only words the owner sees for a payment."});var xC={proposed:"Pending",awaiting_owner:"Pending",authorized:"Pending",issued:"Card issued",submitted:"Settling",settled:"Completed",released:"Cancelled",refused:"Cancelled",declined:"Cancelled",expired:"Cancelled",failed:"Failed",unknown:"Needs attention"};function UC(e){return e.overdue_operation||e.state==="settled"&&e.delivery==="unavailable"?"Needs attention":xC[e.state]}});var pc=P(Ye=>{"use strict";Object.defineProperty(Ye,"__esModule",{value:!0});Ye.ALWAYS_POSSIBLE=Ye.SPENDING_OFF_REFUSALS=Ye.Problem=Ye.ERROR_STAGES=Ye.WIRE_ERROR_FAMILIES=Ye.ERROR_FAMILY_NAMES=Ye.ERROR_FAMILIES=void 0;var zr=ct(),$l=Et(),LC=Rt();Ye.ERROR_FAMILIES={update_required:{kind:"caller",status:426,retryable:!1,message:"This Visa CLI is older than the server accepts. Update the CLI: npm install -g @visa/cli@rc",fix:"Update Visa CLI, restart the agent session, then retry the same request."},setup_required:{kind:"caller",status:401,retryable:!1,message:"This agent is not connected, signed in or set up here.",fix:"Run visa connect (shell) or call the connect tool (MCP) and have the owner finish the browser step; both resume where they left off. Then retry the original request."},owner_approval_required:{kind:"platform",status:403,retryable:!0,message:"The owner must approve this first.",fix:"Show the owner the approval link in the continuation and wait. Then retry the same request with the same identifiers; do not change it or start a new one."},owner_declined:{kind:"platform",status:403,retryable:!1,message:"The owner declined this.",fix:"Stop. Do not retry it automatically. Tell the owner; only if they ask again, start a new request, which asks them again."},agent_inactive:{kind:"platform",status:403,retryable:!1,message:"This agent cannot act: it is paused, revoked or its keys were replaced.",fix:"Do not retry. Ask the owner to check the agent in the Visa Console: they resume a paused agent, or connect a new one."},grant_required:{kind:"platform",status:403,retryable:!1,message:"This agent has no current spending approval.",fix:"Nothing was charged. Ask the owner to approve or renew the agent\u2019s limits in the Visa Console, then retry the same payment once."},limit_reached:{kind:"platform",status:403,retryable:!1,message:"This payment is over a spending limit.",fix:"Nothing was charged. Try a smaller amount or later, or ask the owner to raise the limit. Do not loop, and do not switch agents or payment methods to get around it."},blocked:{kind:"platform",status:403,retryable:!1,message:"Visa refused this request.",fix:"Tell the owner what was refused. Do not retry, and do not switch agents, payment methods or merchants to get around it."},merchant_unsupported:{kind:"caller",status:422,retryable:!1,message:"This merchant cannot be paid this way.",fix:"Nothing was charged. Do not retry it unchanged: pay a merchant that supports this payment, or tell the human."},invalid_request:{kind:"caller",status:400,retryable:!1,message:"Some details in this request were not valid.",fix:"Correct the request and try again. To check an earlier purchase, use its original reference."},not_found:{kind:"caller",status:404,retryable:!1,message:"Visa could not find that for this agent.",fix:"Check the reference and the selected agent. Do not create a replacement because a read found nothing."},expired:{kind:"caller",status:410,retryable:!1,message:"That request expired before it was completed.",fix:"Check the original request\u2019s outcome first, then start a fresh one."},conflict:{kind:"caller",status:409,retryable:!0,message:"An existing request conflicts with this one.",fix:"Check the original request by its reference; if it is still in progress, wait and retry the same request. Do not start a replacement."},outcome_unknown:{kind:"caller",status:202,retryable:!0,message:"The result of this request is not known yet.",fix:"Do not pay again or create a replacement. Read the original purchase, or repeat the request with the same identifiers, until its outcome is known."},unavailable:{kind:"platform",status:503,retryable:!0,message:"Visa, or a service it depends on, did not answer.",fix:"Check whether the original request went through before trying another payment, and retry later. Do not switch agents or payment methods."},not_enabled:{kind:"platform",status:403,retryable:!1,message:"This feature is not available right now.",fix:"Tell Visa support which feature you tried to use. Retrying or signing in again will not turn it on."},local_keystore:{kind:"platform",status:0,retryable:!0,message:"This computer\u2019s key store could not be used, so nothing was signed or sent.",fix:"Ask the owner to fix the key store on this computer (unlock it, restore access or sync the clock), then retry once."},rate_limited:{kind:"caller",status:429,retryable:!0,message:"Too many requests from this caller right now.",fix:"Wait for the Retry-After time (also in retry_after_seconds), then repeat the same request with the same identifiers. Do not switch agents to get around it."},internal_error:{kind:"platform",status:500,retryable:!1,message:"Visa could not complete this request.",fix:"Tell a human, with the request reference. Do not retry a payment automatically."}};Ye.ERROR_FAMILY_NAMES=Object.keys(Ye.ERROR_FAMILIES);Ye.WIRE_ERROR_FAMILIES=Ye.ERROR_FAMILY_NAMES.filter(e=>Ye.ERROR_FAMILIES[e].status!==0);Ye.ERROR_STAGES=["edge","identity","grant","controls","policy","approval","execution","settlement"];Ye.Problem=zr.z.object({code:zr.z.enum(Ye.ERROR_FAMILY_NAMES),detail:zr.z.string().clone().register($l.apiMetadata,{description:"The specific check that refused. Diagnostic only."}),stage:zr.z.enum(Ye.ERROR_STAGES),message:zr.z.string(),fix:zr.z.string(),retryable:zr.z.boolean(),request_id:zr.z.string(),retry_after_seconds:zr.z.number().int().min(0).nullable().clone().register($l.apiMetadata,{description:"Set with rate_limited (and mirrored in the Retry-After header)."}),continuation:LC.Continuation.nullable()}).clone().register($l.apiMetadata,{id:"Problem",description:"The one refusal shape. Branch on `code` only. Money refusals state whether anything was charged in `message`."});Ye.SPENDING_OFF_REFUSALS={operator_kill_switch:{code:"not_enabled",detail:"spending_admission_off"},owner_stop_all:{code:"blocked",detail:"owner_spending_stopped"}};Ye.ALWAYS_POSSIBLE=["invalid_request","rate_limited","unavailable","internal_error"]});var xa=P(W=>{"use strict";Object.defineProperty(W,"__esModule",{value:!0});W.NATIVE_FINANCIAL_OPERATIONS=W.NativeFinancialRefusal=W.NativeAtumSettlementResult=W.NativeAtumSignResult=W.NativeAtumApprovalDetail=W.NativeAtumOperationResult=W.NativeAtumOperation=W.NativeTempoContext=W.NativeAtumSettleInput=W.NativeAtumSettlement=W.NativeAtumConfirmInput=W.NativeAtumOperationInput=W.NativeAtumSignPrivateInput=W.NativeAtumSignInput=W.NativeTempoContextInput=W.NativeAtumOwnerTerms=W.NativeAtumSignRequest=W.NativeAtumSigningOperation=W.NativeAtumDeployment=W.NativeAtumFundingPlan=W.NativeAtumFundingTerms=void 0;var v=ct(),Ze=Et(),B_=Sl(),ZC=Pr(),qC=pc(),fr=v.z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/),Fe=v.z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i),Ve=v.z.string().regex(/^0x[0-9a-fA-F]{40}$/),Tr=v.z.string().regex(/^0x[0-9a-fA-F]*$/),Ma=v.z.string().regex(/^0x[0-9a-fA-F]{64}$/),Xt=v.z.string().regex(/^(0|[1-9][0-9]{0,15})$/),bi=v.z.json().register(Ze.apiMetadata,{id:"NativeFinancialJson",description:"Original JSON protocol value. No reconstruction, HTTP body capture, logging or telemetry permission."}),mc=v.z.record(v.z.string(),bi),Ol=v.z.strictObject({to:Ve,data:Tr,value:v.z.literal("0x0")}),FC=v.z.strictObject({network:v.z.string(),token:Ve,recipient:Ve,amount:Xt}),X_=v.z.strictObject({url:v.z.string(),method:v.z.enum(["GET","POST"]),bodySha256:v.z.string().regex(/^[0-9a-f]{64}$/).nullable()}),VC=v.z.strictObject({token:Ve,maxAmountInMicros:Xt});W.NativeAtumFundingTerms=v.z.strictObject({v:v.z.literal(1),agentId:Fe,runtimeId:Fe,economicIntentId:v.z.string(),ownerAccount:Ve,fundingAccount:Ve,sourceNetwork:v.z.literal("eip155:4217"),sourceToken:v.z.literal("0x20c000000000000000000000b9537d11c60e8b50"),sourceCapMicros:Xt,approvalFeeCapMicros:Xt,ownerTransferFeeCapMicros:Xt,maxOwnerDebitMicros:Xt,ownerSwap:VC.optional(),merchant:X_,destination:FC}).register(Ze.apiMetadata,{id:"NativeAtumFundingTerms"});W.NativeAtumFundingPlan=v.z.strictObject({terms:W.NativeAtumFundingTerms,termsHash:v.z.string().regex(/^[0-9a-f]{64}$/),fundedAmountMicros:Xt,ownerDebitCapMicros:Xt,ownerTransfer:Ol,ownerCalls:v.z.array(Ol),permit2Approval:Ol}).register(Ze.apiMetadata,{id:"NativeAtumFundingPlan"});W.NativeAtumDeployment=v.z.strictObject({chainId:v.z.literal(4217),escrow:Ve,reserver:Ve,releaser:Ve}).register(Ze.apiMetadata,{id:"NativeAtumDeployment"});var Da=v.z.strictObject({chainId:v.z.number(),maxPriorityFeePerGas:Tr,maxFeePerGas:Tr,gas:Tr,calls:v.z.array(v.z.strictObject({to:Ve.nullable(),value:Tr,data:Tr})),accessList:v.z.array(bi),nonceKey:Tr,nonce:Tr,validBefore:v.z.number().nullable(),validAfter:v.z.number().nullable(),feeToken:Ve.nullable(),feePayer:v.z.boolean(),authorizationList:v.z.array(bi),keyAuthorization:bi}),Q_=v.z.strictObject({witness:v.z.strictObject({depositId:Ma,quoteHash:Ma,depositRequestHash:Ma,destinationHash:Ma,depositor:Ve,token:Ve,amount:Xt,feeAmount:Xt,reserver:Ve,releaser:Ve,settler:Ve}),signature:Tr});W.NativeAtumSigningOperation=v.z.discriminatedUnion("kind",[v.z.strictObject({kind:v.z.literal("prefund"),transaction:Da}),v.z.strictObject({kind:v.z.literal("permit2_approval"),transaction:Da}),v.z.strictObject({kind:v.z.literal("permit2_revoke"),transaction:Da}),v.z.strictObject({kind:v.z.literal("deposit_witness"),deadline:v.z.number(),escrow:Ve,reserver:Ve,releaser:Ve}),v.z.strictObject({kind:v.z.literal("refund"),transaction:Da,amountMicros:Xt}),v.z.strictObject({kind:v.z.literal("escrow_refund"),transaction:Da,authorization:Q_})]).register(Ze.apiMetadata,{id:"NativeAtumSigningOperation"});W.NativeAtumSignRequest=v.z.strictObject({deployment:W.NativeAtumDeployment,plan:W.NativeAtumFundingPlan,operation:W.NativeAtumSigningOperation,keyRef:v.z.strictObject({subOrganizationId:v.z.string(),accessKeyAddress:Ve})}).register(Ze.apiMetadata,{id:"NativeAtumSignRequest"});W.NativeAtumOwnerTerms=v.z.strictObject({v:v.z.literal(1),plan:W.NativeAtumFundingPlan,prefundSigningHash:v.z.string().regex(/^[A-Za-z0-9_-]{43}$/),grantId:Fe,grantVersion:v.z.number().int().positive()}).register(Ze.apiMetadata,{id:"NativeAtumOwnerTerms"});var gc=v.z.string().min(1).max(65536);W.NativeTempoContextInput=v.z.strictObject({requestId:Fe,agentId:Fe,runtimeId:Fe}).register(Ze.apiMetadata,{id:"NativeTempoContextInput"});var eh={requestId:fr,runtimeId:fr,requestPop:gc,request:W.NativeAtumSignRequest,intent:bi.clone().register(Ze.apiMetadata,{description:"The original signing context, canonical JSON at most 4096 bytes. Transient replay at this existing boundary; not a capture or telemetry request."})};W.NativeAtumSignInput=v.z.strictObject({...eh,approvalOperationId:Fe.clone().register(Ze.apiMetadata,{description:"Original public approval lookup reference. Never signed owner authorization."}).optional()}).register(Ze.apiMetadata,{id:"NativeAtumSignInput"});W.NativeAtumSignPrivateInput=v.z.strictObject({...eh,ownerApproval:v.z.strictObject({statement:gc,terms:W.NativeAtumOwnerTerms}).optional()}).register(Ze.apiMetadata,{id:"NativeAtumSignPrivateInput"});W.NativeAtumOperationInput=v.z.strictObject({requestId:fr,runtimeId:fr,requestPop:gc,operationRequestId:fr}).register(Ze.apiMetadata,{id:"NativeAtumOperationInput"});W.NativeAtumConfirmInput=W.NativeAtumOperationInput.extend({transactionHash:Ma}).register(Ze.apiMetadata,{id:"NativeAtumConfirmInput"});var BC=v.z.object({version:v.z.string(),request_id:v.z.string(),source:v.z.strictObject({asset_identifier:v.z.string(),account:v.z.string()}),destination:v.z.array(v.z.strictObject({asset_identifier:v.z.string(),account:v.z.string()})),fulfillment_amount:v.z.string(),max_source_amount:v.z.string(),quote_deadline:v.z.string(),fulfillment_deadline:v.z.string(),escrow_contract_address:v.z.string(),fulfillment_proxy:v.z.string(),quote_selector:v.z.string(),fulfillment_verifier:v.z.strictObject({account:v.z.string(),endpoint:v.z.string()}),sender_auth:v.z.strictObject({message_scheme:v.z.string(),signed_messages:v.z.array(v.z.strictObject({message:v.z.string(),message_prehash:v.z.string(),signature:v.z.string()}))}),executor:v.z.strictObject({deposit:v.z.literal("settler"),reserve:v.z.literal("settler"),fulfill:v.z.literal("originator")}),presentation:mc.optional()}).catchall(bi),G_=v.z.strictObject({scheme:v.z.string(),network:v.z.string(),asset:v.z.string(),amount:v.z.string(),payTo:v.z.string(),maxTimeoutSeconds:v.z.number(),extra:mc}),J_=v.z.strictObject({request:BC,paymentRequired:v.z.strictObject({x402Version:v.z.number(),error:v.z.string().optional(),resource:v.z.strictObject({url:v.z.string(),description:v.z.string().optional(),mimeType:v.z.string().optional(),serviceName:v.z.string().optional(),tags:v.z.array(v.z.string()).optional(),iconUrl:v.z.string().optional()}),accepts:v.z.array(G_),extensions:mc.optional()}),requirements:G_,merchantRequest:X_}),GC=v.z.object({version:v.z.string(),scheme:v.z.literal("EIP-3009"),authorization:v.z.strictObject({message:v.z.string(),message_prehash:v.z.string().optional(),signature:v.z.string(),payload:mc.optional()}),fulfillment_quote_json:v.z.string(),evidence:v.z.strictObject({transaction_id:v.z.string(),log_index:v.z.number()})}).catchall(bi);W.NativeAtumSettlement=v.z.union([v.z.strictObject({operationRequestId:fr,abort:v.z.literal(!0)}),v.z.strictObject({operationRequestId:fr,prepared:J_,sourceTransactionHash:v.z.string(),refundAuthorization:Q_}),v.z.strictObject({operationRequestId:fr,prepared:J_,sourceTransactionHash:v.z.string(),fulfillment:GC,destinationTransactionHash:v.z.string()})]).register(Ze.apiMetadata,{id:"NativeAtumSettlement"});W.NativeAtumSettleInput=v.z.strictObject({requestId:fr,runtimeId:fr,requestPop:gc,settlement:W.NativeAtumSettlement}).register(Ze.apiMetadata,{id:"NativeAtumSettleInput"});var W_={v:v.z.literal(1),available:v.z.boolean(),swapAvailable:v.z.boolean()};W.NativeTempoContext=v.z.union([v.z.strictObject({...W_,enrolled:v.z.literal(!1)}),v.z.strictObject({...W_,enrolled:v.z.literal(!0),paymentMode:v.z.strictObject({mode:v.z.string(),reason:v.z.string(),reasonText:v.z.string()}).nullable(),budget:v.z.strictObject({remainingMicros:v.z.string(),perTransactionMicros:v.z.string(),expiresAt:v.z.string()}).nullable(),accountAddress:Ve,accessKeyAddress:Ve,accessKeyPublicKey:v.z.string(),subOrganizationId:v.z.string(),tokenAddress:Ve,limitMicros:v.z.string().nullable(),periodSeconds:v.z.number(),expiresAtSeconds:v.z.number(),atum:v.z.strictObject({deployment:W.NativeAtumDeployment,forwardAvailable:v.z.boolean()}).optional()})]).register(Ze.apiMetadata,{id:"NativeTempoContext"});var Y_=v.z.strictObject({blockNumber:v.z.string().nullable(),blockHash:v.z.string().nullable(),timestamp:v.z.number()}),JC=W.NativeAtumFundingTerms.pick({economicIntentId:!0,ownerAccount:!0,fundingAccount:!0,sourceCapMicros:!0,approvalFeeCapMicros:!0,ownerTransferFeeCapMicros:!0,ownerSwap:!0,destination:!0}).extend({planTermsHash:v.z.string(),fundedAmountMicros:v.z.string(),ownerDebitCapMicros:v.z.string()});W.NativeAtumOperation=v.z.strictObject({v:v.z.literal(1),status:v.z.enum(["admitted","signed","refused","indeterminate","confirmed","expired","not_found","failed"]),operationId:Fe,requestId:Fe,requestHash:v.z.string(),purchaseId:Fe,signingHash:v.z.string(),kind:v.z.enum(["prefund","permit2_approval","permit2_revoke","deposit_witness","refund","escrow_refund"]),attempt:v.z.number().int().positive(),reservedMicros:v.z.string(),destination:v.z.strictObject({network:v.z.string(),token:v.z.string(),recipient:v.z.string(),amountBaseUnits:v.z.string()}),signature:v.z.string().optional(),transactionHash:v.z.string().optional(),activity:v.z.strictObject({organizationId:v.z.string(),activityId:v.z.string(),fingerprint:v.z.string(),validBefore:v.z.string(),status:v.z.string()}).optional(),resumable:v.z.boolean().optional(),nonLandingEvidence:v.z.strictObject({kind:v.z.string(),reference:v.z.string().nullable()}).optional(),receipt:v.z.strictObject({blockNumber:v.z.string().nullable().optional(),blockHash:v.z.string().nullable().optional(),sender:v.z.string().nullable().optional(),reverted:v.z.boolean().nullable().optional(),delivered:v.z.boolean().nullable().optional(),feeMicros:v.z.string().nullable().optional(),status:v.z.literal("expired").optional(),anchor:Y_.optional(),finalized:Y_.optional()}).optional(),request:W.NativeAtumSignRequest.optional(),originalAccessKeyPublicKey:v.z.string().optional(),financial:v.z.strictObject({binding:JC,operation:W.NativeAtumSigningOperation}).optional()}).register(Ze.apiMetadata,{id:"NativeAtumOperation"});var th=v.z.strictObject({v:v.z.literal(1),status:v.z.literal("not_found")});W.NativeAtumOperationResult=v.z.union([W.NativeAtumOperation,th]).register(Ze.apiMetadata,{id:"NativeAtumOperationResult"});W.NativeAtumApprovalDetail=v.z.strictObject({v:v.z.literal(1),approvalId:Fe,purchaseId:Fe,agentId:Fe,runtimeId:Fe,terms:W.NativeAtumOwnerTerms,binding:v.z.strictObject({ownerPrincipalId:Fe,associationId:Fe,associationVersion:v.z.number().int().positive(),agentId:Fe,rootJkt:v.z.string().regex(/^[A-Za-z0-9_-]{43}$/),operationId:Fe}),expiresAt:v.z.iso.datetime()}).register(Ze.apiMetadata,{id:"NativeAtumApprovalDetail",description:"Original native owner review from the authenticated Money reader. approvalId names the existing approval route; purchaseId and binding.operationId name the original purchase. Exact optional review terms are separately deletable and never telemetry or immutable history. The owner resolves the existing named identity root through the authenticated SDK and verifies its JKT against binding.rootJkt; this record is not authorization."});W.NativeAtumSignResult=v.z.union([W.NativeAtumOperation,v.z.strictObject({v:v.z.literal(1),status:v.z.literal("owner_approval_required"),purchaseId:Fe,approvalId:Fe.optional().clone().register(Ze.apiMetadata,{description:"Original approval route ID, distinct from the purchase lookup reference. Supplied by the canonical native owner approval receiver."}),agentId:Fe,originalRequest:W.NativeAtumSignRequest,expiresAt:v.z.string(),ownerTerms:W.NativeAtumOwnerTerms})]).register(Ze.apiMetadata,{id:"NativeAtumSignResult"});var K_=v.z.enum(["OUSD","USDC.e","USD"]),WC=v.z.strictObject({word:v.z.enum(["Pending","Card issued","Settling","Completed","Cancelled","Failed","Needs attention"]),authorizedMicros:v.z.string(),asset:K_,mayStillOweMicros:v.z.string(),fundingAsset:K_,debitedMicros:v.z.string().nullable(),feeMicros:v.z.string().nullable(),movedMicros:v.z.string(),movedQuality:v.z.enum(["proven","conservative_max"]).nullable(),refundedMicros:v.z.string(),received:v.z.enum(["none","available","unavailable"]),settlement:v.z.strictObject({kind:v.z.literal("merchant_held"),networkRef:v.z.string()}).nullable()});W.NativeAtumSettlementResult=v.z.union([th,v.z.strictObject({v:v.z.literal(1),status:v.z.literal("pending"),purchaseId:Fe}),v.z.strictObject({v:v.z.literal(1),status:v.z.enum(["completed","refunded","not_funded"]),purchaseId:Fe,accounting:WC})]).register(Ze.apiMetadata,{id:"NativeAtumSettlementResult"});W.NativeFinancialRefusal=v.z.union([v.z.strictObject({code:v.z.enum(qC.WIRE_ERROR_FAMILIES),detail:v.z.string(),retryable:v.z.boolean(),next_action:v.z.string().optional()}),v.z.strictObject({code:v.z.literal("internal_error"),detail:v.z.literal("unexpected")})]).register(Ze.apiMetadata,{id:"NativeFinancialRefusal"});var H_={"tempo-context":{body:W.NativeTempoContextInput,response:W.NativeTempoContext,summary:"Read the current laptop Tempo runtime and native ATUM availability"},"atum-sign":{body:W.NativeAtumSignInput,response:W.NativeAtumSignResult,summary:"Admit or resume the original native ATUM signing operation"},"atum-operation":{body:W.NativeAtumOperationInput,response:W.NativeAtumOperationResult,summary:"Read the original admitted native ATUM operation"},"atum-confirm":{body:W.NativeAtumConfirmInput,response:W.NativeAtumOperationResult,summary:"Reconcile a native ATUM operation against its transaction"},"atum-settle":{body:W.NativeAtumSettleInput,response:W.NativeAtumSettlementResult,summary:"Reconcile original native ATUM settlement or cancellation evidence"}};W.NATIVE_FINANCIAL_OPERATIONS=(0,ZC.defineOperations)(Object.keys(H_).map(e=>{let t=e,r=H_[t];return{id:B_.FINANCIAL_RUNTIME_ROUTES[t].nativeAgentOperation,family:"agent",method:"POST",path:(0,B_.financialRuntimeRoutePath)(t),...r,auth:["agent_token"],errorResponse:W.NativeFinancialRefusal,status:200,idempotency:"request_id",backedBy:"authority",launch:"on",errors:["setup_required","update_required","agent_inactive","invalid_request","blocked","grant_required","limit_reached","owner_approval_required","owner_declined","expired","not_found","conflict","outcome_unknown","not_enabled","unavailable","rate_limited","internal_error"],description:"Existing laptop-only carrier. Auth verifies the current agent token and immutable installation before signed Authority forwarding. Money verifies the original PoP, signed financial meaning and admission/recovery fences. Public paying pause and effective controls remain enforced; declaration does not activate this route. Request/response transport bound: 262144 bytes. Original private context is not telemetry or HTTP capture."}}))});var Pl=P(pr=>{"use strict";Object.defineProperty(pr,"__esModule",{value:!0});pr.OwnerCleanupIntent=pr.OwnerChainRemovalStatement=pr.OwnerRemovalStatement=void 0;var de=ct(),rh=Et(),Ct=Rt(),ea=de.z.string().regex(/^[A-Za-z0-9_:.-]{1,128}$/),El=de.z.array(ea).min(1).max(50).refine(e=>new Set(e).size===e.length),YC=de.z.discriminatedUnion("kind",[de.z.strictObject({kind:de.z.literal("key"),agent_id:Ct.Id,key_id:Ct.Id,installation_id:Ct.Id,generation:de.z.number().int().positive(),purpose:de.z.enum(["wallet","identity"]),provider_ref:ea}),de.z.strictObject({kind:de.z.literal("approver"),agent_id:Ct.Id,approver_id:Ct.Id,installation_id:Ct.Id,provider_ref:ea})]),Ua={kind:de.z.literal("owner_provider_removal"),intent_id:Ct.Id,operation_id:Ct.Id,step_no:de.z.number().int().positive(),action:de.z.enum(["revoke_wallet_key","remove_custody_user","remove_device_approver"]),owner_id:Ct.Id,organization_id:ea,owner_user_id:ea,security_epoch:de.z.number().int().nonnegative(),created_at:Ct.Timestamp,targets:de.z.array(YC).min(1).max(50)},nh=de.z.strictObject({type:de.z.literal("ACTIVITY_TYPE_DELETE_POLICIES"),parameters:de.z.strictObject({policyIds:El})});pr.OwnerRemovalStatement=de.z.discriminatedUnion("phase",[de.z.strictObject({...Ua,phase:de.z.literal("delete_policies"),request:nh}),de.z.strictObject({...Ua,phase:de.z.literal("delete_users"),request:de.z.strictObject({type:de.z.literal("ACTIVITY_TYPE_DELETE_USERS"),parameters:de.z.strictObject({userIds:El})})}),de.z.strictObject({...Ua,phase:de.z.literal("delete_denies"),request:nh}),de.z.strictObject({...Ua,phase:de.z.literal("delete_private_keys"),request:de.z.strictObject({type:de.z.literal("ACTIVITY_TYPE_DELETE_PRIVATE_KEYS"),parameters:de.z.strictObject({privateKeyIds:El,deleteWithoutExport:de.z.literal(!0)})})})]).refine(e=>e.action==="remove_device_approver"?e.targets.length===1&&e.targets[0].kind==="approver"&&(e.phase==="delete_users"||e.phase==="delete_denies"):e.targets.every(t=>t.kind==="key"&&t.purpose===(e.action==="revoke_wallet_key"?"wallet":"identity"))&&(e.action!=="revoke_wallet_key"||e.targets.length===1),{message:"removal action and targets must agree"}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).length<=32768,{message:"removal intent exceeds 32 KiB"}).clone().register(rh.apiMetadata,{id:"OwnerRemovalStatement"});var Il=de.z.templateLiteral(["0x",de.z.string()]).refine(e=>/^0x[0-9a-f]{40}$/.test(e),{message:"exact lowercase chain address"});pr.OwnerChainRemovalStatement=de.z.strictObject({...Ua,kind:de.z.literal("owner_wallet_revocation"),phase:de.z.literal("revoke_chain_key"),action:de.z.literal("revoke_wallet_key"),targets:de.z.tuple([de.z.strictObject({kind:de.z.literal("key"),agent_id:Ct.Id,key_id:Ct.Id,installation_id:Ct.Id,generation:de.z.number().int().positive(),purpose:de.z.literal("wallet"),provider_ref:ea})]),account:Il,access_key:Il,chain_id:de.z.literal(4217),fee_token:Il}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).length<=32768,{message:"removal intent exceeds 32 KiB"}).clone().register(rh.apiMetadata,{id:"OwnerChainRemovalStatement"});pr.OwnerCleanupIntent=de.z.union([pr.OwnerRemovalStatement,pr.OwnerChainRemovalStatement])});var zl=P(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.HostedIdentityChallenge=nt.HostedIdentitySubmission=nt.HostedProviderRequest=nt.TapEnrollmentChallenge=nt.TapEnrollmentSubmission=nt.TAP_ENROLLMENT_SUBMISSION_MAX_BYTES=void 0;var M=ct(),ah=Et(),ih=Rt();nt.TAP_ENROLLMENT_SUBMISSION_MAX_BYTES=60*1024;var vt=M.z.object({body:M.z.string().min(1).max(32768),stamp:M.z.object({stampHeaderName:M.z.string().min(1).max(64),stampHeaderValue:M.z.string().min(1).max(16384)}).strict()}).strict();nt.TapEnrollmentSubmission=M.z.object({method:M.z.literal("tap_enrollment"),request_id:M.z.string().uuid(),owner_whoami:vt,proof:M.z.discriminatedUnion("phase",[M.z.object({phase:M.z.literal("authorizations"),owner_authorization:vt,gate_authorization:vt,delegation:vt}).strict(),M.z.object({phase:M.z.literal("root_challenge"),root_challenge:vt}).strict()])}).strict().refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=nt.TAP_ENROLLMENT_SUBMISSION_MAX_BYTES,{message:"TAP original submission exceeds the bounded owner envelope"}).clone().register(ah.apiMetadata,{id:"TapEnrollmentSubmission",description:"The original owner-stamped TAP protocol requests for the final step of the existing setup operation. Every request is checked against its server-prepared input, recorded before relay and independently read back. Unknown delivery never authorizes a new request."});var Gr={request_id:M.z.string().uuid(),organization_id:ih.Id,root_key_id:ih.Id},Ar=M.z.string().max(16384).regex(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/);nt.TapEnrollmentChallenge=M.z.discriminatedUnion("phase",[M.z.object({...Gr,phase:M.z.literal("authorizations"),owner_authorization_signing_input:Ar,gate_authorization_signing_input:Ar,delegation_signing_input:Ar,authorization_expires_at:M.z.number().int().nonnegative()}).strict(),M.z.object({...Gr,phase:M.z.literal("root_challenge"),payload_hex:M.z.string().regex(/^[0-9a-f]{64}$/),expires_at:M.z.number().int().nonnegative()}).strict(),M.z.object({request_id:M.z.string().uuid(),phase:M.z.literal("pending"),reason:M.z.enum(["provider_response_unknown","gate_response_unknown","directory_response_unknown","directory_pending","contact_required","authorization_expired"])}).strict()]).clone().register(ah.apiMetadata,{id:"TapEnrollmentChallenge",description:"Prepared TAP-only inputs for the existing owner setup tap. Provider-aware preflight checks serialized bodies before owner signing; complete original stamps must still pass the submission bound. Pending names an unfinished obligation and has no new signing input. Neither pending nor a missing directory ID proves enrollment, publication or payment readiness."});var KC=M.z.strictObject({policyName:M.z.string().min(1).max(512),effect:M.z.enum(["EFFECT_ALLOW","EFFECT_DENY"]),consensus:M.z.string().min(1).max(16384),condition:M.z.string().min(1).max(16384),notes:M.z.string().max(1024)});nt.HostedProviderRequest=M.z.discriminatedUnion("type",[M.z.strictObject({type:M.z.enum(["ACTIVITY_TYPE_CREATE_USERS_V3","ACTIVITY_TYPE_CREATE_USERS_V4"]),parameters:M.z.strictObject({users:M.z.tuple([M.z.strictObject({userName:M.z.string().min(1).max(256),apiKeys:M.z.tuple([M.z.strictObject({apiKeyName:M.z.string().min(1).max(256),publicKey:M.z.string().regex(/^0[23][0-9a-f]{64}$/),curveType:M.z.literal("API_KEY_CURVE_P256")})]),authenticators:M.z.tuple([]),oauthProviders:M.z.tuple([]),userTags:M.z.tuple([])})])})}),M.z.strictObject({type:M.z.literal("ACTIVITY_TYPE_CREATE_POLICIES"),parameters:M.z.strictObject({policies:M.z.array(KC).min(1).max(2)})})]);nt.HostedIdentitySubmission=M.z.strictObject({method:M.z.literal("hosted_identity"),request_id:M.z.string().uuid(),owner_whoami:vt,proof:M.z.discriminatedUnion("phase",[M.z.strictObject({phase:M.z.literal("principal"),principal:vt}),M.z.strictObject({phase:M.z.literal("enrollment_authorization"),owner_authorization:vt}),M.z.strictObject({phase:M.z.literal("root_challenge"),root_challenge:vt}),M.z.strictObject({phase:M.z.literal("runtime_authorizations"),certificate:vt,presence_delegation:vt,gate_authorization:vt,money_delegation:vt}),M.z.strictObject({phase:M.z.literal("wallet_policy"),request:vt}),M.z.strictObject({phase:M.z.literal("tap_authorization"),tap_delegation:vt})])}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=nt.TAP_ENROLLMENT_SUBMISSION_MAX_BYTES,{message:"Hosted original submission exceeds the bounded owner envelope"});nt.HostedIdentityChallenge=M.z.discriminatedUnion("phase",[M.z.strictObject({...Gr,phase:M.z.literal("principal"),action:M.z.enum(["create_user","create_policies"]),request:nt.HostedProviderRequest}),M.z.strictObject({...Gr,phase:M.z.literal("enrollment_authorization"),authorization_undispatched:M.z.literal(!0).optional(),owner_authorization_signing_input:Ar,authorization_expires_at:M.z.number().int().nonnegative()}),M.z.strictObject({...Gr,phase:M.z.literal("root_challenge"),payload_hex:M.z.string().regex(/^[0-9a-f]{64}$/),expires_at:M.z.number().int().nonnegative()}),M.z.strictObject({...Gr,phase:M.z.literal("runtime_authorizations"),certificate_signing_input:Ar,presence_delegation_signing_input:Ar,gate_authorization_signing_input:Ar,money_delegation_signing_input:Ar,authorization_expires_at:M.z.number().int().nonnegative()}),M.z.strictObject({...Gr,phase:M.z.literal("tap_authorization"),tap_delegation_signing_input:Ar,authorization_expires_at:M.z.number().int().nonnegative()}),M.z.strictObject({...Gr,phase:M.z.literal("wallet_policy"),step_no:M.z.union([M.z.literal(4),M.z.literal(5),M.z.literal(6)]),action:M.z.enum(["create_tempo_signer_guard","create_tempo_signer_user","create_device_approver_policy"]),request:nt.HostedProviderRequest}),M.z.strictObject({request_id:M.z.string().uuid(),phase:M.z.literal("pending"),reason:M.z.enum(["provider_response_unknown","gate_response_unknown","authorization_expired"])})])});var Al=P(jr=>{"use strict";Object.defineProperty(jr,"__esModule",{value:!0});jr.ChainLimitScope=jr.ChainLimitUpdate=jr.ChainLimitStatement=void 0;var Ne=ct(),oh=Et(),vc=Rt(),_c=Ne.z.string().regex(/^0x[0-9a-f]{40}$/),Tl=Ne.z.string().regex(/^0x[0-9a-f]{64}$/);jr.ChainLimitStatement=Ne.z.strictObject({kind:Ne.z.literal("chain_limit"),operation_id:vc.Id,key_id:vc.Id,chain_id:Ne.z.literal(4217),account:_c,access_key_address:_c,tokens:Ne.z.tuple([_c,_c]),limit_micros:vc.Micros.refine(e=>BigInt(e)>0n),period_seconds:Ne.z.literal(604800),fee:Ne.z.literal("owner")}).register(oh.apiMetadata,{id:"ChainLimitStatement"});var hc={agent_id:vc.Id,statement:jr.ChainLimitStatement};jr.ChainLimitUpdate=Ne.z.discriminatedUnion("phase",[Ne.z.strictObject({...hc,phase:Ne.z.literal("prepared")}),Ne.z.strictObject({...hc,phase:Ne.z.literal("pending"),signed_tx:Ne.z.string().max(4096).regex(/^0x76(?:[0-9a-f]{2})+$/),tx_hash:Tl,valid_before:Ne.z.number().int().positive().max(Number.MAX_SAFE_INTEGER)}),Ne.z.strictObject({...hc,phase:Ne.z.literal("applied"),tx_hash:Tl}),Ne.z.strictObject({...hc,phase:Ne.z.literal("not_applied"),tx_hash:Tl,reason:Ne.z.enum(["missed","reverted"])})]).register(oh.apiMetadata,{id:"ChainLimitUpdate"});jr.ChainLimitScope=Ne.z.union([Ne.z.strictObject({agentId:Ne.z.string().uuid(),grantId:Ne.z.string().uuid(),version:Ne.z.number().int().positive()}),Ne.z.strictObject({operationIds:Ne.z.array(Ne.z.string().uuid()).min(1).max(100)})])});var Si=P(_=>{"use strict";Object.defineProperty(_,"__esModule",{value:!0});_.GrantVersion=_.Grant=_.SetupClaimed=_.SetupClaim=_.OwnerSetupStart=_.AgentSetupStarted=_.AgentSetupStart=_.Setup=_.SETUP_STATES=_.SETUP_KINDS=_.GrantRequest=_.GrantTerms=_.GrantMode=_.GRANT_MODES=_.AgentTokenAlreadyCreated=_.AgentTokenCreated=_.AgentToken=_.Device=_.AgentPatch=_.Agent=_.HostedSetupRecovery=_.Installation=_.AGENT_END_REASONS=_.AGENT_LIFECYCLE=_.DeviceApprover=_.APPROVER_STATES=_.KEY_END_REASONS=_.KEY_LIFECYCLE=_.KEY_CUSTODY=_.Owner=_.OWNER_LIFECYCLE_FROM_TODAY=_.OWNER_ACCESS_FROM_TODAY=_.OWNER_LIFECYCLE=_.OWNER_ACCESS=_.Session=_.SessionSigner=_.SignatureResult=_.OwnerPaymentProgress=_.SignatureSubmission=_.Challenge=_.WalletKeyAuthorizationResume=_.WithdrawalTransaction=_.RecordedOwnerCleanupTransaction=_.WalletKeyChainAuthorizationStatement=_.CardCodeStep=_.CardCodeDelivery=_.ApprovalKind=_.APPROVAL_KINDS=_.CHALLENGE_SIGNERS=_.EVIDENCE_METHODS=void 0;_.Timestamp=_.Id=_.ToolDescriptor=_.ClientEvent=_.MerchantResult=_.AgentStatus=_.WalletSigningContext=_.Console=_.Security=_.SpendingState=_.ActivityList=_.ActivityItem=_.CardEnrollmentAlreadyStarted=_.CardEnrollment=_.Card=_.Withdrawal=_.Wallet=_.Approval=_.CardCredential=_.PaymentReport=_.PaymentList=_.Payment=_.SigningExchange=_.PaymentCreate=_.ApprovalReviewDetail=_.OwnerPreparedPayment=_.OriginalHostedPurchaseContext=_.MerchantReceipt=_.RETAINED_PAYMENT_FACTS=_.ATTEMPT_TERMS_FIELDS=_.PURCHASE_IDENTITY_FIELDS=_.RuntimeAuthorization=_.TapSignatureBasePayload=_.POP_INTENT_CLAIM=_.PreparedCharge=_.ApprovalReviewChargeRequest=_.TempoChargeRequestWire=_.PaymentTarget=_.GrantChange=_.GrantHistory=void 0;var lh=xa(),l=ct(),w=Et(),HC=Pl(),Za=zl(),XC=Al(),I=Rt();Object.defineProperty(_,"Id",{enumerable:!0,get:function(){return I.Id}});Object.defineProperty(_,"Timestamp",{enumerable:!0,get:function(){return I.Timestamp}});_.EVIDENCE_METHODS=["passkey","owner_jws","email_code","owner_session"];_.CHALLENGE_SIGNERS=["passkey","owner_jws","card_otp","transaction","provider_activity","email_code","tap_enrollment","hosted_identity"];_.APPROVAL_KINDS=["setup","grant","payment","connector_autonomy","replacement","account_closure","agent_reissue","spending_activation","autonomy_increase","contact_email"];_.ApprovalKind=l.z.enum(_.APPROVAL_KINDS).clone().register(w.apiMetadata,{id:"ApprovalKind"});_.CardCodeDelivery=l.z.object({identifier:l.z.string().min(1).max(512).clone().register(w.apiMetadata,{description:"Opaque choice id; owner.cards.collect { send_to } sends a new code there."}),method:l.z.string().clone().register(w.apiMetadata,{description:"How the issuer sends the code, for example OTPSMS or OTPEMAIL."}),value:l.z.string().nullable().clone().register(w.apiMetadata,{description:"Where it goes, already masked by the issuer (a\u2022\u2022\u2022@example.com)."})}).clone().register(w.apiMetadata,{id:"CardCodeDelivery"});_.CardCodeStep=l.z.object({delivery:l.z.array(_.CardCodeDelivery),sent_to:l.z.string().nullable().clone().register(w.apiMetadata,{description:"Where the newest code went, as the issuer masked it; null before any code is sent."}),resend_in_seconds:l.z.number().int().min(0).nullable().clone().register(w.apiMetadata,{description:"Seconds before another code may be requested (each new code invalidates the earlier ones)."})}).clone().register(w.apiMetadata,{id:"CardCodeStep"});_.WalletKeyChainAuthorizationStatement=l.z.strictObject({kind:l.z.literal("wallet_key_chain_authorization"),operation_id:I.Id,key_id:I.Id,account:l.z.string().regex(/^0x[0-9a-fA-F]{40}$/),access_key_address:l.z.string().regex(/^0x[0-9a-fA-F]{40}$/),access_key_public_key:l.z.string().regex(/^(?:0x)?(?:0[23][0-9a-fA-F]{64}|04[0-9a-fA-F]{128})$/),limits:l.z.array(l.z.strictObject({token:l.z.string(),micros:l.z.string().regex(/^(?:0|[1-9][0-9]*)$/),period_seconds:l.z.number().int().min(1).max(Number.MAX_SAFE_INTEGER)})).length(2),expires_at_seconds:l.z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),scope:l.z.literal("mpp_only")}).clone().register(w.apiMetadata,{id:"WalletKeyChainAuthorizationStatement"});_.RecordedOwnerCleanupTransaction=l.z.strictObject({raw:l.z.string().regex(/^0x76(?:[0-9a-f]{2})+$/).max(4096),hash:l.z.string().regex(/^0x[0-9a-f]{64}$/),intent:HC.OwnerChainRemovalStatement}).clone().register(w.apiMetadata,{description:"Owner-only original acknowledged revoke bytes and hash; resume these bytes without signing again."});_.WithdrawalTransaction=l.z.object({signed_tx:l.z.string().max(4096).regex(/^0x76(?:[0-9a-f]{2})+$/),tx_hash:l.z.string().regex(/^0x[0-9a-f]{64}$/)}).clone().register(w.apiMetadata,{description:"Owner-only withdrawal bytes durably bound before broadcast. Resume this exact transaction after a lost acknowledgement; this binding does not prove payment."});_.WalletKeyAuthorizationResume=l.z.object({signed_tx:l.z.string().max(16384).regex(/^0x76(?:[0-9a-f]{2})+$/),tx_hash:l.z.string().regex(/^0x[0-9a-f]{64}$/),intent:_.WalletKeyChainAuthorizationStatement.nullable().optional().clone().register(w.apiMetadata,{description:"The existing original chain statement, verified against these recorded bytes and owner-bound stored terms. Null when newer facts cannot establish the original intent; never permission to sign or proof of finalized absence."})}).clone().register(w.apiMetadata,{description:"The original recorded wallet key authorization. Owner-only recovery bytes; neither chain inclusion nor an active grant is implied."});_.Challenge=l.z.object({challenge_id:I.Id,purpose:l.z.enum(["session","setup_approval","grant","payment_approval","wallet_enable","wallet_conversion","withdrawal","card_enrollment","spending_reopen","agent_reissue","account_closure","autonomy_increase","provider_cleanup","contact_email","provider_cleanup"]),approval_kind:_.ApprovalKind.nullable().clone().register(w.apiMetadata,{description:"The approval row this signature creates; null for signatures that are not consents (sign-in, a withdrawal transaction, a wallet key authorisation)."}),signer:l.z.enum(_.CHALLENGE_SIGNERS).clone().register(w.apiMetadata,{description:"How this challenge is answered. passkey: a WebAuthn assertion. owner_jws: a stamped Turnkey activity / owner JWS over the statement. provider_activity: the id of the owner\u2019s own Turnkey activity in which the identity root signed the statement\u2019s money_delegation_signing_input (wallet key authorisation), or the completed deletion activity for the exact OwnerRemovalStatement (provider cleanup). email_code: proof of a contact address only; never a money, setup or autonomy consent. card_otp: the one-time code the card issuer sent the cardholder (card enrollment only; owner.cards.collect sends it). transaction: the owner\u2019s own wallet\u2019s transfer hash (withdrawal), its signed on-chain limit update (sign_chain_limit), the original signed revoke bytes for the exact OwnerChainRemovalStatement (provider_cleanup), or its wallet key authorisation (sign_key_authorization, signed_tx or independently read tx_hash)."}),transaction_modes:l.z.array(l.z.enum(["signed_tx","tx_hash"])).optional().clone().register(w.apiMetadata,{description:"Wallet key authorization only: submit exactly one named field. signed_tx is recorded before dispatch; tx_hash is independently read on chain."}),step_up:l.z.object({accepted:l.z.array(l.z.enum(["email_code","passkey"])).clone().register(w.apiMetadata,{description:"The accepted proof for this contact-email challenge."}),email_code_sent_to:l.z.string().nullable().clone().register(w.apiMetadata,{description:"The masked verified owner email the code was sent to."})}).nullable().optional().clone().register(w.apiMetadata,{description:"Set for the contact-email proof. Console autonomy changes and reopening spending use the current owner session, not this challenge."}),statement:l.z.string().clone().register(w.apiMetadata,{description:"The canonical terms the owner signs: amounts, merchant, limits, expiry. Never request content. The client renders it and checks it against the resource it shows before signing."}),payload:l.z.string().clone().register(w.apiMetadata,{description:"The encoding of `statement` to sign, base64url. The client re-derives it; it never signs bytes it cannot read."}),card_otp:_.CardCodeStep.nullable().optional().clone().register(w.apiMetadata,{description:"Set when signer is card_otp: where the issuer can send the code, and where the newest code went."}),tap_enrollment:Za.TapEnrollmentChallenge.optional().clone().register(w.apiMetadata,{description:"The exact final TAP setup protocol phase; required only when signer is tap_enrollment."}),hosted_identity:Za.HostedIdentityChallenge.optional(),resource:l.z.object({type:l.z.string(),id:I.Id}),expires_at:I.Timestamp}).refine(e=>e.signer==="tap_enrollment"==(e.tap_enrollment!==void 0),{message:"tap_enrollment signer requires its exact TAP phase"}).refine(e=>e.signer==="hosted_identity"==(e.hosted_identity!==void 0),{message:"hosted_identity signer requires its exact hosted phase"}).clone().register(w.apiMetadata,{id:"Challenge",description:"Returned with 202 by every owner action that needs the owner\u2019s own signature. Submit it at POST /owner/v1/signatures/{challengeId}; Authority verifies."});_.SignatureSubmission=l.z.discriminatedUnion("method",[Za.TapEnrollmentSubmission,Za.HostedIdentitySubmission,l.z.object({method:l.z.enum(["passkey","owner_jws"]),assertion:l.z.string().min(1).clone().register(w.apiMetadata,{description:"The passkey assertion or owner JWS / Turnkey stamp over the statement, base64url."}),terms:lh.NativeAtumOwnerTerms.optional().clone().register(w.apiMetadata,{description:"Transient exact native original terms resupply with the owner JWS only; Money verifies immutable commitments and current original bindings. Never stored by this submission or used as authority."})}).refine(e=>e.terms===void 0||e.method==="owner_jws",{message:"native terms require the original owner JWS"}),l.z.object({method:l.z.literal("card_otp"),code:l.z.string().min(1).max(32).regex(/^[^\u0000-\u001f\u007f]+$/).clone().register(w.apiMetadata,{description:"The one-time code the card issuer sent the cardholder (card enrollment). Checked by the issuer through the card executor and never stored."})}),l.z.object({method:l.z.literal("provider_activity"),activity_id:l.z.string().regex(/^[A-Za-z0-9_:.-]{1,128}$/).clone().register(w.apiMetadata,{description:"The owner\u2019s Turnkey activity for the challenge: a wallet key money-delegation signature, or the exact deletion in an owner_provider_removal statement. The server reads the activity and independently verifies removal; a client success report is never completion evidence."})}),l.z.object({method:l.z.literal("transaction"),tx_hash:l.z.string().regex(/^0x[0-9a-fA-F]{64}$/).optional().clone().register(w.apiMetadata,{description:"A withdrawal: the hash of the transfer the owner\u2019s own wallet signed and broadcast; Visa holds no signature and confirms it on chain (decided 8 Oct, proposal 5)."}),signed_tx:l.z.string().max(16384).regex(/^0x76(?:[0-9a-f]{2})+$/).optional().clone().register(w.apiMetadata,{description:"The owner root\u2019s signed transaction: wallet key authorization (sign_key_authorization, at most 16384 characters) an owner provider-cleanup revoke (revoke_wallet_key, at most 4096), or an on-chain limit update (sign_chain_limit, at most 4096). Visa verifies and records it before dispatch and recovers the same bytes until the chain answers. The wallet pays the existing fee."})}).refine(e=>e.tx_hash===void 0!=(e.signed_tx===void 0),{message:"exactly one of tx_hash or signed_tx"}),l.z.object({method:l.z.literal("email_code"),code:l.z.string().regex(/^[0-9]{6}$/).clone().register(w.apiMetadata,{description:"The six-digit code sent to the contact address the owner is verifying. Accepted only for contact_email; the approval records the verifier receipt and verification time, never the code."})})]).clone().register(w.apiMetadata,{id:"SignatureSubmission",description:"One answer to one challenge, by the challenge\u2019s signer: a signature (passkey or owner JWS) for consents, the owner\u2019s provider activity for the wallet key authorisation, an email code only for contact_email verification, a card code only for a card_enrollment challenge whose signer is card_otp, a transaction hash for a withdrawal or independently verified wallet key authorization, or original signed transaction bytes for wallet key authorization / provider cleanup / on-chain limit update. Any other pairing is refused."});_.OwnerPaymentProgress=l.z.strictObject({state:l.z.enum(["awaiting_owner","approved","cosign_needed","signed","paid","not_paid","unknown"]),cosign:l.z.strictObject({organization_id:l.z.string().regex(/^[-_A-Za-z0-9]{1,256}$/),activity_id:l.z.string().regex(/^[A-Za-z0-9_:.-]{1,128}$/),fingerprint:l.z.string().min(1).max(256),valid_before:l.z.number().int().positive()}).nullable().clone().register(w.apiMetadata,{description:"While Turnkey waits for the owner\u2019s own vote: the recorded signing activity. The Console reads it with the owner\u2019s session, checks it against the approved charge, and only then approves it. Never voted for automatically."}),reason:l.z.string().regex(/^[a-z0-9_]{1,64}$/).nullable()}).clone().register(w.apiMetadata,{id:"OwnerPaymentProgress",description:"An owner-approved hosted payment after the owner pressed Approve and pay. signed means the payment was signed once and the agent\u2019s app completes it; paid only on chain evidence. Never a receipt by itself. approved means the owner\u2019s signature is recorded and the agent\u2019s own runtime finishes it (a laptop resumes and casts its own vote, as today). Absent while owner-approved paying is paused."});_.SignatureResult=l.z.object({withdrawal_transaction:_.WithdrawalTransaction.nullable().optional(),chain_limit_update:XC.ChainLimitUpdate.optional(),wallet_key_authorization:_.WalletKeyAuthorizationResume.nullable().optional(),challenge_id:I.Id,state:l.z.enum(["pending","accepted","rejected","expired"]),resource:l.z.object({type:l.z.string(),id:I.Id,version:l.z.number().int().min(1).max(Number.MAX_SAFE_INTEGER).optional().clone().register(w.apiMetadata,{description:"Only for an accepted grant with an exact applied receipt: the immutable version this signature applied. Later replacements do not advance it. Absence means application cannot be confirmed from this result; never infer the version from a current grant read."})}),challenge:_.Challenge.nullable().clone().register(w.apiMetadata,{description:"While pending: the full challenge (statement and payload), so any browser can sign it."}),continuation:I.Continuation.nullable(),recorded_transaction:_.RecordedOwnerCleanupTransaction.optional(),native:lh.NativeAtumApprovalDetail.optional(),progress:_.OwnerPaymentProgress.optional()}).refine(e=>e.resource.version===void 0||e.state==="accepted"&&e.resource.type==="grant",{message:"a version receipt requires an accepted grant"}).clone().register(w.apiMetadata,{id:"SignatureResult"});_.SessionSigner=l.z.object({provider:l.z.literal("turnkey"),organization_id:l.z.string(),user_id:l.z.string()}).clone().register(w.apiMetadata,{id:"SessionSigner",description:"The Turnkey organisation and user the sign-in proved for this session. Owner-signed actions in this session must be signed by this user; the Console never infers it from the owner id."});_.Session=l.z.object({id:I.Id,owner_id:I.Id,scope:l.z.enum(["product","exit"]).clone().register(w.apiMetadata,{description:"exit: product admission is refused but the owner can still withdraw, export and close."}),created_at:I.Timestamp.nullable().clone().register(w.apiMetadata,{description:"Nullable until cutover B: today Auth does not record it for every live session. Required from B."}),expires_at:I.Timestamp.nullable().clone().register(w.apiMetadata,{description:"Nullable until cutover B: today Auth does not record it for every live session. Required from B."}),current:l.z.boolean(),client:l.z.string().nullable().clone().register(w.apiMetadata,{description:"A coarse device description, never a fingerprint."}),last_active_at:I.Timestamp.nullable().clone().register(w.apiMetadata,{description:"When this session last made a request (to the minute); null if never since issue (decided 8 Oct, 10b)."})}).clone().register(w.apiMetadata,{id:"Session",description:"Auth change needed before /owner/v1/sessions serves non-null times: record created_at at issue and expires_at from the session TTL (or the web-session token exp) for every owner session, web and CLI. Sessions issued before that change may lack them, so both stay nullable until cutover B, which rebuilds sessions empty; from B both are required."});_.OWNER_ACCESS=["pending","approved","rejected"];_.OWNER_LIFECYCLE=["active","closing","closed"];_.OWNER_ACCESS_FROM_TODAY=[{today:"ownerAccess v4 (every users.status row approved)",access:"approved"},{today:"ownerAccess revoked (any users.status row rejected)",access:"rejected"},{today:"ownerAccess none with rows (some pending, none rejected)",access:"pending"},{today:"ownerAccess none with no rows",access:null}];_.OWNER_LIFECYCLE_FROM_TODAY=[{today:"no account closure",lifecycle:"active"},{today:"POST /v4/account/close accepted, closure not finished",lifecycle:"closing"},{today:"closure finished (GET /v4/account/closure/:id done)",lifecycle:"closed"}];_.Owner=l.z.object({id:I.Id,wallet_address:l.z.string().regex(/^0x[0-9a-f]{40}$/).nullable().clone().register(w.apiMetadata,{description:"The recorded owner wallet address, published after the owner wallet and identity roots complete custody readback. null until that ceremony completes."}),display_name:l.z.string().nullable(),photo_url:l.z.url().nullable(),contact_email:l.z.string().nullable().clone().register(w.apiMetadata,{description:"A5: the one verified owner email, used only for the TAP directory and essential notices."}),access:l.z.enum(_.OWNER_ACCESS).clone().register(w.apiMetadata,{description:"Whether Visa admits this owner (entry gate: Visa identity plus legal geo-blocking). Mapping from today: see OWNER_ACCESS_FROM_TODAY."}),lifecycle:l.z.enum(_.OWNER_LIFECYCLE).clone().register(w.apiMetadata,{description:"closing: an account_closure operation is running (exit still works). closed: done."}),renewal_due_at:I.Timestamp.nullable().clone().register(w.apiMetadata,{description:"The account's one spending renewal date: every agent's grant ends on it, and one owner tap renews them all for 90 days from that tap. null until the first agent is set up."}),created_at:I.Timestamp}).clone().register(w.apiMetadata,{id:"Owner"});_.KEY_CUSTODY=["device","enclave","turnkey"];_.KEY_LIFECYCLE=["pending","active","ending","ended"];_.KEY_END_REASONS=["rotated","upgraded","replaced","emergency_replaced","recovered","revoked","agent_ended","expired","abandoned"];_.APPROVER_STATES=["pending","active","removing","removed"];_.DeviceApprover=l.z.object({id:I.Id,installation_id:I.Id.clone().register(w.apiMetadata,{description:"The installation whose device holds the approver credential."}),provider:l.z.literal("turnkey"),state:l.z.enum(_.APPROVER_STATES).clone().register(w.apiMetadata,{description:"pending: created, policy not yet in force. removing: provider removal in flight."}),created_at:I.Timestamp,activated_at:I.Timestamp.nullable(),removed_at:I.Timestamp.nullable()}).clone().register(w.apiMetadata,{id:"DeviceApprover",description:"A provider approver that must vote on this agent\u2019s signing (two of two, at most 8 per agent). Approvers only vote; they never sign. Removed by a remove_device_approver operation step."});_.AGENT_LIFECYCLE=["pending","active","paused","ending","ended"];_.AGENT_END_REASONS=["revoked","owner_closed","setup_abandoned"];_.Installation=l.z.object({id:I.Id,surface:I.Surface,lifecycle:l.z.enum(_.KEY_LIFECYCLE).clone().register(w.apiMetadata,{description:"The lifecycle of this installation\u2019s current key generation."}),end_reason:l.z.enum(_.KEY_END_REASONS).nullable(),key_generation:l.z.number().int().min(1),custody:l.z.enum(_.KEY_CUSTODY).clone().register(w.apiMetadata,{description:"device: an OS key store on the owner\u2019s computer. enclave: a key held by an attested enclave. turnkey: a non-exportable Turnkey-held key."}),client:l.z.string().nullable(),created_at:I.Timestamp,last_used_at:I.Timestamp.nullable()}).clone().register(w.apiMetadata,{id:"Installation",description:"Where the durable agent runs. One active installation per agent is policy; replacing it never loses the agent or resets its grant."});_.HostedSetupRecovery=l.z.strictObject({setup_id:I.Id,operation_id:I.Id,agent_id:I.Id,installation_id:I.Id,organization_id:l.z.string().min(1),owner_user_id:l.z.string().min(1),private_key_name:l.z.string().min(1),wallet_policy:Za.HostedIdentityChallenge}).clone().register(w.apiMetadata,{id:"HostedSetupRecovery"});_.Agent=l.z.object({id:I.Id,setup_id:I.Id.nullable().optional(),name:l.z.string(),surface:I.Surface,lifecycle:l.z.enum(_.AGENT_LIFECYCLE),end_reason:l.z.enum(_.AGENT_END_REASONS).nullable(),installations:l.z.array(_.Installation),active_installation_id:I.Id.nullable().clone().register(w.apiMetadata,{description:"The one installation allowed to act (policy)."}),approvers:l.z.array(_.DeviceApprover).clone().register(w.apiMetadata,{description:"The device-approver roster for laptop co-signing, separate from the active installation."}),tap_agent_id:l.z.string().nullable().clone().register(w.apiMetadata,{description:"The public Trusted Agent Protocol directory id."}),grant_version:l.z.number().int().nullable(),grants:l.z.array(l.z.lazy(()=>_.Grant)).max(I.Rail.options.length).optional().clone().register(w.apiMetadata,{description:"Current or latest ended grant per rail. Owner reads always supply an explicit empty collection when none exist; absent means unavailable, never zero permission."}),grant_history:l.z.lazy(()=>_.GrantHistory).optional().clone().register(w.apiMetadata,{description:"A bounded page of immutable terms versions on owner agent detail reads."}),readiness:l.z.array(I.Readiness),created_at:I.Timestamp}).clone().register(w.apiMetadata,{id:"Agent"});_.AgentPatch=l.z.object({name:l.z.string().min(1).max(80).optional(),paused:l.z.boolean().optional()}).clone().register(w.apiMetadata,{id:"AgentPatch"});_.Device=l.z.object({id:I.Id.clone().register(w.apiMetadata,{description:"The app\u2019s own device id (registering it again is idempotent)."}),platform:l.z.enum(["ios"]),app_env:l.z.enum(["preview","production"]).clone().register(w.apiMetadata,{description:"The APNs environment; a sandbox token is never sent to production APNs."}),created_at:I.Timestamp,updated_at:I.Timestamp}).clone().register(w.apiMetadata,{id:"Device",description:"A phone registered for the owner\u2019s notifications (proposal 30). Registration only: nothing is sent at launch. The push token is never answered."});_.AgentToken=l.z.object({key_id:I.Id,label:l.z.string().clone().register(w.apiMetadata,{description:"Server-assigned from the app; not set by the owner."}),app:l.z.string().nullable().clone().register(w.apiMetadata,{description:"The app or harness the token is for."}),created_at:I.Timestamp,expires_at:I.Timestamp,last_used_at:I.Timestamp.nullable(),prefix:l.z.string().clone().register(w.apiMetadata,{description:"The non-secret first characters of the token, to tell tokens apart (decided 8 Oct, 10b)."})}).clone().register(w.apiMetadata,{id:"AgentToken"});_.AgentTokenCreated=_.AgentToken.extend({token:l.z.string().clone().register(w.apiMetadata,{description:"Shown once. Visa keeps only a hash."})}).clone().register(w.apiMetadata,{id:"AgentTokenCreated"});var dh=l.z.literal(!0),fh=l.z.string().clone().register(w.apiMetadata,{description:"What to do if the first answer was lost."});_.AgentTokenAlreadyCreated=_.AgentToken.extend({already_created:dh,message:fh}).clone().register(w.apiMetadata,{id:"AgentTokenAlreadyCreated",description:"This request_id already created this token. Its secret was shown once and is not stored; if it was lost, revoke this token and create a new one."});_.GRANT_MODES=["within_limit","ask_each_time"];_.GrantMode=l.z.enum(_.GRANT_MODES).clone().register(w.apiMetadata,{id:"GrantMode",description:"within_limit: pay without asking up to the limits. ask_each_time: every payment needs an approval (hosted agents default here). Not a versioned term: switching keeps the grant version and its usage."});_.GrantTerms=l.z.object({max_per_payment:I.Amount,max_per_period:I.Amount,period_seconds:l.z.number().int().min(3600).max(2678400),expires_at:I.Timestamp,instrument_id:I.Id.nullable().clone().register(w.apiMetadata,{description:"card: the enrolled card the VIC mandate binds."})}).clone().register(w.apiMetadata,{id:"GrantTerms",description:"The consented, immutable terms of one rail\u2019s grant version. No grant on a rail means zero spend there, never unlimited."});_.GrantRequest=l.z.object({rail:I.Rail,mode:_.GrantMode,terms:_.GrantTerms}).clone().register(w.apiMetadata,{id:"GrantRequest"});_.SETUP_KINDS=["laptop","hosted","card","replacement"];_.SETUP_STATES=["open","claimed","approved","completed","cancelled","expired"];_.Setup=l.z.object({id:I.Id,kind:l.z.enum(_.SETUP_KINDS),agent_id:I.Id.nullable(),installation_id:I.Id.nullable(),state:l.z.enum(_.SETUP_STATES),terminal_joined:l.z.boolean().optional().clone().register(w.apiMetadata,{description:"The laptop installation joined this setup, independently of owner claim."}),replacement_reason:l.z.enum(["planned","emergency"]).nullable().clone().register(w.apiMetadata,{description:"replacement only. emergency: the old keys ended before this setup existed."}),replaces_key_id:I.Id.nullable(),approval_id:I.Id.nullable().clone().register(w.apiMetadata,{description:"The owner\u2019s consent for this setup, once approved."}),code:l.z.string().clone().register(w.apiMetadata,{description:"The short code the owner matches on the setup page."}),owner_url:l.z.url(),client:l.z.object({name:l.z.string(),version:l.z.string().nullable()}),requested_grants:l.z.array(_.GrantRequest),operation_id:I.Id.nullable().clone().register(w.apiMetadata,{description:"The durable operation that carries this setup."}),expires_at:I.Timestamp,continuation:I.Continuation.nullable()}).clone().register(w.apiMetadata,{id:"Setup",description:"One setup ceremony, durable across browsers and restarts. It owns the CLI rendezvous (the old login and handoff doors). The original task is kept and resumes after approval."});var sh={installation_key:l.z.record(l.z.string(),l.z.unknown()).clone().register(w.apiMetadata,{description:"The new installation\u2019s public JWK (Ed25519)."}),client:l.z.object({name:l.z.string(),version:l.z.string()}),setup_key:l.z.string().optional().clone().register(w.apiMetadata,{description:"Join a setup the owner started in the Console (web-start pickup)."}),resume_proof:l.z.object({signature:l.z.string().clone().register(w.apiMetadata,{description:"Ed25519 signature by the installation key, base64url."}),setup_id:I.Id.nullable().clone().register(w.apiMetadata,{description:"The open setup being resumed, if the client still knows it."}),nonce:l.z.string().min(16).max(64).clone().register(w.apiMetadata,{description:"Random, single use per installation."}),issued_at:l.z.number().int().clone().register(w.apiMetadata,{description:"Unix seconds; accepted only within 120 s."})}).optional().clone().register(w.apiMetadata,{description:'Required to resume an open setup for this installation key (repeating the same start). Signs exactly "visa-setup-resume:v1:" + jwk_thumbprint + ":" + (setup_id or "-") + ":" + nonce + ":" + issued_at. The request must also match the open setup (same kind and, for a replacement, the same agent); otherwise conflict.'})};_.AgentSetupStart=l.z.discriminatedUnion("kind",[l.z.object({kind:l.z.literal("laptop"),...sh}),l.z.object({kind:l.z.literal("replacement"),agent_id:I.Id.clone().register(w.apiMetadata,{description:"The durable agent whose installation is replaced."}),...sh})]).clone().register(w.apiMetadata,{id:"AgentSetupStart"});_.AgentSetupStarted=l.z.object({setup:_.Setup,setup_secret:l.z.string().clone().register(w.apiMetadata,{description:"Shown once; authorizes polling and claim."})}).clone().register(w.apiMetadata,{id:"AgentSetupStarted"});var jl=l.z.string().clone().register(w.apiMetadata,{description:"The app the owner picked (for example a CLI harness)."}),kl=I.Id.clone().register(w.apiMetadata,{description:"Client-generated key: repeating a start with the same request_id returns the same setup, never a second one."});_.OwnerSetupStart=l.z.discriminatedUnion("kind",[l.z.object({kind:l.z.literal("laptop"),request_id:kl,client:jl}),l.z.object({kind:l.z.literal("hosted"),request_id:kl,client:jl}),l.z.object({kind:l.z.literal("replacement"),request_id:kl,agent_id:I.Id.clone().register(w.apiMetadata,{description:"The durable agent whose installation is replaced."}),replacement_reason:l.z.enum(["planned","emergency"]),client:jl})]).clone().register(w.apiMetadata,{id:"OwnerSetupStart",description:"Card setups start at POST /owner/v1/cards."});_.SetupClaim=l.z.object({proof:l.z.string().clone().register(w.apiMetadata,{description:"A signature by the installation key over the setup id."})}).clone().register(w.apiMetadata,{id:"SetupClaim"});_.SetupClaimed=l.z.object({agent:_.Agent,installation_id:I.Id,wallet_context:l.z.lazy(()=>_.WalletSigningContext).nullable()}).clone().register(w.apiMetadata,{id:"SetupClaimed"});_.Grant=l.z.object({grant_id:I.Id,agent_id:I.Id,rail:I.Rail,version:l.z.number().int().min(1),mode:_.GrantMode,mode_changed_at:I.Timestamp.nullable(),mode_approval_id:I.Id.nullable().clone().register(w.apiMetadata,{description:"The autonomy_increase approval (current Console product-session consent) consumed by the last widening."}),terms:_.GrantTerms,approval_id:I.Id.clone().register(w.apiMetadata,{description:"The owner consent these terms sit inside."}),lifecycle:l.z.enum(["active","ended"]),end_reason:l.z.enum(["replaced","revoked","expired","agent_ended","owner_closed","recovered"]).nullable(),usage:l.z.object({period_used:I.Amount,period_started_at:I.Timestamp,period_booked:I.Amount.optional(),period_held:I.Amount.optional(),period_remaining:I.Amount.optional(),observed_at:I.Timestamp.optional(),budget_use:l.z.object({spent_pct:l.z.number().int().min(0).max(100),reserved_pct:l.z.number().int().min(0).max(100),used_pct:l.z.number().int().min(0).max(100),tone:l.z.enum(["normal","warning","critical"])}).optional()}).clone().register(w.apiMetadata,{description:"Current rolling usage counted by grant_id across versions. Booked debits plus unresolved holds consume room; refunds never restore it. Missing split facts mean unavailable, never zero. observed_at and period_started_at describe this read, not the creation of an earlier terms version."}),created_at:I.Timestamp,continuation:I.Continuation.nullable()}).clone().register(w.apiMetadata,{id:"Grant",description:"What one agent may spend on one rail. Narrower terms mint a version that keeps the existing consent; wider terms, a new rail, card or key need fresh consent; a mode change is in place."});_.GrantVersion=_.Grant.pick({grant_id:!0,agent_id:!0,rail:!0,version:!0,terms:!0,approval_id:!0,lifecycle:!0,end_reason:!0,created_at:!0}).extend({key_id:I.Id.nullable()}).clone().register(w.apiMetadata,{id:"GrantVersion",description:"Retained immutable terms and consent of an exact grant version, with its current lifecycle/end reason. No historical mode or usage is inferred."});_.GrantHistory=l.z.object({versions:l.z.array(_.GrantVersion).max(100),truncated:l.z.boolean(),next_cursor:l.z.string().nullable()}).clone().register(w.apiMetadata,{id:"GrantHistory"});_.GrantChange=l.z.object({grant:_.Grant,consent:l.z.enum(["kept","fresh_required"]).clone().register(w.apiMetadata,{description:"kept: the change sits inside what the owner already approved and applied at once. fresh_required: the owner must sign `challenge` first; nothing changed yet."}),challenge:_.Challenge.nullable()}).clone().register(w.apiMetadata,{id:"GrantChange"});_.PaymentTarget=l.z.discriminatedUnion("kind",[l.z.object({kind:l.z.literal("url"),url:l.z.url(),method:l.z.enum(["GET","POST"]).default("GET"),body:l.z.string().optional().clone().register(w.apiMetadata,{description:"Forwarded to the merchant in memory only. Visa stores no request content."})}),l.z.object({kind:l.z.literal("checkout"),merchant:l.z.string(),checkout_url:l.z.url(),amount:I.Amount,country:l.z.string().length(2).optional()})]).clone().register(w.apiMetadata,{id:"PaymentTarget",description:"url: an API that answers HTTP 402 with a Tempo charge (tempo rail). checkout: exact card checkout terms the host established independently (card rail)."});_.TempoChargeRequestWire=l.z.object({tempoTransaction:l.z.record(l.z.string(),l.z.unknown()),charge:l.z.object({chainId:l.z.number().int(),account:l.z.string(),token:l.z.string(),recipient:l.z.string(),amount:l.z.string().regex(/^(0|[1-9][0-9]*)$/),memo:l.z.string(),notAfter:l.z.number().int(),maxNetworkFee:l.z.string().regex(/^(0|[1-9][0-9]*)$/),funding:l.z.object({token:l.z.string(),maxAmount:l.z.string().regex(/^(0|[1-9][0-9]*)$/)}).optional()}),keyRef:l.z.object({subOrganizationId:l.z.string(),accessKeyAddress:l.z.string()})}).clone().register(w.apiMetadata,{id:"TempoChargeRequestWire",description:"Frozen wire: the Tempo charge request exactly as the signing enclave verifies it. Transaction commitments only, never merchant request or result content."});var yc=l.z.string().regex(/^0x(|[1-9a-f][0-9a-f]{0,63})$/),wi=l.z.string().regex(/^0x[0-9a-f]{40}$/),Nl=l.z.string().regex(/^(0|[1-9][0-9]{0,38})$/).refine(e=>BigInt(e)<1n<<128n);_.ApprovalReviewChargeRequest=l.z.strictObject({tempoTransaction:l.z.strictObject({chainId:l.z.literal(4217),maxPriorityFeePerGas:yc,maxFeePerGas:yc,gas:yc,calls:l.z.array(l.z.strictObject({to:wi,value:l.z.literal("0x"),data:l.z.string().regex(/^0x(?:[0-9a-f]{136}|[0-9a-f]{264}|[0-9a-f]{200})$/)})).min(1).max(3),accessList:l.z.tuple([]),nonceKey:yc,nonce:l.z.literal("0x"),validBefore:l.z.number().int().nonnegative().nullable(),validAfter:l.z.number().int().nonnegative().nullable(),feeToken:wi.nullable(),feePayer:l.z.boolean(),authorizationList:l.z.tuple([]),keyAuthorization:l.z.null()}),charge:l.z.strictObject({chainId:l.z.literal(4217),account:wi,token:wi,recipient:wi,amount:Nl,memo:l.z.string().regex(/^0x[0-9a-f]{64}$/),notAfter:l.z.number().int().positive(),maxNetworkFee:Nl,funding:l.z.strictObject({token:wi,maxAmount:Nl}).optional()}),keyRef:l.z.strictObject({subOrganizationId:I.Id,accessKeyAddress:wi})}).clone().register(w.apiMetadata,{id:"ApprovalReviewChargeRequest",description:"The original body-free unsigned Tempo charge, with only the existing canonical transaction/charge/custody fields. Independent wallet verification still checks selectors, charge equality, nonce, fee and time bounds; parsing does not reconstruct or authorize a transaction. Unknown nested fields refuse instead of being stripped."});_.PreparedCharge=l.z.object({request:_.TempoChargeRequestWire,merchant_origin:l.z.url(),method:l.z.enum(["GET","POST"]),endpoint_path:l.z.string().regex(/^\/[^?#]*$/).clone().register(w.apiMetadata,{description:"The path only: no query string."}),mpp:l.z.object({challenge_id:l.z.string().regex(/^[\x21-\x7e]{1,256}$/),realm:l.z.string().regex(/^[\x20-\x7e]{1,256}$/)}).clone().register(w.apiMetadata,{description:"The merchant\u2019s MPP challenge this charge answers (its id and realm). The charge\u2019s memo must be exactly MPP\u2019s anonymous attribution memo for them (hash prefixes only): nothing caller-chosen goes on chain."})}).clone().register(w.apiMetadata,{id:"PreparedCharge",description:"A Tempo charge the laptop prepared locally from the merchant\u2019s 402 using its wallet signing context. The server re-derives the terms and the signing payload from it and checks them against the grant; it never hands the laptop a payload to sign blind."});_.POP_INTENT_CLAIM="int";_.TapSignatureBasePayload=l.z.object({kind:l.z.literal("tap_signature_base"),method:l.z.string().regex(/^[A-Z]{1,16}$/),authority:l.z.string().min(1).max(255),path:l.z.string().regex(/^\/[^\n\r]{0,4095}$/),coveredComponents:l.z.array(l.z.string().min(1).max(64)).min(4).max(8),paymentHeaderName:l.z.enum(["payment-signature","x-payment","authorization"]),paymentHeaderValue:l.z.string().min(1).max(16384),contentDigest:l.z.string().max(256).optional(),created:l.z.number().int(),expires:l.z.number().int(),keyId:l.z.string().regex(/^[A-Za-z0-9_-]{43}$/),nonce:l.z.string().regex(/^[A-Za-z0-9+/]{43}=$/).clone().register(w.apiMetadata,{description:"32 random bytes, base64."}),tag:l.z.literal("agent-payer-auth"),signatureBase:l.z.string().min(1).max(32768)}).clone().register(w.apiMetadata,{id:"TapSignatureBasePayload",description:"The TAP signature base the agent sends the merchant, as the identity gate takes it (frozen wire, its field names). keyId is the agent\u2019s TAP key thumbprint (status `tap`). The gate signs only the base it rebuilds from these fields; expires \u2212 created is at most 480 s."});_.RuntimeAuthorization=l.z.object({pop_jwt:l.z.string().regex(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/).clone().register(w.apiMetadata,{description:'Compact JWS, typ visa-agent-pop+jwt, signed by the installation key (header kid = its JWK thumbprint, cnf.jwk = its public key). Claims: aud visa-tempo-mpp-payment:v1, nonce = the execution\u2019s wire_request_id (the verifier\u2019s financial request id), int = tempoPayIntentHash(financialRequestHash("wallet.tempo.mpp.sign", request), intent), iat within 120 s. A fresh one on every submission.'}),intent:l.z.record(l.z.string(),l.z.unknown()).clone().register(w.apiMetadata,{description:"The JSON object the proof commits to (at most 4 KiB). Forwarded to the verifier in memory and never stored."})}).clone().register(w.apiMetadata,{id:"RuntimeAuthorization"});_.PURCHASE_IDENTITY_FIELDS=["agent_id","request_id","rail","merchant_origin","method","endpoint_path","max"];_.ATTEMPT_TERMS_FIELDS=["amount","asset","funding_asset","recipient","funding_max","fee_ceiling","valid_before","signing_payload"];_.RETAINED_PAYMENT_FACTS=[..._.PURCHASE_IDENTITY_FIELDS,..._.ATTEMPT_TERMS_FIELDS,"state","delivery","network_ref","provider_evidence","timestamps"];var ch=l.z.uuid().clone().register(w.apiMetadata,{description:"Client-generated UUID for one execution: the verifier\u2019s financial request id and the PoP nonce. The same execution\u2019s retries reuse it; a replacement execution under the same request_id gets a new one."}),La={request_id:I.Id.clone().register(w.apiMetadata,{description:"Client idempotency key. New per purchase; unchanged on every later step. It fixes the purchase identity fields."}),agent_id:I.Id.optional().clone().register(w.apiMetadata,{description:"Needed only when the credential holds more than one agent."})},uh=l.z.string().min(1).max(200).optional().clone().register(w.apiMetadata,{description:"What the purchase is for, used only in this response\u2019s continuation (for the agent to relay at the approval moment). Never stored and never returned by a later read."});_.MerchantReceipt=l.z.object({kind:l.z.enum(["receipt","job_reference"]),value:l.z.string().min(1).max(512)}).clone().register(w.apiMetadata,{id:"MerchantReceipt",description:"What the caller kept from the merchant. Visa asks the merchant to verify it; Visa never keeps request content to compare against."});_.OriginalHostedPurchaseContext=l.z.strictObject({terms:l.z.strictObject({v:l.z.literal(1),resource:l.z.string().max(2048),method:l.z.enum(["GET","HEAD","POST","PUT","PATCH","DELETE"]),bodySha256:l.z.string().regex(/^[A-Za-z0-9_-]{43}$/).nullable(),maxAmountMicros:l.z.string(),recipient:l.z.string(),intent:l.z.record(l.z.string(),l.z.unknown())}),request:l.z.strictObject({method:l.z.enum(["GET","HEAD","POST","PUT","PATCH","DELETE"]),headers:l.z.array(l.z.tuple([l.z.string().refine(e=>/^(accept|accept-language|content-type|user-agent|x-[a-z0-9-]+)$/i.test(e)&&!/^(authorization|cookie|proxy-authorization|payment|x-payment|x-payment-response)$|auth|token|secret|key|session|cookie|signature|credential|password/i.test(e)),l.z.string().max(1024)])).max(32),bodyBase64:l.z.string().regex(/^[A-Za-z0-9+/=_-]*$/).nullable()})}).clone().register(w.apiMetadata,{id:"OriginalHostedPurchaseContext",description:"Original canonical Tempo v1 signing terms and transient public replay request. Consumers check the existing canonical verifier, actual body digest, authenticated purchase and original commitment. Configured private owner approval review may retain only supported exact signing context; other paths remain local/hash-only. Replay body and headers never enter retained state. Missing replay bytes cannot be reconstructed from hashes. Never put this context into URLs, logs or telemetry."});_.OwnerPreparedPayment=l.z.strictObject({ownerId:I.Id,agentId:I.Id,paymentId:I.Id,approvalId:I.Id,executionAttemptId:I.Id,requestedTerms:_.OriginalHostedPurchaseContext.shape.terms,terms:_.OriginalHostedPurchaseContext.shape.terms.extend({v:l.z.literal(2),runtimeId:I.Id,charge:l.z.strictObject({chainId:l.z.literal(4217),account:l.z.string(),accessKeyAddress:l.z.string(),token:l.z.string(),amountMicros:l.z.string().regex(/^[1-9][0-9]*$/),fundingToken:l.z.string().optional(),maxFundingMicros:l.z.string().regex(/^[1-9][0-9]*$/).optional(),memo:l.z.string(),notAfter:l.z.number().int().positive(),maxNetworkFee:l.z.string().regex(/^(0|[1-9][0-9]*)$/),signingHash:l.z.string()})}),request:_.ApprovalReviewChargeRequest,mppChallengeId:_.PreparedCharge.shape.mpp.shape.challenge_id,mppRealm:_.PreparedCharge.shape.mpp.shape.realm,signingInput:l.z.string().min(1),decisionExpiresAt:I.Timestamp}).clone().register(w.apiMetadata,{id:"OwnerPreparedPayment",description:"The original requested terms, exact approved charge and root-signing input from the existing owner approval producer. The client independently verifies these against its original context and current owner facts before signing. This response carries no HTTP replay body or headers. Public owner-approved paying remains paused."});_.ApprovalReviewDetail=l.z.strictObject({requestedTerms:_.OriginalHostedPurchaseContext.shape.terms,prepared:_.OwnerPreparedPayment.optional()}).clone().register(w.apiMetadata,{id:"ApprovalReviewDetail",description:"Private owner-scoped original signing context for the existing approval page. Retention is configurable, initially on; product capture never enables telemetry. No replay HTTP body/headers. Later reads preserve original record bindings and quote/decision expiry. Null detail means no available captured context, not a deletion or renewal claim."});_.PaymentCreate=l.z.discriminatedUnion("step",[l.z.object({step:l.z.literal("prepare"),...La,target:_.PaymentTarget,original:_.OriginalHostedPurchaseContext.optional(),max:I.Amount.clone().register(w.apiMetadata,{description:"Hard ceiling. Pricing without paying is a discover call."}),description:uh}),l.z.object({step:l.z.literal("admit"),...La,original:_.OriginalHostedPurchaseContext.optional(),wire_request_id:ch,charge:_.PreparedCharge,authorization:_.RuntimeAuthorization,max:I.Amount,replaces_attempt_id:I.Id.optional().clone().register(w.apiMetadata,{description:"A re-quote on the same purchase: allowed only once that attempt is closed with evidence it can no longer execute."}),description:uh}),l.z.object({step:l.z.literal("vote"),...La,attempt_id:I.Id.clone().register(w.apiMetadata,{description:"The exact attempt voted on; a vote for a closed attempt has no effect."}),vote:l.z.object({organization_id:l.z.string(),activity_id:l.z.string(),fingerprint:l.z.string(),voted_at:I.Timestamp})}),l.z.object({step:l.z.literal("resume"),...La,attempt_id:I.Id.optional().clone().register(w.apiMetadata,{description:"Laptop: the attempt being resumed."}),wire_request_id:ch.optional().clone().register(w.apiMetadata,{description:"Laptop: the same execution\u2019s wire id."}),charge:_.PreparedCharge.optional().clone().register(w.apiMetadata,{description:"Laptop: identical to the admitted charge."}),authorization:_.RuntimeAuthorization.optional().clone().register(w.apiMetadata,{description:"Laptop: a fresh proof for the same charge."}),target:_.PaymentTarget.optional().clone().register(w.apiMetadata,{description:"Hosted, before any credential was released: the request again. Visa kept no copy and never treats it as the original: the merchant\u2019s fresh charge must match the purchase\u2019s retained payment facts exactly."}),original:_.OriginalHostedPurchaseContext.optional()}),l.z.object({step:l.z.literal("recover"),...La,attempt_id:I.Id,receipt:_.MerchantReceipt.optional().clone().register(w.apiMetadata,{description:'Absent when the caller lost its state: the outcome is then "paid, result unavailable".'})})]).clone().register(w.apiMetadata,{id:"PaymentCreate",description:"prepare: hosted, the server runs the 402 exchange. admit: laptop, the agent submits its own prepared charge with its independent proof. vote: the laptop records its vote on one attempt\u2019s provider activity after verifying it. resume: continue after an approval, a vote, a crash or a lost response. recover: after a credential was released, get the result back only through the merchant (receipt or job reference); the credential is never re-sent."});_.SigningExchange=l.z.object({attempt_id:I.Id,wire_request_id:l.z.uuid().clone().register(w.apiMetadata,{description:"The execution\u2019s wire id; the PoP nonce for every retry of it."}),state:l.z.enum(["consensus_needed","signed","expired","refused"]),provider:l.z.literal("turnkey"),organization_id:l.z.string(),activity_id:l.z.string(),fingerprint:l.z.string(),sign_with:l.z.string().clone().register(w.apiMetadata,{description:"The wallet access key the activity signs with."}),valid_before:l.z.number().int(),signature:l.z.string().regex(/^0x[0-9a-f]{130}$/).nullable()}).clone().register(w.apiMetadata,{id:"SigningExchange",description:"The laptop co-signing exchange (two of two). The laptop reads the activity from the provider itself, recomputes the payload from its own prepared charge, checks signer, encoding, organisation and expiry, votes, then resumes. Nothing here is signed on the server\u2019s word."});_.Payment=l.z.object({id:I.Id,request_id:I.Id,agent_id:I.Id,rail:I.Rail,protocol:l.z.enum(["standard","atum"]).optional().clone().register(w.apiMetadata,{description:"How the wallet paid: standard (the merchant\u2019s Tempo charge, MPP) or atum (a native ATUM purchase). Receipts label it; the rail stays the funding rail."}),merchant:l.z.string().clone().register(w.apiMetadata,{description:"The merchant origin."}),method:l.z.enum(["GET","POST"]).nullable(),endpoint_path:l.z.string().nullable(),state:l.z.enum(I.PAYMENT_STATES),word:I.OwnerStatusWordSchema,money:I.PaymentMoney,facts:I.PaymentFacts,attempts:l.z.array(I.Attempt),signing:_.SigningExchange.nullable().clone().register(w.apiMetadata,{description:"Present while a laptop execution is being co-signed."}),approval_id:I.Id.nullable(),approval:l.z.object({id:I.Id,state:l.z.enum(["requested","approved","declined","expired"]),expires_at:l.z.string().datetime()}).nullable().optional().clone().register(w.apiMetadata,{description:"The persisted owner decision and its original deadline, when approval is needed."}),result:l.z.object({status:l.z.number().int(),content_type:l.z.string().nullable(),body_base64:l.z.string(),truncated:l.z.boolean().clone().register(w.apiMetadata,{description:"True when the merchant\u2019s answer was longer than the hosted limit (1 MB) and only its first part is in body_base64."})}).nullable().clone().register(w.apiMetadata,{description:"Hosted only: the merchant\u2019s answer, returned once in the response that executed the payment and never stored."}),created_at:I.Timestamp,updated_at:I.Timestamp,continuation:I.Continuation.nullable()}).clone().register(w.apiMetadata,{id:"Payment",description:'The stable purchase identity, described only by payment facts. A quote expiring during review keeps the same purchase; an unknown outcome is never reported as "nothing was paid".'});_.PaymentList=l.z.object({payments:l.z.array(_.Payment),page:I.Page}).clone().register(w.apiMetadata,{id:"PaymentList"});_.PaymentReport=l.z.object({wire_request_id:l.z.uuid().optional().clone().register(w.apiMetadata,{description:"Laptop: the execution being reported."}),network_ref:l.z.string().optional().clone().register(w.apiMetadata,{description:"Laptop: the transaction hash it submitted. Settlement is still read from the chain."}),delivery:l.z.enum(["delivered","unavailable"]).optional(),merchant_reference:l.z.string().max(200).optional(),authorization:l.z.object({pop_jwt:l.z.string().clone().register(w.apiMetadata,{description:"Laptop: compact JWS by the installation key, aud visa-tempo-mpp-report:v1, nonce = the execution\u2019s wire_request_id, int = tempoReportIntentHash(outcome, network_ref)."})}).optional()}).clone().register(w.apiMetadata,{id:"PaymentReport",description:"The agent reports what the merchant delivered. Payment facts are never inferred from it."});_.CardCredential=l.z.object({payment_id:I.Id,network_token:l.z.string(),expiry:l.z.string(),cryptogram:l.z.string(),bound_to:l.z.object({merchant:l.z.string(),expires_at:I.Timestamp})}).clone().register(w.apiMetadata,{id:"CardCredential",description:"A network token and cryptogram for one checkout, never the funding card. Suppressed at launch: how it reaches agents without entering model transcripts is open (decision P1)."});_.Approval=l.z.object({id:I.Id,kind:_.ApprovalKind,payment_id:I.Id.nullable().clone().register(w.apiMetadata,{description:"Set for kind payment."}),agent_id:I.Id.nullable(),subject:l.z.object({type:l.z.enum(["setup","grant","payment_attempt","agent_key","control","owner","agent"]),id:I.Id}),statement:l.z.string().clone().register(w.apiMetadata,{description:"The terms the owner signs (never request content)."}),state:l.z.enum(["requested","approved","declined","expired"]),rail:I.Rail.nullable().clone().register(w.apiMetadata,{description:"Set for kind payment and grant."}),amount:I.Amount.nullable().clone().register(w.apiMetadata,{description:"Set for kind payment."}),merchant:l.z.string().nullable().clone().register(w.apiMetadata,{description:"Set for kind payment."}),endpoint_path:l.z.string().nullable(),evidence:l.z.discriminatedUnion("method",[l.z.object({method:l.z.enum(["passkey","owner_jws"]),signature:l.z.string()}),l.z.object({method:l.z.enum(["email_code","owner_session"]),verification_ref:l.z.string().clone().register(w.apiMetadata,{description:"The verified consent\u2019s non-secret receipt or session/epoch reference; never a code or token."}),verified_at:I.Timestamp})]).nullable().clone().register(w.apiMetadata,{description:"Set once approved: how the owner consented. owner_session only for Console autonomy_increase consent; historical email_code receipts remain readable."}),consumed_at:I.Timestamp.nullable().clone().register(w.apiMetadata,{description:"When the consent was used; each approval is used once."}),expires_at:I.Timestamp,created_at:I.Timestamp}).clone().register(w.apiMetadata,{id:"Approval",description:"One owner consent of one kind (#10983 approvals). A payment approval is shown by its payment facts (no free-text purpose is kept). Controls are re-checked when the approval is consumed, not only when it is requested."});_.Wallet=l.z.object({state:l.z.enum(["disabled","enabling","enabled","disabling"]),address:l.z.string().nullable(),network:l.z.string().nullable(),balances:l.z.array(l.z.object({asset:I.Asset,micros:I.Micros,spendable:l.z.boolean()})),setup_fee_covered:l.z.boolean().nullable().optional().clone().register(w.apiMetadata,{description:"Authority confirms that the owner wallet covers the existing OUSD setup-fee reserve. null or absent: coverage is unknown, never permission to sign."}),other_tokens:l.z.array(l.z.object({contract_address:l.z.string(),symbol:l.z.string().nullable(),base_units:l.z.string(),decimals:l.z.number().int().nullable()})).clone().register(w.apiMetadata,{description:"Tokens held that cannot be spent here; each can be withdrawn."}),other_tokens_status:l.z.enum(["complete","unavailable"]).clone().register(w.apiMetadata,{description:"complete: other_tokens lists every other token held. unavailable: they could not be discovered, so other_tokens may be missing some (never read as nothing held)."}),readiness:I.Readiness}).clone().register(w.apiMetadata,{id:"Wallet"});_.Withdrawal=l.z.object({request_id:I.Id.clone().register(w.apiMetadata,{description:"Client key: repeating the same request_id returns the same withdrawal operation (after a lost response), never a second one."}),chain_id:l.z.number().int().optional().clone().register(w.apiMetadata,{description:"Default: the wallet\u2019s network."}),to_address:l.z.string().regex(/^0x[0-9a-fA-F]{40}$/),token:I.TokenRef.clone().register(w.apiMetadata,{description:"The exit for unsupported tokens: any token the wallet holds can be withdrawn, independent of what agents may spend."}),amount_base_units:l.z.string().regex(/^(0|[1-9][0-9]{0,77})$/).nullable().clone().register(w.apiMetadata,{description:"In the token\u2019s own base units. null withdraws the whole balance, dust included."})}).clone().register(w.apiMetadata,{id:"Withdrawal"});_.Card=l.z.object({id:I.Id,brand:l.z.string().nullable(),last4:l.z.string().length(4).nullable(),country:l.z.string().regex(/^[A-Z]{2}$/).nullable().clone().register(w.apiMetadata,{description:"Issuing country from the card BIN; null until the issuer attributes are read."}),state:l.z.enum(["collecting","verifying","active","removed","failed"]),is_default:l.z.boolean(),created_at:I.Timestamp}).clone().register(w.apiMetadata,{id:"Card",description:"The owner\u2019s enrolled card. Entered once; agents get grants, never per-agent cards."});_.CardEnrollment=l.z.object({card:_.Card,setup_id:I.Id.clone().register(w.apiMetadata,{description:"The setup of kind card that carries this enrollment."}),collect:l.z.object({vault_id:l.z.string(),environment:l.z.string(),form_token:l.z.string()}).clone().register(w.apiMetadata,{description:"Configuration for the VGS hosted fields. Card numbers never reach Visa servers. form_token is the card executor\u2019s Collect bearer for this setup."})}).clone().register(w.apiMetadata,{id:"CardEnrollment"});_.CardEnrollmentAlreadyStarted=l.z.object({card:_.Card,setup_id:I.Id,already_started:dh,message:fh}).clone().register(w.apiMetadata,{id:"CardEnrollmentAlreadyStarted",description:"This request_id already started this enrollment; the card is shown as it is now. The hosted-fields form_token is not stored or shown again: to enter the card, start a new enrollment (a new request_id), which opens a fresh form."});_.ActivityItem=l.z.object({id:I.Id,kind:l.z.enum(["payment","grant","agent","setup","security","operation"]),at:I.Timestamp,agent_id:I.Id.nullable(),title:l.z.string(),word:I.OwnerStatusWordSchema.nullable(),payment:_.Payment.nullable(),authority:l.z.object({action:l.z.string(),actor_kind:l.z.enum(["owner","agent","operator","server"]),subject_type:l.z.string().nullable(),subject_id:l.z.string().nullable(),outcome:l.z.enum(["succeeded","refused","failed"]),reason_code:l.z.string().nullable()}).optional().clone().register(w.apiMetadata,{description:"Actual retained audit metadata. It does not prove a grant version or confer permission."})}).clone().register(w.apiMetadata,{id:"ActivityItem"});_.ActivityList=l.z.object({items:l.z.array(_.ActivityItem),page:I.Page}).clone().register(w.apiMetadata,{id:"ActivityList"});_.SpendingState=l.z.object({state:l.z.enum(["open","stopped"]),changed_at:I.Timestamp.nullable(),continuation:I.Continuation.nullable()}).clone().register(w.apiMetadata,{id:"SpendingState",description:"The owner\u2019s stop-all switch. Stopping is immediate, from any owner session; reopening needs the current Console product owner session and CSRF protection. Withdrawals, export and cleanup continue while stopped."});_.Security=l.z.object({sessions:l.z.array(_.Session),events:l.z.array(l.z.object({at:I.Timestamp,kind:l.z.string(),detail:l.z.string(),actor:l.z.string(),agent_id:I.Id.nullable().optional().clone().register(w.apiMetadata,{description:"The agent the event is about, when it is about one."})})),devices:l.z.array(_.Device).optional().clone().register(w.apiMetadata,{description:"The phones registered for notifications, newest first (never their tokens): what the owner removes with owner.devices.remove."}),spending:_.SpendingState}).clone().register(w.apiMetadata,{id:"Security",description:"Read from the audit log; its reader is Authority. Events are the newest 100 security events only (sign-in, sign-in methods, agents and their keys, setups, limits, TAP, contact email, spending stop/reopen, recovery), so payments never crowd them out."});var QC=l.z.object({id:I.Id,kind:l.z.string(),title:l.z.string(),since:I.Timestamp});_.Console=l.z.object({owner:_.Owner.extend({eligibility:l.z.enum(["unchecked","eligible","ineligible"]).clone().register(w.apiMetadata,{description:"Stored US-card eligibility, established by eligible US card enrollment and VIC verification. Independent of admission and current card inventory; remains eligible after the last card is removed."})}),readiness:l.z.array(I.Readiness),agents:l.z.array(_.Agent).max(100),agents_page:l.z.object({truncated:l.z.boolean(),next_cursor:l.z.string().nullable()}).optional(),wallet:_.Wallet.nullable(),cards:l.z.array(_.Card),pending_approvals:l.z.number().int().min(0),needs_attention:l.z.array(QC),spending:_.SpendingState,payment_availability:l.z.object({tempo:l.z.object({setup_rail_enabled:l.z.boolean().clone().register(w.apiMetadata,{description:"Current Tempo rail switch; custody setup retains its own owner guards."}),admission_enabled:l.z.boolean().clone().register(w.apiMetadata,{description:"Spending admission and Tempo rail are enabled; each payment still checks its current guards."})}),selectable_modes:l.z.object({laptop:l.z.tuple([l.z.literal("ask_each_time"),l.z.literal("within_limit")]),hosted:l.z.tuple([l.z.literal("ask_each_time")])}).clone().register(w.apiMetadata,{description:"Modes the existing grant command can save, separately from executable payments."}),within_limit_available:l.z.object({laptop:l.z.object({tempo:l.z.boolean()}),hosted:l.z.object({tempo:l.z.literal(!1)})}).clone().register(w.apiMetadata,{description:"Shared payment-mode policy allows the mode; admission, stops and grant limits remain separate."}),owner_approved_payments:l.z.object({enabled:l.z.boolean(),reason:l.z.literal("owner_approved_payments_paused").nullable()}),card_payments:l.z.object({enabled:l.z.literal(!1),reason:l.z.literal("card_rail_not_built")})}).clone().register(w.apiMetadata,{description:"Current service and mode availability; wallet custody readiness is independent and this read never authorizes a payment."})}).clone().register(w.apiMetadata,{id:"Console",description:"The screen answer: everything the Console home needs in one read. The server decides what is allowed and what comes next."});_.WalletSigningContext=l.z.object({chain_id:l.z.number().int(),account_address:l.z.string().clone().register(w.apiMetadata,{description:"The owner wallet that pays (charge.account)."}),access_key_address:l.z.string(),access_key_public_key:l.z.string().clone().register(w.apiMetadata,{description:"Used by the transaction serializer; the laptop prepares charges with it."}),sub_organization_id:l.z.string().clone().register(w.apiMetadata,{description:"The provider organisation (keyRef.subOrganizationId)."}),key_generation:l.z.number().int().min(1),limit:I.Amount.clone().register(w.apiMetadata,{description:"The chain-enforced limit mirroring the grant."}),expires_at:I.Timestamp,swap_available:l.z.boolean()}).clone().register(w.apiMetadata,{id:"WalletSigningContext",description:"The current-generation wallet signing context of this installation, bound to its approved key and payer. Everything the laptop needs to prepare a charge before admission."});_.AgentStatus=l.z.object({agent:_.Agent.nullable(),installation_id:I.Id.nullable(),wallet_context:_.WalletSigningContext.nullable(),readiness:l.z.array(I.Readiness),min_cli_version:l.z.string(),renewal_due_at:I.Timestamp.nullable().optional().clone().register(w.apiMetadata,{description:"When the owner's spending renewal is due (the account's one date). From 7 days before it, tell the user once per cycle; after it, new payments refuse grant_required (renewal_required) until the owner renews in the Console. Status and cancellation keep working."}),continuation:I.Continuation.nullable()}).clone().register(w.apiMetadata,{id:"AgentStatus",description:"The live oracle for an agent: identity, every capability\u2019s rung and what comes next. Clients trust it over any document."});_.MerchantResult=l.z.object({results:l.z.array(l.z.object({name:l.z.string(),url:l.z.url(),description:l.z.string().nullable(),listed_price:I.Amount.nullable().clone().register(w.apiMetadata,{description:"Advisory; the payment re-prices."}),rails:l.z.array(I.Rail),method:l.z.enum(["GET","POST"]).optional(),request_format:l.z.enum(["json","query"]).optional().clone().register(w.apiMetadata,{description:"How the listed input is sent: JSON body or query."}),input:l.z.record(l.z.string(),l.z.unknown()).optional().clone().register(w.apiMetadata,{description:"The provider\u2019s declared input schema (advisory)."}),price_hint:l.z.string().optional().clone().register(w.apiMetadata,{description:"The listing\u2019s free-text price hint (advisory)."}),pricing_dynamic:l.z.boolean().optional(),service_id:l.z.string().optional()})),probe:l.z.object({url:l.z.url(),payable:l.z.boolean(),price:I.Amount.nullable(),rail:I.Rail.nullable()}).nullable()}).clone().register(w.apiMetadata,{id:"MerchantResult",description:"Read-only: searching and probing never spend."});_.ClientEvent=l.z.object({name:l.z.string().regex(/^[a-z][a-z0-9_.]*$/),at:I.Timestamp,attributes:l.z.record(l.z.string(),l.z.union([l.z.string(),l.z.number(),l.z.boolean()]))}).clone().register(w.apiMetadata,{id:"ClientEvent",description:"A closed-schema client event. Never secrets, keys, tokens, card data, passkey material, prompts or request content; filtered before every sink."});_.ToolDescriptor=l.z.object({name:l.z.string(),description:l.z.string(),input_schema:l.z.record(l.z.string(),l.z.unknown())}).clone().register(w.apiMetadata,{id:"ToolDescriptor"})});var gh=P(Se=>{"use strict";Object.defineProperty(Se,"__esModule",{value:!0});Se.ADMIN_OPERATIONS=Se.PolicyAuditEntry=Se.AuditEntry=Se.MerchantRule=Se.Control=Se.AdminUser=Se.AdminClosedAccount=Se.AdminOperation=void 0;var S=ct(),yt=Et(),eD=Pr(),ta=Si(),_e=Rt(),Ee=["operator_session"];Se.AdminOperation=_e.Operation.extend({owner_id:_e.Id.nullable(),agent_id:_e.Id.nullable(),due_at:_e.Timestamp,next_action:S.z.string().nullable(),waiting_on:S.z.string().nullable().clone().register(yt.apiMetadata,{description:"Why the operation last stopped (its error class), e.g. closure_awaiting_reconciliation."})}).clone().register(yt.apiMetadata,{id:"AdminOperation"});Se.AdminClosedAccount=S.z.object({owner_id:_e.Id,lifecycle:S.z.enum(["closing","closed"]),closed_at:_e.Timestamp.nullable(),closure:Se.AdminOperation.nullable(),wallet:ta.Wallet.nullable().clone().register(yt.apiMetadata,{description:"Read from the chain now; null when the read failed (never shown as empty)."}),wallet_status:S.z.enum(["read","unavailable","none"]),blockers:S.z.array(S.z.enum(["funds_remain","balance_unavailable","payments_unresolved","withdrawal_open","keys_not_cleared","holdings_unknown"])).clone().register(yt.apiMetadata,{description:"What a closing account still waits on, read now (empty once closed). Funds never hold closure: they stay the owner's exit obligation."})}).clone().register(yt.apiMetadata,{id:"AdminClosedAccount"});Se.AdminUser=ta.Owner.extend({login:S.z.string(),is_admin:S.z.boolean(),tags:S.z.array(S.z.string()),agents:S.z.number().int(),spent_24h_micros:_e.Micros.optional().clone().register(yt.apiMetadata,{description:"admin.users.get only: what the owner spent and holds against their operator limit in the last 24 hours."})}).clone().register(yt.apiMetadata,{id:"AdminUser"});Se.Control=S.z.object({key:S.z.string(),type:S.z.enum(["capability","spending_limit","agent_override","block"]),scope:S.z.enum(["global","owner","agent"]),subject:_e.Id.nullable(),value:S.z.union([S.z.boolean(),S.z.string()]).nullable().clone().register(yt.apiMetadata,{description:"null = absent (the typed default applies)."}),default_meaning:S.z.string().clone().register(yt.apiMetadata,{description:"capability: deny. spending_limit: zero spend. agent_override: inherit. block: not blocked."}),updated_at:_e.Timestamp.nullable(),updated_by:S.z.string().nullable()}).clone().register(yt.apiMetadata,{id:"Control",description:"A typed control with an explicit default. Precedence global \u2192 owner \u2192 agent; blocks always win; an outage fails closed. Every change is audited."});Se.MerchantRule=S.z.object({origin:S.z.string(),decision:S.z.enum(["allow","block","review"]),reason:S.z.string().max(500).nullable(),reason_code:S.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),updated_by:S.z.uuid().nullable(),updated_at:_e.Timestamp}).clone().register(yt.apiMetadata,{id:"MerchantRule"});Se.AuditEntry=S.z.object({id:_e.Id,at:_e.Timestamp,actor:S.z.string(),action:S.z.string(),subject:S.z.string().nullable(),detail:S.z.string(),actor_name:S.z.string().nullable().optional(),actor_email:S.z.string().nullable().optional(),owner_id:_e.Id.nullable().optional(),owner_name:S.z.string().nullable().optional(),owner_email:S.z.string().nullable().optional(),agent_id:_e.Id.nullable().optional(),control:S.z.object({key:S.z.string(),scope:S.z.enum(["global","owner","agent"]),agent_id:_e.Id.nullable(),enabled:S.z.boolean().nullable(),limit_micros:S.z.string().nullable()}).optional()}).clone().register(yt.apiMetadata,{id:"AuditEntry"});var ph=S.z.object({decision:S.z.enum(["allow","block","review"]),reason:S.z.string().nullable()}).nullable();Se.PolicyAuditEntry=Se.AuditEntry.extend({change:S.z.enum(["set","clear"]),before:ph,after:ph}).clone().register(yt.apiMetadata,{id:"PolicyAuditEntry"});var mh=S.z.object({login:S.z.string()});Se.ADMIN_OPERATIONS=(0,eD.defineOperations)([{id:"admin.session.start",backedBy:"edge",family:"admin",method:"POST",path:"/admin/v1/session",summary:"Open an operator session",description:"Needs an existing verified product owner session (never the exit session), its X-CSRF-Token, and current operator membership. No second sign-in assertion is required. Sets the visa_operator_session cookie (HttpOnly, Secure, SameSite=Strict, Path=/admin/v1); every admin write then sends X-CSRF-Token with the csrf_token answered here, and operator membership is re-checked on every request.",auth:["owner_session"],body:S.z.object({}).strict(),response:S.z.object({expires_at:_e.Timestamp,csrf_token:S.z.string()}),status:201,errors:["blocked","setup_required"],launch:"on"},{id:"admin.session.end",backedBy:"edge",family:"admin",method:"DELETE",path:"/admin/v1/session",summary:"Operator sign-out",auth:Ee,response:null,status:204,errors:[],launch:"on"},{id:"admin.users.list",family:"admin",method:"GET",path:"/admin/v1/users",summary:"List owners",auth:Ee,query:_e.PageQuery.extend({q:S.z.string().optional(),access:ta.Owner.shape.access.optional()}),response:S.z.object({users:S.z.array(Se.AdminUser),page:_e.Page}),status:200,errors:["setup_required"],launch:"on"},{id:"admin.users.get",family:"admin",method:"GET",path:"/admin/v1/users/:login",summary:"Read one owner",auth:Ee,params:mh,response:Se.AdminUser,status:200,errors:["setup_required","not_found"],launch:"on"},{id:"admin.users.update",family:"admin",method:"PATCH",path:"/admin/v1/users/:login",summary:"Change an owner\u2019s access, admin role or tags",description:"Granting admin needs a second admin\u2019s approval (admin requests).",auth:Ee,params:mh,body:S.z.object({access:ta.Owner.shape.access.optional(),is_admin:S.z.boolean().optional(),tags:S.z.array(S.z.string()).optional()}),response:Se.AdminUser,status:200,errors:["setup_required","not_found","conflict"],launch:"on"},{id:"admin.users.bulk",family:"admin",method:"POST",path:"/admin/v1/users/bulk",summary:"Approve or reject several owners",auth:Ee,body:S.z.object({logins:S.z.array(S.z.string()).min(1).max(200),access:S.z.enum(["approved","rejected"])}),response:S.z.object({updated:S.z.number().int()}),status:200,errors:["setup_required"],launch:"on"},{id:"admin.adminRequests.list",family:"admin",method:"GET",path:"/admin/v1/admin-requests",summary:"Pending two-admin grant requests",auth:Ee,response:S.z.object({requests:S.z.array(S.z.object({id:_e.Id,login:S.z.string(),requested_by:S.z.string(),at:_e.Timestamp}))}),status:200,errors:["setup_required"],launch:"on"},{id:"admin.controls.list",family:"admin",method:"GET",path:"/admin/v1/controls",summary:"Read every control (capabilities, limits, overrides, blocks, kill switch)",auth:Ee,query:S.z.object({scope:Se.Control.shape.scope.optional(),subject:_e.Id.optional()}),response:S.z.object({controls:S.z.array(Se.Control)}),status:200,errors:["setup_required"],launch:"on"},{id:"admin.controls.set",family:"admin",method:"PUT",path:"/admin/v1/controls/:key",summary:"Set or clear one control",description:"Setting value null makes the control absent, so its typed default applies. Stopping spending admission is the operator kill switch.",auth:Ee,params:S.z.object({key:S.z.string()}),body:S.z.object({scope:Se.Control.shape.scope,subject:_e.Id.nullable(),value:Se.Control.shape.value,reason:S.z.string().min(1)}),response:Se.Control,status:200,errors:["setup_required","not_found","conflict"],launch:"on"},{id:"admin.activation.request",family:"admin",method:"POST",path:"/admin/v1/activation",summary:"Ask to turn spending on after the rebuild (proposal 3)",description:"Creates the spending_activation approval, bound to this operator session and live for ten minutes. Only the named operator may (Dom, 8 Oct); the operator is the session, never the body, and no email code is asked. #10366: a passkey step-up and two-person approval are required before production.",auth:Ee,body:S.z.object({}).strict(),response:S.z.object({approval_id:_e.Id,expires_at:_e.Timestamp}),status:202,errors:["setup_required","blocked","invalid_request","conflict"],launch:"on"},{id:"admin.activation.approve",family:"admin",method:"POST",path:"/admin/v1/activation/:approvalId/approve",summary:"Approve the activation from the same session: spending opens, once",description:"Opens spending admission and the Tempo rail in one audited step, once. Only the operator session that asked approves (the approval records it as evidence operator_session). One operator for now (Dom, 8 Oct): the requester approves; #10366: a passkey step-up and two-person approval (approver not the requester, enforced) are required before production. Stopping and reopening are admin.controls.set.",auth:Ee,params:S.z.object({approvalId:_e.Id}),body:S.z.object({}).strict(),response:S.z.object({activated:S.z.enum(["now","already"]),approval_id:_e.Id}),status:200,errors:["setup_required","blocked","invalid_request","not_found","expired","conflict"],launch:"on"},{id:"admin.policy.defaults.get",backedBy:"policy",family:"admin",method:"GET",path:"/admin/v1/policy/defaults",summary:"Read Policy\u2019s default rules",auth:Ee,response:S.z.record(S.z.string(),S.z.unknown()),status:200,errors:["setup_required"],launch:"future"},{id:"admin.policy.defaults.set",backedBy:"policy",family:"admin",method:"PUT",path:"/admin/v1/policy/defaults",summary:"Replace Policy\u2019s default rules",auth:Ee,body:S.z.record(S.z.string(),S.z.unknown()),response:S.z.record(S.z.string(),S.z.unknown()),status:200,errors:["setup_required","conflict"],launch:"future"},{id:"admin.policy.merchants.list",backedBy:"policy",family:"admin",method:"GET",path:"/admin/v1/policy/merchants",summary:"List merchant rules",auth:Ee,query:S.z.object({after:S.z.string().optional()}),response:S.z.object({merchants:S.z.array(Se.MerchantRule),nextAfter:S.z.string().nullable()}),status:200,errors:["setup_required"],launch:"on"},{id:"admin.policy.merchants.set",backedBy:"policy",family:"admin",method:"PUT",path:"/admin/v1/policy/merchants/:origin",summary:"Set a merchant rule",auth:Ee,params:S.z.object({origin:S.z.string()}),body:Se.MerchantRule.pick({decision:!0,reason:!0}).partial({reason:!0}).strict(),response:Se.MerchantRule,status:200,errors:["setup_required"],launch:"on"},{id:"admin.policy.merchants.remove",backedBy:"policy",family:"admin",method:"DELETE",path:"/admin/v1/policy/merchants/:origin",summary:"Remove a merchant rule",auth:Ee,params:S.z.object({origin:S.z.string()}),response:null,status:204,errors:["setup_required","not_found"],launch:"on"},{id:"admin.policy.simulate",backedBy:"policy",family:"admin",method:"POST",path:"/admin/v1/policy/simulate",summary:"Simulate a Policy decision",auth:Ee,body:S.z.record(S.z.string(),S.z.unknown()),response:S.z.record(S.z.string(),S.z.unknown()),status:200,errors:["setup_required"],launch:"future"},{id:"admin.policy.audit",backedBy:"policy",family:"admin",method:"GET",path:"/admin/v1/policy/audit",summary:"Policy\u2019s rule-change history, each change with its before and after",auth:Ee,query:_e.PageQuery,response:S.z.object({entries:S.z.array(Se.PolicyAuditEntry),page:_e.Page}),status:200,errors:["setup_required"],launch:"on"},{id:"admin.policy.screening.status",backedBy:"policy",family:"admin",method:"GET",path:"/admin/v1/policy/screening",summary:"Whether wallet payees are being screened, its settings and the last day",auth:Ee,response:S.z.record(S.z.string(),S.z.unknown()),status:200,errors:["setup_required"],launch:"on"},{id:"admin.policy.screening.set",backedBy:"policy",family:"admin",method:"PUT",path:"/admin/v1/policy/screening",summary:"Turn screening enforcement on or off, or change its block level and reuse window",auth:Ee,body:S.z.object({required:S.z.boolean().optional(),blockLevel:S.z.union([S.z.literal(5),S.z.literal(10),S.z.literal(15)]).optional(),reuseSeconds:S.z.number().int().min(0).max(604800).optional()}),response:S.z.record(S.z.string(),S.z.unknown()),status:200,errors:["setup_required","conflict"],launch:"on"},{id:"admin.policy.screening.results",backedBy:"policy",family:"admin",method:"GET",path:"/admin/v1/policy/screening/results",summary:"The screening record: every payment, withdrawal and operator check",auth:Ee,query:S.z.object({outcome:S.z.enum(["allow","deny","unavailable","bypass"]).optional(),before:S.z.string().uuid().optional(),limit:S.z.coerce.number().int().min(1).max(500).optional(),scope:S.z.literal("traffic").optional()}),response:S.z.record(S.z.string(),S.z.unknown()),status:200,errors:["setup_required"],launch:"on"},{id:"admin.policy.screening.check",backedBy:"policy",family:"admin",method:"POST",path:"/admin/v1/policy/screening/check",summary:"What a payment to this address or merchant would meet now: the block list, then TRM; keeps nothing",auth:Ee,body:S.z.union([S.z.object({chainId:S.z.union([S.z.literal(4217),S.z.literal(8453)]),address:S.z.string()}),S.z.object({merchantUrl:S.z.string()})]),response:S.z.record(S.z.string(),S.z.unknown()),status:200,errors:["setup_required"],launch:"on"},{id:"admin.policy.screening.rescreen",backedBy:"policy",family:"admin",method:"POST",path:"/admin/v1/policy/screening/rescreen",summary:"Screen one address now and replace the answer payments reuse",auth:Ee,body:S.z.object({chainId:S.z.union([S.z.literal(4217),S.z.literal(8453)]),address:S.z.string()}),response:S.z.record(S.z.string(),S.z.unknown()),status:200,errors:["setup_required"],launch:"on"},{id:"admin.audit.list",family:"admin",method:"GET",path:"/admin/v1/audit",summary:"The append-only audit log",auth:Ee,query:_e.PageQuery.extend({subject:S.z.string().optional(),actor_kind:S.z.enum(["owner","agent","operator","server"]).optional()}),response:S.z.object({entries:S.z.array(Se.AuditEntry),page:_e.Page}),status:200,errors:["setup_required"],launch:"on"},{id:"admin.metrics.get",family:"admin",method:"GET",path:"/admin/v1/metrics",summary:"Operator metrics",auth:Ee,response:S.z.record(S.z.string(),S.z.number()),status:200,errors:["setup_required"],launch:"on"},{id:"admin.agents.list",family:"admin",method:"GET",path:"/admin/v1/agents",summary:"List agents across owners",auth:Ee,query:_e.PageQuery.extend({login:S.z.string().optional()}),response:S.z.object({agents:S.z.array(ta.Agent),page:_e.Page}),status:200,errors:["setup_required"],launch:"on"},{id:"admin.agents.tap",family:"admin",method:"POST",path:"/admin/v1/agents/:agentId/tap",summary:"Retry or reset an agent\u2019s TAP setup",description:"retry: clear the background job\u2019s backoff and list the agent\u2019s TAP key in the directory now. reset: end the TAP key at once (no TAP signature with it from then on), withdraw its directory entry through a provider_cleanup operation, and enroll and list a new one when the deployment can (otherwise the owner\u2019s finish_tap_setup step does). Never moves money. Every action is written to the audit log with the operator and the reason code. Contract proposal 29.",auth:Ee,params:S.z.object({agentId:_e.Id}),body:S.z.object({action:S.z.enum(["retry","reset"]),reason:S.z.enum(["stuck_publication","directory_conflict","owner_request","other"])}),response:ta.Agent,status:200,errors:["setup_required","invalid_request","not_found","agent_inactive","not_enabled"],launch:"on"},{id:"admin.operations.list",family:"admin",method:"GET",path:"/admin/v1/operations",summary:"Operations that need attention, across owners",description:"Stuck, overdue or unsafe operations, each with its owner, age, next action and evidence.",auth:Ee,query:_e.PageQuery.extend({needs_attention:S.z.enum(["true","false"]).optional()}),response:S.z.object({operations:S.z.array(Se.AdminOperation),page:_e.Page}),status:200,errors:["setup_required"],launch:"on"},{id:"admin.operations.resolve",family:"admin",method:"POST",path:"/admin/v1/operations/:id/resolve",summary:"Mark a stuck operation failed or succeeded, on proof",description:"Decision A4: operators never initiate, re-send, change or approve a payment, and there is no operator retry. Financial operations (withdrawal) take money proofs: mark_failed requires Authority to independently verify the bound transaction\u2019s reverted receipt; a missing report, pending receipt or chain outage cannot prove no money moved. mark_succeeded must name the bound transaction and is independently reconciled before success. Non-money operations (cleanup, closure, recovery, telemetry deletion) take removal proofs: mark_succeeded with proof the provider removal is confirmed, mark_failed with proof it was not done. A proof of the wrong kind for the operation is refused (invalid_request). Every resolution is written to the audit log with the operator and the evidence.",auth:Ee,params:S.z.object({id:_e.Id}),body:S.z.discriminatedUnion("resolution",[S.z.object({resolution:S.z.literal("mark_failed"),evidence:S.z.object({proves:S.z.enum(["no_money_moved","removal_not_done"]),ref:S.z.string().min(1).clone().register(yt.apiMetadata,{description:"Chain read, provider record or ticket that shows it."})})}),S.z.object({resolution:S.z.literal("mark_succeeded"),evidence:S.z.object({proves:S.z.enum(["money_moved","removal_confirmed"]),ref:S.z.string().min(1).clone().register(yt.apiMetadata,{description:"Transaction hash or provider record that shows it."})})})]),response:Se.AdminOperation,status:200,errors:["setup_required","not_found","conflict","unavailable"],launch:"on"},{id:"admin.payments.attention",family:"admin",method:"GET",path:"/admin/v1/payments/attention",summary:"Payments that need attention, across owners",description:"Purchases whose answer was lost, that are overdue to settle, or whose paid result did not arrive, oldest first. The reconciler resolves them from chain evidence; operators never act on a payment (decision A4), so this is a read.",auth:Ee,response:S.z.object({payments:S.z.array(S.z.object({payment_id:_e.Id,owner_id:_e.Id,agent_id:_e.Id,reason:S.z.enum(["outcome_unknown","overdue","paid_result_unavailable","paid_result_overdue"]),state:S.z.string(),age_seconds:S.z.number().int()})),truncated:S.z.boolean()}),status:200,errors:["setup_required"],launch:"on"},{id:"admin.closures.list",family:"admin",method:"GET",path:"/admin/v1/closures",summary:"Closing and closed accounts and the money they still hold",description:"The closed-account obligations list: every closing or closed account with a wallet, its closure operation and its balances read from the chain now. Funds stay the owner's to withdraw from the exit page; operators never move them.",auth:Ee,query:_e.PageQuery,response:S.z.object({accounts:S.z.array(Se.AdminClosedAccount),page:_e.Page}),status:200,errors:["setup_required"],launch:"on"},{id:"admin.db.query",family:"admin",method:"POST",path:"/admin/v1/db/query",summary:"Audited read-only SQL",auth:Ee,body:S.z.object({sql:S.z.string(),store:S.z.enum(["postgres","redis"]).optional()}),response:S.z.object({rows:S.z.array(S.z.record(S.z.string(),S.z.unknown())),truncated:S.z.boolean()}),status:200,errors:["setup_required","blocked"],launch:"on"}])});var vh=P(bc=>{"use strict";Object.defineProperty(bc,"__esModule",{value:!0});bc.AGENT_OPERATIONS=void 0;var fe=ct(),hh=Et(),tD=xa(),Ft=Pr(),rt=Si(),$i=Rt(),Rl=fe.z.object({id:$i.Id}),Cl=fe.z.object({id:$i.Id.clone().register(hh.apiMetadata,{description:"The agent's request_id for the payment (the key it always holds, even after a lost answer). Visa's payment id is not accepted here."})}),_h=["setup_required","update_required","agent_inactive","grant_required","limit_reached","owner_approval_required","owner_declined","blocked","merchant_unsupported","conflict","outcome_unknown","not_enabled"];bc.AGENT_OPERATIONS=(0,Ft.defineOperations)([...tD.NATIVE_FINANCIAL_OPERATIONS,{id:"agent.status.get",family:"agent",method:"GET",path:"/agent/v1/status",summary:"Identity, readiness and what comes next",auth:Ft.AGENT_AUTH,response:rt.AgentStatus,status:200,errors:["setup_required","update_required"],launch:"on"},{id:"agent.token.create",family:"agent",method:"POST",path:"/agent/v1/token",summary:"Exchange an installation-key proof for a short access token",description:"Exchange a request signed by an active laptop installation key for an agent access token. Hosted agents use OAuth or an owner-issued app token. A CLI session is not an agent token.",auth:["agent_signature"],body:fe.z.object({audience:fe.z.string().optional()}),response:fe.z.object({access_token:fe.z.string(),expires_at:$i.Timestamp}),status:201,errors:["setup_required","update_required","agent_inactive"],launch:"on"},{id:"agent.setups.start",family:"agent",method:"POST",path:"/agent/v1/setups",summary:"Start (or resume) a laptop setup",description:"Returns the owner link and short code. Repeating the same start resumes an interrupted setup. Hosted agents are set up by OAuth, not here.",auth:["none"],body:rt.AgentSetupStart,response:rt.AgentSetupStarted,status:201,errors:["update_required","conflict","blocked"],launch:"on"},{id:"agent.setups.get",family:"agent",method:"GET",path:"/agent/v1/setups/:id",summary:"Poll a setup",auth:["setup_secret"],params:Rl,response:rt.Setup,status:200,errors:["not_found","expired"],launch:"on"},{id:"agent.setups.claim",family:"agent",method:"POST",path:"/agent/v1/setups/:id/claim",summary:"Claim an approved setup with the installation key",auth:["setup_secret"],params:Rl,body:rt.SetupClaim,response:rt.SetupClaimed,status:200,errors:["not_found","expired","owner_approval_required","owner_declined","conflict"],launch:"on"},{id:"agent.keys.lease",family:"agent",method:"POST",path:"/agent/v1/keys/lease",summary:"Lease the installation for one operation",description:"Today the only operation is `tap_signature_base`: a `visa-agent-runtime-lease+jwt` (at most 120 s) from Authority\u2019s identity lease issuer, for this installation\u2019s TAP authority (contract proposal 28). The agent presents it to agent.keys.tapSign.",auth:["agent_signature","agent_token"],body:fe.z.object({operation:fe.z.literal("tap_signature_base"),request_id:$i.Id}),response:fe.z.object({lease:fe.z.string(),expires_at:$i.Timestamp}),status:201,errors:["setup_required","update_required","agent_inactive","not_enabled"],launch:"on"},{id:"agent.keys.tapSign",family:"agent",method:"POST",path:"/agent/v1/keys/tap-sign",summary:"Sign a merchant request with the agent\u2019s TAP key",description:"The identity gate signs the agent\u2019s TAP signature base (contract proposal 28). request_id is a new UUID per signature (the gate refuses a replay). authorization.lease comes from agent.keys.lease; authorization.pop_jwt is the installation key\u2019s proof: typ visa-agent-pop+jwt, aud urn:visa:tvc:identity-gate, nonce = request_id, int = the payload digest (identityTapPayloadSha256), at most 60 s old. The answer\u2019s signature_input and signature are the Signature-Input and Signature header values (label sig2).",auth:["agent_signature","agent_token"],body:fe.z.object({request_id:fe.z.uuid(),payload:rt.TapSignatureBasePayload,authorization:fe.z.object({lease:fe.z.string(),pop_jwt:fe.z.string()})}),response:fe.z.object({signature:fe.z.string(),signature_input:fe.z.string(),key_id:fe.z.string()}),status:200,errors:["setup_required","update_required","agent_inactive","not_enabled","expired","unavailable"],launch:"on"},{id:"agent.keys.reissue",family:"agent",method:"POST",path:"/agent/v1/keys/reissue",summary:"Pick up an owner-approved key re-issue (#10945)",auth:["agent_signature"],body:fe.z.object({installation_key:fe.z.record(fe.z.string(),fe.z.unknown()),proof:fe.z.string()}),response:fe.z.object({installation_id:$i.Id,key_generation:fe.z.number().int()}),status:200,errors:["setup_required","update_required","agent_inactive","owner_approval_required"],launch:"future"},{id:"agent.payments.create",family:"agent",method:"POST",path:"/agent/v1/payments",summary:"Create, co-sign, resume or recover a purchase",description:'One purchase, several steps, all under the same request_id (purchase identity: PURCHASE_IDENTITY_FIELDS; a different value under the same request_id is a conflict). Hosted (prepare): every payment first answers owner_approval_required (A2: the owner approves each connector payment at launch, whatever the grant mode or controls; ownerApprovalRequired); after approval the server runs the 402 exchange and returns the merchant result once. Laptop (admit \u2192 vote \u2192 resume): the laptop prepares the charge itself from its wallet signing context (agent.status.get), picks a new wire_request_id for this execution, and sends both with its independent proof (RuntimeAuthorization, nonce = wire_request_id); retries of the same execution reuse its wire_request_id, a replacement execution picks a new one under the same request_id; the server adds the delegation, lease and root key, admits it against the grant and controls, commits the attempt and its signing hash before contacting the provider (pre-dispatch fence), and answers with a signing exchange; the laptop verifies and votes directly with the provider on that attempt, records the vote, then resumes with the identical charge and a fresh proof to receive the signature. Recovery: repeating a step with the same request_id and identical terms returns the same attempt; a lost provider response is found again by reading the provider for the exact signing payload, otherwise the attempt stays fenced as unknown (dispatchRecovery). Time alone never closes a signed attempt: it stays fenced until a landed transaction settles it or finalized non-landing or a provider void closes it (executionDecision); only then may admit name it in replaces_attempt_id for a re-quote, which needs fresh consent above the consented terms. Hosted, after a credential was released, the credential is never re-sent: recover asks the merchant to verify the caller\u2019s receipt or job reference, otherwise the outcome is "paid, result unavailable" (hostedResumeDecision). Ask-each-time or over the limit: owner_approval_required, then resume. Spending switched off: the operator kill switch answers not_enabled (spending_admission_off); the owner\u2019s stop-all answers blocked (owner_spending_stopped).',auth:Ft.AGENT_AUTH,body:rt.PaymentCreate,response:rt.Payment,status:200,idempotency:"request_id",controls:["spending_admission"],errors:_h,launch:"on"},{id:"agent.payments.list",family:"agent",method:"GET",path:"/agent/v1/payments",summary:"This agent\u2019s purchases, newest first",auth:Ft.AGENT_AUTH,query:$i.PageQuery,response:rt.PaymentList,status:200,errors:["setup_required","update_required"],launch:"on"},{id:"agent.payments.get",family:"agent",method:"GET",path:"/agent/v1/payments/:id",summary:"Read a purchase, optionally waiting for it to change",description:"With `wait` (seconds, at most 30) the answer comes as soon as the purchase changes (its state or updated_at), or at the deadline with it unchanged: compare updated_at to tell which. A resolved purchase answers at once. Use it instead of polling in a loop, for example while the owner approves.",auth:Ft.AGENT_AUTH,params:Cl,query:fe.z.object({wait:fe.z.coerce.number().int().min(0).max(30).optional()}),response:rt.Payment,status:200,errors:["setup_required","update_required","not_found"],launch:"on"},{id:"agent.payments.cancel",family:"agent",method:"POST",path:"/agent/v1/payments/:id/cancel",summary:"Cancel a purchase that has not executed",auth:Ft.AGENT_AUTH,params:Cl,response:rt.Payment,status:200,errors:["setup_required","update_required","not_found","conflict","outcome_unknown"],launch:"on"},{id:"agent.payments.report",family:"agent",method:"POST",path:"/agent/v1/payments/:id/report",summary:"Report what the merchant delivered",auth:Ft.AGENT_AUTH,params:Cl,body:rt.PaymentReport,response:rt.Payment,status:200,errors:["setup_required","update_required","not_found","conflict"],launch:"on"},{id:"agent.payments.credential",family:"agent",method:"POST",path:"/agent/v1/payments/:id/credential",summary:"Deliver the card credential for an admitted card purchase",description:"Future, not in the launch build (A1 cut card paying; enrollment, IDV and TAP stay). Before it returns: the testers\u2019 CLI drained and the floor raised, existing card records resolved, enrollment and TAP proven on real Postgres, the code saved on a tagged branch, and the credential-delivery decision (P1). Then: an unsupported card host is refused before any credential is issued.",auth:Ft.AGENT_AUTH,params:Rl,body:fe.z.object({host:fe.z.string().clone().register(hh.apiMetadata,{description:"The agent host, checked against the card host support matrix."})}),response:rt.CardCredential,status:200,controls:["card_payments_enabled","spending_admission"],errors:["setup_required","update_required","not_found","not_enabled","expired","outcome_unknown","merchant_unsupported"],launch:"future"},{id:"agent.merchants.search",family:"agent",method:"GET",path:"/agent/v1/merchants",summary:"Search paid services, or probe one target\u2019s live terms",description:"Read-only: signs and spends nothing. Listed prices are advisory.",auth:Ft.AGENT_AUTH,query:fe.z.object({q:fe.z.string().optional(),target:fe.z.url().optional(),limit:fe.z.coerce.number().int().min(1).max(50).optional()}),response:rt.MerchantResult,status:200,errors:["setup_required","update_required","unavailable"],launch:"on"},{id:"agent.events.create",backedBy:"edge",family:"agent",method:"POST",path:"/agent/v1/events",summary:"Send closed-schema client events",auth:[...Ft.AGENT_AUTH,"none"],body:fe.z.object({events:fe.z.array(rt.ClientEvent).max(50)}),response:null,status:204,errors:[],launch:"on"},{id:"agent.tools.list",backedBy:"edge",family:"agent",method:"GET",path:"/agent/v1/tools",summary:"The MCP tool catalogue, for REST apps",auth:Ft.AGENT_AUTH,response:fe.z.object({tools:fe.z.array(rt.ToolDescriptor)}),status:200,errors:["setup_required"],launch:"on"},{id:"agent.tools.call",family:"agent",method:"POST",path:"/agent/v1/tools/:name",summary:"Call one MCP tool over REST",auth:Ft.AGENT_AUTH,params:fe.z.object({name:fe.z.string()}),body:fe.z.record(fe.z.string(),fe.z.unknown()),response:fe.z.record(fe.z.string(),fe.z.unknown()),status:200,errors:[..._h,"not_found"],launch:"on"}])});var wh=P(Sc=>{"use strict";Object.defineProperty(Sc,"__esModule",{value:!0});Sc.OWNER_OPERATIONS=void 0;var yh=xa(),R=ct(),Ge=Et(),nD=Pr(),G=Si(),ye=Rt(),bh=ye.Id.clone().register(Ge.apiMetadata,{description:"Client-generated retry key, one per owner action: repeating it never creates a second one."}),Dl=ye.Operation.extend({hosted_setup_recovery:G.HostedSetupRecovery.nullable().optional(),withdrawal_transaction:G.WithdrawalTransaction.nullable().optional(),wallet_key_authorization:G.WalletKeyAuthorizationResume.nullable().optional()}),Be=["owner_session"],Ae=["owner_session","owner_exit_session"],na=R.z.object({agentId:ye.Id}),lt=R.z.object({id:ye.Id}),wc=e=>R.z.object({resource:e,challenge:G.Challenge});Sc.OWNER_OPERATIONS=(0,nD.defineOperations)([{id:"owner.session.start",backedBy:"edge",family:"owner",method:"POST",path:"/owner/v1/session",summary:"Start owner sign-in",description:"Begins Turnkey sign-in and the entry gate (Visa identity plus legal geo-blocking). Returns the challenge to complete at /owner/v1/session/verify.",auth:["none"],body:R.z.object({email:R.z.email().optional(),return_to:R.z.string().optional()}),response:R.z.object({challenge:G.Challenge,terms:R.z.object({bundle_version:R.z.string().regex(/^[0-9]{4}-[0-9]{2}-[0-9]{2}(\.[0-9]+)?$/).clone().register(Ge.apiMetadata,{description:"The legal bundle (Terms of Service and Privacy Notice) the owner accepts."}),terms_path:R.z.string().regex(/^\/legal\/[a-z-]+$/).clone().register(Ge.apiMetadata,{description:"The Terms of Service page, on this API\u2019s own origin."}),privacy_path:R.z.string().regex(/^\/legal\/[a-z-]+$/).clone().register(Ge.apiMetadata,{description:"The Privacy Notice page, on this API\u2019s own origin."})}).clone().register(Ge.apiMetadata,{description:"What signing in accepts; the owner must see both links before verify."})}),status:202,errors:["blocked","not_enabled"],launch:"on"},{id:"owner.session.verify",backedBy:"edge",family:"owner",method:"POST",path:"/owner/v1/session/verify",summary:"Complete owner sign-in",description:"One Turnkey user is one owner, whichever of its sign-in methods (email code, Google, passkey) proved it: owners are keyed by the Turnkey user, never by an email. Refuses invalid_request (terms_acceptance_required) unless accepted_terms names the current legal bundle.",auth:["none"],body:R.z.object({challenge_id:ye.Id,assertion:R.z.string(),accepted_terms:R.z.string().clone().register(Ge.apiMetadata,{description:"The terms.bundle_version from owner.session.start, sent only when the owner accepted it. Required on every sign-in; recorded once per owner and version."}),identity_token:R.z.string().max(8192).optional().clone().register(Ge.apiMetadata,{description:"The Google or Apple ID token of this sign-in, when it used one. Believed only when its signature checks against the provider's published keys and its account is one the signing-in Turnkey user holds; then the owner's name, verified email and Google photo are recorded (a name the owner set is kept). Never required: a sign-in without it, or with one that does not check, proceeds unchanged."})}),response:R.z.object({session:G.Session,owner:G.Owner,csrf_token:R.z.string().clone().register(Ge.apiMetadata,{description:"Send it as the X-CSRF-Token header on every owner write in this session."}),signer:G.SessionSigner.nullable().optional().clone().register(Ge.apiMetadata,{description:"Who may sign for the owner in this session (INT-3). Absent: not yet named."})}),status:201,errors:["expired","blocked"],launch:"on"},{id:"owner.session.get",backedBy:"edge",family:"owner",method:"GET",path:"/owner/v1/session",summary:"Read the current session",auth:Ae,response:R.z.object({session:G.Session,owner:G.Owner,csrf_token:R.z.string().clone().register(Ge.apiMetadata,{description:"Send it as the X-CSRF-Token header on every owner write in this session."}),signer:G.SessionSigner.nullable().optional().clone().register(Ge.apiMetadata,{description:"Who may sign for the owner in this session (INT-3). Absent: not yet named."})}),status:200,errors:["setup_required"],launch:"on"},{id:"owner.session.end",backedBy:"edge",family:"owner",method:"DELETE",path:"/owner/v1/session",summary:"Sign out",auth:Ae,response:null,status:204,errors:[],launch:"on"},{id:"owner.sessions.list",backedBy:"edge",family:"owner",method:"GET",path:"/owner/v1/sessions",summary:"List the owner\u2019s signed-in sessions",auth:Be,response:R.z.object({sessions:R.z.array(G.Session)}),status:200,errors:["setup_required"],launch:"on"},{id:"owner.sessions.revoke",backedBy:"edge",family:"owner",method:"DELETE",path:"/owner/v1/sessions/:id",summary:"Revoke one session",auth:Be,params:lt,response:null,status:204,errors:["setup_required","not_found"],launch:"on"},{id:"owner.console.get",family:"owner",method:"GET",path:"/owner/v1/console",summary:"The Console screen answer",description:"One read for the Console home: readiness ladder per capability, agents, wallet, cards, pending approvals, needs-attention items and the stop-all state.",auth:Ae,response:G.Console,status:200,errors:["setup_required"],launch:"on"},{id:"owner.agents.list",family:"owner",method:"GET",path:"/owner/v1/agents",summary:"List agents",auth:Ae,query:R.z.object({section:R.z.enum(["live","ended"]).optional(),...ye.PageQuery.shape}),description:"Live agents by default, including ending agents. The ended section preserves owner history. Each page is bounded to 100 with deterministic ordering and server-projected per-rail grant facts. Cursor pagination: pass next_cursor back as cursor (with the same section); null on the last page.",response:ye.Page.extend({agents:R.z.array(G.Agent).max(100),truncated:R.z.boolean().optional()}),status:200,errors:["setup_required"],launch:"on"},{id:"owner.agents.get",family:"owner",method:"GET",path:"/owner/v1/agents/:agentId",summary:"Read one agent",auth:Ae,params:na,query:R.z.object({history_cursor:R.z.string().optional(),history_limit:R.z.coerce.number().int().min(1).max(100).optional()}),description:"Includes ended agents and a bounded exact grant terms history page, newest first; pass grant_history.next_cursor back as history_cursor for the next page. History is retained evidence, never active authority.",response:G.Agent,status:200,errors:["setup_required","not_found"],launch:"on"},{id:"owner.agents.update",family:"owner",method:"PATCH",path:"/owner/v1/agents/:agentId",summary:"Rename, pause or resume an agent",description:"Pausing blocks new admissions at once; resuming re-checks the current controls.",auth:Be,params:na,body:G.AgentPatch,response:G.Agent,status:200,errors:["setup_required","not_found","conflict"],launch:"on"},{id:"owner.agents.revoke",family:"owner",method:"DELETE",path:"/owner/v1/agents/:agentId",summary:"Revoke an agent",description:"New admissions stop at once. Signed admissions already issued live at most 60 s at SlipGate (a frozen verifier limit). Submitted money settles or reconciles; provider credentials and directory entries are cleaned up by a revocation_teardown operation.",auth:Ae,params:na,response:R.z.object({agent:G.Agent,operation:ye.Operation}),status:202,errors:["setup_required","not_found"],launch:"on"},{id:"owner.agents.reissue",family:"owner",method:"POST",path:"/owner/v1/agents/:agentId/reissue",summary:"Replace an agent\u2019s installation key (upgrade, planned or emergency)",description:"upgrade (#10945) and planned: a replacement setup the owner signs; the old generation ends when the new installation activates. emergency (device lost): the old installation\u2019s keys end immediately in this request, before any new device exists, and new admissions are refused from then on; the agent stays active with no usable key until the replacement setup completes. Admissions signed before it can still be honoured for up to 60 s at SlipGate, and money already submitted settles or reconciles. Agent identity and grants are kept in every case.",auth:Be,params:na,body:R.z.object({reason:R.z.enum(["upgrade","planned","emergency"])}),response:R.z.object({agent:G.Agent,setup:G.Setup,challenge:G.Challenge}),status:202,variants:[{status:200,description:"emergency: the old keys are already ended; the replacement setup is open.",response:R.z.object({agent:G.Agent,ended_installation_id:ye.Id,keys_ended_at:ye.Timestamp,admissions_honoured_until:ye.Timestamp.clone().register(Ge.apiMetadata,{description:"At most 60 s after keys_ended_at."}),setup:G.Setup})}],signed:!0,errors:["setup_required","not_found","agent_inactive"],launch:"on"},{id:"owner.tokens.list",family:"owner",method:"GET",path:"/owner/v1/agents/:agentId/tokens",summary:"List an agent\u2019s app tokens",description:"OWNER_OR_EXIT (decided 8 Oct, 10a): a leaving owner can list and then revoke every token of an app (owner.tokens.revoke), so disconnecting an app needs no extra operation.",auth:Ae,params:na,response:R.z.object({tokens:R.z.array(G.AgentToken)}),status:200,errors:["setup_required","not_found"],launch:"on"},{id:"owner.tokens.create",family:"owner",method:"POST",path:"/owner/v1/agents/:agentId/tokens",summary:"Mint an app token for an agent",description:"Send a request_id to retry safely: the same request_id never mints a second token; it answers 200 with the token it created (no secret, which is shown once and never stored) and says to revoke and create again if the secret was lost. The same request_id with a different app is a conflict. Without a request_id, minting again ends the agent\u2019s earlier token for that app.",auth:Be,params:na,body:R.z.object({app:R.z.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/).optional().clone().register(Ge.apiMetadata,{description:"The app or harness the token is for. The label is server-assigned from it."}),request_id:bh.optional()}),response:G.AgentTokenCreated,status:201,variants:[{status:200,description:"A retry with the same request_id: the token it already created, without the secret.",response:G.AgentTokenAlreadyCreated}],idempotency:"request_id",errors:["setup_required","not_found","agent_inactive"],launch:"on"},{id:"owner.tokens.revoke",family:"owner",method:"DELETE",path:"/owner/v1/agents/:agentId/tokens/:keyId",summary:"Revoke an app token",auth:Ae,params:R.z.object({agentId:ye.Id,keyId:ye.Id}),response:null,status:204,errors:["setup_required","not_found"],launch:"on"},{id:"owner.setups.start",family:"owner",method:"POST",path:"/owner/v1/setups",summary:"Start a setup from the Console",description:"Laptop: returns the one command the owner pastes; the terminal joins with the setup key. Hosted: returns the connector link.",auth:Be,body:G.OwnerSetupStart,idempotency:"request_id",response:R.z.object({setup:G.Setup,setup_key:R.z.string()}),status:201,errors:["setup_required","blocked","conflict","not_found","agent_inactive"],launch:"on"},{id:"owner.setups.get",family:"owner",method:"GET",path:"/owner/v1/setups/:id",summary:"Read a setup",auth:Be,params:lt,response:G.Setup,status:200,errors:["setup_required","not_found"],launch:"on"},{id:"owner.setups.approve",family:"owner",method:"POST",path:"/owner/v1/setups/:id/approve",summary:"Approve a setup and its first grant",auth:Be,params:lt,body:R.z.object({code:R.z.string(),grants:R.z.array(G.GrantRequest)}),response:wc(G.Setup),status:202,signed:!0,errors:["setup_required","not_found","expired","conflict"],launch:"on"},{id:"owner.setups.decline",family:"owner",method:"POST",path:"/owner/v1/setups/:id/decline",summary:"Decline a setup",auth:Be,params:lt,response:G.Setup,status:200,errors:["setup_required","not_found","expired"],launch:"on"},{id:"owner.grants.get",family:"owner",method:"GET",path:"/owner/v1/agents/:agentId/grants/:rail",summary:"Read an agent\u2019s current grant on one rail",auth:Ae,params:R.z.object({agentId:ye.Id,rail:ye.Rail}),query:R.z.object({grant_id:ye.Id.optional().clone().register(Ge.apiMetadata,{description:"An exact retained grant identity; combine with version to read its immutable terms without choosing a successor."}),version:R.z.coerce.number().int().min(1).optional().clone().register(Ge.apiMetadata,{description:"An immutable terms version. Supply grant_id to disambiguate earlier identities after an ended grant is replaced. Usage and mode on Grant are current read facts, not historical snapshots."})}),response:G.Grant,status:200,errors:["setup_required","not_found"],launch:"on"},{id:"owner.grants.replace",family:"owner",method:"PUT",path:"/owner/v1/agents/:agentId/grants/:rail",summary:"Change a grant\u2019s terms (a new version)",description:"Lower limits or an earlier expiry: a new version that keeps the existing consent, applied at once (200). Higher limits, a later expiry, another period, a first grant on this rail, or a new card or key: fresh consent (202 with a challenge); nothing changes until it is signed. Usage carries across versions. A hosted agent\u2019s grant is always ask_each_time at launch (A2). Card grants are not in the launch build (A1).",auth:Be,params:R.z.object({agentId:ye.Id,rail:ye.Rail}),body:R.z.object({terms:G.GrantTerms,mode:G.GrantMode.optional().clone().register(Ge.apiMetadata,{description:"First grant only."})}),response:G.GrantChange,status:202,variants:[{status:200,description:"Narrower terms: applied with the existing consent.",response:G.GrantChange}],signed:!0,errors:["setup_required","not_found","agent_inactive","not_enabled"],launch:"on"},{id:"owner.grants.setMode",family:"owner",method:"PATCH",path:"/owner/v1/agents/:agentId/grants/:rail",summary:"Switch within_limit \u21C4 ask_each_time in place",description:"The required grant_id and version name the displayed grant whose terms the owner intends to change. Authority checks that exact grant/version for this owner, agent and rail under the owner lock before any consent or mutation; stale intent refuses conflict. Not a new version: the grant version, its consent and its usage are kept. Narrowing (to ask_each_time) applies at once (200). Widening (to within_limit) is a Console button action from the current product owner session with CSRF protection. It applies at once (200), recording and consuming an autonomy_increase consent; no email code or additional credential. Agent/CLI credentials and exit sessions cannot widen. Hosted agents cannot be widened at launch (A2): every hosted payment needs the owner\u2019s approval until a connector-side signing key exists, so widening a hosted agent is refused (not_enabled, hosted_autonomy_unsupported).",auth:Be,params:R.z.object({agentId:ye.Id,rail:ye.Rail}),body:R.z.object({mode:G.GrantMode,grant_id:ye.Id.clone().register(Ge.apiMetadata,{description:"The displayed Grant.grant_id whose terms the owner intends to change."}),version:R.z.number().int().min(1).max(Number.MAX_SAFE_INTEGER).clone().register(Ge.apiMetadata,{description:"The displayed Grant.version; must still be current at the effect boundary."})}),response:G.GrantChange,status:200,signed:!0,errors:["setup_required","not_found","agent_inactive","not_enabled","conflict"],launch:"on"},{id:"owner.approvals.list",family:"owner",method:"GET",path:"/owner/v1/approvals",summary:"List approvals waiting for the owner",auth:Be,query:ye.PageQuery.extend({state:R.z.enum(["requested","all"]).optional()}),response:R.z.object({approvals:R.z.array(G.Approval),page:ye.Page}),status:200,errors:["setup_required"],launch:"on"},{id:"owner.approvals.get",family:"owner",method:"GET",path:"/owner/v1/approvals/:id",summary:"Read one approval",auth:Be,params:lt,response:G.Approval.extend({detail:G.ApprovalReviewDetail.nullable().optional(),native:yh.NativeAtumApprovalDetail.optional(),progress:G.OwnerPaymentProgress.optional()}),status:200,errors:["setup_required","not_found","unavailable","conflict"],launch:"on"},{id:"owner.approvals.approve",family:"owner",method:"POST",path:"/owner/v1/approvals/:id/approve",summary:"Approve one purchase",auth:Be,params:lt,body:R.z.object({original:G.OriginalHostedPurchaseContext.optional()}).optional(),response:R.z.union([wc(G.Approval).extend({prepared:G.OwnerPreparedPayment.optional()}),R.z.strictObject({resource:G.Approval,challenge:R.z.null(),native:yh.NativeAtumApprovalDetail})]),status:202,signed:!0,controls:["spending_admission"],errors:["setup_required","not_found","expired","conflict","limit_reached","not_enabled"],launch:"on"},{id:"owner.approvals.decline",family:"owner",method:"POST",path:"/owner/v1/approvals/:id/decline",summary:"Decline one purchase (terminal)",auth:Be,params:lt,response:G.Approval,status:200,errors:["setup_required","not_found","expired"],launch:"on"},{id:"owner.wallet.get",family:"owner",method:"GET",path:"/owner/v1/wallet",summary:"Read the owner wallet",auth:Ae,response:G.Wallet,status:200,errors:["setup_required"],launch:"on"},{id:"owner.wallet.enable",family:"owner",method:"POST",path:"/owner/v1/wallet",summary:"Enable the Tempo wallet",auth:Be,response:wc(G.Wallet),variants:[{status:200,description:"The wallet is already enabled.",response:G.Wallet}],status:202,signed:!0,errors:["setup_required","conflict","not_enabled"],launch:"on"},{id:"owner.wallet.disable",family:"owner",method:"DELETE",path:"/owner/v1/wallet",summary:"Disable the wallet for spending",description:"Stops agent spending from the wallet. Funds stay withdrawable.",auth:Ae,response:R.z.object({wallet:G.Wallet,operation:ye.Operation.nullable()}),status:202,errors:["setup_required"],launch:"on"},{id:"owner.wallet.withdraw",family:"owner",method:"POST",path:"/owner/v1/wallet/withdrawals",summary:"Withdraw from the wallet",description:"Recorded as a withdrawal operation with its immutable terms before any signature or broadcast. Repeating the same request_id returns the same operation (after a lost response). Another browser or the exit session finds it with owner.operations.list or .get (terms included) and fetches or renews its signing challenge with owner.operations.challenge. Works while spending is stopped. Any token the wallet holds, by contract address, dust included.",auth:Ae,body:G.Withdrawal,response:R.z.object({operation:ye.Operation,challenge:G.Challenge}),status:202,signed:!0,errors:["setup_required","conflict"],launch:"on"},{id:"owner.wallet.withdrawals.cancel",family:"owner",method:"POST",path:"/owner/v1/wallet/withdrawals/:id/cancel",summary:"Cancel an unsigned or reverted withdrawal",description:"Ends a withdrawal waiting for the owner with no bound signed transaction and no unresolved broadcast. A reported transaction permits cancellation only after Authority independently verifies its reverted receipt and clears its binding. The historical hash remains recorded. The owner can then withdraw to another destination. Missing reports, balances and elapsed time never prove that signed bytes are unsent; unresolved or successor-bound transfers refuse cancellation (conflict).",auth:Ae,params:lt,response:R.z.object({operation:ye.Operation}),status:200,signed:!0,errors:["setup_required","not_found","conflict","unavailable"],launch:"on"},{id:"owner.cards.list",family:"owner",method:"GET",path:"/owner/v1/cards",summary:"List enrolled cards",auth:Ae,response:R.z.object({cards:R.z.array(G.Card)}),status:200,errors:["setup_required"],launch:"on"},{id:"owner.cards.enroll",family:"owner",method:"POST",path:"/owner/v1/cards",summary:"Start enrolling a card (VGS hosted fields)",description:"Opens a setup of kind card and answers the VGS hosted-fields configuration. Card entry happens once, in VGS hosted fields. One card enrollment runs at a time: starting another ends the earlier unfinished one. Send a request_id to retry safely: the same request_id starts nothing new and answers 200 with that enrollment\u2019s current state and no form token (it is never stored); a new request_id opens a fresh form. To swap cards, enroll the new one, then remove the old one.",auth:Be,body:R.z.object({request_id:bh.optional()}),response:G.CardEnrollment,status:201,variants:[{status:200,description:"A retry with the same request_id: the enrollment it already started, without a form token.",response:G.CardEnrollmentAlreadyStarted}],idempotency:"request_id",errors:["setup_required","blocked"],launch:"on"},{id:"owner.cards.collect",family:"owner",method:"POST",path:"/owner/v1/cards/:id/collect",summary:"Finish card collection",description:"Receives the VGS alias of the card the owner typed, with the email the card issuer verifies against and the owner\u2019s residency attestation. Reads the issuer attributes and applies the entry rule (a US-issued Visa card): an ineligible card stops here (blocked, `unsupported_issuer_country:<country>` or `unsupported_card_brand`) and nothing is enrolled. An eligible card is enrolled with VIC, the issuer sends a one-time code to its first delivery choice, and the card is answered as `verifying` with a card_enrollment challenge (signer card_otp) naming where the code went and the other choices. Calling it again with only `send_to` sends a new code to that choice (refused rate_limited inside `resend_in_seconds`; each new code invalidates the earlier ones). With only `restart: true` it starts the verification again on the card already collected, after the issuer refused the attempt. Answer the challenge with owner.signatures.submit { method: card_otp, code }; the owner then signs the acceptance with their own key, and only then is the card active and the owner eligible.",auth:Be,params:lt,body:R.z.union([R.z.object({aliases:R.z.object({card:R.z.string().min(1).max(256)}),email:R.z.email().max(254),residency_attested:R.z.literal(!0)}),R.z.object({send_to:R.z.string().min(1).max(512).clone().register(Ge.apiMetadata,{description:"A delivery choice from the challenge: send a new code there."})}),R.z.object({restart:R.z.literal(!0).clone().register(Ge.apiMetadata,{description:"Start the verification again with the card already collected (the owner never types it again): a fresh VIC enrollment, and a code to its first choice."})})]),response:wc(G.Card),status:202,signed:!0,errors:["setup_required","not_found","expired","blocked","conflict","rate_limited"],launch:"on"},{id:"owner.cards.update",family:"owner",method:"PATCH",path:"/owner/v1/cards/:id",summary:"Make a card the default",auth:Be,params:lt,body:R.z.object({is_default:R.z.literal(!0)}),response:G.Card,status:200,errors:["setup_required","not_found"],launch:"on"},{id:"owner.cards.remove",family:"owner",method:"DELETE",path:"/owner/v1/cards/:id",summary:"Remove a card",description:"Also revokes the VIC mandates of every grant that used it (a provider_cleanup operation).",auth:Ae,params:lt,response:R.z.object({card:G.Card,operation:ye.Operation.nullable()}),status:202,errors:["setup_required","not_found"],launch:"on"},{id:"owner.activity.list",family:"owner",method:"GET",path:"/owner/v1/activity",summary:"List activity",auth:Ae,query:ye.PageQuery.extend({agent_id:ye.Id.optional(),kind:G.ActivityItem.shape.kind.optional()}),response:G.ActivityList,status:200,errors:["setup_required"],launch:"on"},{id:"owner.activity.get",family:"owner",method:"GET",path:"/owner/v1/activity/:id",summary:"Read one activity item",auth:Ae,params:lt,response:G.ActivityItem,status:200,errors:["setup_required","not_found"],launch:"on"},{id:"owner.activity.export",family:"owner",method:"GET",path:"/owner/v1/activity/export",summary:"Export activity as CSV",auth:Ae,query:R.z.object({from:ye.Timestamp.optional(),to:ye.Timestamp.optional()}),response:R.z.string().clone().register(Ge.apiMetadata,{description:"text/csv"}),status:200,errors:["setup_required"],launch:"on"},{id:"owner.security.get",family:"owner",method:"GET",path:"/owner/v1/security",summary:"Sessions, security history and the stop-all state",auth:Ae,response:G.Security,status:200,errors:["setup_required"],launch:"on"},{id:"owner.spending.stop",family:"owner",method:"POST",path:"/owner/v1/spending/stop",summary:"Stop all spending now",description:"Takes effect at once. Allowed from the exit session too: a refused or closing owner may always stop spending, withdraw and export. Withdrawals, export and cleanup continue while stopped.",auth:Ae,response:R.z.object({spending:G.SpendingState}),status:200,errors:["setup_required"],launch:"on"},{id:"owner.spending.reopen",family:"owner",method:"POST",path:"/owner/v1/spending/reopen",summary:"Reopen spending from the Console",description:"A Console button action from the current product owner session with CSRF protection; agent/CLI credentials and exit sessions cannot reopen. Reopens only the owner\u2019s own stop at once, retaining a consumed autonomy_increase consent. No email code or additional credential; an operator stop cannot be lifted.",auth:Be,response:R.z.object({spending:G.SpendingState,challenge:R.z.null()}),status:200,signed:!0,errors:["setup_required","blocked"],launch:"on"},{id:"owner.account.update",family:"owner",method:"PATCH",path:"/owner/v1/account",summary:"Update the owner profile",auth:Be,description:"contact_email: null clears the owner\u2019s contact email (proposal 10). Setting one goes through owner.contact.start.",body:R.z.object({display_name:R.z.string().max(80).optional(),photo:R.z.string().optional(),contact_email:R.z.null().optional()}),response:G.Owner,status:200,errors:["setup_required"],launch:"on"},{id:"owner.contact.start",family:"owner",method:"POST",path:"/owner/v1/account/contact",summary:"Prove a contact email address (TAP directory and essential notices)",description:"Sends a one-time code to the address and answers a challenge with signer email_code; the owner submits the code at owner.signatures.submit, and the address becomes contact_email (source owner_code). The code proves the address only: it never approves money, a setup or a grant (proposal 10). Owners whose sign-in provider vouched for an email already have one and are asked only at the TAP step.",auth:Be,body:R.z.object({email:R.z.email().max(254)}),response:R.z.object({challenge:G.Challenge}),status:202,signed:!0,errors:["setup_required","blocked","unavailable"],launch:"on"},{id:"owner.account.export",family:"owner",method:"POST",path:"/owner/v1/account/export",summary:"Export the owner\u2019s data",auth:Ae,response:R.z.record(R.z.string(),R.z.unknown()).clone().register(Ge.apiMetadata,{description:"The export document (JSON)."}),status:200,errors:["setup_required"],launch:"on"},{id:"owner.devices.register",family:"owner",method:"PUT",path:"/owner/v1/devices/:id",summary:"Register this phone for notifications",description:"Registration only (nothing is sent at launch; it grants no authority). The id is the app\u2019s own: registering again updates the token in place. A token or app install registered under another account moves to this one. At most 20 devices. Works from the exit session, so a pending owner can be told when they are admitted. Closing the account deletes every device.",auth:Ae,params:lt,body:R.z.object({platform:R.z.literal("ios"),app_env:R.z.enum(["preview","production"]),token:R.z.string().regex(/^[0-9a-fA-F]{16,200}$/).clone().register(Ge.apiMetadata,{description:"The APNs device token (hex)."})}),response:G.Device,status:200,errors:["setup_required","invalid_request","conflict"],launch:"on"},{id:"owner.devices.remove",family:"owner",method:"DELETE",path:"/owner/v1/devices/:id",summary:"Stop notifications to a phone",auth:Ae,params:lt,response:null,status:204,errors:["setup_required","not_found"],launch:"on"},{id:"owner.account.close",family:"owner",method:"POST",path:"/owner/v1/account/close",summary:"Close the account",description:"Starts an account_closure operation. It is accepted while money remains, a payment is unresolved or a withdrawal is open: signing it stops all spending at once, and the operation finishes after the reconciler settles payments (next_action reconcile_payments) and the owner withdraws (owner_withdraw). Closing keeps the owner\u2019s custody and exit sign-in, so later funds stay withdrawable; recovery can never revive spending authority. A never-used account (no wallet ever enabled, no agent ever set up) is closed on the owner\u2019s sign-in alone: `challenge` is null and the operation has already started.",auth:Ae,response:R.z.object({operation:ye.Operation,challenge:G.Challenge.nullable()}),status:202,signed:!0,errors:["setup_required","conflict"],launch:"on"},{id:"owner.signatures.submit",family:"owner",method:"POST",path:"/owner/v1/signatures/:challengeId",summary:"Submit the owner\u2019s signature for a challenge",auth:Ae,params:R.z.object({challengeId:ye.Id}),body:G.SignatureSubmission,response:G.SignatureResult,status:200,errors:["setup_required","not_found","expired","conflict","blocked"],launch:"on"},{id:"owner.signatures.get",family:"owner",method:"GET",path:"/owner/v1/signatures/:challengeId",summary:"Read a challenge\u2019s state",auth:Ae,params:R.z.object({challengeId:ye.Id}),response:G.SignatureResult,status:200,errors:["setup_required","not_found","unavailable","conflict"],launch:"on"},{id:"owner.renewal.start",family:"owner",method:"POST",path:"/owner/v1/renewal",summary:"Begin deliberate account spending-consent renewal",description:"Available before the seven-day reminder window. Returns the existing open renewal operation or opens one awaiting the owner\u2019s exact signature through owner.operations.challenge and owner.signatures.submit. Starting changes no consent, budget, hold, key, TAP or bearer authority. Repeat an interrupted start to recover the open operation; after completion, a new start awaits a new signature. Consent ends ninety days from the tap, without carry-over. This operation renews spending consent only; technical authority readiness remains separate.",auth:Be,response:ye.Operation,status:200,errors:["setup_required","blocked","conflict"],launch:"on"},{id:"owner.operations.list",family:"owner",method:"GET",path:"/owner/v1/operations",summary:"List the owner\u2019s operations",description:'`needs_attention=true` is the owner\u2019s "Needs attention" list.',auth:Ae,query:ye.PageQuery.extend({needs_attention:R.z.enum(["true","false"]).optional()}),response:R.z.object({operations:R.z.array(Dl),page:ye.Page}),status:200,errors:["setup_required"],launch:"on"},{id:"owner.operations.challenge",family:"owner",method:"POST",path:"/owner/v1/operations/:id/challenge",summary:"Fetch or renew the signing challenge an operation is waiting for",description:"For an operation in needs_owner_action: returns the current challenge if it is still valid, or a fresh one for the same step and the same immutable terms if it expired. A recorded wallet key authorization instead returns its original owner-only signed bytes and hash with challenge null, including while running or retained terminal; unknown outcomes never create a new challenge. Never changes the terms and never signs for the owner.",auth:Ae,params:lt,response:R.z.object({operation:Dl,challenge:G.Challenge.nullable()}),status:200,errors:["setup_required","not_found","conflict"],launch:"on"},{id:"owner.operations.get",family:"owner",method:"GET",path:"/owner/v1/operations/:id",summary:"Read one operation",auth:Ae,params:lt,response:Dl,status:200,errors:["setup_required","not_found"],launch:"on"}])});var Ul=P(Ke=>{"use strict";Object.defineProperty(Ke,"__esModule",{value:!0});Ke.PUBLIC_OPERATIONS=Ke.CliFailureReport=Ke.CLI_FAILURE_EVENT_MAX_BYTES=Ke.CLI_FAILURE_PLATFORMS=Ke.CLI_FAILURE_KINDS=Ke.CLI_FAILURE_STEPS=Ke.CLI_FAILURE_SURFACES=void 0;var te=ct(),rD=Pr(),Ml=Si(),$c=Rt(),Jr=te.z.record(te.z.string(),te.z.unknown()),xl="RFC 6749 errors: { error, error_description }";Ke.CLI_FAILURE_SURFACES=["cli","mcp"];Ke.CLI_FAILURE_STEPS=["connect","connect_sign_in","connect_enroll","connect_mount","connect_skill","connect_hud","disconnect","update","statusline","keychain","enrollment_finisher","get_status","agent_enroll","discover","pay","history","purchase_create","purchase_retrieve","purchase_cancel","crash","other"];Ke.CLI_FAILURE_KINDS=["caller","platform","unknown"];Ke.CLI_FAILURE_PLATFORMS=["darwin","linux","win32","other"];Ke.CLI_FAILURE_EVENT_MAX_BYTES=2048;Ke.CliFailureReport=te.z.strictObject({reference:te.z.string().regex(/^[0-9a-f]{8}$/),failedRequestId:te.z.uuid().optional(),surface:te.z.enum(Ke.CLI_FAILURE_SURFACES),step:te.z.enum(Ke.CLI_FAILURE_STEPS),code:te.z.string().regex(/^[a-z][a-z0-9_]{1,63}$/),kind:te.z.enum(Ke.CLI_FAILURE_KINDS),httpStatus:te.z.number().int().min(100).max(599).optional(),cliVersion:te.z.string().max(40),platform:te.z.enum(Ke.CLI_FAILURE_PLATFORMS),harness:te.z.string().regex(/^[a-z0-9_-]{1,32}$/).optional()});Ke.PUBLIC_OPERATIONS=(0,rD.defineOperations)([{id:"mcp.endpoint",backedBy:"edge",family:"mcp",method:"ALL",path:"/mcp",summary:"The MCP server (streamable HTTP)",description:"JSON-RPC over POST; GET opens the event stream and DELETE ends a session. Serves the 7-tool catalogue in mcp.ts, each tool an adapter over an /agent/v1 operation.",auth:["oauth_token","agent_token","app_token"],body:Jr,response:Jr,status:200,errors:["setup_required","update_required"],launch:"on",externalSpec:"Model Context Protocol, streamable HTTP transport"},{id:"oauth.authorize",backedBy:"edge",family:"oauth",method:"GET",path:"/oauth/authorize",summary:"Authorization request (PKCE)",description:"Redirects (302) to the Console consent page (/agent/enroll/connector) with `request_id` in the query string; the Console signs the owner in if needed (the browser holds no Auth session). The request_id identifies one decision and expires after 10 minutes; the page posts it to oauth.decision, and the first owner who decides it binds it (an owner session present at authorize binds it at once). Re-requesting the same parameters issues a fresh request_id.",auth:["none","owner_session"],query:te.z.object({response_type:te.z.literal("code"),client_id:te.z.string(),redirect_uri:te.z.url(),code_challenge:te.z.string(),code_challenge_method:te.z.literal("S256"),scope:te.z.string().optional(),state:te.z.string().optional(),resource:te.z.url().optional()}),response:null,status:302,errors:[],launch:"on",externalSpec:`RFC 6749, RFC 7636. ${xl}; until the client and redirect_uri are verified the error is answered directly, after that it is redirected to the client's callback. \`resource\` is accepted and not used: the token is bound to one agent.`},{id:"oauth.decision",backedBy:"edge",family:"oauth",method:"POST",path:"/oauth/authorize/decision",summary:"The owner\u2019s consent decision; creates the hosted agent and its setup",description:"request_id is the one the consent page received in the query string of the oauth.authorize redirect. deny: 200 with the redirect carrying access_denied. allow carries the original visible ask_each_time Tempo grant; an identical retry retains the same setup and approval. allow: 202 with the hosted setup and its setup_approval challenge; the Console signs it silently with the owner\u2019s browser key (no extra step) through owner.signatures.submit, whose continuation.url is the redirect carrying the code. No code is issued before the owner\u2019s signature over the setup statement is verified (contract proposal 7, decided 8 Oct).",auth:["owner_session"],body:te.z.discriminatedUnion("decision",[te.z.object({request_id:$c.Id,decision:te.z.literal("allow"),agent_id:$c.Id.optional(),grant:Ml.GrantRequest.extend({rail:te.z.literal("tempo"),mode:te.z.literal("ask_each_time")})}),te.z.object({request_id:$c.Id,decision:te.z.literal("deny"),agent_id:$c.Id.optional()})]),response:te.z.object({redirect_to:te.z.url()}),status:200,variants:[{status:202,description:"allow: the owner signs the setup statement; the code follows the signature.",response:te.z.object({setup:Ml.Setup,challenge:Ml.Challenge})}],errors:["setup_required","expired","blocked","invalid_request","conflict"],launch:"on",externalSpec:"RFC 6749 (the consent step). The Console calls it; refusals are the Problem."},{id:"oauth.token",backedBy:"edge",family:"oauth",method:"POST",path:"/oauth/token",summary:"Token endpoint (authorization_code, refresh_token)",description:"A refresh keeps the same hosted agent identity.",auth:["none"],bodyType:"application/x-www-form-urlencoded",body:te.z.object({grant_type:te.z.enum(["authorization_code","refresh_token"]),code:te.z.string().optional(),code_verifier:te.z.string().optional(),refresh_token:te.z.string().optional(),client_id:te.z.string(),redirect_uri:te.z.url().optional()}),response:te.z.object({access_token:te.z.string(),token_type:te.z.literal("Bearer"),expires_in:te.z.number().int(),refresh_token:te.z.string().optional(),scope:te.z.string().optional()}),status:200,errors:[],launch:"on",externalSpec:`RFC 6749. ${xl}`},{id:"oauth.register",backedBy:"edge",family:"oauth",method:"POST",path:"/oauth/register",summary:"Dynamic client registration",auth:["none"],body:Jr,response:Jr,status:201,errors:[],launch:"on",externalSpec:`RFC 7591; client ID metadata documents. ${xl}`},{id:"oauth.revoke",backedBy:"edge",family:"oauth",method:"POST",path:"/oauth/revoke",summary:"Token revocation",auth:["none"],bodyType:"application/x-www-form-urlencoded",body:te.z.object({token:te.z.string(),token_type_hint:te.z.string().optional()}),response:null,status:200,errors:[],launch:"on",externalSpec:"RFC 7009"},{id:"oauth.connect",backedBy:"edge",family:"oauth",method:"GET",path:"/oauth/connect/:ticket",summary:"Redeem a one-time connect ticket",description:"The one ticket-redemption door: a connector app link or the Console handoff.",auth:["none","owner_session"],params:te.z.object({ticket:te.z.string()}),response:null,status:302,errors:["expired","not_found"],launch:"future"},...[["oauthAuthorizationServer","oauth-authorization-server","OAuth server metadata","RFC 8414"],["oauthProtectedResource","oauth-protected-resource","Protected resource metadata","RFC 9728"],["mcp","mcp.json","MCP server discovery","MCP discovery"],["agentJwks","agent-jwks.json","Agent public keys (JWKS)","RFC 7517"],["httpMessageSignaturesDirectory","http-message-signatures-directory","Web Bot Auth key directory","Web Bot Auth (HTTP message signatures directory)"]].map(([e,t,r,i])=>({id:`wellKnown.${e}`,backedBy:"edge",family:"well-known",method:"GET",path:`/.well-known/${t}`,summary:r,auth:["none"],response:Jr,status:200,errors:[],launch:"on",externalSpec:i})),{id:"public.tapRegistry.agent",backedBy:"authority",family:"public",method:"GET",path:"/v1/tap/registry/agents/:tapAgentId",summary:"Resolve a Trusted Agent Protocol agent",description:"A merchant contract; the path is kept.",auth:["none"],params:te.z.object({tapAgentId:te.z.string()}),response:Jr,status:200,errors:["not_found"],launch:"on",externalSpec:"Visa Trusted Agent Protocol registry"},{id:"public.tapRegistry.key",backedBy:"authority",family:"public",method:"GET",path:"/v1/tap/registry/keys/:jkt",summary:"Resolve a TAP signing key by thumbprint",auth:["none"],params:te.z.object({jkt:te.z.string()}),response:Jr,status:200,errors:["not_found"],launch:"on",externalSpec:"Visa Trusted Agent Protocol registry"},{id:"public.cliFailure.report",backedBy:"edge",family:"public",method:"POST",path:"/v1/cli/failure-event",summary:"Report a CLI or MCP step that failed on the person\u2019s machine",description:"Fire-and-forget, so a failure that never reached Visa (an unreadable keychain, a crash) can be found by its reference. Unauthenticated on purpose: a CLI whose keychain cannot be read must still report it; an agent token, if sent and current, adds the owner. A closed shape of bounded codes (no prompt, argument, path, email or free text); at most 2048 bytes; rate limited per client address (30 a minute) in its own bucket. 204 on success; an invalid report is invalid_request naming the first offending field (`cli_failure_event_<field>`).",auth:["none","agent_token"],body:Ke.CliFailureReport,response:null,status:204,errors:["invalid_request","rate_limited"],launch:"on"},{id:"public.openapi",backedBy:"edge",family:"public",method:"GET",path:"/openapi.json",summary:"This contract as OpenAPI 3.1",auth:["none"],response:Jr,status:200,errors:[],launch:"on"},{id:"public.health",backedBy:"edge",family:"public",method:"GET",path:"/health",summary:"Readiness of the public API and its Authority connection",description:"Returns 200 when Authority is ready, or 503 with the same health shape when it is unavailable.",auth:["none"],response:te.z.object({status:te.z.enum(["ok","degraded"]),cutover:te.z.literal("B"),checks:te.z.object({authority:te.z.enum(["ok","unavailable"])})}),status:200,errors:[],launch:"on"}])});var Ll=P(Wr=>{"use strict";Object.defineProperty(Wr,"__esModule",{value:!0});Wr.MCP_DESCRIPTION_BUDGET=Wr.MCP_TOOLS=void 0;Wr.mcpToolDescriptors=oD;var ue=ct(),Qt=Et(),Fa=Rt(),iD=Si(),$h=["agent_signature"],Oh=["oauth_token","app_token"],qa=e=>({laptop:{available:!0,auth:$h,identityCustody:"device",moneyCustody:"none",approval:"none",note:e},hosted:{available:!0,auth:Oh,identityCustody:"turnkey",moneyCustody:"none",approval:"none",note:e}}),kr={agent:ue.z.string().min(1).max(128).optional().clone().register(Qt.apiMetadata,{description:"The agent\u2019s name or id, needed only when this computer or credential holds more than one; never guessed."})},Sh=ue.z.object({target:ue.z.string().clone().register(Qt.apiMetadata,{description:"An http(s) URL that answers 402 with a Tempo charge."}),max:ue.z.string().clone().register(Qt.apiMetadata,{description:"Hard ceiling as a decimal string in the charge asset."}),description:ue.z.string().optional().clone().register(Qt.apiMetadata,{description:"What it is for, shown to the owner at approval and kept with the payment as its context."}),original:iD.OriginalHostedPurchaseContext.optional(),request_id:Fa.Id,method:ue.z.enum(["GET","POST"]).optional(),body:ue.z.string().optional(),...kr}),aD=ue.z.object({request_id:Fa.Id.clone().register(Qt.apiMetadata,{description:"New UUID per purchase. Send the same request_id and arguments again to continue it (after the owner approves, or an unknown outcome): it is never paid twice."}),tempoChallenge:ue.z.string().min(1).max(8192).clone().register(Qt.apiMetadata,{description:'REQUIRED to pay. The merchant 402 `WWW-Authenticate: Payment` header value offering a Tempo charge (method="tempo"), verbatim. Visa pays a fresh charge for no more than this amount, to this payee only.'}),resource:ue.z.string().min(1).max(2048).clone().register(Qt.apiMetadata,{description:"The https URL that answered the 402; shown to the owner."}),request:ue.z.object({method:ue.z.string().nullable().optional(),headers:ue.z.array(ue.z.tuple([ue.z.string(),ue.z.string().max(1024)])).max(32).nullable().optional(),bodyBase64:ue.z.string().nullable().optional()}).optional().clone().register(Qt.apiMetadata,{description:"The request Visa replays after approval. Omit for a plain GET; otherwise send the original method (GET, HEAD, POST, PUT, PATCH or DELETE) and bodyBase64. Headers are public [name, value] pairs; credentials are never replayed."}),narrative:ue.z.object({userRequest:ue.z.string().min(1).max(2e3),product:ue.z.string().min(1).max(512),category:ue.z.string(),purpose:ue.z.string().min(1).max(512).optional(),quantity:ue.z.number().int().min(1).max(1e6).optional(),expectedResult:ue.z.string().min(1).max(512).optional(),recurring:ue.z.boolean().optional(),initiator:ue.z.string().optional(),discoveredVia:ue.z.string().optional(),alternativesConsidered:ue.z.number().int().min(0).max(1e3).optional()}).strict().clone().register(Qt.apiMetadata,{description:"REQUIRED. What the user asked for and what this buys, as the owner reads it on the approval card. userRequest, product and category are required; category is one of api_inference, api_data, compute_storage, media_content, software_subscription, digital_goods, physical_goods, service_booking, donation_tip, other. Keep personal details out of product, purpose and expectedResult."}),...kr}).strict();Wr.MCP_TOOLS=[{name:"status",operations:["agent.status.get"],description:"Who this agent is, each capability\u2019s readiness (supported \u2192 configured \u2192 authorized \u2192 funded \u2192 ready) and the next step with who must take it. Call first. READ-ONLY.",input:ue.z.object(kr),annotations:{readOnlyHint:!0,idempotentHint:!0,openWorldHint:!1},surfaces:qa()},{name:"connect",operations:["agent.setups.start","agent.setups.get","agent.setups.claim"],description:"Connect this computer as an agent, add another agent (another: true), or replace one agent\u2019s key (mode: replace, with agent when this computer holds several). Returns one owner link and short code; this computer picks up approval automatically. Call status for progress. Never use it to repair an existing agent.",input:ue.z.object({mode:ue.z.enum(["new","replace"]).optional(),setup:ue.z.string().optional().clone().register(Qt.apiMetadata,{description:"A setup key the owner started in the Console."}),another:ue.z.boolean().optional().clone().register(Qt.apiMetadata,{description:"Set up one more agent on this computer, with its own key and limits. Without it, connect resumes or answers the agent already here."}),...kr}),annotations:{idempotentHint:!0},surfaces:{laptop:{available:!0,auth:["setup_secret","agent_signature"],identityCustody:"device",moneyCustody:"none",approval:"none",note:"Creates the installation key in the OS key store; the owner approves in their browser."},hosted:{available:!1,auth:[],identityCustody:"none",moneyCustody:"none",approval:"none",note:"A hosted agent is set up by OAuth consent (oauth.authorize), not by a tool."}}},{name:"discover",operations:["agent.merchants.search"],description:"Search paid services with `query` (Mercator: each result\u2019s url, method and input schema), or price one URL\u2019s live charge with `target` (and its `method`/`body`). READ-ONLY: signs and spends nothing; listed prices are advisory. Paying always needs an explicit max.",input:ue.z.object({query:ue.z.string().optional(),target:ue.z.url().optional(),method:ue.z.enum(["GET","POST"]).optional(),body:ue.z.string().optional(),limit:ue.z.number().int().min(1).max(50).optional(),...kr}),annotations:{readOnlyHint:!0,idempotentHint:!0,openWorldHint:!0},surfaces:qa()},{name:"pay",operations:["agent.payments.create","agent.payments.credential"],description:"Pay a merchant from the owner\u2019s wallet (MPP on Tempo), through the owner. Send `tempoChallenge`, the merchant 402 `WWW-Authenticate: Payment` header value offering a Tempo charge, exactly as you received it, with `resource` (the https URL that answered 402), `request` for anything but a plain GET, a `narrative`, and a new `request_id`. This returns an owner-approval link: nothing is spent until the owner approves. Then call `payment_status` with `wait: 240` straight away, and when it reports the approval, call pay again with the same arguments: that call pays once and returns the merchant\u2019s answer. Never poll in a loop, never ask the owner whether they approved, never invent missing fields. MOVES REAL MONEY. Reply in a line or two.",input:aD,laptopInput:Sh.extend({max:Sh.shape.max.optional()}),laptopDescription:"Pay a supported URL with an explicit max and a new request_id per purchase; reuse the same request_id and arguments to recover it, never pay it twice. Omit max for a read-only price preview: nothing is signed, funded or paid. A phrase as target searches services instead and pays nothing. Native paying remains gated. Reply in a line or two.",annotations:{destructiveHint:!0,idempotentHint:!0,openWorldHint:!0},surfaces:{laptop:{available:!0,auth:$h,identityCustody:"device",moneyCustody:"owner_wallet_via_slipgate",approval:"grant_mode",note:"Co-signs two of two: the CLI admits its own prepared charge, verifies and votes on the provider activity, then resumes. Tempo only at launch: card paying is cut from the launch build (A1)."},hosted:{available:!0,auth:Oh,identityCustody:"turnkey",moneyCustody:"owner_wallet_via_slipgate",approval:"every_payment",note:"Every hosted payment needs the owner\u2019s fresh web approval at launch, whatever the grant mode or controls (A2); hosted autonomy waits for a connector-side signing key. Replay body and headers are forwarded in memory and never stored. Supported original signing context follows the private approval-review data policy. Tempo only (A1)."}}},{name:"payment_status",operations:["agent.payments.get"],description:'Read one purchase by id. With `wait` (up to 240 s) this call blocks until the purchase changes, for example the owner approving or declining, and then answers: one call, no polling loop. An unknown outcome is never "nothing was paid". READ-ONLY.',input:ue.z.object({id:Fa.Id,wait:ue.z.number().int().min(0).max(240).optional(),...kr}),laptopInput:ue.z.object({id:Fa.Id,wait:ue.z.number().int().min(0).max(30).optional(),...kr}),laptopDescription:'Read one purchase by id, optionally waiting up to 30 s for it to change. An unknown outcome is never "nothing was paid". READ-ONLY.',annotations:{readOnlyHint:!0,idempotentHint:!0,openWorldHint:!1},surfaces:qa()},{name:"payment_cancel",operations:["agent.payments.cancel"],description:"Cancel a purchase that has not executed. A purchase already submitted settles or reconciles instead.",input:ue.z.object({id:Fa.Id,...kr}),annotations:{destructiveHint:!0,idempotentHint:!0},surfaces:qa()},{name:"history",operations:["agent.payments.list"],description:"This agent\u2019s purchases on every rail, newest first. READ-ONLY.",input:ue.z.object({limit:ue.z.number().int().min(1).max(100).optional(),...kr}),annotations:{readOnlyHint:!0,idempotentHint:!0,openWorldHint:!1},surfaces:qa()}];Wr.MCP_DESCRIPTION_BUDGET=3e3;function oD(e){return Wr.MCP_TOOLS.filter(t=>t.surfaces[e].available).map(t=>{let{$schema:r,...i}=ue.z.toJSONSchema(e==="laptop"?t.laptopInput??t.input:t.input,{target:"draft-2020-12",unrepresentable:"any"});return{name:t.name,description:e==="laptop"?t.laptopDescription??t.description:t.description,input_schema:i,annotations:t.annotations}})}});var jh=P(Ba=>{"use strict";Object.defineProperty(Ba,"__esModule",{value:!0});Ba.jsonSchema=Nr;Ba.successOutcomes=Ah;Ba.buildOpenApi=mD;var Zl=ct(),Ic=Et(),Yr=pc(),Ih=Ll(),Oc=Pr(),Va="#/components/schemas/",sD=["get","put","post","patch","delete"],cD={owner_session:{type:"apiKey",in:"cookie",name:"visa_owner_session",description:"Owner Console session cookie. Every write also sends X-CSRF-Token with the csrf_token from owner.session.verify or owner.session.get."},owner_exit_session:{type:"apiKey",in:"cookie",name:"visa_owner_session",description:"The same owner cookie in its reduced exit scope (stop spending, withdraw, export, close). Writes send X-CSRF-Token as for owner_session."},agent_signature:{type:"http",scheme:"signature",description:"HTTP message signature (RFC 9421) by the agent installation key, plus the CLI version header."},agent_token:{type:"http",scheme:"bearer",description:"Short-lived agent access token from POST /agent/v1/token."},oauth_token:{type:"oauth2",flows:{authorizationCode:{authorizationUrl:"/oauth/authorize",tokenUrl:"/oauth/token",refreshUrl:"/oauth/token",scopes:{}}}},app_token:{type:"http",scheme:"bearer",description:"Owner-minted app token for one agent (REST apps)."},setup_secret:{type:"http",scheme:"Setup",description:"One-time setup secret returned by POST /agent/v1/setups, sent as Authorization: Setup <secret> (never in the URL)."},operator_session:{type:"apiKey",in:"cookie",name:"visa_operator_session",description:"Operator session from admin.session.start (current valid product owner session, owner CSRF and live operator membership). Cookie only (HttpOnly, Secure, SameSite=Strict, Path=/admin/v1); writes send X-CSRF-Token with the csrf_token from admin.session.start; operator membership is re-checked on every request."}};function uD(e){return(0,Ic.apiMetadataOf)(e)?.id}function Nr(e){let t=uD(e);if(t)return{$ref:`${Va}${t}`};let r=Zl.z.toJSONSchema(e,{metadata:Ic.apiMetadata,target:"draft-2020-12",unrepresentable:"any"}),i=r.$defs??{};for(let n of Object.keys(i))if(!lD().has(n))throw new Error(`unregistered shared schema ${n}`);return delete r.$defs,delete r.$schema,JSON.parse(JSON.stringify(r).replaceAll('"#/$defs/',`"${Va}`))}var Eh=null;function lD(){return Eh??=new Set(Object.keys(Th())),Eh}function Th(){let e=Zl.z.toJSONSchema(Ic.apiMetadata,{metadata:Ic.apiMetadata,target:"draft-2020-12",unrepresentable:"any",uri:r=>`${Va}${r}`}).schemas,t={};for(let r of Object.keys(e).sort()){let{$schema:i,$id:n,...a}=e[r];t[r]=a}return t}function dD(e){let t=[],r=e.params?.shape??{};for(let i of(0,Oc.pathParams)(e.path)){let n=r[i]??Zl.z.string();t.push({name:i,in:"path",required:!0,schema:Nr(n)})}for(let[i,n]of Object.entries(e.query?.shape??{})){let a=n;t.push({name:i,in:"query",required:!a.safeParse(void 0).success,schema:Nr(a)})}return t}function Ah(e){let t=[],r=e.response&&e.status!==204&&e.status!==302;t.push({status:e.status,description:e.summary,schema:r?Nr(e.response):null});for(let i of e.variants??[])t.push({status:i.status,description:i.description,schema:Nr(i.response)});for(let i of e.errors){let n=Yr.ERROR_FAMILIES[i].status;n>=200&&n<300&&t.push({status:n,description:`${i}: ${Yr.ERROR_FAMILIES[i].message} The body is ${e.errorResponse?"the declared refusal":"a Problem"}; never read it as a failure.`,schema:e.errorResponse?Nr(e.errorResponse):{$ref:`${Va}Problem`}})}return t}function fD(e){let t=new Map;for(let i of Ah(e)){let n=t.get(i.status)??[];n.push(i),t.set(i.status,n)}let r={};for(let i of[...t.keys()].sort((n,a)=>n-a)){let n=t.get(i),a=n.flatMap(s=>s.schema?[s.schema]:[]),o={description:n.map(s=>s.description).join(" Or: ")};if(a.length>0){let s=e.id==="owner.activity.export";o.content={[s?"text/csv":"application/json"]:{schema:a.length===1?a[0]:{oneOf:a}}}}r[String(i)]=o}if(e.errorResponse){let i=Nr(e.errorResponse);for(let n of e.errors){let a=Yr.ERROR_FAMILIES[n].status;a<400||(r[String(a)]={description:"Declared native transport refusal. Branch on code; preserve the original request.",content:{"application/json":{schema:i}}})}for(let n of["4XX","5XX"])r[n]={description:"Declared native transport refusal.",content:{"application/json":{schema:i}}}}else(!e.externalSpec||e.family==="mcp")&&(r["4XX"]={$ref:"#/components/responses/Refused"},r["5XX"]={$ref:"#/components/responses/Unavailable"});return r}function Ph(e){return{description:e,headers:{"Retry-After":{description:"Seconds to wait, sent with rate_limited.",schema:{type:"integer",minimum:0}}},content:{"application/json":{schema:{$ref:`${Va}Problem`}}}}}function pD(e){let t=Nr(e),r=t.oneOf??t.anyOf;if(!r)return t;let i=r[0]?.properties,n=Object.fromEntries(Object.entries(i??{}).filter(([a,o])=>r.every(s=>JSON.stringify(s.properties?.[a])===JSON.stringify(o))));return Object.keys(n).length>0&&(t.properties=n),t}function zh(e){let t={operationId:e.id,tags:[e.family],summary:e.summary};e.description&&(t.description=e.description);let r=dD(e);r.length>0&&(t.parameters=r),e.body&&(t.requestBody={required:!e.body.isOptional(),content:{[e.bodyType??"application/json"]:{schema:pD(e.body)}}}),t.responses=fD(e);let i=e.auth.filter(n=>n!=="none");return t.security=[...i.map(n=>({[n]:[]})),...e.auth.includes("none")?[{}]:[]],t["x-launch"]=e.launch,e.errors.length>0&&(t["x-error-families"]=[...e.errors]),e.signed&&(t["x-owner-signature"]=!0),e.idempotency&&(t["x-idempotency"]=e.idempotency),e.controls&&(t["x-controls"]=[...e.controls]),t["x-backed-by"]=e.backedBy??"authority",e.externalSpec&&(t["x-external-spec"]=e.externalSpec),t}function mD(e){Yr.Problem;let t={};for(let i of e){if(!(0,Oc.operationPathMatchesFamily)(i))throw new Error(`${i.id}: ${i.path} is outside ${Oc.FAMILY_PREFIX[i.family]}`);let n=(0,Oc.openApiPath)(i.path),a=t[n]??={},o=(s,c)=>{if(a[s])throw new Error(`duplicate ${s.toUpperCase()} ${i.path}`);a[s]=c};if(i.method==="ALL"){let s=zh(i);o("post",s),o("get",{...s,operationId:`${i.id}.stream`,summary:"Open the server event stream",requestBody:void 0,responses:{200:{description:"Server-sent events.",content:{"text/event-stream":{schema:{type:"string"}}}},"4XX":{$ref:"#/components/responses/Refused"},"5XX":{$ref:"#/components/responses/Unavailable"}}}),o("delete",{...s,operationId:`${i.id}.end`,summary:"End the MCP session",requestBody:void 0,responses:{204:{description:"Session ended."},"4XX":{$ref:"#/components/responses/Refused"},"5XX":{$ref:"#/components/responses/Unavailable"}}})}else o(i.method.toLowerCase(),zh(i))}let r={};for(let i of Object.keys(t).sort()){let n={};for(let a of sD)t[i][a]&&(n[a]=t[i][a]);r[i]=n}return{openapi:"3.1.0",info:{title:"Visa CLI target API",version:"1.0.0-draft",description:"The target contract from the clean-slate plan v4. Not served yet. Families: /owner/v1, /agent/v1, /admin/v1, /mcp, /oauth, /.well-known and the public registry."},servers:[{url:"/",description:"The Auth edge of each environment (the only public API host)."}],paths:r,components:{schemas:Th(),responses:{Refused:Ph("Refused. Branch on `code` (an error family)."),Unavailable:Ph("Unavailable or internal error.")},securitySchemes:cD},"x-error-families":Object.fromEntries(Yr.WIRE_ERROR_FAMILIES.map(i=>[i,{status:Yr.ERROR_FAMILIES[i].status,retryable:Yr.ERROR_FAMILIES[i].retryable,kind:Yr.ERROR_FAMILIES[i].kind}])),"x-mcp":{descriptionBudget:Ih.MCP_DESCRIPTION_BUDGET,tools:Ih.MCP_TOOLS.map(i=>({name:i.name,operations:[...i.operations],description:i.description,annotations:i.annotations,inputSchema:Nr(i.input),surfaces:i.surfaces}))}}}});var kh=P(Rr=>{"use strict";Object.defineProperty(Rr,"__esModule",{value:!0});Rr.RECOVERY_RESPONSIBILITIES=void 0;Rr.executionDecision=gD;Rr.replacementAllowed=_D;Rr.dispatchRecovery=hD;Rr.hostedResumeDecision=vD;Rr.ownerApprovalRequired=yD;function gD(e){return e.chain==="landed"?{action:"settle"}:e.signature==="never_created"?e.provider_void?{action:"close",evidence:"provider_void"}:e.past_valid_before?{action:"close",evidence:"expired_unsigned"}:{action:"keep_open"}:e.signature==="pending_at_provider"&&e.provider_void?{action:"close",evidence:"provider_void"}:e.past_valid_before&&e.chain==="not_landed_final"?{action:"close",evidence:"expired_on_chain"}:e.past_valid_before?{action:"fence"}:{action:"keep_open"}}function _D(e){return e.action==="close"}function hD(e){return e.locator_recorded?"read_recorded_activity":e.readback==="found"?"bind_found_activity":"fenced_unknown"}function vD(e){return e.credential_released?e.supplied==="request"?"refuse_credential_released":e.supplied==="receipt"&&e.merchant_verified_receipt===!0?"retrieve_from_merchant":"paid_result_unavailable":e.supplied==="request"?"requote_must_match_retained_facts":"still_waiting"}Rr.RECOVERY_RESPONSIBILITIES={visa:"Keeps only RETAINED_PAYMENT_FACTS; never re-sends a released credential; fails closed.",caller:"Keeps its own request and the merchant receipt or job reference if it wants its result back.",merchant:"Answers a receipt or job-reference lookup for a paid request and treats a repeated paid request idempotently."};function yD(e){return e.surface==="hosted"?!0:!(e.mode==="within_limit"&&e.within_limit_control_enabled&&e.within_limits)}});var Ch=P(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.SETUP_AUTH_SCHEME=Me.AGENT_SIGNATURE_MAX_AGE_SECONDS=Me.AGENT_SIGNATURE_ALG=Me.CLI_VERSION_HEADER=Me.AGENT_SIGNATURE_LABEL=void 0;Me.agentSignatureParams=ql;Me.agentSignatureBase=SD;Me.agentSignatureHeaders=$D;Me.parseAgentSignature=OD;Me.setupClaimMessage=ID;Me.setupResumeMessage=ED;Me.AGENT_SIGNATURE_LABEL="visa";Me.CLI_VERSION_HEADER="x-visa-cli-version";Me.AGENT_SIGNATURE_ALG="ed25519";Me.AGENT_SIGNATURE_MAX_AGE_SECONDS=120;Me.SETUP_AUTH_SCHEME="Setup";var Nh=["@method","@target-uri","content-digest",Me.CLI_VERSION_HEADER],Rh=["@method","@target-uri",Me.CLI_VERSION_HEADER],bD=/^[A-Za-z0-9_-]{16,64}$/,wD=/^[A-Za-z0-9_-]{43}$/;function ql(e,t){if(!Number.isSafeInteger(t.created)||t.created<0)throw new Error("agent_signature_created_invalid");if(!bD.test(t.nonce))throw new Error("agent_signature_nonce_invalid");if(!wD.test(t.keyid))throw new Error("agent_signature_keyid_invalid");return`(${(e?Nh:Rh).map(i=>`"${i}"`).join(" ")});created=${t.created};nonce="${t.nonce}";keyid="${t.keyid}";alg="${Me.AGENT_SIGNATURE_ALG}"`}function SD(e,t){if(/[\r\n]/.test(e.cliVersion)||/[\r\n]/.test(e.targetUri))throw new Error("agent_signature_component_invalid");let r=[`"@method": ${e.method.toUpperCase()}`,`"@target-uri": ${e.targetUri}`];if(e.contentDigest!==void 0){if(!/^sha-256=:[A-Za-z0-9+/]{43}=:$/.test(e.contentDigest))throw new Error("agent_signature_digest_invalid");r.push(`"content-digest": ${e.contentDigest}`)}return r.push(`"${Me.CLI_VERSION_HEADER}": ${e.cliVersion}`),r.push(`"@signature-params": ${ql(e.contentDigest!==void 0,t)}`),r.join(`
58
- `)}function $D(e,t,r){return{"signature-input":`${Me.AGENT_SIGNATURE_LABEL}=${ql(e,t)}`,signature:`${Me.AGENT_SIGNATURE_LABEL}=:${r}:`}}function OD(e){let t=e.signatureInput?.trim()??"",r=e.signature?.trim()??"",i=`${Me.AGENT_SIGNATURE_LABEL}=`;if(!t.startsWith(i)||!r.startsWith(i))return null;let n=/^\(([^)]*)\);created=(\d{1,12});nonce="([A-Za-z0-9_-]{16,64})";keyid="([A-Za-z0-9_-]{43})";alg="ed25519"$/.exec(t.slice(i.length)),a=/^:([A-Za-z0-9+/]{86}==):$/.exec(r.slice(i.length));if(!n||!a)return null;let o=n[1],s=o===Nh.map(c=>`"${c}"`).join(" ");return!s&&o!==Rh.map(c=>`"${c}"`).join(" ")?null:{hasBody:s,created:Number(n[2]),nonce:n[3],keyid:n[4],signature:a[1]}}function ID(e){return`visa-setup-claim:${e}`}function ED(e){return`visa-setup-resume:v1:${e.jkt}:${e.setupId??"-"}:${e.nonce}:${e.issuedAt}`}});var xh=P(Oi=>{"use strict";Object.defineProperty(Oi,"__esModule",{value:!0});Oi.DeviceApproverPhaseStatement=Oi.DeviceApproverRoster=void 0;var ne=ct(),Dh=Rt(),Ce=ne.z.string().min(1),Vl=ne.z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),Mh=ne.z.strictObject({kty:ne.z.literal("OKP"),crv:ne.z.literal("Ed25519"),x:ne.z.string().regex(/^[A-Za-z0-9_-]{43}$/)}),Ec=ne.z.strictObject({policyName:Ce,effect:ne.z.enum(["EFFECT_ALLOW","EFFECT_DENY"]),consensus:Ce,condition:Ce,notes:ne.z.string()});Oi.DeviceApproverRoster=ne.z.array(ne.z.strictObject({approverId:Ce,installationId:Ce,identityKeyId:Ce,identityGeneration:Vl,identityJkt:ne.z.string().regex(/^[A-Za-z0-9_-]{43}$/),publicJwk:Mh,provider:ne.z.literal("turnkey"),providerUserRef:ne.z.string(),state:ne.z.enum(["pending","active","removing"])})).max(8);var Fl=ne.z.strictObject({userName:Ce,apiKeys:ne.z.tuple([ne.z.strictObject({apiKeyName:Ce,publicKey:Ce,curveType:ne.z.enum(["API_KEY_CURVE_ED25519","API_KEY_CURVE_P256"])})]),authenticators:ne.z.tuple([]),oauthProviders:ne.z.tuple([]),userTags:ne.z.tuple([])}),PD=ne.z.discriminatedUnion("type",[ne.z.strictObject({type:ne.z.enum(["ACTIVITY_TYPE_CREATE_USERS_V3","ACTIVITY_TYPE_CREATE_USERS_V4"]),parameters:ne.z.strictObject({users:ne.z.union([ne.z.tuple([Fl]),ne.z.tuple([Fl,Fl])])})}),ne.z.strictObject({type:ne.z.literal("ACTIVITY_TYPE_CREATE_POLICIES"),parameters:ne.z.strictObject({policies:ne.z.union([ne.z.tuple([Ec]),ne.z.tuple([Ec,Ec])])})}),ne.z.strictObject({type:ne.z.literal("ACTIVITY_TYPE_UPDATE_POLICY_V2"),parameters:ne.z.strictObject({policyId:Ce,policyName:Ce,policyEffect:ne.z.enum(["EFFECT_ALLOW","EFFECT_DENY"]),policyCondition:Ce,policyConsensus:Ce,policyNotes:ne.z.string().optional()})})]);Oi.DeviceApproverPhaseStatement=ne.z.strictObject({kind:ne.z.literal("device_approver"),operation_id:Ce,step_no:ne.z.number().int().min(2).max(6),action:ne.z.enum(Dh.DEVICE_APPROVER_ACTIONS),recorded_body_hash:ne.z.string().regex(/^[A-Za-z0-9_-]{43}$/).nullable(),recorded_activity_ref:Ce.nullable(),intent:ne.z.strictObject({fence:ne.z.strictObject({ownerId:Ce,ownerSecurityEpoch:ne.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),agentId:Ce,setupId:Ce,operationId:Ce,installationId:Ce,walletKeyId:Ce,walletGeneration:Vl,identityKeyId:Ce,identityGeneration:Vl,identityJkt:ne.z.string().regex(/^[A-Za-z0-9_-]{43}$/),installationPublicJwk:Mh,organizationId:Ce,ownerUserId:Ce,rosterHash:ne.z.string().regex(/^[A-Za-z0-9_-]{43}$/)}),stepNo:ne.z.union([ne.z.literal(2),ne.z.literal(3),ne.z.literal(4),ne.z.literal(5),ne.z.literal(6)]),accessKeyId:Ce,accessKeyAddress:ne.z.string().regex(/^0x[0-9a-fA-F]{40}$/),stampPublicKey:ne.z.string().regex(/^0[23][0-9a-fA-F]{64}$/),roster:Oi.DeviceApproverRoster,action:ne.z.enum(Dh.DEVICE_APPROVER_ACTIONS),request:PD,previousPolicy:Ec.nullable().optional(),previousPolicyHash:ne.z.string().regex(/^[A-Za-z0-9_-]{43}$/).optional(),targetPolicyRef:Ce.optional()})}).superRefine((e,t)=>{let r=e.intent,i={create_device_approver_guard:2,create_device_approver_user:3,create_tempo_signer_guard:4,create_tempo_signer_user:5,create_device_approver_policy:6,update_device_approver_policy:6},n=e.action.endsWith("_user")?"ACTIVITY_TYPE_CREATE_USERS_V3":e.action==="update_device_approver_policy"?"ACTIVITY_TYPE_UPDATE_POLICY_V2":"ACTIVITY_TYPE_CREATE_POLICIES";(e.operation_id!==r.fence.operationId||e.action!==r.action||e.step_no!==r.stepNo||e.step_no!==i[e.action]||r.request.type!==n&&!(n==="ACTIVITY_TYPE_CREATE_USERS_V3"&&r.request.type==="ACTIVITY_TYPE_CREATE_USERS_V4")||e.recorded_activity_ref!==null&&e.recorded_body_hash===null||(e.action==="update_device_approver_policy"?r.previousPolicy===void 0||!r.previousPolicyHash||!r.targetPolicyRef||r.request.type!=="ACTIVITY_TYPE_UPDATE_POLICY_V2"||r.request.parameters.policyId!==r.targetPolicyRef||r.previousPolicy===null&&!e.recorded_body_hash:r.previousPolicy!==void 0||r.previousPolicyHash!==void 0||r.targetPolicyRef!==void 0))&&t.addIssue({code:"custom",message:"The device approver phase is inconsistent."})})});var Gl=P(ee=>{"use strict";var zD=ee&&ee.__createBinding||(Object.create?(function(e,t,r,i){i===void 0&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);(!n||("get"in n?!t.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}):(function(e,t,r,i){i===void 0&&(i=r),e[i]=t[r]})),en=ee&&ee.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&zD(t,e,r)};Object.defineProperty(ee,"__esModule",{value:!0});ee.apiMetadataOf=ee.successOutcomes=ee.buildOpenApi=ee.PUBLIC_OPERATIONS=ee.OWNER_OPERATIONS=ee.AGENT_OPERATIONS=ee.ADMIN_OPERATIONS=ee.mcpToolDescriptors=ee.MCP_DESCRIPTION_BUDGET=ee.MCP_TOOLS=ee.CliFailureReport=ee.CLI_FAILURE_SURFACES=ee.CLI_FAILURE_STEPS=ee.CLI_FAILURE_PLATFORMS=ee.CLI_FAILURE_KINDS=ee.CLI_FAILURE_EVENT_MAX_BYTES=ee.MCP_TOOL_CEILING=ee.PRODUCT_ROUTE_CEILING=ee.OPERATIONS=void 0;ee.operationById=AD;ee.countByFamily=jD;ee.productOperationCount=kD;var Uh=gh();Object.defineProperty(ee,"ADMIN_OPERATIONS",{enumerable:!0,get:function(){return Uh.ADMIN_OPERATIONS}});var Lh=vh();Object.defineProperty(ee,"AGENT_OPERATIONS",{enumerable:!0,get:function(){return Lh.AGENT_OPERATIONS}});var Zh=wh();Object.defineProperty(ee,"OWNER_OPERATIONS",{enumerable:!0,get:function(){return Zh.OWNER_OPERATIONS}});var qh=Ul();Object.defineProperty(ee,"PUBLIC_OPERATIONS",{enumerable:!0,get:function(){return qh.PUBLIC_OPERATIONS}});var TD=Pr();ee.OPERATIONS=[...Zh.OWNER_OPERATIONS,...Lh.AGENT_OPERATIONS,...Uh.ADMIN_OPERATIONS,...qh.PUBLIC_OPERATIONS];function AD(e){return ee.OPERATIONS.find(t=>t.id===e)}function jD(){let e={owner:0,agent:0,admin:0,mcp:0,oauth:0,"well-known":0,public:0};for(let t of ee.OPERATIONS)e[t.family]+=1;return e}function kD(){return ee.OPERATIONS.filter(e=>TD.PRODUCT_FAMILIES.includes(e.family)).length}ee.PRODUCT_ROUTE_CEILING=77;ee.MCP_TOOL_CEILING=7;en(pc(),ee);var ra=Ul();Object.defineProperty(ee,"CLI_FAILURE_EVENT_MAX_BYTES",{enumerable:!0,get:function(){return ra.CLI_FAILURE_EVENT_MAX_BYTES}});Object.defineProperty(ee,"CLI_FAILURE_KINDS",{enumerable:!0,get:function(){return ra.CLI_FAILURE_KINDS}});Object.defineProperty(ee,"CLI_FAILURE_PLATFORMS",{enumerable:!0,get:function(){return ra.CLI_FAILURE_PLATFORMS}});Object.defineProperty(ee,"CLI_FAILURE_STEPS",{enumerable:!0,get:function(){return ra.CLI_FAILURE_STEPS}});Object.defineProperty(ee,"CLI_FAILURE_SURFACES",{enumerable:!0,get:function(){return ra.CLI_FAILURE_SURFACES}});Object.defineProperty(ee,"CliFailureReport",{enumerable:!0,get:function(){return ra.CliFailureReport}});en(Pr(),ee);en(Rt(),ee);en(Si(),ee);en(Pl(),ee);var Bl=Ll();Object.defineProperty(ee,"MCP_TOOLS",{enumerable:!0,get:function(){return Bl.MCP_TOOLS}});Object.defineProperty(ee,"MCP_DESCRIPTION_BUDGET",{enumerable:!0,get:function(){return Bl.MCP_DESCRIPTION_BUDGET}});Object.defineProperty(ee,"mcpToolDescriptors",{enumerable:!0,get:function(){return Bl.mcpToolDescriptors}});var Fh=jh();Object.defineProperty(ee,"buildOpenApi",{enumerable:!0,get:function(){return Fh.buildOpenApi}});Object.defineProperty(ee,"successOutcomes",{enumerable:!0,get:function(){return Fh.successOutcomes}});en(kh(),ee);en(Ch(),ee);en(xh(),ee);en(zl(),ee);en(Al(),ee);var ND=Et();Object.defineProperty(ee,"apiMetadataOf",{enumerable:!0,get:function(){return ND.apiMetadataOf}});en(xa(),ee)});var Jl=P((F4,RD)=>{RD.exports={name:"@visa/cli",version:"5.0.0-rc.411",description:"Visa CLI runtime for stable agent identity and separately authorized payment capabilities",bin:{"visa-cli":"./bin/visa-cli.js",visa:"./bin/visa-cli.js","visa-runtime-converge":"./dist/managed-runtime/resolve-and-update.mjs","visa-tool":"./bin/visa-tool.js"},scripts:{"sync:server-json":"node scripts/sync-server-json.mjs","check:server-json":"node scripts/sync-server-json.mjs --check",prebuild:"node scripts/sync-server-json.mjs",build:"pnpm test:types && node esbuild.config.js",prepack:"node scripts/sync-server-json.mjs --check",dev:"tsc --watch",pretest:"pnpm build",start:"node dist/mcp-server/index.js",test:"jest --config jest.config.js","test:types":"tsc -p tsconfig.test.json","pretest:unit":"pnpm test:types","test:unit":"jest --config jest.config.js","pretest:unit:watch":"pnpm test:types","test:unit:watch":"jest --config jest.config.js --watch","pretest:unit:coverage":"pnpm test:types","test:unit:coverage":"jest --config jest.config.js --coverage","test:smoke":"VISA_AUTH_URL=https://auth.visacli.sh jest --config jest.smoke.config.js","test:packed":"node scripts/packed-cli-smoke.mjs","test:e2e":"jest --config jest.e2e.config.js","test:all":"npm run test:unit && npm run test:e2e",prepublishOnly:"npm run build && npm test",lint:"eslint src/**/*.ts",format:'prettier --write "src/**/*.ts"',"format:check":'prettier --check "src/**/*.ts"'},keywords:["visa","checkout","mcp","ai-agent","payments","click-to-pay","usdc","stablecoin"],author:"Visa Crypto Labs",license:"SEE LICENSE IN LICENSE",dependencies:{"@modelcontextprotocol/server":"2.0.0",commander:"^12.1.0",punycode:"^2.3.1"},devDependencies:{"@types/express":"^5.0.0","@types/jest":"^30.0.0","@types/node":"^22.20.5","@typescript-eslint/eslint-plugin":"^8.68.0","@typescript-eslint/parser":"^8.68.0","@visa/financial-core":"workspace:*","@visa/identity":"workspace:*","@visa/contracts":"workspace:*","@visa/observability":"workspace:*","@visa/shared":"workspace:*","@visa/wallet":"workspace:*",esbuild:"^0.28.1",eslint:"^10.0.2",express:"^4.21.0",jest:"^30.3.0",prettier:"^3.9.6","ts-jest":"^29.4.12",typescript:"^5.7.0",viem:"^2.56.0"},engines:{node:">=20.0.0"},mcpName:"io.github.visa-crypto-labs/visa-cli",files:["bin/visa-cli.js","bin/visa-tool.js","dist/","install.ps1","install.sh","server.json","README.md"]}});var Wa=P((J4,tv)=>{"use strict";var Xl=Object.defineProperty,DD=Object.getOwnPropertyDescriptor,MD=Object.getOwnPropertyNames,xD=Object.prototype.hasOwnProperty,UD=(e,t)=>{for(var r in t)Xl(e,r,{get:t[r],enumerable:!0})},LD=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of MD(t))!xD.call(e,n)&&n!==r&&Xl(e,n,{get:()=>t[n],enumerable:!(i=DD(t,n))||i.enumerable});return e},ZD=e=>LD(Xl({},"__esModule",{value:!0}),e),Kh={};UD(Kh,{base64UrlToBytes:()=>rM,bytesToBase64Url:()=>nM,bytesToHex:()=>XD,hexToBytes:()=>QD});tv.exports=ZD(Kh);var Ql=Object.freeze,aa=0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,Yl=0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,zc=0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Kl=0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Hl=0x6666666666666666666666666666666666666666666666666666666666666658n,Tc=aa-1n,qD=Ql({p:aa,n:Yl,h:8n,a:Tc,d:zc,Gx:Kl,Gy:Hl}),Hh=32,Bh=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&e.BYTES_PER_ELEMENT===1,Ac=(e,t,r="")=>{if(Bh(e)&&(t===void 0||e.length===t))return e;let i=Bh(e),n=t!==void 0?` of length ${t}`:"",a=i?`length=${e.length}`:`type=${typeof e}`,o=(r?`"${r}" `:"")+"expected Uint8Array"+n+", got "+a;throw i?new RangeError(o):new TypeError(o)},FD=(e,t="",r)=>Uint8Array.from(Ac(e,r,t)),Xh=(e,t)=>e.toString(16).padStart(t,"0"),ed=e=>{let t="";for(let r of Ac(e))t+=Xh(r,2);return t},td=e=>{let t="hex invalid";if(typeof e!="string")throw new TypeError(t);if(e.length%2||!/^[\da-f]*$/i.test(e))throw new RangeError(t);let r=new Uint8Array(e.length/2);for(let i=0,n=0;i<r.length;i++,n+=2){let a=e.charCodeAt(n),o=e.charCodeAt(n+1);r[i]=((a&15)+(a>>6)*9)*16+(o&15)+(o>>6)*9}return r},VD=(...e)=>{let t=0;for(let n of e)t+=Ac(n).length;let r=new Uint8Array(t),i=0;for(let n of e)r.set(n,i),i+=n.length;return r},BD=(e=Hh)=>{let t=globalThis?.crypto;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined, consider polyfill");return t.getRandomValues(new Uint8Array(e))},Ii=(e,t,r,i="bad number: out of range")=>{if(typeof e!="bigint")throw new TypeError(i);if(t<=e&&e<r)return e;throw new RangeError(i)},qe=(e,t=aa)=>(e%=t)>=0n?e:t+e,Gh=(1n<<255n)-1n,K=e=>{if(e<0n)throw new RangeError("negative coordinate");let t=(e>>255n)*19n+(e&Gh);return t=(t>>255n)*19n+(t&Gh),t%aa},Qh=(e,t)=>{if(e===0n)throw new Error("invert: expected non-zero number");if(t<=1n)throw new Error("invert: expected modulus > 1, got "+t);let r=qe(e,t),i=t,n=0n,a=1n;for(;r!==0n;){let s=i/r,c=i-r*s,u=n-a*s;i=r,r=c,n=a,a=u}if(i!==1n)throw new Error("invert: does not exist");return qe(n,t)},Wl=e=>{if(e instanceof Ja)return e;throw new TypeError("Point expected")},ev=2n**256n,Ja=class Ei{static BASE;static ZERO;X;Y;Z;T;constructor(t,r,i,n){let a=ev;this.X=Ii(t,0n,a),this.Y=Ii(r,0n,a),this.Z=Ii(i,1n,a),this.T=Ii(n,0n,a),Ql(this)}static CURVE(){return qD}static fromAffine(t){return new Ei(t.x,t.y,1n,K(t.x*t.y))}static fromBytes(t,r=!1){let i=FD(t,"point",Hh),n=i[31];i[31]=n&-129;let a=JD(i);r||Ii(a,0n,aa);let o=K(a*a),s=qe(o-1n),c=K(zc*o+1n),{isValid:u,value:d}=YD(s,c);if(!u)throw new Error("bad point: y not sqrt");let p=!!(n&128);if(!r&&d===0n&&p)throw new Error("bad point: x==0, isLastByteOdd");return p!==!!(d&1n)&&(d=qe(-d)),new Ei(d,a,1n,K(d*a))}static fromHex(t,r){return Ei.fromBytes(td(t),r)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=Tc,r=zc,i=this;if(i.is0())throw new Error("bad point: ZERO");let{X:n,Y:a,Z:o,T:s}=i,c=K(n*n),u=K(a*a),d=K(o*o),p=K(d*d),m=K(c*t),b=K(d*(m+u)),y=qe(p+K(r*K(c*u)));if(b!==y)throw new Error("bad point: equation left != right (1)");let O=K(n*a),z=K(o*s);if(O!==z)throw new Error("bad point: equation left != right (2)");return this}equals(t){let{X:r,Y:i,Z:n}=this,{X:a,Y:o,Z:s}=Wl(t);return K(r*s)===K(a*n)&&K(i*s)===K(o*n)}is0(){return this.equals(Pi)}negate(){return new Ei(qe(-this.X),this.Y,this.Z,qe(-this.T))}double(){let{X:t,Y:r,Z:i}=this,n=Tc,a=K(t*t),o=K(r*r),s=K(2n*i*i),c=K(n*a),u=qe(t+r),d=qe(K(u*u)-a-o),p=qe(c+o),m=qe(p-s),b=qe(c-o),y=K(d*m),O=K(p*b),z=K(d*b),re=K(m*p);return new Ei(y,O,re,z)}add(t){let{X:r,Y:i,Z:n,T:a}=this,{X:o,Y:s,Z:c,T:u}=Wl(t),d=Tc,p=zc,m=K(r*o),b=K(i*s),y=K(K(a*p)*u),O=K(n*c),z=qe(K(qe(r+i)*qe(o+s))-m-b),re=qe(O-y),C=qe(O+y),Z=qe(b-K(d*m)),oe=K(z*re),ve=K(C*Z),me=K(z*Z),Pe=K(re*C);return new Ei(oe,ve,Pe,me)}subtract(t){return this.add(Wl(t).negate())}multiply(t,r=!0){if(!r&&t===0n||(Ii(t,1n,Yl),!r&&this.is0()))return Pi;if(t===1n)return this;if(this.equals(Ga))return HD(t).p;let i=Pi,n=Ga,a=this;for(let o=0;r?o<256:t>0n;o++)t&1n?i=i.add(a):r&&(n=n.add(a)),a=a.double(),t>>=1n;return i}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){let{X:t,Y:r,Z:i}=this;if(this.equals(Pi))return{x:0n,y:1n};let n=Qh(i,aa);if(K(i*n)!==1n)throw new Error("invalid inverse");return{x:K(t*n),y:K(r*n)}}toBytes(){let{x:t,y:r}=this.toAffine(),i=GD(r);return i[31]|=t&1n?128:0,i}toHex(){return ed(this.toBytes())}clearCofactor(){return this.multiply(8n,!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return this.multiply(Yl/2n,!1).double().add(this).is0()}},Ga=new Ja(Kl,Hl,1n,qe(Kl*Hl)),Pi=new Ja(0n,1n,1n,0n);Ja.BASE=Ga;Ja.ZERO=Pi;var GD=e=>td(Xh(Ii(e,0n,ev),64)).reverse(),JD=e=>BigInt("0x"+ed(Uint8Array.from(Ac(e)).reverse())),mr=(e,t)=>{let r=e;for(;t-- >0;)r=K(r*r);return r},WD=e=>{let t=K(e*e),r=K(t*e),i=K(mr(r,2)*r),n=K(mr(i,1)*e),a=K(mr(n,5)*n),o=K(mr(a,10)*a),s=K(mr(o,20)*o),c=K(mr(s,40)*s),u=K(mr(c,80)*c),d=K(mr(u,80)*c),p=K(mr(d,10)*a);return K(mr(p,2)*e)},Jh=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,YD=(e,t)=>{let r=K(t*K(t*t)),i=K(K(r*r)*t),n=WD(K(e*i)),a=K(e*K(r*n)),o=K(t*K(a*a)),s=a,c=K(a*Jh),u=o===e,d=o===qe(-e),p=o===qe(-e*Jh);return u&&(a=s),(d||p)&&(a=c),(qe(a)&1n)===1n&&(a=qe(-a)),{isValid:u||d,value:a}},nd=Ql({bytesToHex:ed,hexToBytes:td,concatBytes:VD,mod:qe,invert:Qh,randomBytes:BD}),KD=()=>{let e=[],t=Ga,r;for(let i=0;i<33;i++){r=t,e.push(r);for(let n=1;n<128;n++)r=r.add(t),e.push(r);t=r.double()}return e},Wh=void 0,Yh=(e,t)=>{let r=t.negate();return e?r:t},HD=e=>{let t=Wh||(Wh=KD()),r=Pi,i=Ga;for(let n=0;n<33;n++){let a=Number(e&255n);e>>=8n,a>128&&(a-=256,e+=1n);let o=n*128,s=o+Math.abs(a)-1,c=n%2!==0,u=a<0;a===0?i=i.add(Yh(c,t[o])):r=r.add(Yh(u,t[s]))}if(e!==0n)throw new Error("invalid wnaf");return{p:r,f:i}},XD=nd.bytesToHex,QD=nd.hexToBytes,G4=nd.concatBytes;function eM(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function tM(e){let t=atob(e),r=new Uint8Array(t.length);for(let i=0;i<t.length;i++)r[i]=t.charCodeAt(i);return r}function nM(e){return eM(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function rM(e){let t=e.length%4===0?0:4-e.length%4,r=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat(t);return tM(r)}});var _d=P((H4,Nv)=>{"use strict";var cd=Object.defineProperty,iM=Object.getOwnPropertyDescriptor,aM=Object.getOwnPropertyNames,oM=Object.prototype.hasOwnProperty,sM=(e,t)=>{for(var r in t)cd(e,r,{get:t[r],enumerable:!0})},cM=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of aM(t))!oM.call(e,n)&&n!==r&&cd(e,n,{get:()=>t[n],enumerable:!(i=iM(t,n))||i.enumerable});return e},uM=e=>cM(cd({},"__esModule",{value:!0}),e),mv={};sM(mv,{computeJkt:()=>n1,sha256:()=>kv,sign:()=>KM,signAsync:()=>XM,verify:()=>HM,verifyAsync:()=>QM});Nv.exports=uM(mv);var ud=Object.freeze,ca=0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,Dc=0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,Rc=0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,ad=0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,od=0x6666666666666666666666666666666666666666666666666666666666666658n,Cc=ca-1n,lM=ud({p:ca,n:Dc,h:8n,a:Cc,d:Rc,Gx:ad,Gy:od}),ji=32,nv=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&e.BYTES_PER_ELEMENT===1,Bt=(e,t,r="")=>{if(nv(e)&&(t===void 0||e.length===t))return e;let i=nv(e),n=t!==void 0?` of length ${t}`:"",a=i?`length=${e.length}`:`type=${typeof e}`,o=(r?`"${r}" `:"")+"expected Uint8Array"+n+", got "+a;throw i?new RangeError(o):new TypeError(o)},Uc=(e,t="",r)=>Uint8Array.from(Bt(e,r,t)),gv=(e,t)=>e.toString(16).padStart(t,"0"),ld=e=>{let t="";for(let r of Bt(e))t+=gv(r,2);return t},dd=e=>{let t="hex invalid";if(typeof e!="string")throw new TypeError(t);if(e.length%2||!/^[\da-f]*$/i.test(e))throw new RangeError(t);let r=new Uint8Array(e.length/2);for(let i=0,n=0;i<r.length;i++,n+=2){let a=e.charCodeAt(n),o=e.charCodeAt(n+1);r[i]=((a&15)+(a>>6)*9)*16+(o&15)+(o>>6)*9}return r},ki=(...e)=>{let t=0;for(let n of e)t+=Bt(n).length;let r=new Uint8Array(t),i=0;for(let n of e)r.set(n,i),i+=n.length;return r},dM=(e=ji)=>{let t=globalThis?.crypto;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined, consider polyfill");return t.getRandomValues(new Uint8Array(e))},zi=(e,t,r,i="bad number: out of range")=>{if(typeof e!="bigint")throw new TypeError(i);if(t<=e&&e<r)return e;throw new RangeError(i)},xe=(e,t=ca)=>(e%=t)>=0n?e:t+e,rv=(1n<<255n)-1n,H=e=>{if(e<0n)throw new RangeError("negative coordinate");let t=(e>>255n)*19n+(e&rv);return t=(t>>255n)*19n+(t&rv),t%ca},_v=e=>xe(e,Dc),hv=(e,t)=>{if(e===0n)throw new Error("invert: expected non-zero number");if(t<=1n)throw new Error("invert: expected modulus > 1, got "+t);let r=xe(e,t),i=t,n=0n,a=1n;for(;r!==0n;){let s=i/r,c=i-r*s,u=n-a*s;i=r,r=c,n=a,a=u}if(i!==1n)throw new Error("invert: does not exist");return xe(n,t)},vv=e=>{let t=Ev[e];if(typeof t!="function")throw new Error("hashes."+e+" not set");return t},fd=(e,...t)=>Bt(vv(e)(ki(...t)),64,"digest"),pd=async(e,...t)=>Bt(await vv(e)(ki(...t)),64,"digest"),rd=e=>{if(e instanceof Ni)return e;throw new TypeError("Point expected")},yv=2n**256n,Ni=class Ti{static BASE;static ZERO;X;Y;Z;T;constructor(t,r,i,n){let a=yv;this.X=zi(t,0n,a),this.Y=zi(r,0n,a),this.Z=zi(i,1n,a),this.T=zi(n,0n,a),ud(this)}static CURVE(){return lM}static fromAffine(t){return new Ti(t.x,t.y,1n,H(t.x*t.y))}static fromBytes(t,r=!1){let i=Uc(t,"point",ji),n=i[31];i[31]=n&-129;let a=md(i);r||zi(a,0n,ca);let o=H(a*a),s=xe(o-1n),c=H(Rc*o+1n),{isValid:u,value:d}=pM(s,c);if(!u)throw new Error("bad point: y not sqrt");let p=!!(n&128);if(!r&&d===0n&&p)throw new Error("bad point: x==0, isLastByteOdd");return p!==!!(d&1n)&&(d=xe(-d)),new Ti(d,a,1n,H(d*a))}static fromHex(t,r){return Ti.fromBytes(dd(t),r)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=Cc,r=Rc,i=this;if(i.is0())throw new Error("bad point: ZERO");let{X:n,Y:a,Z:o,T:s}=i,c=H(n*n),u=H(a*a),d=H(o*o),p=H(d*d),m=H(c*t),b=H(d*(m+u)),y=xe(p+H(r*H(c*u)));if(b!==y)throw new Error("bad point: equation left != right (1)");let O=H(n*a),z=H(o*s);if(O!==z)throw new Error("bad point: equation left != right (2)");return this}equals(t){let{X:r,Y:i,Z:n}=this,{X:a,Y:o,Z:s}=rd(t);return H(r*s)===H(a*n)&&H(i*s)===H(o*n)}is0(){return this.equals(Ai)}negate(){return new Ti(xe(-this.X),this.Y,this.Z,xe(-this.T))}double(){let{X:t,Y:r,Z:i}=this,n=Cc,a=H(t*t),o=H(r*r),s=H(2n*i*i),c=H(n*a),u=xe(t+r),d=xe(H(u*u)-a-o),p=xe(c+o),m=xe(p-s),b=xe(c-o),y=H(d*m),O=H(p*b),z=H(d*b),re=H(m*p);return new Ti(y,O,re,z)}add(t){let{X:r,Y:i,Z:n,T:a}=this,{X:o,Y:s,Z:c,T:u}=rd(t),d=Cc,p=Rc,m=H(r*o),b=H(i*s),y=H(H(a*p)*u),O=H(n*c),z=xe(H(xe(r+i)*xe(o+s))-m-b),re=xe(O-y),C=xe(O+y),Z=xe(b-H(d*m)),oe=H(z*re),ve=H(C*Z),me=H(z*Z),Pe=H(re*C);return new Ti(oe,ve,Pe,me)}subtract(t){return this.add(rd(t).negate())}multiply(t,r=!0){if(!r&&t===0n||(zi(t,1n,Dc),!r&&this.is0()))return Ai;if(t===1n)return this;if(this.equals(Qr))return SM(t).p;let i=Ai,n=Qr,a=this;for(let o=0;r?o<256:t>0n;o++)t&1n?i=i.add(a):r&&(n=n.add(a)),a=a.double(),t>>=1n;return i}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){let{X:t,Y:r,Z:i}=this;if(this.equals(Ai))return{x:0n,y:1n};let n=hv(i,ca);if(H(i*n)!==1n)throw new Error("invalid inverse");return{x:H(t*n),y:H(r*n)}}toBytes(){let{x:t,y:r}=this.toAffine(),i=bv(r);return i[31]|=t&1n?128:0,i}toHex(){return ld(this.toBytes())}clearCofactor(){return this.multiply(8n,!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return this.multiply(Dc/2n,!1).double().add(this).is0()}},Qr=new Ni(ad,od,1n,xe(ad*od)),Ai=new Ni(0n,1n,1n,0n);Ni.BASE=Qr;Ni.ZERO=Ai;var bv=e=>dd(gv(zi(e,0n,yv),64)).reverse(),md=e=>BigInt("0x"+ld(Uint8Array.from(Bt(e)).reverse())),gr=(e,t)=>{let r=e;for(;t-- >0;)r=H(r*r);return r},fM=e=>{let t=H(e*e),r=H(t*e),i=H(gr(r,2)*r),n=H(gr(i,1)*e),a=H(gr(n,5)*n),o=H(gr(a,10)*a),s=H(gr(o,20)*o),c=H(gr(s,40)*s),u=H(gr(c,80)*c),d=H(gr(u,80)*c),p=H(gr(d,10)*a);return H(gr(p,2)*e)},iv=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,pM=(e,t)=>{let r=H(t*H(t*t)),i=H(H(r*r)*t),n=fM(H(e*i)),a=H(e*H(r*n)),o=H(t*H(a*a)),s=a,c=H(a*iv),u=o===e,d=o===xe(-e),p=o===xe(-e*iv);return u&&(a=s),(d||p)&&(a=c),(xe(a)&1n)===1n&&(a=xe(-a)),{isValid:u||d,value:a}},Mc=e=>_v(md(e)),wv=e=>{let t=Uc(e),r=t.slice(0,32);r[0]&=248,r[31]&=127,r[31]|=64;let i=t.slice(32),n=Mc(r),a=Qr.multiply(n),o=a.toBytes();return{head:r,prefix:i,scalar:n,point:a,pointBytes:o}},mM=e=>pd("sha512Async",Bt(e,ji,"secretKey")).then(wv),gM=e=>wv(fd("sha512",Bt(e,ji,"secretKey"))),Sv=async e=>e[1](await pd("sha512Async",e[0])),$v=e=>e[1](fd("sha512",e[0])),Ov=(e,t,r)=>{let{pointBytes:i,scalar:n}=e,a=Mc(t),o=Qr.multiply(a).toBytes();return[ki(o,i,r),u=>{let d=_v(a+Mc(u)*n);return Bt(ki(o,bv(d)),64)}]},_M=async(e,t)=>{let r=Uc(e,"message"),i=await mM(t);return Sv(Ov(i,await pd("sha512Async",i.prefix,r),r))},hM=(e,t)=>{let r=Uc(e,"message"),i=gM(t);return $v(Ov(i,fd("sha512",i.prefix,r),r))},vM=e=>{if(e===null||typeof e!="object")throw new TypeError("expected valid options object");return e.zip215??!0},Iv=(e,t,r,i)=>{e=Bt(e,64,"signature"),t=Bt(t,void 0,"message"),r=Bt(r,ji,"publicKey");let n=vM(i),a=e.subarray(0,ji),o=md(e.subarray(ji,64)),s,c,u,d=Uint8Array.of(),p=!1;try{s=Ni.fromBytes(r,n),c=Ni.fromBytes(a,n),u=Qr.multiply(o,!1),d=ki(a,r,t),p=!0}catch{}return[d,b=>{if(!p||!n&&s.isSmallOrder())return!1;let y=Mc(b);return c.add(s.multiply(y,!1)).subtract(u).clearCofactor().is0()}]},yM=async(e,t,r,i={})=>Sv(Iv(e,t,r,i)),bM=(e,t,r,i={})=>$v(Iv(e,t,r,i)),gd=ud({bytesToHex:ld,hexToBytes:dd,concatBytes:ki,mod:xe,invert:hv,randomBytes:dM}),Ev={sha512Async:async e=>{let t=globalThis?.crypto?.subtle;if(!t)throw new Error("crypto.subtle must be defined, consider polyfill");return new Uint8Array(await t.digest("SHA-512",ki(e)))},sha512:void 0},wM=()=>{let e=[],t=Qr,r;for(let i=0;i<33;i++){r=t,e.push(r);for(let n=1;n<128;n++)r=r.add(t),e.push(r);t=r.double()}return e},av=void 0,ov=(e,t)=>{let r=t.negate();return e?r:t},SM=e=>{let t=av||(av=wM()),r=Ai,i=Qr;for(let n=0;n<33;n++){let a=Number(e&255n);e>>=8n,a>128&&(a-=256,e+=1n);let o=n*128,s=o+Math.abs(a)-1,c=n%2!==0,u=a<0;a===0?i=i.add(ov(c,t[o])):r=r.add(ov(u,t[s]))}if(e!==0n)throw new Error("invalid wnaf");return{p:r,f:i}},jc=BigInt(2**32-1),sv=BigInt(32);function $M(e,t=!1){return t?{h:Number(e&jc),l:Number(e>>sv&jc)}:{h:Number(e>>sv&jc)|0,l:Number(e&jc)|0}}function OM(e,t=!1){let r=e.length,i=new Uint32Array(r),n=new Uint32Array(r);for(let a=0;a<r;a++){let{h:o,l:s}=$M(e[a],t);[i[a],n[a]]=[o,s]}return[i,n]}var IM=e=>e/2**32|0,EM=e=>e>>>0;function PM(e,t,r,i){let n=IM(r),a=EM(r);e.setUint32(t,i?a:n,i),e.setUint32(t+4,i?n:a,i)}var cv=(e,t,r)=>e>>>r,uv=(e,t,r)=>e<<32-r|t>>>r,oa=(e,t,r)=>e>>>r|t<<32-r,sa=(e,t,r)=>e<<32-r|t>>>r,kc=(e,t,r)=>e<<64-r|t>>>r-32,Nc=(e,t,r)=>e>>>r-32|t<<64-r;function Cr(e,t,r,i){let n=(t>>>0)+(i>>>0);return{h:e+r+(n/2**32|0)|0,l:n|0}}var zM=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),TM=(e,t,r,i)=>t+r+i+(e/2**32|0)|0,AM=(e,t,r,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(i>>>0),jM=(e,t,r,i,n)=>t+r+i+n+(e/2**32|0)|0,kM=(e,t,r,i,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(i>>>0)+(n>>>0),NM=(e,t,r,i,n,a)=>t+r+i+n+a+(e/2**32|0)|0;function lv(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var sd=e=>e?`"${e}" `:"";function RM(e,t=""){if(typeof e!="number")throw new TypeError(sd(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(sd(t)+"expected integer >= 0, got "+e);return e}function Pv(e,t,r=""){if(lv(e)&&(t===void 0||e.length===t))return e;t!==void 0&&RM(t,"length");let i=lv(e),n=t!==void 0?` of length ${t}`:"",a=i?`length=${e.length}`:`type=${typeof e}`,o=sd(r)+"expected Uint8Array"+n+", got "+a;throw i?new RangeError(o):new TypeError(o)}var CM=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},dv=(e,t)=>{CM(e,t);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw new TypeError(`"${t}.__proto__" is not allowed`)};function fv(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function DM(e,t){Pv(e,void 0,"output");let r=t.outputLen;if(!(e.length>=r))throw new RangeError('"output" expected length >= '+r)}function xc(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function id(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function _r(e,t){return e<<32-t|e>>>t}function MM(e,t,r="opts"){return dv(e,"defaults"),t!==void 0&&dv(t,r),Object.assign(Object.create(null),e,t)}function zv(e,t={}){if(typeof e!="function")throw new TypeError('"hashCons" expected function, got type='+typeof e);t=MM({},t,"info");let r=(n,a)=>e(a).update(n).digest(),i=e(void 0);return r.outputLen=i.outputLen,r.blockLen=i.blockLen,r.canXOF=i.canXOF,r.create=n=>e(n),Object.assign(r,t),Object.freeze(r)}var Tv=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function xM(e,t,r){return e&t^~e&r}function UM(e,t,r){return e&t^e&r^t&r}var Av=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,i){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(e),this.view=id(this.buffer)}update(e){fv(this),Pv(e);let{view:t,buffer:r,blockLen:i}=this,n=e.length,a=!1;for(let o=0;o<n;){let s=Math.min(i-this.pos,n-o);if(s===i){let c=id(e);for(;i<=n-o;o+=i)this.process(c,o);a=!0;continue}r.set(o===0&&s===n?e:e.subarray(o,o+s),this.pos),this.pos+=s,o+=s,this.pos===i&&(this.process(t,0),this.pos=0,a=!0)}return this.length+=e.length,a&&this.roundClean(),this}digestInto(e){fv(this),DM(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:i,isLE:n}=this,{pos:a}=this;t[a++]=128,t.fill(0,a),this.padOffset>i-a&&(this.process(r,0),t.fill(0)),PM(r,i-8,this.length*8,n),this.process(r,0),this.roundClean();let o=e===t?r:id(e),s=this.outputLen,c=s/4,u=this.get();if(s%4||c>u.length)throw new Error("invalid outputLen");for(let d=0;d<c;d++)o.setUint32(4*d,u[d],n)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneIntoMeta(e){let{buffer:t,length:r,finished:i,destroyed:n,pos:a}=this;return e.destroyed=n,e.finished=i,e.length=r,e.pos=a,a&&e.buffer.set(t),e}clone(){return this._cloneInto()}},LM=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ZM=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),qM=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Kr=new Uint32Array(64),FM=class extends Av{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:r,D:i,E:n,F:a,G:o,H:s}=this;return[e,t,r,i,n,a,o,s]}set(e,t,r,i,n,a,o,s){this.A=e|0,this.B=t|0,this.C=r|0,this.D=i|0,this.E=n|0,this.F=a|0,this.G=o|0,this.H=s|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let d=0;d<16;d++,t+=4)Kr[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let p=Kr[d-15],m=Kr[d-2],b=_r(p,7)^_r(p,18)^p>>>3,y=_r(m,17)^_r(m,19)^m>>>10;Kr[d]=y+Kr[d-7]+b+Kr[d-16]|0}let{A:r,B:i,C:n,D:a,E:o,F:s,G:c,H:u}=this;for(let d=0;d<64;d++){let p=_r(o,6)^_r(o,11)^_r(o,25),m=u+p+xM(o,s,c)+qM[d]+Kr[d]|0,y=(_r(r,2)^_r(r,13)^_r(r,22))+UM(r,i,n)|0;u=c,c=s,s=o,o=a+m|0,a=n,n=i,i=r,r=m+y|0}r=r+this.A|0,i=i+this.B|0,n=n+this.C|0,a=a+this.D|0,o=o+this.E|0,s=s+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(r,i,n,a,o,s,c,u)}roundClean(){xc(Kr)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),xc(this.buffer)}},VM=class extends FM{constructor(){super(32,LM)}},jv=OM(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),BM=jv[0],GM=jv[1],Hr=new Uint32Array(80),Xr=new Uint32Array(80),JM=class extends Av{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(e,t){super(128,e,16,!1),this.Ah=t[0]|0,this.Al=t[1]|0,this.Bh=t[2]|0,this.Bl=t[3]|0,this.Ch=t[4]|0,this.Cl=t[5]|0,this.Dh=t[6]|0,this.Dl=t[7]|0,this.Eh=t[8]|0,this.El=t[9]|0,this.Fh=t[10]|0,this.Fl=t[11]|0,this.Gh=t[12]|0,this.Gl=t[13]|0,this.Hh=t[14]|0,this.Hl=t[15]|0}get(){let{Ah:e,Al:t,Bh:r,Bl:i,Ch:n,Cl:a,Dh:o,Dl:s,Eh:c,El:u,Fh:d,Fl:p,Gh:m,Gl:b,Hh:y,Hl:O}=this;return[e,t,r,i,n,a,o,s,c,u,d,p,m,b,y,O]}set(e,t,r,i,n,a,o,s,c,u,d,p,m,b,y,O){this.Ah=e|0,this.Al=t|0,this.Bh=r|0,this.Bl=i|0,this.Ch=n|0,this.Cl=a|0,this.Dh=o|0,this.Dl=s|0,this.Eh=c|0,this.El=u|0,this.Fh=d|0,this.Fl=p|0,this.Gh=m|0,this.Gl=b|0,this.Hh=y|0,this.Hl=O|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let C=0;C<16;C++,t+=4)Hr[C]=e.getUint32(t),Xr[C]=e.getUint32(t+=4);for(let C=16;C<80;C++){let Z=Hr[C-15]|0,oe=Xr[C-15]|0,ve=oa(Z,oe,1)^oa(Z,oe,8)^cv(Z,oe,7),me=sa(Z,oe,1)^sa(Z,oe,8)^uv(Z,oe,7),Pe=Hr[C-2]|0,ft=Xr[C-2]|0,si=oa(Pe,ft,19)^kc(Pe,ft,61)^cv(Pe,ft,6),Li=sa(Pe,ft,19)^Nc(Pe,ft,61)^uv(Pe,ft,6),ci=AM(me,Li,Xr[C-7],Xr[C-16]),va=jM(ci,ve,si,Hr[C-7],Hr[C-16]);Hr[C]=va|0,Xr[C]=ci|0}let{Ah:r,Al:i,Bh:n,Bl:a,Ch:o,Cl:s,Dh:c,Dl:u,Eh:d,El:p,Fh:m,Fl:b,Gh:y,Gl:O,Hh:z,Hl:re}=this;for(let C=0;C<80;C++){let Z=oa(d,p,14)^oa(d,p,18)^kc(d,p,41),oe=sa(d,p,14)^sa(d,p,18)^Nc(d,p,41),ve=d&m^~d&y,me=p&b^~p&O,Pe=kM(re,oe,me,GM[C],Xr[C]),ft=NM(Pe,z,Z,ve,BM[C],Hr[C]),si=Pe|0,Li=oa(r,i,28)^kc(r,i,34)^kc(r,i,39),ci=sa(r,i,28)^Nc(r,i,34)^Nc(r,i,39),va=r&n^r&o^n&o,ru=i&a^i&s^a&s;z=y|0,re=O|0,y=m|0,O=b|0,m=d|0,b=p|0,{h:d,l:p}=Cr(c|0,u|0,ft|0,si|0),c=o|0,u=s|0,o=n|0,s=a|0,n=r|0,a=i|0;let tf=zM(si,ci,ru);r=TM(tf,ft,Li,va),i=tf|0}({h:r,l:i}=Cr(this.Ah|0,this.Al|0,r|0,i|0)),{h:n,l:a}=Cr(this.Bh|0,this.Bl|0,n|0,a|0),{h:o,l:s}=Cr(this.Ch|0,this.Cl|0,o|0,s|0),{h:c,l:u}=Cr(this.Dh|0,this.Dl|0,c|0,u|0),{h:d,l:p}=Cr(this.Eh|0,this.El|0,d|0,p|0),{h:m,l:b}=Cr(this.Fh|0,this.Fl|0,m|0,b|0),{h:y,l:O}=Cr(this.Gh|0,this.Gl|0,y|0,O|0),{h:z,l:re}=Cr(this.Hh|0,this.Hl|0,z|0,re|0),this.set(r,i,n,a,o,s,c,u,d,p,m,b,y,O,z,re)}roundClean(){xc(Hr,Xr)}destroy(){this.destroyed=!0,xc(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},WM=class extends JM{constructor(){super(64,ZM)}},kv=zv(()=>new VM,Tv(1)),YM=zv(()=>new WM,Tv(3)),pv=Ev;pv.sha512||(pv.sha512=e=>YM(e));function KM(e,t){return hM(t,e)}function HM(e,t,r){return bM(t,r,e)}function XM(e,t){return _M(t,e)}function QM(e,t,r){return yM(t,r,e)}var W4=gd.bytesToHex,Y4=gd.hexToBytes,K4=gd.concatBytes;function e1(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function t1(e){return e1(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function n1(e){if(e.kty!=="OKP")throw new Error(`computeJkt expects an OKP JWK; got kty="${e.kty}"`);let t=JSON.stringify({crv:e.crv,kty:e.kty,x:e.x});return t1(kv(new TextEncoder().encode(t)))}});var hd=P(Lc=>{"use strict";Object.defineProperty(Lc,"__esModule",{value:!0});Lc.computeJkt=void 0;var r1=_d();Object.defineProperty(Lc,"computeJkt",{enumerable:!0,get:function(){return r1.computeJkt}})});var Rv=P(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});Zc.prepareRootSignedJws=i1;Zc.completeRootSignedJws=a1;var vd=Wa();function i1(e,t,r){let i=(0,vd.bytesToBase64Url)(new TextEncoder().encode(JSON.stringify({alg:"EdDSA",kid:t,typ:e}))),n=(0,vd.bytesToBase64Url)(new TextEncoder().encode(JSON.stringify(r)));return{signingInput:`${i}.${n}`}}function a1(e,t,r){if(!(t instanceof Uint8Array)||t.length!==64)throw new Error(`${r} signature must be exactly 64 raw Ed25519 bytes`);return`${e}.${(0,vd.bytesToBase64Url)(t)}`}});var ua=P(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.CLOCK_SKEW_SECONDS=N.PUBLIC_MATERIAL_TTL_SECONDS=N.ENROLLMENT_RECEIPT_TTL_SECONDS=N.AGENT_OPERATION_MAX_TTL_SECONDS=N.AGENT_OPERATION_MAX_AGE_SECONDS=N.MAX_OWNER_APPROVED_CHARGE_WINDOW_SECONDS=N.MAX_CHARGE_WINDOW_AFTER_ADMISSION_SECONDS=N.OWNER_STATEMENT_MAX_SECONDS=N.TAP_MAX_AGE_SECONDS=N.POP_MAX_AGE_SECONDS=N.WALLET_BINDING_MAX_TTL_SECONDS=N.RUNTIME_CERTIFICATE_MAX_TTL_SECONDS=N.REGISTRY_ENTRY_MAX_TTL_SECONDS=N.IDENTITY_GATE_ENROLLMENT_MAX_TTL_SECONDS=N.IDENTITY_GATE_AUTHORIZATION_MAX_TTL_SECONDS=N.FINANCIAL_ADMISSION_MAX_TTL_SECONDS=N.ASSOCIATION_ADMISSION_MAX_TTL_SECONDS=N.RUNTIME_ADMISSION_MAX_TTL_SECONDS=N.IDENTITY_SLIP_MAX_TTL_SECONDS=N.RENEWAL_MARGIN_SECONDS=N.TAP_DIRECTORY_RENEW_WINDOW_SECONDS=N.TAP_KEY_TTL_DAYS=N.APP_CONNECT_TTL_SECONDS=N.APP_TOKEN_IDLE_SECONDS=N.CLI_CEREMONY_GRACE_MS=N.CLI_HANDOFF_TTL_MS=N.OWNER_ENROLLMENT_CLAIM_WINDOW_SECONDS=N.OWNER_PAYMENT_APPROVAL_SECONDS=N.RUNTIME_LEASE_REQUEST_MAX_AGE_SECONDS=N.ENROLLMENT_CHALLENGE_MAX_AGE_MS=N.AGENT_PAIRING_TTL_SECONDS=N.HOSTED_CONNECTOR_PROOF_TTL_SECONDS=N.RUNTIME_LEASE_MAX_TTL_SECONDS=N.RUNTIME_DELEGATION_MAX_TTL_SECONDS=N.WALLET_GRANT_MAX_TERM_SECONDS=N.WALLET_GRANT_DEFAULT_DAYS=N.CARD_MANDATE_MAX_SECONDS=N.CARD_GRANT_DEFAULT_TERM_SECONDS=N.CARD_GRANT_MAX_TERM_SECONDS=N.DAY_SECONDS=void 0;N.walletGrantExpiry=o1;N.defaultGrantExpiry=s1;N.renewalDue=c1;N.DAY_SECONDS=86400;N.CARD_GRANT_MAX_TERM_SECONDS=7*N.DAY_SECONDS;N.CARD_GRANT_DEFAULT_TERM_SECONDS=N.CARD_GRANT_MAX_TERM_SECONDS-3600;N.CARD_MANDATE_MAX_SECONDS=N.CARD_GRANT_DEFAULT_TERM_SECONDS;N.WALLET_GRANT_DEFAULT_DAYS=30;N.WALLET_GRANT_MAX_TERM_SECONDS=90*N.DAY_SECONDS;function o1(e,t=new Date){if(e==null)return new Date(t.getTime()+N.WALLET_GRANT_DEFAULT_DAYS*N.DAY_SECONDS*1e3);if(Number.isNaN(e.getTime()))throw new RangeError("grant_expiry_invalid");if(e.getTime()<=t.getTime())throw new RangeError("grant_expiry_past");if(e.getTime()>t.getTime()+N.WALLET_GRANT_MAX_TERM_SECONDS*1e3)throw new RangeError("grant_expiry_beyond_maximum");return new Date(Math.floor(e.getTime()/1e3)*1e3)}function s1(e,t){return t.card?new Date(e.getTime()+N.CARD_GRANT_DEFAULT_TERM_SECONDS*1e3):new Date(e.getTime()+N.WALLET_GRANT_DEFAULT_DAYS*N.DAY_SECONDS*1e3)}N.RUNTIME_DELEGATION_MAX_TTL_SECONDS=366*N.DAY_SECONDS;N.RUNTIME_LEASE_MAX_TTL_SECONDS=300;N.HOSTED_CONNECTOR_PROOF_TTL_SECONDS=300;N.AGENT_PAIRING_TTL_SECONDS=3600;N.ENROLLMENT_CHALLENGE_MAX_AGE_MS=6e4;N.RUNTIME_LEASE_REQUEST_MAX_AGE_SECONDS=60;N.OWNER_PAYMENT_APPROVAL_SECONDS=240;N.OWNER_ENROLLMENT_CLAIM_WINDOW_SECONDS=600;N.CLI_HANDOFF_TTL_MS=15*6e4;N.CLI_CEREMONY_GRACE_MS=45*6e4;N.APP_TOKEN_IDLE_SECONDS=90*N.DAY_SECONDS;N.APP_CONNECT_TTL_SECONDS=900;N.TAP_KEY_TTL_DAYS=365;N.TAP_DIRECTORY_RENEW_WINDOW_SECONDS=30*N.DAY_SECONDS;N.RENEWAL_MARGIN_SECONDS=30*N.DAY_SECONDS;function c1(e){let t=e.marginSeconds??N.RENEWAL_MARGIN_SECONDS,r=Math.max(e.nowSec,e.grantEndSec??e.nowSec)+t,i=e.maxLifetimeSeconds===void 0?r:e.nowSec+e.maxLifetimeSeconds-t;return e.endSec<=Math.min(r,i)}N.IDENTITY_SLIP_MAX_TTL_SECONDS=60;N.RUNTIME_ADMISSION_MAX_TTL_SECONDS=600;N.ASSOCIATION_ADMISSION_MAX_TTL_SECONDS=60;N.FINANCIAL_ADMISSION_MAX_TTL_SECONDS=60;N.IDENTITY_GATE_AUTHORIZATION_MAX_TTL_SECONDS=366*N.DAY_SECONDS;N.IDENTITY_GATE_ENROLLMENT_MAX_TTL_SECONDS=366*N.DAY_SECONDS;N.REGISTRY_ENTRY_MAX_TTL_SECONDS=366*N.DAY_SECONDS;N.RUNTIME_CERTIFICATE_MAX_TTL_SECONDS=N.DAY_SECONDS;N.WALLET_BINDING_MAX_TTL_SECONDS=366*N.DAY_SECONDS;N.POP_MAX_AGE_SECONDS=120;N.TAP_MAX_AGE_SECONDS=480;N.OWNER_STATEMENT_MAX_SECONDS=300;N.MAX_CHARGE_WINDOW_AFTER_ADMISSION_SECONDS=30;N.MAX_OWNER_APPROVED_CHARGE_WINDOW_SECONDS=300;N.AGENT_OPERATION_MAX_AGE_SECONDS=300;N.AGENT_OPERATION_MAX_TTL_SECONDS=600;N.ENROLLMENT_RECEIPT_TTL_SECONDS=366*N.DAY_SECONDS;N.PUBLIC_MATERIAL_TTL_SECONDS=300;N.CLOCK_SKEW_SECONDS=30});var Uv=P(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.HOSTED_RUNTIME_CERTIFICATE_PURPOSES=He.RUNTIME_CERTIFICATE_PURPOSES=He.CARD_RUNTIME_CERTIFICATE_MAX_TTL_SECONDS=He.RUNTIME_CERTIFICATE_VERSION=He.RUNTIME_CERTIFICATE_TYP=He.RUNTIME_CERTIFICATE_MAX_TTL_SECONDS=void 0;He.runtimeCertificateMaxTtl=xv;He.isCanonicalBase64Url32=bd;He.prepareRuntimeCertificate=_1;var Cv=Wa(),Dv=hd(),u1=Rv(),l1=ua();Object.defineProperty(He,"RUNTIME_CERTIFICATE_MAX_TTL_SECONDS",{enumerable:!0,get:function(){return l1.RUNTIME_CERTIFICATE_MAX_TTL_SECONDS}});var Mv=ua();He.RUNTIME_CERTIFICATE_TYP="visa-agent-runtime-cert+jwt";He.RUNTIME_CERTIFICATE_VERSION=1;He.CARD_RUNTIME_CERTIFICATE_MAX_TTL_SECONDS=366*24*60*60;function xv(e){return e.length===1&&e[0]==="card:vic"?He.CARD_RUNTIME_CERTIFICATE_MAX_TTL_SECONDS:Mv.RUNTIME_CERTIFICATE_MAX_TTL_SECONDS}He.RUNTIME_CERTIFICATE_PURPOSES=["tap","subway","card:vic","wallet:x402"];He.HOSTED_RUNTIME_CERTIFICATE_PURPOSES=["card:vic","wallet:x402","tap"];var d1=new Set(He.RUNTIME_CERTIFICATE_PURPOSES),yd=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,f1=/^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/;function bd(e){if(typeof e!="string"||!f1.test(e))return!1;let t=(0,Cv.base64UrlToBytes)(e);return t.length===32&&(0,Cv.bytesToBase64Url)(t)===e}function p1(e){return{kty:"OKP",crv:"Ed25519",x:e.x}}function m1(e){if(!Array.isArray(e)||e.length===0)throw new Error("runtime certificate requires at least one purpose");let t=[...new Set(e)];if(t.length!==e.length||t.some(r=>!d1.has(r)))throw new Error("runtime certificate purposes must be unique supported values");return t.sort()}function g1(e,t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative unix-seconds integer`)}function _1(e){let t=e.nowSec??Math.floor(Date.now()/1e3),r=e.ttlSeconds??Mv.RUNTIME_CERTIFICATE_MAX_TTL_SECONDS,i=xv(e.purposes),n=e.certificateId??globalThis.crypto.randomUUID();if(g1("nowSec",t),!Number.isSafeInteger(r)||r<=0||r>i)throw new Error(`runtime certificate ttlSeconds must be in (0, ${i}]`);if(!yd.test(e.agentId)||!yd.test(e.runtimeId))throw new Error("runtime certificate agentId/runtimeId must be canonical UUIDs");if(!yd.test(n))throw new Error("runtime certificate certificateId must be a canonical UUID");if(!bd(e.rootJkt))throw new Error("runtime certificate rootJkt must be a canonical RFC 7638 thumbprint");if(!e.rootKid||e.rootKid.length>256)throw new Error("runtime certificate rootKid must be a bounded non-empty identifier");if((0,Dv.computeJkt)(e.rootPublicJwk)!==e.rootJkt)throw new Error("runtime certificate signer public key does not match rootJkt");let o=p1(e.runtimePublicJwk);if(!bd(o.x))throw new Error("runtime certificate child key must be canonical Ed25519");let s=(0,Dv.computeJkt)(o);if(s===e.rootJkt)throw new Error("runtime certificate child key must differ from the identity root");let c={v:He.RUNTIME_CERTIFICATE_VERSION,iss:e.rootJkt,sub:e.agentId,jti:n,runtimeId:e.runtimeId,cnf:{jwk:o,jkt:s},purposes:m1(e.purposes),iat:t,nbf:t,exp:t+r};return{...(0,u1.prepareRootSignedJws)(He.RUNTIME_CERTIFICATE_TYP,e.rootKid,c),claims:c}}});var Sd=P(wd=>{"use strict";Object.defineProperty(wd,"__esModule",{value:!0});wd.signJwtWithSigner=h1;var Zv=Wa(),Lv=e=>(0,Zv.bytesToBase64Url)(new TextEncoder().encode(JSON.stringify(e)));async function h1(e,t,r){let i=Lv({alg:"EdDSA",kid:e.kid,typ:t.typ}),n=Lv(r),a=`${i}.${n}`,o=await e.sign(new TextEncoder().encode(a));if(!(o instanceof Uint8Array)||o.length!==64)throw new Error(`signer.sign must return a raw 64-byte Ed25519 signature; got ${o instanceof Uint8Array?`${o.length} bytes`:typeof o} (check the vault adapter is not DER-wrapping or re-encoding)`);return`${a}.${(0,Zv.bytesToBase64Url)(o)}`}});var $d=P(la=>{"use strict";Object.defineProperty(la,"__esModule",{value:!0});la.POP_JWT_TYP=void 0;la.createPopProofWithSigner=y1;var v1=Sd();la.POP_JWT_TYP="visa-agent-pop+jwt";async function y1(e,t){let i={cnf:{jwk:{kty:e.publicJwk.kty,crv:e.publicJwk.crv,x:e.publicJwk.x}},nonce:t.nonce,aud:t.audience,iat:t.nowSec};return t.intentHash!==void 0&&(i.int=t.intentHash),t.runtimeCertificate!==void 0&&(i.rkc=t.runtimeCertificate),(0,v1.signJwtWithSigner)(e,{typ:la.POP_JWT_TYP},i)}});var Od=P(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.WALLET_BINDING_TYP=Pt.RUNTIME_AUTHORITY_CLOCK_SKEW_SECONDS=Pt.RUNTIME_LEASE_MAX_TTL_SECONDS=Pt.RUNTIME_DELEGATION_MAX_TTL_SECONDS=Pt.RUNTIME_LEASE_SIGNING_MODES=Pt.RUNTIME_DELEGATION_TYP=void 0;Pt.RUNTIME_DELEGATION_TYP="visa-agent-runtime-delegation+jwt";Pt.RUNTIME_LEASE_SIGNING_MODES=["eip3009:exact","permit2:upto"];var qv=ua();Object.defineProperty(Pt,"RUNTIME_DELEGATION_MAX_TTL_SECONDS",{enumerable:!0,get:function(){return qv.RUNTIME_DELEGATION_MAX_TTL_SECONDS}});Object.defineProperty(Pt,"RUNTIME_LEASE_MAX_TTL_SECONDS",{enumerable:!0,get:function(){return qv.RUNTIME_LEASE_MAX_TTL_SECONDS}});var b1=ua();Pt.RUNTIME_AUTHORITY_CLOCK_SKEW_SECONDS=b1.CLOCK_SKEW_SECONDS;Pt.WALLET_BINDING_TYP="visa-agent-wallet-binding+jwt"});var Vv=P(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.RUNTIME_LEASE_REQUEST_MAX_AGE_SECONDS=Gt.RUNTIME_LEASE_REQUEST_AUDIENCE=Gt.RUNTIME_LEASE_REQUEST_VERSION=void 0;Gt.runtimeLeaseRequestIntentHash=Fv;Gt.createRuntimeLeaseRequestProofWithSigner=T1;var w1=_d(),S1=Wa(),$1=$d(),O1=Od(),I1=ua();Object.defineProperty(Gt,"RUNTIME_LEASE_REQUEST_MAX_AGE_SECONDS",{enumerable:!0,get:function(){return I1.RUNTIME_LEASE_REQUEST_MAX_AGE_SECONDS}});Gt.RUNTIME_LEASE_REQUEST_VERSION=1;Gt.RUNTIME_LEASE_REQUEST_AUDIENCE="visa-runtime-lease-requests:v1";var E1=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,P1=new Set(O1.RUNTIME_LEASE_SIGNING_MODES);function Id(e,t){if(!E1.test(t))throw new Error(`${e} must be a canonical UUID`)}function z1(e){if(Id("agentId",e.agentId),Id("runtimeId",e.runtimeId),Id("requestId",e.requestId),!P1.has(e.signingMode))throw new Error("runtime lease request signingMode is unsupported");return{v:Gt.RUNTIME_LEASE_REQUEST_VERSION,agentId:e.agentId,runtimeId:e.runtimeId,requestId:e.requestId,signingMode:e.signingMode}}function Fv(e){return(0,S1.bytesToBase64Url)((0,w1.sha256)(new TextEncoder().encode(JSON.stringify(z1(e)))))}function T1(e,t){if(!Number.isSafeInteger(t.nowSec)||t.nowSec<0)throw new Error("runtime lease request nowSec must be a non-negative safe integer");return(0,$1.createPopProofWithSigner)(e,{nonce:t.requestId,audience:Gt.RUNTIME_LEASE_REQUEST_AUDIENCE,nowSec:t.nowSec,intentHash:Fv(t)})}});var Bv=P(Dt=>{"use strict";var A1=Dt&&Dt.__createBinding||(Object.create?(function(e,t,r,i){i===void 0&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);(!n||("get"in n?!t.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}):(function(e,t,r,i){i===void 0&&(i=r),e[i]=t[r]})),Ya=Dt&&Dt.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&A1(t,e,r)};Object.defineProperty(Dt,"__esModule",{value:!0});Dt.computeJkt=void 0;Ya(Uv(),Dt);Ya(Vv(),Dt);Ya($d(),Dt);Ya(Sd(),Dt);Ya(Od(),Dt);var j1=hd();Object.defineProperty(Dt,"computeJkt",{enumerable:!0,get:function(){return j1.computeJkt}})});var ty=P(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.TVC_PROVIDER_WARN_THRESHOLD=dt.TURNKEY_SUBORG_RESOURCE_LIMITS=void 0;dt.tvcProviderCapacityEvidence=ey;dt.parseTvcProviderCapacityEvidence=V1;dt.TURNKEY_SUBORG_RESOURCE_LIMITS=Object.freeze({users:100,policies:100,source:"https://docs.turnkey.com/reference/resource-limits",verifiedOn:"2026-08-29"});dt.TVC_PROVIDER_WARN_THRESHOLD=70;function ey(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error("user count is invalid");if(!Number.isSafeInteger(t)||t<0)throw new Error("policy count is invalid");let r=dt.TURNKEY_SUBORG_RESOURCE_LIMITS.users-e,i=dt.TURNKEY_SUBORG_RESOURCE_LIMITS.policies-t;return{userCount:e,policyCount:t,userLimit:dt.TURNKEY_SUBORG_RESOURCE_LIMITS.users,policyLimit:dt.TURNKEY_SUBORG_RESOURCE_LIMITS.policies,remainingUsers:r,remainingPolicies:i,pressure:e>dt.TVC_PROVIDER_WARN_THRESHOLD||t>dt.TVC_PROVIDER_WARN_THRESHOLD,limitsSource:dt.TURNKEY_SUBORG_RESOURCE_LIMITS.source,limitsVerifiedOn:dt.TURNKEY_SUBORG_RESOURCE_LIMITS.verifiedOn}}function V1(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("TVC provider capacity evidence is invalid");let t=e,r=ey(t.userCount??-1,t.policyCount??-1);for(let i of Object.keys(r))if(t[i]!==r[i])throw new Error("TVC provider capacity evidence is invalid");if(Object.keys(t).length!==Object.keys(r).length)throw new Error("TVC provider capacity evidence is invalid");return r}});var ny=P(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});Bc.TVC_SIGNER_POLICY_CONTRACT_VERSION=void 0;Bc.TVC_SIGNER_POLICY_CONTRACT_VERSION=1});var iy=P(Nd=>{"use strict";Object.defineProperty(Nd,"__esModule",{value:!0});Nd.checkTvcPinParity=K1;var Gc=/^[0-9a-f]{64}$/,ry=16*1024,B1=4096,G1="tvc-proof-verifier.railway.internal",Jc=class extends Error{};function J1(e,t){return Object.keys(e).sort().join(",")===[...t].sort().join(",")}function W1(e){try{let t=new URL(e),r=t.protocol==="http:"&&t.hostname===G1&&t.port!=="";return t.protocol!=="https:"&&!r||t.username!==""||t.password!==""||t.search!==""||t.hash!==""?null:(t.pathname="/effective-pins",t)}catch{return null}}async function Y1(e){let t=Number(e.headers.get("content-length"));if(Number.isFinite(t)&&t>ry)throw await e.body?.cancel().catch(()=>{}),new Error("response too large");let r=e.body?.getReader();if(!r)throw new Error("response body missing");let i=[],n=0,a=async()=>{try{return await r.read()}catch{throw new Jc}};try{for(;;){let c=await a();if(c.done)break;if(n+=c.value.byteLength,n>ry)throw await r.cancel().catch(()=>{}),new Error("response too large");i.push(c.value)}}finally{r.releaseLock()}let o=new Uint8Array(n),s=0;for(let c of i)o.set(c,s),s+=c.byteLength;return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(o))}async function K1(e){let t=e.verifierUrl?.trim()??"",r=e.bearerToken?.trim()??"",i=e.approvedManifestDigest?.trim()??"",n=e.approvedPivotDigest?.trim()??"",a=[t,r,i,n].filter(Boolean).length;if(a===0)return{status:"dark"};let o=t?W1(t):null;if(a!==4||!o||r.length>B1||!Gc.test(i)||!Gc.test(n))return{status:"invalid_configuration"};let s;try{s=await(e.fetchImpl??fetch)(o,{method:"GET",redirect:"error",headers:{accept:"application/json",authorization:`Bearer ${r}`},signal:AbortSignal.timeout(Math.min(Math.max(e.timeoutMs??5e3,100),1e4))})}catch{return{status:"verifier_unavailable"}}if(!s.ok)return await s.body?.cancel().catch(()=>{}),s.status===401||s.status===403?{status:"verifier_auth_failed"}:s.status===408||s.status===425||s.status===429||s.status>=500?{status:"verifier_unavailable"}:{status:"verifier_invalid_response"};let c;try{c=await Y1(s)}catch(d){return{status:d instanceof Jc?"verifier_unavailable":"verifier_invalid_response"}}if(typeof c!="object"||c===null||Array.isArray(c)||!J1(c,["approvedManifestDigest","approvedPivotDigest"]))return{status:"verifier_invalid_response"};let u=c;return typeof u.approvedManifestDigest!="string"||!Gc.test(u.approvedManifestDigest)||typeof u.approvedPivotDigest!="string"||!Gc.test(u.approvedPivotDigest)?{status:"verifier_invalid_response"}:u.approvedManifestDigest!==i?{status:"manifest_mismatch"}:u.approvedPivotDigest!==n?{status:"pivot_mismatch"}:{status:"ready"}}});var ay=P(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.ACCOUNT_OPERATION_EVIDENCE_TYPES=bt.ACCOUNT_OPERATION_PROOF_LEVELS=bt.ACCOUNT_OPERATION_OUTCOMES=bt.ACCOUNT_OPERATION_RECEIPT_SCHEMA_VERSION=void 0;bt.parseAccountOperationReceipt=Q1;bt.ACCOUNT_OPERATION_RECEIPT_SCHEMA_VERSION=1;bt.ACCOUNT_OPERATION_OUTCOMES=["pending","completed","failed","uncertain","released","reversed","disputed"];bt.ACCOUNT_OPERATION_PROOF_LEVELS=["none","platform_observed","merchant_reported","owner_attested","processor_confirmed","network_verified","settled"];bt.ACCOUNT_OPERATION_EVIDENCE_TYPES=["platform_activity","merchant_confirmation","card_lifecycle","onchain_transaction"];function ti(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function xr(e){return e===null||typeof e=="string"}function to(e){return typeof e=="string"&&e.length>0&&!Number.isNaN(Date.parse(e))}function ni(e,t){let r=Object.keys(e).sort(),i=[...t].sort();return r.length===i.length&&r.every((n,a)=>n===i[a])}function H1(e){return ti(e)?ni(e,["type","source","observedAt","reference","url"])&&typeof e.type=="string"&&bt.ACCOUNT_OPERATION_EVIDENCE_TYPES.includes(e.type)&&typeof e.source=="string"&&to(e.observedAt)&&xr(e.reference)&&xr(e.url):!1}function X1(e){return ti(e)?ni(e,["type","at"])&&typeof e.type=="string"&&e.type.length>0&&to(e.at):!1}function Q1(e){if(!ti(e)||!ni(e,["schemaVersion","operationId","activityId","payment","route","party","authority","outcome","evidence","timeline","dataCompleteness"])||e.schemaVersion!==bt.ACCOUNT_OPERATION_RECEIPT_SCHEMA_VERSION||typeof e.operationId!="string"||typeof e.activityId!="string"||e.dataCompleteness!=="complete"&&e.dataCompleteness!=="partial"||!Array.isArray(e.evidence)||!e.evidence.every(H1)||!Array.isArray(e.timeline)||!e.timeline.every(X1))return null;let t=e.payment,r=e.route,i=e.party,n=e.authority,a=e.outcome;return!ti(t)||!ni(t,["amountAtomic","decimals","currency","merchant","description","createdAt"])||typeof t.amountAtomic!="string"||!/^\d+$/.test(t.amountAtomic)||typeof t.decimals!="number"||!Number.isInteger(t.decimals)||t.decimals<0||t.decimals>18||typeof t.currency!="string"||typeof t.merchant!="string"||typeof t.description!="string"||!to(t.createdAt)||!ti(r)||!ni(r,["rail","protocol","network","cardLast4"])||r.rail!=="wallet"&&r.rail!=="card"||!(r.protocol===null||r.protocol==="x402"||r.protocol==="mpp"||r.protocol==="vic"||r.protocol==="virtual_card")||!xr(r.network)||!xr(r.cardLast4)||!ti(i)||!ni(i,["agentId","agentName"])||!xr(i.agentId)||!xr(i.agentName)||!ti(n)||!ni(n,["grantId","mandateId","drawId"])||!xr(n.grantId)||!xr(n.mandateId)||!xr(n.drawId)||!ti(a)||!ni(a,["status","proofLevel","final","updatedAt","finalizesBy",..."held"in a?["held"]:[]])||typeof a.status!="string"||!bt.ACCOUNT_OPERATION_OUTCOMES.includes(a.status)||typeof a.proofLevel!="string"||!bt.ACCOUNT_OPERATION_PROOF_LEVELS.includes(a.proofLevel)||typeof a.final!="boolean"||"held"in a&&(a.held!==!0||r.rail!=="wallet"||r.protocol!=="mpp"||a.status!=="failed"||a.final!==!0)||!to(a.updatedAt)||!(a.finalizesBy===null||to(a.finalizesBy))?null:e}});var Rd=P(Ie=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.CARD_PAYMENT_ATTEMPT_STATUSES=Ie.CARD_PAYMENT_EVENT_REQUIRED_PROVENANCE=Ie.CARD_PAYMENT_PROCESSOR_TRUTH_EVENT_TYPES=Ie.CARD_PAYMENT_SOURCE_PROVENANCE=Ie.CARD_PAYMENT_PROVENANCES=Ie.OWNER_ATTESTATION_VERDICTS=Ie.CARD_PAYMENT_EVENT_TYPES=Ie.CARD_PAYMENT_INTENTS=Ie.CARD_PAYMENT_SOURCES=Ie.CARD_PAYMENT_PROCESSORS=void 0;Ie.isOwnerAttestationVerdict=cy;Ie.provenanceOfSource=uy;Ie.requiresProviderProvenance=ex;Ie.requiredProvenanceFor=ly;Ie.reduceCardPaymentEvents=ux;Ie.CARD_PAYMENT_PROCESSORS=["cybersource","vgs"];Ie.CARD_PAYMENT_SOURCES=["auth_request","mpp_gateway","cybersource_tss","cybersource_report","cybersource_webhook","web_vgs","admin","owner_attestation"];Ie.CARD_PAYMENT_INTENTS=["sale","auth","capture","refund","void","unknown"];Ie.CARD_PAYMENT_EVENT_TYPES=["charge_requested","charge_ambiguous","sale_accepted","auth_held","capture_pending","captured","voided","refund_pending","refund_succeeded","refund_failed","chargeback_opened","chargeback_lost","chargeback_won","processor_unknown","reconciliation_gap","owner_attested"];Ie.OWNER_ATTESTATION_VERDICTS=["found_charge","merchant_completed","no_charge_visible"];function cy(e){return typeof e=="string"&&Ie.OWNER_ATTESTATION_VERDICTS.includes(e)}Ie.CARD_PAYMENT_PROVENANCES=["provider","platform_caller","owner","operator"];Ie.CARD_PAYMENT_SOURCE_PROVENANCE={auth_request:"platform_caller",mpp_gateway:"platform_caller",web_vgs:"platform_caller",cybersource_tss:"provider",cybersource_report:"provider",cybersource_webhook:"provider",admin:"operator",owner_attestation:"owner"};function uy(e){return Ie.CARD_PAYMENT_SOURCE_PROVENANCE[e]??"platform_caller"}Ie.CARD_PAYMENT_PROCESSOR_TRUTH_EVENT_TYPES=new Set(["auth_held","capture_pending","captured","voided","refund_pending","refund_succeeded","refund_failed","chargeback_opened","chargeback_lost","chargeback_won"]);function ex(e){return Ie.CARD_PAYMENT_PROCESSOR_TRUTH_EVENT_TYPES.has(e)}Ie.CARD_PAYMENT_EVENT_REQUIRED_PROVENANCE={...Object.fromEntries([...Ie.CARD_PAYMENT_PROCESSOR_TRUTH_EVENT_TYPES].map(e=>[e,"provider"])),owner_attested:"owner"};function ly(e){return Ie.CARD_PAYMENT_EVENT_REQUIRED_PROVENANCE[e]??null}Ie.CARD_PAYMENT_ATTEMPT_STATUSES=["pending","needs_reconciliation","auth_held","capture_pending","sale_accepted","captured","voided","refund_pending","partially_refunded","refunded","chargeback_open","chargeback_lost","chargeback_won"];var tx=-9223372036854775808n,nx=9223372036854775807n;function oy(e){if(!e)return null;let r=(e instanceof Date?e:new Date(e)).getTime();return Number.isFinite(r)?r:null}function dy(e){if(!/^-?\d+$/.test(e))return null;try{let t=BigInt(e);return t>=tx&&t<=nx?t:null}catch{return null}}function rx(e){return e==null?0n:typeof e=="number"?Number.isSafeInteger(e)?BigInt(e):0n:dy(e)??0n}function ix(e){let t=oy(e.observedAt)??0;return{event:e,primaryAt:oy(e.occurredAt)??t,observedAt:t,id:rx(e.id)}}function ax(e,t){let r=e.primaryAt-t.primaryAt;if(r!==0)return r;let i=e.observedAt-t.observedAt;if(i!==0)return i;let n=e.id-t.id;return n<0n?-1:n>0n?1:0}function sy(e){return e==null?null:typeof e=="bigint"?e:typeof e=="number"?Number.isFinite(e)&&Number.isSafeInteger(e)?BigInt(e):null:dy(e)}function ox(e,t){return e>0n&&t<e?"partially_refunded":"refunded"}function sx(e){return e==="charge_requested"||e==="auth_held"||e==="capture_pending"||e==="sale_accepted"||e==="captured"}function cx(e,t){return e===t||t==="needs_reconciliation"?!0:e==="captured"?t==="refund_pending"||t==="partially_refunded"||t==="refunded":e==="sale_accepted"?t==="captured"||t==="refund_pending"||t==="partially_refunded"||t==="refunded"||t==="voided":e==="refund_pending"?t==="partially_refunded"||t==="refunded"||t==="refund_pending":e==="partially_refunded"?t==="partially_refunded"||t==="refunded":e==="refunded"?t==="refunded":e==="voided"?t==="voided":!0}function Ur(e,t,r,i){return cx(e,t)?{status:t,reason:i}:{status:e,reason:r}}function ux(e,t={}){let r="needs_reconciliation",i="no_processor_events",n=[],a=!1,o=null,s=0n,c=sy(t.attemptAmountMicros),u=c!==null&&c>0n?c:0n,d=null,p=null,m=!1,b=t.attemptAmountMicros!==null&&t.attemptAmountMicros!==void 0&&(c===null||c<0n)?"invalid_amount":null,y=e.map(ix).sort(ax).map(({event:O})=>O);for(let O of y){let z=uy(O.source),re=ly(O.eventType);if(re!==null&&z!==re){n.push({eventType:O.eventType,source:O.source,provenance:z,requiredProvenance:re});continue}if(O.eventType==="owner_attested"){a=!0,cy(O.ownerVerdict)&&(o=O.ownerVerdict);continue}let C=sy(O.amountMicros);if(O.amountMicros!==null&&O.amountMicros!==void 0&&(C===null||C<0n)){b="invalid_amount",r="needs_reconciliation",i="invalid_amount";continue}if((O.amountMicros===null||O.amountMicros===void 0)&&sx(O.eventType)&&u<=0n){b="missing_amount",r="needs_reconciliation",i="missing_amount";continue}let Z=C??u;if(O.eventType==="chargeback_opened"||O.eventType==="chargeback_lost"){d=O.eventType==="chargeback_opened"?"chargeback_open":"chargeback_lost",p=O.eventType,m=!0;continue}if(O.eventType==="chargeback_won"){d=null,p=null,m=!1,r==="needs_reconciliation"&&(r="chargeback_won",i="chargeback_won");continue}switch(O.eventType){case"charge_requested":Z>u&&(u=Z),{status:r,reason:i}=Ur(r,"pending",i,"charge_requested");break;case"charge_ambiguous":case"processor_unknown":case"reconciliation_gap":({status:r,reason:i}=Ur(r,"needs_reconciliation",i,O.eventType));break;case"auth_held":Z>u&&(u=Z),{status:r,reason:i}=Ur(r,"auth_held",i,"auth_held");break;case"capture_pending":Z>u&&(u=Z),{status:r,reason:i}=Ur(r,"capture_pending",i,"capture_pending");break;case"sale_accepted":Z>u&&(u=Z),{status:r,reason:i}=Ur(r,"sale_accepted",i,"sale_accepted");break;case"captured":Z>u&&(u=Z),{status:r,reason:i}=Ur(r,"captured",i,"captured");break;case"voided":({status:r,reason:i}=Ur(r,"voided",i,"voided"));break;case"refund_pending":({status:r,reason:i}=Ur(r,"refund_pending",i,"refund_pending"));break;case"refund_succeeded":if(C===null){b="missing_amount",r="needs_reconciliation",i="missing_amount";continue}s+=Z,u>0n&&s>u&&(s=u),{status:r,reason:i}=Ur(r,ox(u,s),i,"refund_succeeded");break;case"refund_failed":i="refund_failed";break}}return d?{status:d,statusReason:p??d,refundMicros:s,hasChargeback:m,rejectedProcessorClaims:n,ownerAttested:a,ownerVerdict:o}:b?{status:"needs_reconciliation",statusReason:b,refundMicros:s,hasChargeback:m,rejectedProcessorClaims:n,ownerAttested:a,ownerVerdict:o}:{status:r,statusReason:i,refundMicros:s,hasChargeback:m,rejectedProcessorClaims:n,ownerAttested:a,ownerVerdict:o}}});var hy=P(Lr=>{"use strict";Object.defineProperty(Lr,"__esModule",{value:!0});Lr.CardPaymentDbValidationError=void 0;Lr.validateCardPaymentEventInsertRow=py;Lr.assertValidCardPaymentAttemptStatus=my;Lr.insertCardPaymentLifecycleEvent=yx;Lr.insertCardPaymentLifecycleEventWithId=_y;Lr.refreshCardPaymentAttemptProjection=bx;var ro=Rd(),Mi=class extends Error{table;offendingKeys;constructor(t,r,i){super(`[pg:${r}] ${t}`),this.table=r,this.offendingKeys=i,this.name="CardPaymentDbValidationError"}};Lr.CardPaymentDbValidationError=Mi;function Tt(e,t,r){throw new Mi(t,e,Object.keys(r))}function lx(e,t){if(!t||typeof t!="object"||Array.isArray(t))throw new Mi("row must be a non-array object",e,[]);return t}function dx(e,t,r){for(let i of Object.keys(t))r.has(i)||Tt(e,`unknown column "${i}"`,t)}function fx(e,t,r){for(let i of r)(t[i]===void 0||t[i]===null)&&Tt(e,`required column "${i}" is missing`,t)}function no(e,t,r,i={}){let n=t[r];if(n==null){if(i.nullable)return;Tt(e,`${r} must be a string`,t)}typeof n!="string"&&Tt(e,`${r} must be a string`,t),i.nonEmpty&&n.length===0&&Tt(e,`${r} must be non-empty`,t),i.maxLen&&n.length>i.maxLen&&Tt(e,`${r} exceeds ${i.maxLen} chars`,t)}function Cd(e,t,r,i){let n=t[r];(typeof n!="string"||!i.has(n))&&Tt(e,`${r} must be one of ${[...i].join("|")}`,t)}function px(e,t,r){let i=t[r],n=9223372036854775807n,a=typeof i=="bigint"?i:typeof i=="string"&&/^\d+$/.test(i)&&i.length<=19?BigInt(i):null;a===null&&Tt(e,`${r} must be a numeric integer string`,t),a<=0n&&Tt(e,`${r} must be positive`,t),a>n&&Tt(e,`${r} must fit signed 64-bit integer`,t)}var mx=new Set(["attempt_id","transaction_id","user_login","processor","source","event_type","processor_event_id","processor_transaction_id","amount_micros","currency","processor_status","occurred_at","payload"]),gx=["user_login","processor","source","event_type","payload"],_x=new Set(ro.CARD_PAYMENT_PROCESSORS),hx=new Set(ro.CARD_PAYMENT_SOURCES),vx=new Set(ro.CARD_PAYMENT_EVENT_TYPES),fy=new Set(ro.CARD_PAYMENT_ATTEMPT_STATUSES);function py(e){let t=lx("card_payment_events",e);dx("card_payment_events",t,mx),fx("card_payment_events",t,gx);for(let r of["attempt_id","transaction_id"]){let i=t[r];if(i!=null){let n=typeof i=="string"&&/^\d+$/.test(i)?Number(i):i;(typeof n!="number"||!Number.isInteger(n)||n<=0)&&Tt("card_payment_events",`${r} must be a positive integer or null`,t)}}no("card_payment_events",t,"user_login",{nonEmpty:!0,maxLen:255}),Cd("card_payment_events",t,"processor",_x),Cd("card_payment_events",t,"source",hx),Cd("card_payment_events",t,"event_type",vx),t.processor_event_id!==null&&t.processor_event_id!==void 0&&no("card_payment_events",t,"processor_event_id",{nonEmpty:!0,maxLen:255,nullable:!0}),t.processor_transaction_id!==null&&t.processor_transaction_id!==void 0&&no("card_payment_events",t,"processor_transaction_id",{nonEmpty:!0,maxLen:255,nullable:!0}),t.amount_micros!==null&&t.amount_micros!==void 0&&px("card_payment_events",t,"amount_micros"),t.currency!==null&&t.currency!==void 0&&no("card_payment_events",t,"currency",{nonEmpty:!0,maxLen:3,nullable:!0}),t.processor_status!==null&&t.processor_status!==void 0&&no("card_payment_events",t,"processor_status",{nonEmpty:!0,maxLen:128,nullable:!0}),t.occurred_at!==null&&t.occurred_at!==void 0&&!(t.occurred_at instanceof Date)&&typeof t.occurred_at!="string"&&Tt("card_payment_events","occurred_at must be a Date, ISO string, or null",t),typeof t.payload!="string"&&Tt("card_payment_events","payload must be a JSON string",t);try{JSON.parse(t.payload)}catch{Tt("card_payment_events","payload must be valid JSON",t)}}function my(e){if(!fy.has(e))throw new Mi(`current_status must be one of ${[...fy].join("|")}`,"card_payment_attempts",["current_status"])}function gy(e){return e===null?null:typeof e=="number"?e:Number(e)}async function yx(e,t){return(await _y(e,t)).inserted}async function _y(e,t){let r={attempt_id:gy(t.attemptId),transaction_id:t.transactionId,user_login:t.userLogin,processor:t.processor??"cybersource",source:t.source,event_type:t.eventType,processor_event_id:t.processorEventId,processor_transaction_id:t.processorTransactionId,amount_micros:t.amountMicros,currency:t.currency,processor_status:t.processorStatus,occurred_at:t.occurredAt??null,payload:JSON.stringify(t.payload)};py(r);let n=(await e.query(`INSERT INTO card_payment_events (
58
+ `)}function $D(e,t,r){return{"signature-input":`${Me.AGENT_SIGNATURE_LABEL}=${ql(e,t)}`,signature:`${Me.AGENT_SIGNATURE_LABEL}=:${r}:`}}function OD(e){let t=e.signatureInput?.trim()??"",r=e.signature?.trim()??"",i=`${Me.AGENT_SIGNATURE_LABEL}=`;if(!t.startsWith(i)||!r.startsWith(i))return null;let n=/^\(([^)]*)\);created=(\d{1,12});nonce="([A-Za-z0-9_-]{16,64})";keyid="([A-Za-z0-9_-]{43})";alg="ed25519"$/.exec(t.slice(i.length)),a=/^:([A-Za-z0-9+/]{86}==):$/.exec(r.slice(i.length));if(!n||!a)return null;let o=n[1],s=o===Nh.map(c=>`"${c}"`).join(" ");return!s&&o!==Rh.map(c=>`"${c}"`).join(" ")?null:{hasBody:s,created:Number(n[2]),nonce:n[3],keyid:n[4],signature:a[1]}}function ID(e){return`visa-setup-claim:${e}`}function ED(e){return`visa-setup-resume:v1:${e.jkt}:${e.setupId??"-"}:${e.nonce}:${e.issuedAt}`}});var xh=P(Oi=>{"use strict";Object.defineProperty(Oi,"__esModule",{value:!0});Oi.DeviceApproverPhaseStatement=Oi.DeviceApproverRoster=void 0;var ne=ct(),Dh=Rt(),Ce=ne.z.string().min(1),Vl=ne.z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),Mh=ne.z.strictObject({kty:ne.z.literal("OKP"),crv:ne.z.literal("Ed25519"),x:ne.z.string().regex(/^[A-Za-z0-9_-]{43}$/)}),Ec=ne.z.strictObject({policyName:Ce,effect:ne.z.enum(["EFFECT_ALLOW","EFFECT_DENY"]),consensus:Ce,condition:Ce,notes:ne.z.string()});Oi.DeviceApproverRoster=ne.z.array(ne.z.strictObject({approverId:Ce,installationId:Ce,identityKeyId:Ce,identityGeneration:Vl,identityJkt:ne.z.string().regex(/^[A-Za-z0-9_-]{43}$/),publicJwk:Mh,provider:ne.z.literal("turnkey"),providerUserRef:ne.z.string(),state:ne.z.enum(["pending","active","removing"])})).max(8);var Fl=ne.z.strictObject({userName:Ce,apiKeys:ne.z.tuple([ne.z.strictObject({apiKeyName:Ce,publicKey:Ce,curveType:ne.z.enum(["API_KEY_CURVE_ED25519","API_KEY_CURVE_P256"])})]),authenticators:ne.z.tuple([]),oauthProviders:ne.z.tuple([]),userTags:ne.z.tuple([])}),PD=ne.z.discriminatedUnion("type",[ne.z.strictObject({type:ne.z.enum(["ACTIVITY_TYPE_CREATE_USERS_V3","ACTIVITY_TYPE_CREATE_USERS_V4"]),parameters:ne.z.strictObject({users:ne.z.union([ne.z.tuple([Fl]),ne.z.tuple([Fl,Fl])])})}),ne.z.strictObject({type:ne.z.literal("ACTIVITY_TYPE_CREATE_POLICIES"),parameters:ne.z.strictObject({policies:ne.z.union([ne.z.tuple([Ec]),ne.z.tuple([Ec,Ec])])})}),ne.z.strictObject({type:ne.z.literal("ACTIVITY_TYPE_UPDATE_POLICY_V2"),parameters:ne.z.strictObject({policyId:Ce,policyName:Ce,policyEffect:ne.z.enum(["EFFECT_ALLOW","EFFECT_DENY"]),policyCondition:Ce,policyConsensus:Ce,policyNotes:ne.z.string().optional()})})]);Oi.DeviceApproverPhaseStatement=ne.z.strictObject({kind:ne.z.literal("device_approver"),operation_id:Ce,step_no:ne.z.number().int().min(2).max(6),action:ne.z.enum(Dh.DEVICE_APPROVER_ACTIONS),recorded_body_hash:ne.z.string().regex(/^[A-Za-z0-9_-]{43}$/).nullable(),recorded_activity_ref:Ce.nullable(),intent:ne.z.strictObject({fence:ne.z.strictObject({ownerId:Ce,ownerSecurityEpoch:ne.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),agentId:Ce,setupId:Ce,operationId:Ce,installationId:Ce,walletKeyId:Ce,walletGeneration:Vl,identityKeyId:Ce,identityGeneration:Vl,identityJkt:ne.z.string().regex(/^[A-Za-z0-9_-]{43}$/),installationPublicJwk:Mh,organizationId:Ce,ownerUserId:Ce,rosterHash:ne.z.string().regex(/^[A-Za-z0-9_-]{43}$/)}),stepNo:ne.z.union([ne.z.literal(2),ne.z.literal(3),ne.z.literal(4),ne.z.literal(5),ne.z.literal(6)]),accessKeyId:Ce,accessKeyAddress:ne.z.string().regex(/^0x[0-9a-fA-F]{40}$/),stampPublicKey:ne.z.string().regex(/^0[23][0-9a-fA-F]{64}$/),roster:Oi.DeviceApproverRoster,action:ne.z.enum(Dh.DEVICE_APPROVER_ACTIONS),request:PD,previousPolicy:Ec.nullable().optional(),previousPolicyHash:ne.z.string().regex(/^[A-Za-z0-9_-]{43}$/).optional(),targetPolicyRef:Ce.optional()})}).superRefine((e,t)=>{let r=e.intent,i={create_device_approver_guard:2,create_device_approver_user:3,create_tempo_signer_guard:4,create_tempo_signer_user:5,create_device_approver_policy:6,update_device_approver_policy:6},n=e.action.endsWith("_user")?"ACTIVITY_TYPE_CREATE_USERS_V3":e.action==="update_device_approver_policy"?"ACTIVITY_TYPE_UPDATE_POLICY_V2":"ACTIVITY_TYPE_CREATE_POLICIES";(e.operation_id!==r.fence.operationId||e.action!==r.action||e.step_no!==r.stepNo||e.step_no!==i[e.action]||r.request.type!==n&&!(n==="ACTIVITY_TYPE_CREATE_USERS_V3"&&r.request.type==="ACTIVITY_TYPE_CREATE_USERS_V4")||e.recorded_activity_ref!==null&&e.recorded_body_hash===null||(e.action==="update_device_approver_policy"?r.previousPolicy===void 0||!r.previousPolicyHash||!r.targetPolicyRef||r.request.type!=="ACTIVITY_TYPE_UPDATE_POLICY_V2"||r.request.parameters.policyId!==r.targetPolicyRef||r.previousPolicy===null&&!e.recorded_body_hash:r.previousPolicy!==void 0||r.previousPolicyHash!==void 0||r.targetPolicyRef!==void 0))&&t.addIssue({code:"custom",message:"The device approver phase is inconsistent."})})});var Gl=P(ee=>{"use strict";var zD=ee&&ee.__createBinding||(Object.create?(function(e,t,r,i){i===void 0&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);(!n||("get"in n?!t.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}):(function(e,t,r,i){i===void 0&&(i=r),e[i]=t[r]})),en=ee&&ee.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&zD(t,e,r)};Object.defineProperty(ee,"__esModule",{value:!0});ee.apiMetadataOf=ee.successOutcomes=ee.buildOpenApi=ee.PUBLIC_OPERATIONS=ee.OWNER_OPERATIONS=ee.AGENT_OPERATIONS=ee.ADMIN_OPERATIONS=ee.mcpToolDescriptors=ee.MCP_DESCRIPTION_BUDGET=ee.MCP_TOOLS=ee.CliFailureReport=ee.CLI_FAILURE_SURFACES=ee.CLI_FAILURE_STEPS=ee.CLI_FAILURE_PLATFORMS=ee.CLI_FAILURE_KINDS=ee.CLI_FAILURE_EVENT_MAX_BYTES=ee.MCP_TOOL_CEILING=ee.PRODUCT_ROUTE_CEILING=ee.OPERATIONS=void 0;ee.operationById=AD;ee.countByFamily=jD;ee.productOperationCount=kD;var Uh=gh();Object.defineProperty(ee,"ADMIN_OPERATIONS",{enumerable:!0,get:function(){return Uh.ADMIN_OPERATIONS}});var Lh=vh();Object.defineProperty(ee,"AGENT_OPERATIONS",{enumerable:!0,get:function(){return Lh.AGENT_OPERATIONS}});var Zh=wh();Object.defineProperty(ee,"OWNER_OPERATIONS",{enumerable:!0,get:function(){return Zh.OWNER_OPERATIONS}});var qh=Ul();Object.defineProperty(ee,"PUBLIC_OPERATIONS",{enumerable:!0,get:function(){return qh.PUBLIC_OPERATIONS}});var TD=Pr();ee.OPERATIONS=[...Zh.OWNER_OPERATIONS,...Lh.AGENT_OPERATIONS,...Uh.ADMIN_OPERATIONS,...qh.PUBLIC_OPERATIONS];function AD(e){return ee.OPERATIONS.find(t=>t.id===e)}function jD(){let e={owner:0,agent:0,admin:0,mcp:0,oauth:0,"well-known":0,public:0};for(let t of ee.OPERATIONS)e[t.family]+=1;return e}function kD(){return ee.OPERATIONS.filter(e=>TD.PRODUCT_FAMILIES.includes(e.family)).length}ee.PRODUCT_ROUTE_CEILING=77;ee.MCP_TOOL_CEILING=7;en(pc(),ee);var ra=Ul();Object.defineProperty(ee,"CLI_FAILURE_EVENT_MAX_BYTES",{enumerable:!0,get:function(){return ra.CLI_FAILURE_EVENT_MAX_BYTES}});Object.defineProperty(ee,"CLI_FAILURE_KINDS",{enumerable:!0,get:function(){return ra.CLI_FAILURE_KINDS}});Object.defineProperty(ee,"CLI_FAILURE_PLATFORMS",{enumerable:!0,get:function(){return ra.CLI_FAILURE_PLATFORMS}});Object.defineProperty(ee,"CLI_FAILURE_STEPS",{enumerable:!0,get:function(){return ra.CLI_FAILURE_STEPS}});Object.defineProperty(ee,"CLI_FAILURE_SURFACES",{enumerable:!0,get:function(){return ra.CLI_FAILURE_SURFACES}});Object.defineProperty(ee,"CliFailureReport",{enumerable:!0,get:function(){return ra.CliFailureReport}});en(Pr(),ee);en(Rt(),ee);en(Si(),ee);en(Pl(),ee);var Bl=Ll();Object.defineProperty(ee,"MCP_TOOLS",{enumerable:!0,get:function(){return Bl.MCP_TOOLS}});Object.defineProperty(ee,"MCP_DESCRIPTION_BUDGET",{enumerable:!0,get:function(){return Bl.MCP_DESCRIPTION_BUDGET}});Object.defineProperty(ee,"mcpToolDescriptors",{enumerable:!0,get:function(){return Bl.mcpToolDescriptors}});var Fh=jh();Object.defineProperty(ee,"buildOpenApi",{enumerable:!0,get:function(){return Fh.buildOpenApi}});Object.defineProperty(ee,"successOutcomes",{enumerable:!0,get:function(){return Fh.successOutcomes}});en(kh(),ee);en(Ch(),ee);en(xh(),ee);en(zl(),ee);en(Al(),ee);var ND=Et();Object.defineProperty(ee,"apiMetadataOf",{enumerable:!0,get:function(){return ND.apiMetadataOf}});en(xa(),ee)});var Jl=P((F4,RD)=>{RD.exports={name:"@visa/cli",version:"5.0.0-rc.412",description:"Visa CLI runtime for stable agent identity and separately authorized payment capabilities",bin:{"visa-cli":"./bin/visa-cli.js",visa:"./bin/visa-cli.js","visa-runtime-converge":"./dist/managed-runtime/resolve-and-update.mjs","visa-tool":"./bin/visa-tool.js"},scripts:{"sync:server-json":"node scripts/sync-server-json.mjs","check:server-json":"node scripts/sync-server-json.mjs --check",prebuild:"node scripts/sync-server-json.mjs",build:"pnpm test:types && node esbuild.config.js",prepack:"node scripts/sync-server-json.mjs --check",dev:"tsc --watch",pretest:"pnpm build",start:"node dist/mcp-server/index.js",test:"jest --config jest.config.js","test:types":"tsc -p tsconfig.test.json","pretest:unit":"pnpm test:types","test:unit":"jest --config jest.config.js","pretest:unit:watch":"pnpm test:types","test:unit:watch":"jest --config jest.config.js --watch","pretest:unit:coverage":"pnpm test:types","test:unit:coverage":"jest --config jest.config.js --coverage","test:smoke":"VISA_AUTH_URL=https://auth.visacli.sh jest --config jest.smoke.config.js","test:packed":"node scripts/packed-cli-smoke.mjs","test:e2e":"jest --config jest.e2e.config.js","test:all":"npm run test:unit && npm run test:e2e",prepublishOnly:"npm run build && npm test",lint:"eslint src/**/*.ts",format:'prettier --write "src/**/*.ts"',"format:check":'prettier --check "src/**/*.ts"'},keywords:["visa","checkout","mcp","ai-agent","payments","click-to-pay","usdc","stablecoin"],author:"Visa Crypto Labs",license:"SEE LICENSE IN LICENSE",dependencies:{"@modelcontextprotocol/server":"2.0.0",commander:"^12.1.0",punycode:"^2.3.1"},devDependencies:{"@types/express":"^5.0.0","@types/jest":"^30.0.0","@types/node":"^22.20.5","@typescript-eslint/eslint-plugin":"^8.68.0","@typescript-eslint/parser":"^8.68.0","@visa/financial-core":"workspace:*","@visa/identity":"workspace:*","@visa/contracts":"workspace:*","@visa/observability":"workspace:*","@visa/shared":"workspace:*","@visa/wallet":"workspace:*",esbuild:"^0.28.1",eslint:"^10.0.2",express:"^4.21.0",jest:"^30.3.0",prettier:"^3.9.6","ts-jest":"^29.4.12",typescript:"^5.7.0",viem:"^2.56.0"},engines:{node:">=20.0.0"},mcpName:"io.github.visa-crypto-labs/visa-cli",files:["bin/visa-cli.js","bin/visa-tool.js","dist/","install.ps1","install.sh","server.json","README.md"]}});var Wa=P((J4,tv)=>{"use strict";var Xl=Object.defineProperty,DD=Object.getOwnPropertyDescriptor,MD=Object.getOwnPropertyNames,xD=Object.prototype.hasOwnProperty,UD=(e,t)=>{for(var r in t)Xl(e,r,{get:t[r],enumerable:!0})},LD=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of MD(t))!xD.call(e,n)&&n!==r&&Xl(e,n,{get:()=>t[n],enumerable:!(i=DD(t,n))||i.enumerable});return e},ZD=e=>LD(Xl({},"__esModule",{value:!0}),e),Kh={};UD(Kh,{base64UrlToBytes:()=>rM,bytesToBase64Url:()=>nM,bytesToHex:()=>XD,hexToBytes:()=>QD});tv.exports=ZD(Kh);var Ql=Object.freeze,aa=0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,Yl=0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,zc=0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Kl=0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Hl=0x6666666666666666666666666666666666666666666666666666666666666658n,Tc=aa-1n,qD=Ql({p:aa,n:Yl,h:8n,a:Tc,d:zc,Gx:Kl,Gy:Hl}),Hh=32,Bh=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&e.BYTES_PER_ELEMENT===1,Ac=(e,t,r="")=>{if(Bh(e)&&(t===void 0||e.length===t))return e;let i=Bh(e),n=t!==void 0?` of length ${t}`:"",a=i?`length=${e.length}`:`type=${typeof e}`,o=(r?`"${r}" `:"")+"expected Uint8Array"+n+", got "+a;throw i?new RangeError(o):new TypeError(o)},FD=(e,t="",r)=>Uint8Array.from(Ac(e,r,t)),Xh=(e,t)=>e.toString(16).padStart(t,"0"),ed=e=>{let t="";for(let r of Ac(e))t+=Xh(r,2);return t},td=e=>{let t="hex invalid";if(typeof e!="string")throw new TypeError(t);if(e.length%2||!/^[\da-f]*$/i.test(e))throw new RangeError(t);let r=new Uint8Array(e.length/2);for(let i=0,n=0;i<r.length;i++,n+=2){let a=e.charCodeAt(n),o=e.charCodeAt(n+1);r[i]=((a&15)+(a>>6)*9)*16+(o&15)+(o>>6)*9}return r},VD=(...e)=>{let t=0;for(let n of e)t+=Ac(n).length;let r=new Uint8Array(t),i=0;for(let n of e)r.set(n,i),i+=n.length;return r},BD=(e=Hh)=>{let t=globalThis?.crypto;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined, consider polyfill");return t.getRandomValues(new Uint8Array(e))},Ii=(e,t,r,i="bad number: out of range")=>{if(typeof e!="bigint")throw new TypeError(i);if(t<=e&&e<r)return e;throw new RangeError(i)},qe=(e,t=aa)=>(e%=t)>=0n?e:t+e,Gh=(1n<<255n)-1n,K=e=>{if(e<0n)throw new RangeError("negative coordinate");let t=(e>>255n)*19n+(e&Gh);return t=(t>>255n)*19n+(t&Gh),t%aa},Qh=(e,t)=>{if(e===0n)throw new Error("invert: expected non-zero number");if(t<=1n)throw new Error("invert: expected modulus > 1, got "+t);let r=qe(e,t),i=t,n=0n,a=1n;for(;r!==0n;){let s=i/r,c=i-r*s,u=n-a*s;i=r,r=c,n=a,a=u}if(i!==1n)throw new Error("invert: does not exist");return qe(n,t)},Wl=e=>{if(e instanceof Ja)return e;throw new TypeError("Point expected")},ev=2n**256n,Ja=class Ei{static BASE;static ZERO;X;Y;Z;T;constructor(t,r,i,n){let a=ev;this.X=Ii(t,0n,a),this.Y=Ii(r,0n,a),this.Z=Ii(i,1n,a),this.T=Ii(n,0n,a),Ql(this)}static CURVE(){return qD}static fromAffine(t){return new Ei(t.x,t.y,1n,K(t.x*t.y))}static fromBytes(t,r=!1){let i=FD(t,"point",Hh),n=i[31];i[31]=n&-129;let a=JD(i);r||Ii(a,0n,aa);let o=K(a*a),s=qe(o-1n),c=K(zc*o+1n),{isValid:u,value:d}=YD(s,c);if(!u)throw new Error("bad point: y not sqrt");let p=!!(n&128);if(!r&&d===0n&&p)throw new Error("bad point: x==0, isLastByteOdd");return p!==!!(d&1n)&&(d=qe(-d)),new Ei(d,a,1n,K(d*a))}static fromHex(t,r){return Ei.fromBytes(td(t),r)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=Tc,r=zc,i=this;if(i.is0())throw new Error("bad point: ZERO");let{X:n,Y:a,Z:o,T:s}=i,c=K(n*n),u=K(a*a),d=K(o*o),p=K(d*d),m=K(c*t),b=K(d*(m+u)),y=qe(p+K(r*K(c*u)));if(b!==y)throw new Error("bad point: equation left != right (1)");let O=K(n*a),z=K(o*s);if(O!==z)throw new Error("bad point: equation left != right (2)");return this}equals(t){let{X:r,Y:i,Z:n}=this,{X:a,Y:o,Z:s}=Wl(t);return K(r*s)===K(a*n)&&K(i*s)===K(o*n)}is0(){return this.equals(Pi)}negate(){return new Ei(qe(-this.X),this.Y,this.Z,qe(-this.T))}double(){let{X:t,Y:r,Z:i}=this,n=Tc,a=K(t*t),o=K(r*r),s=K(2n*i*i),c=K(n*a),u=qe(t+r),d=qe(K(u*u)-a-o),p=qe(c+o),m=qe(p-s),b=qe(c-o),y=K(d*m),O=K(p*b),z=K(d*b),re=K(m*p);return new Ei(y,O,re,z)}add(t){let{X:r,Y:i,Z:n,T:a}=this,{X:o,Y:s,Z:c,T:u}=Wl(t),d=Tc,p=zc,m=K(r*o),b=K(i*s),y=K(K(a*p)*u),O=K(n*c),z=qe(K(qe(r+i)*qe(o+s))-m-b),re=qe(O-y),C=qe(O+y),Z=qe(b-K(d*m)),oe=K(z*re),ve=K(C*Z),me=K(z*Z),Pe=K(re*C);return new Ei(oe,ve,Pe,me)}subtract(t){return this.add(Wl(t).negate())}multiply(t,r=!0){if(!r&&t===0n||(Ii(t,1n,Yl),!r&&this.is0()))return Pi;if(t===1n)return this;if(this.equals(Ga))return HD(t).p;let i=Pi,n=Ga,a=this;for(let o=0;r?o<256:t>0n;o++)t&1n?i=i.add(a):r&&(n=n.add(a)),a=a.double(),t>>=1n;return i}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){let{X:t,Y:r,Z:i}=this;if(this.equals(Pi))return{x:0n,y:1n};let n=Qh(i,aa);if(K(i*n)!==1n)throw new Error("invalid inverse");return{x:K(t*n),y:K(r*n)}}toBytes(){let{x:t,y:r}=this.toAffine(),i=GD(r);return i[31]|=t&1n?128:0,i}toHex(){return ed(this.toBytes())}clearCofactor(){return this.multiply(8n,!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return this.multiply(Yl/2n,!1).double().add(this).is0()}},Ga=new Ja(Kl,Hl,1n,qe(Kl*Hl)),Pi=new Ja(0n,1n,1n,0n);Ja.BASE=Ga;Ja.ZERO=Pi;var GD=e=>td(Xh(Ii(e,0n,ev),64)).reverse(),JD=e=>BigInt("0x"+ed(Uint8Array.from(Ac(e)).reverse())),mr=(e,t)=>{let r=e;for(;t-- >0;)r=K(r*r);return r},WD=e=>{let t=K(e*e),r=K(t*e),i=K(mr(r,2)*r),n=K(mr(i,1)*e),a=K(mr(n,5)*n),o=K(mr(a,10)*a),s=K(mr(o,20)*o),c=K(mr(s,40)*s),u=K(mr(c,80)*c),d=K(mr(u,80)*c),p=K(mr(d,10)*a);return K(mr(p,2)*e)},Jh=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,YD=(e,t)=>{let r=K(t*K(t*t)),i=K(K(r*r)*t),n=WD(K(e*i)),a=K(e*K(r*n)),o=K(t*K(a*a)),s=a,c=K(a*Jh),u=o===e,d=o===qe(-e),p=o===qe(-e*Jh);return u&&(a=s),(d||p)&&(a=c),(qe(a)&1n)===1n&&(a=qe(-a)),{isValid:u||d,value:a}},nd=Ql({bytesToHex:ed,hexToBytes:td,concatBytes:VD,mod:qe,invert:Qh,randomBytes:BD}),KD=()=>{let e=[],t=Ga,r;for(let i=0;i<33;i++){r=t,e.push(r);for(let n=1;n<128;n++)r=r.add(t),e.push(r);t=r.double()}return e},Wh=void 0,Yh=(e,t)=>{let r=t.negate();return e?r:t},HD=e=>{let t=Wh||(Wh=KD()),r=Pi,i=Ga;for(let n=0;n<33;n++){let a=Number(e&255n);e>>=8n,a>128&&(a-=256,e+=1n);let o=n*128,s=o+Math.abs(a)-1,c=n%2!==0,u=a<0;a===0?i=i.add(Yh(c,t[o])):r=r.add(Yh(u,t[s]))}if(e!==0n)throw new Error("invalid wnaf");return{p:r,f:i}},XD=nd.bytesToHex,QD=nd.hexToBytes,G4=nd.concatBytes;function eM(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function tM(e){let t=atob(e),r=new Uint8Array(t.length);for(let i=0;i<t.length;i++)r[i]=t.charCodeAt(i);return r}function nM(e){return eM(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function rM(e){let t=e.length%4===0?0:4-e.length%4,r=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat(t);return tM(r)}});var _d=P((H4,Nv)=>{"use strict";var cd=Object.defineProperty,iM=Object.getOwnPropertyDescriptor,aM=Object.getOwnPropertyNames,oM=Object.prototype.hasOwnProperty,sM=(e,t)=>{for(var r in t)cd(e,r,{get:t[r],enumerable:!0})},cM=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of aM(t))!oM.call(e,n)&&n!==r&&cd(e,n,{get:()=>t[n],enumerable:!(i=iM(t,n))||i.enumerable});return e},uM=e=>cM(cd({},"__esModule",{value:!0}),e),mv={};sM(mv,{computeJkt:()=>n1,sha256:()=>kv,sign:()=>KM,signAsync:()=>XM,verify:()=>HM,verifyAsync:()=>QM});Nv.exports=uM(mv);var ud=Object.freeze,ca=0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,Dc=0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,Rc=0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,ad=0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,od=0x6666666666666666666666666666666666666666666666666666666666666658n,Cc=ca-1n,lM=ud({p:ca,n:Dc,h:8n,a:Cc,d:Rc,Gx:ad,Gy:od}),ji=32,nv=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&e.BYTES_PER_ELEMENT===1,Bt=(e,t,r="")=>{if(nv(e)&&(t===void 0||e.length===t))return e;let i=nv(e),n=t!==void 0?` of length ${t}`:"",a=i?`length=${e.length}`:`type=${typeof e}`,o=(r?`"${r}" `:"")+"expected Uint8Array"+n+", got "+a;throw i?new RangeError(o):new TypeError(o)},Uc=(e,t="",r)=>Uint8Array.from(Bt(e,r,t)),gv=(e,t)=>e.toString(16).padStart(t,"0"),ld=e=>{let t="";for(let r of Bt(e))t+=gv(r,2);return t},dd=e=>{let t="hex invalid";if(typeof e!="string")throw new TypeError(t);if(e.length%2||!/^[\da-f]*$/i.test(e))throw new RangeError(t);let r=new Uint8Array(e.length/2);for(let i=0,n=0;i<r.length;i++,n+=2){let a=e.charCodeAt(n),o=e.charCodeAt(n+1);r[i]=((a&15)+(a>>6)*9)*16+(o&15)+(o>>6)*9}return r},ki=(...e)=>{let t=0;for(let n of e)t+=Bt(n).length;let r=new Uint8Array(t),i=0;for(let n of e)r.set(n,i),i+=n.length;return r},dM=(e=ji)=>{let t=globalThis?.crypto;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined, consider polyfill");return t.getRandomValues(new Uint8Array(e))},zi=(e,t,r,i="bad number: out of range")=>{if(typeof e!="bigint")throw new TypeError(i);if(t<=e&&e<r)return e;throw new RangeError(i)},xe=(e,t=ca)=>(e%=t)>=0n?e:t+e,rv=(1n<<255n)-1n,H=e=>{if(e<0n)throw new RangeError("negative coordinate");let t=(e>>255n)*19n+(e&rv);return t=(t>>255n)*19n+(t&rv),t%ca},_v=e=>xe(e,Dc),hv=(e,t)=>{if(e===0n)throw new Error("invert: expected non-zero number");if(t<=1n)throw new Error("invert: expected modulus > 1, got "+t);let r=xe(e,t),i=t,n=0n,a=1n;for(;r!==0n;){let s=i/r,c=i-r*s,u=n-a*s;i=r,r=c,n=a,a=u}if(i!==1n)throw new Error("invert: does not exist");return xe(n,t)},vv=e=>{let t=Ev[e];if(typeof t!="function")throw new Error("hashes."+e+" not set");return t},fd=(e,...t)=>Bt(vv(e)(ki(...t)),64,"digest"),pd=async(e,...t)=>Bt(await vv(e)(ki(...t)),64,"digest"),rd=e=>{if(e instanceof Ni)return e;throw new TypeError("Point expected")},yv=2n**256n,Ni=class Ti{static BASE;static ZERO;X;Y;Z;T;constructor(t,r,i,n){let a=yv;this.X=zi(t,0n,a),this.Y=zi(r,0n,a),this.Z=zi(i,1n,a),this.T=zi(n,0n,a),ud(this)}static CURVE(){return lM}static fromAffine(t){return new Ti(t.x,t.y,1n,H(t.x*t.y))}static fromBytes(t,r=!1){let i=Uc(t,"point",ji),n=i[31];i[31]=n&-129;let a=md(i);r||zi(a,0n,ca);let o=H(a*a),s=xe(o-1n),c=H(Rc*o+1n),{isValid:u,value:d}=pM(s,c);if(!u)throw new Error("bad point: y not sqrt");let p=!!(n&128);if(!r&&d===0n&&p)throw new Error("bad point: x==0, isLastByteOdd");return p!==!!(d&1n)&&(d=xe(-d)),new Ti(d,a,1n,H(d*a))}static fromHex(t,r){return Ti.fromBytes(dd(t),r)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=Cc,r=Rc,i=this;if(i.is0())throw new Error("bad point: ZERO");let{X:n,Y:a,Z:o,T:s}=i,c=H(n*n),u=H(a*a),d=H(o*o),p=H(d*d),m=H(c*t),b=H(d*(m+u)),y=xe(p+H(r*H(c*u)));if(b!==y)throw new Error("bad point: equation left != right (1)");let O=H(n*a),z=H(o*s);if(O!==z)throw new Error("bad point: equation left != right (2)");return this}equals(t){let{X:r,Y:i,Z:n}=this,{X:a,Y:o,Z:s}=rd(t);return H(r*s)===H(a*n)&&H(i*s)===H(o*n)}is0(){return this.equals(Ai)}negate(){return new Ti(xe(-this.X),this.Y,this.Z,xe(-this.T))}double(){let{X:t,Y:r,Z:i}=this,n=Cc,a=H(t*t),o=H(r*r),s=H(2n*i*i),c=H(n*a),u=xe(t+r),d=xe(H(u*u)-a-o),p=xe(c+o),m=xe(p-s),b=xe(c-o),y=H(d*m),O=H(p*b),z=H(d*b),re=H(m*p);return new Ti(y,O,re,z)}add(t){let{X:r,Y:i,Z:n,T:a}=this,{X:o,Y:s,Z:c,T:u}=rd(t),d=Cc,p=Rc,m=H(r*o),b=H(i*s),y=H(H(a*p)*u),O=H(n*c),z=xe(H(xe(r+i)*xe(o+s))-m-b),re=xe(O-y),C=xe(O+y),Z=xe(b-H(d*m)),oe=H(z*re),ve=H(C*Z),me=H(z*Z),Pe=H(re*C);return new Ti(oe,ve,Pe,me)}subtract(t){return this.add(rd(t).negate())}multiply(t,r=!0){if(!r&&t===0n||(zi(t,1n,Dc),!r&&this.is0()))return Ai;if(t===1n)return this;if(this.equals(Qr))return SM(t).p;let i=Ai,n=Qr,a=this;for(let o=0;r?o<256:t>0n;o++)t&1n?i=i.add(a):r&&(n=n.add(a)),a=a.double(),t>>=1n;return i}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){let{X:t,Y:r,Z:i}=this;if(this.equals(Ai))return{x:0n,y:1n};let n=hv(i,ca);if(H(i*n)!==1n)throw new Error("invalid inverse");return{x:H(t*n),y:H(r*n)}}toBytes(){let{x:t,y:r}=this.toAffine(),i=bv(r);return i[31]|=t&1n?128:0,i}toHex(){return ld(this.toBytes())}clearCofactor(){return this.multiply(8n,!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return this.multiply(Dc/2n,!1).double().add(this).is0()}},Qr=new Ni(ad,od,1n,xe(ad*od)),Ai=new Ni(0n,1n,1n,0n);Ni.BASE=Qr;Ni.ZERO=Ai;var bv=e=>dd(gv(zi(e,0n,yv),64)).reverse(),md=e=>BigInt("0x"+ld(Uint8Array.from(Bt(e)).reverse())),gr=(e,t)=>{let r=e;for(;t-- >0;)r=H(r*r);return r},fM=e=>{let t=H(e*e),r=H(t*e),i=H(gr(r,2)*r),n=H(gr(i,1)*e),a=H(gr(n,5)*n),o=H(gr(a,10)*a),s=H(gr(o,20)*o),c=H(gr(s,40)*s),u=H(gr(c,80)*c),d=H(gr(u,80)*c),p=H(gr(d,10)*a);return H(gr(p,2)*e)},iv=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,pM=(e,t)=>{let r=H(t*H(t*t)),i=H(H(r*r)*t),n=fM(H(e*i)),a=H(e*H(r*n)),o=H(t*H(a*a)),s=a,c=H(a*iv),u=o===e,d=o===xe(-e),p=o===xe(-e*iv);return u&&(a=s),(d||p)&&(a=c),(xe(a)&1n)===1n&&(a=xe(-a)),{isValid:u||d,value:a}},Mc=e=>_v(md(e)),wv=e=>{let t=Uc(e),r=t.slice(0,32);r[0]&=248,r[31]&=127,r[31]|=64;let i=t.slice(32),n=Mc(r),a=Qr.multiply(n),o=a.toBytes();return{head:r,prefix:i,scalar:n,point:a,pointBytes:o}},mM=e=>pd("sha512Async",Bt(e,ji,"secretKey")).then(wv),gM=e=>wv(fd("sha512",Bt(e,ji,"secretKey"))),Sv=async e=>e[1](await pd("sha512Async",e[0])),$v=e=>e[1](fd("sha512",e[0])),Ov=(e,t,r)=>{let{pointBytes:i,scalar:n}=e,a=Mc(t),o=Qr.multiply(a).toBytes();return[ki(o,i,r),u=>{let d=_v(a+Mc(u)*n);return Bt(ki(o,bv(d)),64)}]},_M=async(e,t)=>{let r=Uc(e,"message"),i=await mM(t);return Sv(Ov(i,await pd("sha512Async",i.prefix,r),r))},hM=(e,t)=>{let r=Uc(e,"message"),i=gM(t);return $v(Ov(i,fd("sha512",i.prefix,r),r))},vM=e=>{if(e===null||typeof e!="object")throw new TypeError("expected valid options object");return e.zip215??!0},Iv=(e,t,r,i)=>{e=Bt(e,64,"signature"),t=Bt(t,void 0,"message"),r=Bt(r,ji,"publicKey");let n=vM(i),a=e.subarray(0,ji),o=md(e.subarray(ji,64)),s,c,u,d=Uint8Array.of(),p=!1;try{s=Ni.fromBytes(r,n),c=Ni.fromBytes(a,n),u=Qr.multiply(o,!1),d=ki(a,r,t),p=!0}catch{}return[d,b=>{if(!p||!n&&s.isSmallOrder())return!1;let y=Mc(b);return c.add(s.multiply(y,!1)).subtract(u).clearCofactor().is0()}]},yM=async(e,t,r,i={})=>Sv(Iv(e,t,r,i)),bM=(e,t,r,i={})=>$v(Iv(e,t,r,i)),gd=ud({bytesToHex:ld,hexToBytes:dd,concatBytes:ki,mod:xe,invert:hv,randomBytes:dM}),Ev={sha512Async:async e=>{let t=globalThis?.crypto?.subtle;if(!t)throw new Error("crypto.subtle must be defined, consider polyfill");return new Uint8Array(await t.digest("SHA-512",ki(e)))},sha512:void 0},wM=()=>{let e=[],t=Qr,r;for(let i=0;i<33;i++){r=t,e.push(r);for(let n=1;n<128;n++)r=r.add(t),e.push(r);t=r.double()}return e},av=void 0,ov=(e,t)=>{let r=t.negate();return e?r:t},SM=e=>{let t=av||(av=wM()),r=Ai,i=Qr;for(let n=0;n<33;n++){let a=Number(e&255n);e>>=8n,a>128&&(a-=256,e+=1n);let o=n*128,s=o+Math.abs(a)-1,c=n%2!==0,u=a<0;a===0?i=i.add(ov(c,t[o])):r=r.add(ov(u,t[s]))}if(e!==0n)throw new Error("invalid wnaf");return{p:r,f:i}},jc=BigInt(2**32-1),sv=BigInt(32);function $M(e,t=!1){return t?{h:Number(e&jc),l:Number(e>>sv&jc)}:{h:Number(e>>sv&jc)|0,l:Number(e&jc)|0}}function OM(e,t=!1){let r=e.length,i=new Uint32Array(r),n=new Uint32Array(r);for(let a=0;a<r;a++){let{h:o,l:s}=$M(e[a],t);[i[a],n[a]]=[o,s]}return[i,n]}var IM=e=>e/2**32|0,EM=e=>e>>>0;function PM(e,t,r,i){let n=IM(r),a=EM(r);e.setUint32(t,i?a:n,i),e.setUint32(t+4,i?n:a,i)}var cv=(e,t,r)=>e>>>r,uv=(e,t,r)=>e<<32-r|t>>>r,oa=(e,t,r)=>e>>>r|t<<32-r,sa=(e,t,r)=>e<<32-r|t>>>r,kc=(e,t,r)=>e<<64-r|t>>>r-32,Nc=(e,t,r)=>e>>>r-32|t<<64-r;function Cr(e,t,r,i){let n=(t>>>0)+(i>>>0);return{h:e+r+(n/2**32|0)|0,l:n|0}}var zM=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),TM=(e,t,r,i)=>t+r+i+(e/2**32|0)|0,AM=(e,t,r,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(i>>>0),jM=(e,t,r,i,n)=>t+r+i+n+(e/2**32|0)|0,kM=(e,t,r,i,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(i>>>0)+(n>>>0),NM=(e,t,r,i,n,a)=>t+r+i+n+a+(e/2**32|0)|0;function lv(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var sd=e=>e?`"${e}" `:"";function RM(e,t=""){if(typeof e!="number")throw new TypeError(sd(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(sd(t)+"expected integer >= 0, got "+e);return e}function Pv(e,t,r=""){if(lv(e)&&(t===void 0||e.length===t))return e;t!==void 0&&RM(t,"length");let i=lv(e),n=t!==void 0?` of length ${t}`:"",a=i?`length=${e.length}`:`type=${typeof e}`,o=sd(r)+"expected Uint8Array"+n+", got "+a;throw i?new RangeError(o):new TypeError(o)}var CM=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},dv=(e,t)=>{CM(e,t);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw new TypeError(`"${t}.__proto__" is not allowed`)};function fv(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function DM(e,t){Pv(e,void 0,"output");let r=t.outputLen;if(!(e.length>=r))throw new RangeError('"output" expected length >= '+r)}function xc(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function id(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function _r(e,t){return e<<32-t|e>>>t}function MM(e,t,r="opts"){return dv(e,"defaults"),t!==void 0&&dv(t,r),Object.assign(Object.create(null),e,t)}function zv(e,t={}){if(typeof e!="function")throw new TypeError('"hashCons" expected function, got type='+typeof e);t=MM({},t,"info");let r=(n,a)=>e(a).update(n).digest(),i=e(void 0);return r.outputLen=i.outputLen,r.blockLen=i.blockLen,r.canXOF=i.canXOF,r.create=n=>e(n),Object.assign(r,t),Object.freeze(r)}var Tv=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function xM(e,t,r){return e&t^~e&r}function UM(e,t,r){return e&t^e&r^t&r}var Av=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,i){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(e),this.view=id(this.buffer)}update(e){fv(this),Pv(e);let{view:t,buffer:r,blockLen:i}=this,n=e.length,a=!1;for(let o=0;o<n;){let s=Math.min(i-this.pos,n-o);if(s===i){let c=id(e);for(;i<=n-o;o+=i)this.process(c,o);a=!0;continue}r.set(o===0&&s===n?e:e.subarray(o,o+s),this.pos),this.pos+=s,o+=s,this.pos===i&&(this.process(t,0),this.pos=0,a=!0)}return this.length+=e.length,a&&this.roundClean(),this}digestInto(e){fv(this),DM(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:i,isLE:n}=this,{pos:a}=this;t[a++]=128,t.fill(0,a),this.padOffset>i-a&&(this.process(r,0),t.fill(0)),PM(r,i-8,this.length*8,n),this.process(r,0),this.roundClean();let o=e===t?r:id(e),s=this.outputLen,c=s/4,u=this.get();if(s%4||c>u.length)throw new Error("invalid outputLen");for(let d=0;d<c;d++)o.setUint32(4*d,u[d],n)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneIntoMeta(e){let{buffer:t,length:r,finished:i,destroyed:n,pos:a}=this;return e.destroyed=n,e.finished=i,e.length=r,e.pos=a,a&&e.buffer.set(t),e}clone(){return this._cloneInto()}},LM=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ZM=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),qM=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Kr=new Uint32Array(64),FM=class extends Av{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:r,D:i,E:n,F:a,G:o,H:s}=this;return[e,t,r,i,n,a,o,s]}set(e,t,r,i,n,a,o,s){this.A=e|0,this.B=t|0,this.C=r|0,this.D=i|0,this.E=n|0,this.F=a|0,this.G=o|0,this.H=s|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let d=0;d<16;d++,t+=4)Kr[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let p=Kr[d-15],m=Kr[d-2],b=_r(p,7)^_r(p,18)^p>>>3,y=_r(m,17)^_r(m,19)^m>>>10;Kr[d]=y+Kr[d-7]+b+Kr[d-16]|0}let{A:r,B:i,C:n,D:a,E:o,F:s,G:c,H:u}=this;for(let d=0;d<64;d++){let p=_r(o,6)^_r(o,11)^_r(o,25),m=u+p+xM(o,s,c)+qM[d]+Kr[d]|0,y=(_r(r,2)^_r(r,13)^_r(r,22))+UM(r,i,n)|0;u=c,c=s,s=o,o=a+m|0,a=n,n=i,i=r,r=m+y|0}r=r+this.A|0,i=i+this.B|0,n=n+this.C|0,a=a+this.D|0,o=o+this.E|0,s=s+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(r,i,n,a,o,s,c,u)}roundClean(){xc(Kr)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),xc(this.buffer)}},VM=class extends FM{constructor(){super(32,LM)}},jv=OM(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),BM=jv[0],GM=jv[1],Hr=new Uint32Array(80),Xr=new Uint32Array(80),JM=class extends Av{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(e,t){super(128,e,16,!1),this.Ah=t[0]|0,this.Al=t[1]|0,this.Bh=t[2]|0,this.Bl=t[3]|0,this.Ch=t[4]|0,this.Cl=t[5]|0,this.Dh=t[6]|0,this.Dl=t[7]|0,this.Eh=t[8]|0,this.El=t[9]|0,this.Fh=t[10]|0,this.Fl=t[11]|0,this.Gh=t[12]|0,this.Gl=t[13]|0,this.Hh=t[14]|0,this.Hl=t[15]|0}get(){let{Ah:e,Al:t,Bh:r,Bl:i,Ch:n,Cl:a,Dh:o,Dl:s,Eh:c,El:u,Fh:d,Fl:p,Gh:m,Gl:b,Hh:y,Hl:O}=this;return[e,t,r,i,n,a,o,s,c,u,d,p,m,b,y,O]}set(e,t,r,i,n,a,o,s,c,u,d,p,m,b,y,O){this.Ah=e|0,this.Al=t|0,this.Bh=r|0,this.Bl=i|0,this.Ch=n|0,this.Cl=a|0,this.Dh=o|0,this.Dl=s|0,this.Eh=c|0,this.El=u|0,this.Fh=d|0,this.Fl=p|0,this.Gh=m|0,this.Gl=b|0,this.Hh=y|0,this.Hl=O|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let C=0;C<16;C++,t+=4)Hr[C]=e.getUint32(t),Xr[C]=e.getUint32(t+=4);for(let C=16;C<80;C++){let Z=Hr[C-15]|0,oe=Xr[C-15]|0,ve=oa(Z,oe,1)^oa(Z,oe,8)^cv(Z,oe,7),me=sa(Z,oe,1)^sa(Z,oe,8)^uv(Z,oe,7),Pe=Hr[C-2]|0,ft=Xr[C-2]|0,si=oa(Pe,ft,19)^kc(Pe,ft,61)^cv(Pe,ft,6),Li=sa(Pe,ft,19)^Nc(Pe,ft,61)^uv(Pe,ft,6),ci=AM(me,Li,Xr[C-7],Xr[C-16]),va=jM(ci,ve,si,Hr[C-7],Hr[C-16]);Hr[C]=va|0,Xr[C]=ci|0}let{Ah:r,Al:i,Bh:n,Bl:a,Ch:o,Cl:s,Dh:c,Dl:u,Eh:d,El:p,Fh:m,Fl:b,Gh:y,Gl:O,Hh:z,Hl:re}=this;for(let C=0;C<80;C++){let Z=oa(d,p,14)^oa(d,p,18)^kc(d,p,41),oe=sa(d,p,14)^sa(d,p,18)^Nc(d,p,41),ve=d&m^~d&y,me=p&b^~p&O,Pe=kM(re,oe,me,GM[C],Xr[C]),ft=NM(Pe,z,Z,ve,BM[C],Hr[C]),si=Pe|0,Li=oa(r,i,28)^kc(r,i,34)^kc(r,i,39),ci=sa(r,i,28)^Nc(r,i,34)^Nc(r,i,39),va=r&n^r&o^n&o,ru=i&a^i&s^a&s;z=y|0,re=O|0,y=m|0,O=b|0,m=d|0,b=p|0,{h:d,l:p}=Cr(c|0,u|0,ft|0,si|0),c=o|0,u=s|0,o=n|0,s=a|0,n=r|0,a=i|0;let tf=zM(si,ci,ru);r=TM(tf,ft,Li,va),i=tf|0}({h:r,l:i}=Cr(this.Ah|0,this.Al|0,r|0,i|0)),{h:n,l:a}=Cr(this.Bh|0,this.Bl|0,n|0,a|0),{h:o,l:s}=Cr(this.Ch|0,this.Cl|0,o|0,s|0),{h:c,l:u}=Cr(this.Dh|0,this.Dl|0,c|0,u|0),{h:d,l:p}=Cr(this.Eh|0,this.El|0,d|0,p|0),{h:m,l:b}=Cr(this.Fh|0,this.Fl|0,m|0,b|0),{h:y,l:O}=Cr(this.Gh|0,this.Gl|0,y|0,O|0),{h:z,l:re}=Cr(this.Hh|0,this.Hl|0,z|0,re|0),this.set(r,i,n,a,o,s,c,u,d,p,m,b,y,O,z,re)}roundClean(){xc(Hr,Xr)}destroy(){this.destroyed=!0,xc(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},WM=class extends JM{constructor(){super(64,ZM)}},kv=zv(()=>new VM,Tv(1)),YM=zv(()=>new WM,Tv(3)),pv=Ev;pv.sha512||(pv.sha512=e=>YM(e));function KM(e,t){return hM(t,e)}function HM(e,t,r){return bM(t,r,e)}function XM(e,t){return _M(t,e)}function QM(e,t,r){return yM(t,r,e)}var W4=gd.bytesToHex,Y4=gd.hexToBytes,K4=gd.concatBytes;function e1(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function t1(e){return e1(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function n1(e){if(e.kty!=="OKP")throw new Error(`computeJkt expects an OKP JWK; got kty="${e.kty}"`);let t=JSON.stringify({crv:e.crv,kty:e.kty,x:e.x});return t1(kv(new TextEncoder().encode(t)))}});var hd=P(Lc=>{"use strict";Object.defineProperty(Lc,"__esModule",{value:!0});Lc.computeJkt=void 0;var r1=_d();Object.defineProperty(Lc,"computeJkt",{enumerable:!0,get:function(){return r1.computeJkt}})});var Rv=P(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});Zc.prepareRootSignedJws=i1;Zc.completeRootSignedJws=a1;var vd=Wa();function i1(e,t,r){let i=(0,vd.bytesToBase64Url)(new TextEncoder().encode(JSON.stringify({alg:"EdDSA",kid:t,typ:e}))),n=(0,vd.bytesToBase64Url)(new TextEncoder().encode(JSON.stringify(r)));return{signingInput:`${i}.${n}`}}function a1(e,t,r){if(!(t instanceof Uint8Array)||t.length!==64)throw new Error(`${r} signature must be exactly 64 raw Ed25519 bytes`);return`${e}.${(0,vd.bytesToBase64Url)(t)}`}});var ua=P(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.CLOCK_SKEW_SECONDS=N.PUBLIC_MATERIAL_TTL_SECONDS=N.ENROLLMENT_RECEIPT_TTL_SECONDS=N.AGENT_OPERATION_MAX_TTL_SECONDS=N.AGENT_OPERATION_MAX_AGE_SECONDS=N.MAX_OWNER_APPROVED_CHARGE_WINDOW_SECONDS=N.MAX_CHARGE_WINDOW_AFTER_ADMISSION_SECONDS=N.OWNER_STATEMENT_MAX_SECONDS=N.TAP_MAX_AGE_SECONDS=N.POP_MAX_AGE_SECONDS=N.WALLET_BINDING_MAX_TTL_SECONDS=N.RUNTIME_CERTIFICATE_MAX_TTL_SECONDS=N.REGISTRY_ENTRY_MAX_TTL_SECONDS=N.IDENTITY_GATE_ENROLLMENT_MAX_TTL_SECONDS=N.IDENTITY_GATE_AUTHORIZATION_MAX_TTL_SECONDS=N.FINANCIAL_ADMISSION_MAX_TTL_SECONDS=N.ASSOCIATION_ADMISSION_MAX_TTL_SECONDS=N.RUNTIME_ADMISSION_MAX_TTL_SECONDS=N.IDENTITY_SLIP_MAX_TTL_SECONDS=N.RENEWAL_MARGIN_SECONDS=N.TAP_DIRECTORY_RENEW_WINDOW_SECONDS=N.TAP_KEY_TTL_DAYS=N.APP_CONNECT_TTL_SECONDS=N.APP_TOKEN_IDLE_SECONDS=N.CLI_CEREMONY_GRACE_MS=N.CLI_HANDOFF_TTL_MS=N.OWNER_ENROLLMENT_CLAIM_WINDOW_SECONDS=N.OWNER_PAYMENT_APPROVAL_SECONDS=N.RUNTIME_LEASE_REQUEST_MAX_AGE_SECONDS=N.ENROLLMENT_CHALLENGE_MAX_AGE_MS=N.AGENT_PAIRING_TTL_SECONDS=N.HOSTED_CONNECTOR_PROOF_TTL_SECONDS=N.RUNTIME_LEASE_MAX_TTL_SECONDS=N.RUNTIME_DELEGATION_MAX_TTL_SECONDS=N.WALLET_GRANT_MAX_TERM_SECONDS=N.WALLET_GRANT_DEFAULT_DAYS=N.CARD_MANDATE_MAX_SECONDS=N.CARD_GRANT_DEFAULT_TERM_SECONDS=N.CARD_GRANT_MAX_TERM_SECONDS=N.DAY_SECONDS=void 0;N.walletGrantExpiry=o1;N.defaultGrantExpiry=s1;N.renewalDue=c1;N.DAY_SECONDS=86400;N.CARD_GRANT_MAX_TERM_SECONDS=7*N.DAY_SECONDS;N.CARD_GRANT_DEFAULT_TERM_SECONDS=N.CARD_GRANT_MAX_TERM_SECONDS-3600;N.CARD_MANDATE_MAX_SECONDS=N.CARD_GRANT_DEFAULT_TERM_SECONDS;N.WALLET_GRANT_DEFAULT_DAYS=30;N.WALLET_GRANT_MAX_TERM_SECONDS=90*N.DAY_SECONDS;function o1(e,t=new Date){if(e==null)return new Date(t.getTime()+N.WALLET_GRANT_DEFAULT_DAYS*N.DAY_SECONDS*1e3);if(Number.isNaN(e.getTime()))throw new RangeError("grant_expiry_invalid");if(e.getTime()<=t.getTime())throw new RangeError("grant_expiry_past");if(e.getTime()>t.getTime()+N.WALLET_GRANT_MAX_TERM_SECONDS*1e3)throw new RangeError("grant_expiry_beyond_maximum");return new Date(Math.floor(e.getTime()/1e3)*1e3)}function s1(e,t){return t.card?new Date(e.getTime()+N.CARD_GRANT_DEFAULT_TERM_SECONDS*1e3):new Date(e.getTime()+N.WALLET_GRANT_DEFAULT_DAYS*N.DAY_SECONDS*1e3)}N.RUNTIME_DELEGATION_MAX_TTL_SECONDS=366*N.DAY_SECONDS;N.RUNTIME_LEASE_MAX_TTL_SECONDS=300;N.HOSTED_CONNECTOR_PROOF_TTL_SECONDS=300;N.AGENT_PAIRING_TTL_SECONDS=3600;N.ENROLLMENT_CHALLENGE_MAX_AGE_MS=6e4;N.RUNTIME_LEASE_REQUEST_MAX_AGE_SECONDS=60;N.OWNER_PAYMENT_APPROVAL_SECONDS=240;N.OWNER_ENROLLMENT_CLAIM_WINDOW_SECONDS=600;N.CLI_HANDOFF_TTL_MS=15*6e4;N.CLI_CEREMONY_GRACE_MS=45*6e4;N.APP_TOKEN_IDLE_SECONDS=90*N.DAY_SECONDS;N.APP_CONNECT_TTL_SECONDS=900;N.TAP_KEY_TTL_DAYS=365;N.TAP_DIRECTORY_RENEW_WINDOW_SECONDS=30*N.DAY_SECONDS;N.RENEWAL_MARGIN_SECONDS=30*N.DAY_SECONDS;function c1(e){let t=e.marginSeconds??N.RENEWAL_MARGIN_SECONDS,r=Math.max(e.nowSec,e.grantEndSec??e.nowSec)+t,i=e.maxLifetimeSeconds===void 0?r:e.nowSec+e.maxLifetimeSeconds-t;return e.endSec<=Math.min(r,i)}N.IDENTITY_SLIP_MAX_TTL_SECONDS=60;N.RUNTIME_ADMISSION_MAX_TTL_SECONDS=600;N.ASSOCIATION_ADMISSION_MAX_TTL_SECONDS=60;N.FINANCIAL_ADMISSION_MAX_TTL_SECONDS=60;N.IDENTITY_GATE_AUTHORIZATION_MAX_TTL_SECONDS=366*N.DAY_SECONDS;N.IDENTITY_GATE_ENROLLMENT_MAX_TTL_SECONDS=366*N.DAY_SECONDS;N.REGISTRY_ENTRY_MAX_TTL_SECONDS=366*N.DAY_SECONDS;N.RUNTIME_CERTIFICATE_MAX_TTL_SECONDS=N.DAY_SECONDS;N.WALLET_BINDING_MAX_TTL_SECONDS=366*N.DAY_SECONDS;N.POP_MAX_AGE_SECONDS=120;N.TAP_MAX_AGE_SECONDS=480;N.OWNER_STATEMENT_MAX_SECONDS=300;N.MAX_CHARGE_WINDOW_AFTER_ADMISSION_SECONDS=30;N.MAX_OWNER_APPROVED_CHARGE_WINDOW_SECONDS=300;N.AGENT_OPERATION_MAX_AGE_SECONDS=300;N.AGENT_OPERATION_MAX_TTL_SECONDS=600;N.ENROLLMENT_RECEIPT_TTL_SECONDS=366*N.DAY_SECONDS;N.PUBLIC_MATERIAL_TTL_SECONDS=300;N.CLOCK_SKEW_SECONDS=30});var Uv=P(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.HOSTED_RUNTIME_CERTIFICATE_PURPOSES=He.RUNTIME_CERTIFICATE_PURPOSES=He.CARD_RUNTIME_CERTIFICATE_MAX_TTL_SECONDS=He.RUNTIME_CERTIFICATE_VERSION=He.RUNTIME_CERTIFICATE_TYP=He.RUNTIME_CERTIFICATE_MAX_TTL_SECONDS=void 0;He.runtimeCertificateMaxTtl=xv;He.isCanonicalBase64Url32=bd;He.prepareRuntimeCertificate=_1;var Cv=Wa(),Dv=hd(),u1=Rv(),l1=ua();Object.defineProperty(He,"RUNTIME_CERTIFICATE_MAX_TTL_SECONDS",{enumerable:!0,get:function(){return l1.RUNTIME_CERTIFICATE_MAX_TTL_SECONDS}});var Mv=ua();He.RUNTIME_CERTIFICATE_TYP="visa-agent-runtime-cert+jwt";He.RUNTIME_CERTIFICATE_VERSION=1;He.CARD_RUNTIME_CERTIFICATE_MAX_TTL_SECONDS=366*24*60*60;function xv(e){return e.length===1&&e[0]==="card:vic"?He.CARD_RUNTIME_CERTIFICATE_MAX_TTL_SECONDS:Mv.RUNTIME_CERTIFICATE_MAX_TTL_SECONDS}He.RUNTIME_CERTIFICATE_PURPOSES=["tap","subway","card:vic","wallet:x402"];He.HOSTED_RUNTIME_CERTIFICATE_PURPOSES=["card:vic","wallet:x402","tap"];var d1=new Set(He.RUNTIME_CERTIFICATE_PURPOSES),yd=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,f1=/^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/;function bd(e){if(typeof e!="string"||!f1.test(e))return!1;let t=(0,Cv.base64UrlToBytes)(e);return t.length===32&&(0,Cv.bytesToBase64Url)(t)===e}function p1(e){return{kty:"OKP",crv:"Ed25519",x:e.x}}function m1(e){if(!Array.isArray(e)||e.length===0)throw new Error("runtime certificate requires at least one purpose");let t=[...new Set(e)];if(t.length!==e.length||t.some(r=>!d1.has(r)))throw new Error("runtime certificate purposes must be unique supported values");return t.sort()}function g1(e,t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative unix-seconds integer`)}function _1(e){let t=e.nowSec??Math.floor(Date.now()/1e3),r=e.ttlSeconds??Mv.RUNTIME_CERTIFICATE_MAX_TTL_SECONDS,i=xv(e.purposes),n=e.certificateId??globalThis.crypto.randomUUID();if(g1("nowSec",t),!Number.isSafeInteger(r)||r<=0||r>i)throw new Error(`runtime certificate ttlSeconds must be in (0, ${i}]`);if(!yd.test(e.agentId)||!yd.test(e.runtimeId))throw new Error("runtime certificate agentId/runtimeId must be canonical UUIDs");if(!yd.test(n))throw new Error("runtime certificate certificateId must be a canonical UUID");if(!bd(e.rootJkt))throw new Error("runtime certificate rootJkt must be a canonical RFC 7638 thumbprint");if(!e.rootKid||e.rootKid.length>256)throw new Error("runtime certificate rootKid must be a bounded non-empty identifier");if((0,Dv.computeJkt)(e.rootPublicJwk)!==e.rootJkt)throw new Error("runtime certificate signer public key does not match rootJkt");let o=p1(e.runtimePublicJwk);if(!bd(o.x))throw new Error("runtime certificate child key must be canonical Ed25519");let s=(0,Dv.computeJkt)(o);if(s===e.rootJkt)throw new Error("runtime certificate child key must differ from the identity root");let c={v:He.RUNTIME_CERTIFICATE_VERSION,iss:e.rootJkt,sub:e.agentId,jti:n,runtimeId:e.runtimeId,cnf:{jwk:o,jkt:s},purposes:m1(e.purposes),iat:t,nbf:t,exp:t+r};return{...(0,u1.prepareRootSignedJws)(He.RUNTIME_CERTIFICATE_TYP,e.rootKid,c),claims:c}}});var Sd=P(wd=>{"use strict";Object.defineProperty(wd,"__esModule",{value:!0});wd.signJwtWithSigner=h1;var Zv=Wa(),Lv=e=>(0,Zv.bytesToBase64Url)(new TextEncoder().encode(JSON.stringify(e)));async function h1(e,t,r){let i=Lv({alg:"EdDSA",kid:e.kid,typ:t.typ}),n=Lv(r),a=`${i}.${n}`,o=await e.sign(new TextEncoder().encode(a));if(!(o instanceof Uint8Array)||o.length!==64)throw new Error(`signer.sign must return a raw 64-byte Ed25519 signature; got ${o instanceof Uint8Array?`${o.length} bytes`:typeof o} (check the vault adapter is not DER-wrapping or re-encoding)`);return`${a}.${(0,Zv.bytesToBase64Url)(o)}`}});var $d=P(la=>{"use strict";Object.defineProperty(la,"__esModule",{value:!0});la.POP_JWT_TYP=void 0;la.createPopProofWithSigner=y1;var v1=Sd();la.POP_JWT_TYP="visa-agent-pop+jwt";async function y1(e,t){let i={cnf:{jwk:{kty:e.publicJwk.kty,crv:e.publicJwk.crv,x:e.publicJwk.x}},nonce:t.nonce,aud:t.audience,iat:t.nowSec};return t.intentHash!==void 0&&(i.int=t.intentHash),t.runtimeCertificate!==void 0&&(i.rkc=t.runtimeCertificate),(0,v1.signJwtWithSigner)(e,{typ:la.POP_JWT_TYP},i)}});var Od=P(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.WALLET_BINDING_TYP=Pt.RUNTIME_AUTHORITY_CLOCK_SKEW_SECONDS=Pt.RUNTIME_LEASE_MAX_TTL_SECONDS=Pt.RUNTIME_DELEGATION_MAX_TTL_SECONDS=Pt.RUNTIME_LEASE_SIGNING_MODES=Pt.RUNTIME_DELEGATION_TYP=void 0;Pt.RUNTIME_DELEGATION_TYP="visa-agent-runtime-delegation+jwt";Pt.RUNTIME_LEASE_SIGNING_MODES=["eip3009:exact","permit2:upto"];var qv=ua();Object.defineProperty(Pt,"RUNTIME_DELEGATION_MAX_TTL_SECONDS",{enumerable:!0,get:function(){return qv.RUNTIME_DELEGATION_MAX_TTL_SECONDS}});Object.defineProperty(Pt,"RUNTIME_LEASE_MAX_TTL_SECONDS",{enumerable:!0,get:function(){return qv.RUNTIME_LEASE_MAX_TTL_SECONDS}});var b1=ua();Pt.RUNTIME_AUTHORITY_CLOCK_SKEW_SECONDS=b1.CLOCK_SKEW_SECONDS;Pt.WALLET_BINDING_TYP="visa-agent-wallet-binding+jwt"});var Vv=P(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.RUNTIME_LEASE_REQUEST_MAX_AGE_SECONDS=Gt.RUNTIME_LEASE_REQUEST_AUDIENCE=Gt.RUNTIME_LEASE_REQUEST_VERSION=void 0;Gt.runtimeLeaseRequestIntentHash=Fv;Gt.createRuntimeLeaseRequestProofWithSigner=T1;var w1=_d(),S1=Wa(),$1=$d(),O1=Od(),I1=ua();Object.defineProperty(Gt,"RUNTIME_LEASE_REQUEST_MAX_AGE_SECONDS",{enumerable:!0,get:function(){return I1.RUNTIME_LEASE_REQUEST_MAX_AGE_SECONDS}});Gt.RUNTIME_LEASE_REQUEST_VERSION=1;Gt.RUNTIME_LEASE_REQUEST_AUDIENCE="visa-runtime-lease-requests:v1";var E1=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,P1=new Set(O1.RUNTIME_LEASE_SIGNING_MODES);function Id(e,t){if(!E1.test(t))throw new Error(`${e} must be a canonical UUID`)}function z1(e){if(Id("agentId",e.agentId),Id("runtimeId",e.runtimeId),Id("requestId",e.requestId),!P1.has(e.signingMode))throw new Error("runtime lease request signingMode is unsupported");return{v:Gt.RUNTIME_LEASE_REQUEST_VERSION,agentId:e.agentId,runtimeId:e.runtimeId,requestId:e.requestId,signingMode:e.signingMode}}function Fv(e){return(0,S1.bytesToBase64Url)((0,w1.sha256)(new TextEncoder().encode(JSON.stringify(z1(e)))))}function T1(e,t){if(!Number.isSafeInteger(t.nowSec)||t.nowSec<0)throw new Error("runtime lease request nowSec must be a non-negative safe integer");return(0,$1.createPopProofWithSigner)(e,{nonce:t.requestId,audience:Gt.RUNTIME_LEASE_REQUEST_AUDIENCE,nowSec:t.nowSec,intentHash:Fv(t)})}});var Bv=P(Dt=>{"use strict";var A1=Dt&&Dt.__createBinding||(Object.create?(function(e,t,r,i){i===void 0&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);(!n||("get"in n?!t.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}):(function(e,t,r,i){i===void 0&&(i=r),e[i]=t[r]})),Ya=Dt&&Dt.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&A1(t,e,r)};Object.defineProperty(Dt,"__esModule",{value:!0});Dt.computeJkt=void 0;Ya(Uv(),Dt);Ya(Vv(),Dt);Ya($d(),Dt);Ya(Sd(),Dt);Ya(Od(),Dt);var j1=hd();Object.defineProperty(Dt,"computeJkt",{enumerable:!0,get:function(){return j1.computeJkt}})});var ty=P(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.TVC_PROVIDER_WARN_THRESHOLD=dt.TURNKEY_SUBORG_RESOURCE_LIMITS=void 0;dt.tvcProviderCapacityEvidence=ey;dt.parseTvcProviderCapacityEvidence=V1;dt.TURNKEY_SUBORG_RESOURCE_LIMITS=Object.freeze({users:100,policies:100,source:"https://docs.turnkey.com/reference/resource-limits",verifiedOn:"2026-08-29"});dt.TVC_PROVIDER_WARN_THRESHOLD=70;function ey(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error("user count is invalid");if(!Number.isSafeInteger(t)||t<0)throw new Error("policy count is invalid");let r=dt.TURNKEY_SUBORG_RESOURCE_LIMITS.users-e,i=dt.TURNKEY_SUBORG_RESOURCE_LIMITS.policies-t;return{userCount:e,policyCount:t,userLimit:dt.TURNKEY_SUBORG_RESOURCE_LIMITS.users,policyLimit:dt.TURNKEY_SUBORG_RESOURCE_LIMITS.policies,remainingUsers:r,remainingPolicies:i,pressure:e>dt.TVC_PROVIDER_WARN_THRESHOLD||t>dt.TVC_PROVIDER_WARN_THRESHOLD,limitsSource:dt.TURNKEY_SUBORG_RESOURCE_LIMITS.source,limitsVerifiedOn:dt.TURNKEY_SUBORG_RESOURCE_LIMITS.verifiedOn}}function V1(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("TVC provider capacity evidence is invalid");let t=e,r=ey(t.userCount??-1,t.policyCount??-1);for(let i of Object.keys(r))if(t[i]!==r[i])throw new Error("TVC provider capacity evidence is invalid");if(Object.keys(t).length!==Object.keys(r).length)throw new Error("TVC provider capacity evidence is invalid");return r}});var ny=P(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});Bc.TVC_SIGNER_POLICY_CONTRACT_VERSION=void 0;Bc.TVC_SIGNER_POLICY_CONTRACT_VERSION=1});var iy=P(Nd=>{"use strict";Object.defineProperty(Nd,"__esModule",{value:!0});Nd.checkTvcPinParity=K1;var Gc=/^[0-9a-f]{64}$/,ry=16*1024,B1=4096,G1="tvc-proof-verifier.railway.internal",Jc=class extends Error{};function J1(e,t){return Object.keys(e).sort().join(",")===[...t].sort().join(",")}function W1(e){try{let t=new URL(e),r=t.protocol==="http:"&&t.hostname===G1&&t.port!=="";return t.protocol!=="https:"&&!r||t.username!==""||t.password!==""||t.search!==""||t.hash!==""?null:(t.pathname="/effective-pins",t)}catch{return null}}async function Y1(e){let t=Number(e.headers.get("content-length"));if(Number.isFinite(t)&&t>ry)throw await e.body?.cancel().catch(()=>{}),new Error("response too large");let r=e.body?.getReader();if(!r)throw new Error("response body missing");let i=[],n=0,a=async()=>{try{return await r.read()}catch{throw new Jc}};try{for(;;){let c=await a();if(c.done)break;if(n+=c.value.byteLength,n>ry)throw await r.cancel().catch(()=>{}),new Error("response too large");i.push(c.value)}}finally{r.releaseLock()}let o=new Uint8Array(n),s=0;for(let c of i)o.set(c,s),s+=c.byteLength;return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(o))}async function K1(e){let t=e.verifierUrl?.trim()??"",r=e.bearerToken?.trim()??"",i=e.approvedManifestDigest?.trim()??"",n=e.approvedPivotDigest?.trim()??"",a=[t,r,i,n].filter(Boolean).length;if(a===0)return{status:"dark"};let o=t?W1(t):null;if(a!==4||!o||r.length>B1||!Gc.test(i)||!Gc.test(n))return{status:"invalid_configuration"};let s;try{s=await(e.fetchImpl??fetch)(o,{method:"GET",redirect:"error",headers:{accept:"application/json",authorization:`Bearer ${r}`},signal:AbortSignal.timeout(Math.min(Math.max(e.timeoutMs??5e3,100),1e4))})}catch{return{status:"verifier_unavailable"}}if(!s.ok)return await s.body?.cancel().catch(()=>{}),s.status===401||s.status===403?{status:"verifier_auth_failed"}:s.status===408||s.status===425||s.status===429||s.status>=500?{status:"verifier_unavailable"}:{status:"verifier_invalid_response"};let c;try{c=await Y1(s)}catch(d){return{status:d instanceof Jc?"verifier_unavailable":"verifier_invalid_response"}}if(typeof c!="object"||c===null||Array.isArray(c)||!J1(c,["approvedManifestDigest","approvedPivotDigest"]))return{status:"verifier_invalid_response"};let u=c;return typeof u.approvedManifestDigest!="string"||!Gc.test(u.approvedManifestDigest)||typeof u.approvedPivotDigest!="string"||!Gc.test(u.approvedPivotDigest)?{status:"verifier_invalid_response"}:u.approvedManifestDigest!==i?{status:"manifest_mismatch"}:u.approvedPivotDigest!==n?{status:"pivot_mismatch"}:{status:"ready"}}});var ay=P(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.ACCOUNT_OPERATION_EVIDENCE_TYPES=bt.ACCOUNT_OPERATION_PROOF_LEVELS=bt.ACCOUNT_OPERATION_OUTCOMES=bt.ACCOUNT_OPERATION_RECEIPT_SCHEMA_VERSION=void 0;bt.parseAccountOperationReceipt=Q1;bt.ACCOUNT_OPERATION_RECEIPT_SCHEMA_VERSION=1;bt.ACCOUNT_OPERATION_OUTCOMES=["pending","completed","failed","uncertain","released","reversed","disputed"];bt.ACCOUNT_OPERATION_PROOF_LEVELS=["none","platform_observed","merchant_reported","owner_attested","processor_confirmed","network_verified","settled"];bt.ACCOUNT_OPERATION_EVIDENCE_TYPES=["platform_activity","merchant_confirmation","card_lifecycle","onchain_transaction"];function ti(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function xr(e){return e===null||typeof e=="string"}function to(e){return typeof e=="string"&&e.length>0&&!Number.isNaN(Date.parse(e))}function ni(e,t){let r=Object.keys(e).sort(),i=[...t].sort();return r.length===i.length&&r.every((n,a)=>n===i[a])}function H1(e){return ti(e)?ni(e,["type","source","observedAt","reference","url"])&&typeof e.type=="string"&&bt.ACCOUNT_OPERATION_EVIDENCE_TYPES.includes(e.type)&&typeof e.source=="string"&&to(e.observedAt)&&xr(e.reference)&&xr(e.url):!1}function X1(e){return ti(e)?ni(e,["type","at"])&&typeof e.type=="string"&&e.type.length>0&&to(e.at):!1}function Q1(e){if(!ti(e)||!ni(e,["schemaVersion","operationId","activityId","payment","route","party","authority","outcome","evidence","timeline","dataCompleteness"])||e.schemaVersion!==bt.ACCOUNT_OPERATION_RECEIPT_SCHEMA_VERSION||typeof e.operationId!="string"||typeof e.activityId!="string"||e.dataCompleteness!=="complete"&&e.dataCompleteness!=="partial"||!Array.isArray(e.evidence)||!e.evidence.every(H1)||!Array.isArray(e.timeline)||!e.timeline.every(X1))return null;let t=e.payment,r=e.route,i=e.party,n=e.authority,a=e.outcome;return!ti(t)||!ni(t,["amountAtomic","decimals","currency","merchant","description","createdAt"])||typeof t.amountAtomic!="string"||!/^\d+$/.test(t.amountAtomic)||typeof t.decimals!="number"||!Number.isInteger(t.decimals)||t.decimals<0||t.decimals>18||typeof t.currency!="string"||typeof t.merchant!="string"||typeof t.description!="string"||!to(t.createdAt)||!ti(r)||!ni(r,["rail","protocol","network","cardLast4"])||r.rail!=="wallet"&&r.rail!=="card"||!(r.protocol===null||r.protocol==="x402"||r.protocol==="mpp"||r.protocol==="vic"||r.protocol==="virtual_card")||!xr(r.network)||!xr(r.cardLast4)||!ti(i)||!ni(i,["agentId","agentName"])||!xr(i.agentId)||!xr(i.agentName)||!ti(n)||!ni(n,["grantId","mandateId","drawId"])||!xr(n.grantId)||!xr(n.mandateId)||!xr(n.drawId)||!ti(a)||!ni(a,["status","proofLevel","final","updatedAt","finalizesBy",..."held"in a?["held"]:[]])||typeof a.status!="string"||!bt.ACCOUNT_OPERATION_OUTCOMES.includes(a.status)||typeof a.proofLevel!="string"||!bt.ACCOUNT_OPERATION_PROOF_LEVELS.includes(a.proofLevel)||typeof a.final!="boolean"||"held"in a&&(a.held!==!0||r.rail!=="wallet"||r.protocol!=="mpp"||a.status!=="failed"||a.final!==!0)||!to(a.updatedAt)||!(a.finalizesBy===null||to(a.finalizesBy))?null:e}});var Rd=P(Ie=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.CARD_PAYMENT_ATTEMPT_STATUSES=Ie.CARD_PAYMENT_EVENT_REQUIRED_PROVENANCE=Ie.CARD_PAYMENT_PROCESSOR_TRUTH_EVENT_TYPES=Ie.CARD_PAYMENT_SOURCE_PROVENANCE=Ie.CARD_PAYMENT_PROVENANCES=Ie.OWNER_ATTESTATION_VERDICTS=Ie.CARD_PAYMENT_EVENT_TYPES=Ie.CARD_PAYMENT_INTENTS=Ie.CARD_PAYMENT_SOURCES=Ie.CARD_PAYMENT_PROCESSORS=void 0;Ie.isOwnerAttestationVerdict=cy;Ie.provenanceOfSource=uy;Ie.requiresProviderProvenance=ex;Ie.requiredProvenanceFor=ly;Ie.reduceCardPaymentEvents=ux;Ie.CARD_PAYMENT_PROCESSORS=["cybersource","vgs"];Ie.CARD_PAYMENT_SOURCES=["auth_request","mpp_gateway","cybersource_tss","cybersource_report","cybersource_webhook","web_vgs","admin","owner_attestation"];Ie.CARD_PAYMENT_INTENTS=["sale","auth","capture","refund","void","unknown"];Ie.CARD_PAYMENT_EVENT_TYPES=["charge_requested","charge_ambiguous","sale_accepted","auth_held","capture_pending","captured","voided","refund_pending","refund_succeeded","refund_failed","chargeback_opened","chargeback_lost","chargeback_won","processor_unknown","reconciliation_gap","owner_attested"];Ie.OWNER_ATTESTATION_VERDICTS=["found_charge","merchant_completed","no_charge_visible"];function cy(e){return typeof e=="string"&&Ie.OWNER_ATTESTATION_VERDICTS.includes(e)}Ie.CARD_PAYMENT_PROVENANCES=["provider","platform_caller","owner","operator"];Ie.CARD_PAYMENT_SOURCE_PROVENANCE={auth_request:"platform_caller",mpp_gateway:"platform_caller",web_vgs:"platform_caller",cybersource_tss:"provider",cybersource_report:"provider",cybersource_webhook:"provider",admin:"operator",owner_attestation:"owner"};function uy(e){return Ie.CARD_PAYMENT_SOURCE_PROVENANCE[e]??"platform_caller"}Ie.CARD_PAYMENT_PROCESSOR_TRUTH_EVENT_TYPES=new Set(["auth_held","capture_pending","captured","voided","refund_pending","refund_succeeded","refund_failed","chargeback_opened","chargeback_lost","chargeback_won"]);function ex(e){return Ie.CARD_PAYMENT_PROCESSOR_TRUTH_EVENT_TYPES.has(e)}Ie.CARD_PAYMENT_EVENT_REQUIRED_PROVENANCE={...Object.fromEntries([...Ie.CARD_PAYMENT_PROCESSOR_TRUTH_EVENT_TYPES].map(e=>[e,"provider"])),owner_attested:"owner"};function ly(e){return Ie.CARD_PAYMENT_EVENT_REQUIRED_PROVENANCE[e]??null}Ie.CARD_PAYMENT_ATTEMPT_STATUSES=["pending","needs_reconciliation","auth_held","capture_pending","sale_accepted","captured","voided","refund_pending","partially_refunded","refunded","chargeback_open","chargeback_lost","chargeback_won"];var tx=-9223372036854775808n,nx=9223372036854775807n;function oy(e){if(!e)return null;let r=(e instanceof Date?e:new Date(e)).getTime();return Number.isFinite(r)?r:null}function dy(e){if(!/^-?\d+$/.test(e))return null;try{let t=BigInt(e);return t>=tx&&t<=nx?t:null}catch{return null}}function rx(e){return e==null?0n:typeof e=="number"?Number.isSafeInteger(e)?BigInt(e):0n:dy(e)??0n}function ix(e){let t=oy(e.observedAt)??0;return{event:e,primaryAt:oy(e.occurredAt)??t,observedAt:t,id:rx(e.id)}}function ax(e,t){let r=e.primaryAt-t.primaryAt;if(r!==0)return r;let i=e.observedAt-t.observedAt;if(i!==0)return i;let n=e.id-t.id;return n<0n?-1:n>0n?1:0}function sy(e){return e==null?null:typeof e=="bigint"?e:typeof e=="number"?Number.isFinite(e)&&Number.isSafeInteger(e)?BigInt(e):null:dy(e)}function ox(e,t){return e>0n&&t<e?"partially_refunded":"refunded"}function sx(e){return e==="charge_requested"||e==="auth_held"||e==="capture_pending"||e==="sale_accepted"||e==="captured"}function cx(e,t){return e===t||t==="needs_reconciliation"?!0:e==="captured"?t==="refund_pending"||t==="partially_refunded"||t==="refunded":e==="sale_accepted"?t==="captured"||t==="refund_pending"||t==="partially_refunded"||t==="refunded"||t==="voided":e==="refund_pending"?t==="partially_refunded"||t==="refunded"||t==="refund_pending":e==="partially_refunded"?t==="partially_refunded"||t==="refunded":e==="refunded"?t==="refunded":e==="voided"?t==="voided":!0}function Ur(e,t,r,i){return cx(e,t)?{status:t,reason:i}:{status:e,reason:r}}function ux(e,t={}){let r="needs_reconciliation",i="no_processor_events",n=[],a=!1,o=null,s=0n,c=sy(t.attemptAmountMicros),u=c!==null&&c>0n?c:0n,d=null,p=null,m=!1,b=t.attemptAmountMicros!==null&&t.attemptAmountMicros!==void 0&&(c===null||c<0n)?"invalid_amount":null,y=e.map(ix).sort(ax).map(({event:O})=>O);for(let O of y){let z=uy(O.source),re=ly(O.eventType);if(re!==null&&z!==re){n.push({eventType:O.eventType,source:O.source,provenance:z,requiredProvenance:re});continue}if(O.eventType==="owner_attested"){a=!0,cy(O.ownerVerdict)&&(o=O.ownerVerdict);continue}let C=sy(O.amountMicros);if(O.amountMicros!==null&&O.amountMicros!==void 0&&(C===null||C<0n)){b="invalid_amount",r="needs_reconciliation",i="invalid_amount";continue}if((O.amountMicros===null||O.amountMicros===void 0)&&sx(O.eventType)&&u<=0n){b="missing_amount",r="needs_reconciliation",i="missing_amount";continue}let Z=C??u;if(O.eventType==="chargeback_opened"||O.eventType==="chargeback_lost"){d=O.eventType==="chargeback_opened"?"chargeback_open":"chargeback_lost",p=O.eventType,m=!0;continue}if(O.eventType==="chargeback_won"){d=null,p=null,m=!1,r==="needs_reconciliation"&&(r="chargeback_won",i="chargeback_won");continue}switch(O.eventType){case"charge_requested":Z>u&&(u=Z),{status:r,reason:i}=Ur(r,"pending",i,"charge_requested");break;case"charge_ambiguous":case"processor_unknown":case"reconciliation_gap":({status:r,reason:i}=Ur(r,"needs_reconciliation",i,O.eventType));break;case"auth_held":Z>u&&(u=Z),{status:r,reason:i}=Ur(r,"auth_held",i,"auth_held");break;case"capture_pending":Z>u&&(u=Z),{status:r,reason:i}=Ur(r,"capture_pending",i,"capture_pending");break;case"sale_accepted":Z>u&&(u=Z),{status:r,reason:i}=Ur(r,"sale_accepted",i,"sale_accepted");break;case"captured":Z>u&&(u=Z),{status:r,reason:i}=Ur(r,"captured",i,"captured");break;case"voided":({status:r,reason:i}=Ur(r,"voided",i,"voided"));break;case"refund_pending":({status:r,reason:i}=Ur(r,"refund_pending",i,"refund_pending"));break;case"refund_succeeded":if(C===null){b="missing_amount",r="needs_reconciliation",i="missing_amount";continue}s+=Z,u>0n&&s>u&&(s=u),{status:r,reason:i}=Ur(r,ox(u,s),i,"refund_succeeded");break;case"refund_failed":i="refund_failed";break}}return d?{status:d,statusReason:p??d,refundMicros:s,hasChargeback:m,rejectedProcessorClaims:n,ownerAttested:a,ownerVerdict:o}:b?{status:"needs_reconciliation",statusReason:b,refundMicros:s,hasChargeback:m,rejectedProcessorClaims:n,ownerAttested:a,ownerVerdict:o}:{status:r,statusReason:i,refundMicros:s,hasChargeback:m,rejectedProcessorClaims:n,ownerAttested:a,ownerVerdict:o}}});var hy=P(Lr=>{"use strict";Object.defineProperty(Lr,"__esModule",{value:!0});Lr.CardPaymentDbValidationError=void 0;Lr.validateCardPaymentEventInsertRow=py;Lr.assertValidCardPaymentAttemptStatus=my;Lr.insertCardPaymentLifecycleEvent=yx;Lr.insertCardPaymentLifecycleEventWithId=_y;Lr.refreshCardPaymentAttemptProjection=bx;var ro=Rd(),Mi=class extends Error{table;offendingKeys;constructor(t,r,i){super(`[pg:${r}] ${t}`),this.table=r,this.offendingKeys=i,this.name="CardPaymentDbValidationError"}};Lr.CardPaymentDbValidationError=Mi;function Tt(e,t,r){throw new Mi(t,e,Object.keys(r))}function lx(e,t){if(!t||typeof t!="object"||Array.isArray(t))throw new Mi("row must be a non-array object",e,[]);return t}function dx(e,t,r){for(let i of Object.keys(t))r.has(i)||Tt(e,`unknown column "${i}"`,t)}function fx(e,t,r){for(let i of r)(t[i]===void 0||t[i]===null)&&Tt(e,`required column "${i}" is missing`,t)}function no(e,t,r,i={}){let n=t[r];if(n==null){if(i.nullable)return;Tt(e,`${r} must be a string`,t)}typeof n!="string"&&Tt(e,`${r} must be a string`,t),i.nonEmpty&&n.length===0&&Tt(e,`${r} must be non-empty`,t),i.maxLen&&n.length>i.maxLen&&Tt(e,`${r} exceeds ${i.maxLen} chars`,t)}function Cd(e,t,r,i){let n=t[r];(typeof n!="string"||!i.has(n))&&Tt(e,`${r} must be one of ${[...i].join("|")}`,t)}function px(e,t,r){let i=t[r],n=9223372036854775807n,a=typeof i=="bigint"?i:typeof i=="string"&&/^\d+$/.test(i)&&i.length<=19?BigInt(i):null;a===null&&Tt(e,`${r} must be a numeric integer string`,t),a<=0n&&Tt(e,`${r} must be positive`,t),a>n&&Tt(e,`${r} must fit signed 64-bit integer`,t)}var mx=new Set(["attempt_id","transaction_id","user_login","processor","source","event_type","processor_event_id","processor_transaction_id","amount_micros","currency","processor_status","occurred_at","payload"]),gx=["user_login","processor","source","event_type","payload"],_x=new Set(ro.CARD_PAYMENT_PROCESSORS),hx=new Set(ro.CARD_PAYMENT_SOURCES),vx=new Set(ro.CARD_PAYMENT_EVENT_TYPES),fy=new Set(ro.CARD_PAYMENT_ATTEMPT_STATUSES);function py(e){let t=lx("card_payment_events",e);dx("card_payment_events",t,mx),fx("card_payment_events",t,gx);for(let r of["attempt_id","transaction_id"]){let i=t[r];if(i!=null){let n=typeof i=="string"&&/^\d+$/.test(i)?Number(i):i;(typeof n!="number"||!Number.isInteger(n)||n<=0)&&Tt("card_payment_events",`${r} must be a positive integer or null`,t)}}no("card_payment_events",t,"user_login",{nonEmpty:!0,maxLen:255}),Cd("card_payment_events",t,"processor",_x),Cd("card_payment_events",t,"source",hx),Cd("card_payment_events",t,"event_type",vx),t.processor_event_id!==null&&t.processor_event_id!==void 0&&no("card_payment_events",t,"processor_event_id",{nonEmpty:!0,maxLen:255,nullable:!0}),t.processor_transaction_id!==null&&t.processor_transaction_id!==void 0&&no("card_payment_events",t,"processor_transaction_id",{nonEmpty:!0,maxLen:255,nullable:!0}),t.amount_micros!==null&&t.amount_micros!==void 0&&px("card_payment_events",t,"amount_micros"),t.currency!==null&&t.currency!==void 0&&no("card_payment_events",t,"currency",{nonEmpty:!0,maxLen:3,nullable:!0}),t.processor_status!==null&&t.processor_status!==void 0&&no("card_payment_events",t,"processor_status",{nonEmpty:!0,maxLen:128,nullable:!0}),t.occurred_at!==null&&t.occurred_at!==void 0&&!(t.occurred_at instanceof Date)&&typeof t.occurred_at!="string"&&Tt("card_payment_events","occurred_at must be a Date, ISO string, or null",t),typeof t.payload!="string"&&Tt("card_payment_events","payload must be a JSON string",t);try{JSON.parse(t.payload)}catch{Tt("card_payment_events","payload must be valid JSON",t)}}function my(e){if(!fy.has(e))throw new Mi(`current_status must be one of ${[...fy].join("|")}`,"card_payment_attempts",["current_status"])}function gy(e){return e===null?null:typeof e=="number"?e:Number(e)}async function yx(e,t){return(await _y(e,t)).inserted}async function _y(e,t){let r={attempt_id:gy(t.attemptId),transaction_id:t.transactionId,user_login:t.userLogin,processor:t.processor??"cybersource",source:t.source,event_type:t.eventType,processor_event_id:t.processorEventId,processor_transaction_id:t.processorTransactionId,amount_micros:t.amountMicros,currency:t.currency,processor_status:t.processorStatus,occurred_at:t.occurredAt??null,payload:JSON.stringify(t.payload)};py(r);let n=(await e.query(`INSERT INTO card_payment_events (
59
59
  attempt_id, transaction_id, user_login, processor, source, event_type,
60
60
  processor_event_id, processor_transaction_id, amount_micros, currency,
61
61
  processor_status, occurred_at, payload
@@ -83,7 +83,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
83
83
  `;Eb(e)&&process.stderr.write(n),Ob().write(n)}var Mt={debug:(...e)=>fo("DEBUG",...e),info:(...e)=>fo("INFO",...e),warn:(...e)=>fo("WARN",...e),error:(...e)=>fo("ERROR",...e)};function pf(e=2e3){let t=di;return t?(di=null,new Promise(r=>{let i=setTimeout(r,e);i.unref?.(),t.end(()=>{clearTimeout(i),r()})})):Promise.resolve()}function mf(){return qi}var wf=require("node:child_process"),Re=require("node:fs"),go=require("node:path");var gf=je(require("os")),_f=je(require("path")),kb="VISA_CLI_HOME";function fi(e=process.env){let t=e[kb];return typeof t=="string"&&t.trim().length>0?t:_f.join(gf.homedir(),".visa-cli")}var mo="com.visacli.agent-key.v2",Fi=16384,Nb=/^[0-9a-f]{64}$/;function br(e){if(!Nb.test(e))throw new Error("custody_handle_invalid")}function _o(e){if(e.length===0||e.length>Fi)throw new Error("custody_record_too_large")}var hf=null;var vu=(e,t,r,i)=>hf!==null?Promise.reject(new Error(hf)):Rb(e,t,r,i),Rb=(e,t,r,i)=>new Promise(n=>{let a="",o="",s=!1,c=(0,wf.spawn)(e,[...t],{stdio:["pipe","pipe","pipe"],windowsHide:!0}),u=p=>{s||(s=!0,clearTimeout(d),n(p))},d=setTimeout(()=>{c.kill(),u({status:null,stdout:a,stderr:o,error:"timeout"})},i);d.unref(),c.stdout.setEncoding("utf8").on("data",p=>{a+=p}),c.stderr.setEncoding("utf8").on("data",p=>{o+=p}),c.on("error",p=>u({status:null,stdout:a,stderr:o,error:p.code==="ENOENT"?"missing":"failed"})),c.on("close",p=>u({status:p,stdout:a,stderr:o})),c.stdin.on("error",()=>{}),c.stdin.end(r)}),po="/usr/bin/security",vf=44,Cb=45,mu=class{#e;#t;#i=!1;constructor(t={}){if(t.keychain!==void 0&&/["\n\r]/.test(t.keychain))throw new Error("custody_directory_invalid");this.#e=t.keychain,this.#t=t.run??vu}target(){return this.#e===void 0?[]:[this.#e]}refused(){return new Error("keychain_locked_or_unavailable")}async requireKeychain(){if(this.#i)return;let t=this.#e;if(t===void 0){let r=await this.#t(po,["default-keychain","-d","user"],"",5e3);if(t=r.stdout.trim().replace(/^"(.*)"$/,"$1"),r.status!==0||r.error||!t)throw new Error("keychain_not_found")}if(!(0,Re.existsSync)(t))throw new Error("keychain_not_found");this.#i=!0}async create(t,r){br(t),_o(r),await this.requireKeychain();let i=this.#e===void 0?"":` "${this.#e}"`,n=Buffer.from(r).toString("base64"),a=await this.#t(po,["-i"],`add-generic-password -s ${mo} -a ${t} -l visa-cli-agent-key -w ${n}${i}
84
84
  `,1e4);if(!(a.status===0&&!a.error))throw a.status===Cb?new Error("custody_handle_exists"):this.refused()}async read(t){br(t),await this.requireKeychain();let r=await this.#t(po,["find-generic-password","-s",mo,"-a",t,"-w",...this.target()],"",1e4);if(r.status===vf)throw new Error("custody_unavailable");if(r.status!==0||r.error)throw this.refused();let i=r.stdout.trim(),n=/^[A-Za-z0-9+/]+={0,2}$/.test(i)?Buffer.from(i,"base64"):null;if(!n||n.toString("base64")!==i||n.length>Fi)throw new Error("custody_record_invalid");return n}async delete(t){br(t),await this.requireKeychain();let r=await this.#t(po,["delete-generic-password","-s",mo,"-a",t,...this.target()],"",1e4);if(!(r.status===0||r.status===vf))throw this.refused()}},pu="secret-tool",gu=class{#e;constructor(t={}){this.#e=t.run??vu}attributes(t){return["service",mo,"handle",t]}refused(t){return t.error==="missing"?new Error("secret_service_unavailable"):/d-?bus|DBUS_SESSION_BUS_ADDRESS|\$DISPLAY|Could not connect/i.test(t.stderr)?new Error("secret_service_unavailable"):t.error==="timeout"?new Error("secret_service_timeout"):new Error("secret_service_locked_or_unavailable")}async lookup(t){let r=await this.#e(pu,["lookup",...this.attributes(t)],"",1e4);if(r.status===0&&!r.error)return r.stdout;if(r.status===1&&!r.error&&r.stderr.trim()==="")return null;throw this.refused(r)}async create(t,r){if(br(t),_o(r),await this.lookup(t)!==null)throw new Error("custody_handle_exists");let i=await this.#e(pu,["store","--label=Visa CLI agent key",...this.attributes(t)],Buffer.from(r).toString("base64"),1e4);if(i.status!==0||i.error)throw this.refused(i)}async read(t){br(t);let r=await this.lookup(t);if(r===null)throw new Error("custody_unavailable");let i=r.trim(),n=/^[A-Za-z0-9+/]+={0,2}$/.test(i)?Buffer.from(i,"base64"):null;if(!n||n.toString("base64")!==i||n.length>Fi)throw new Error("custody_record_invalid");return n}async delete(t){br(t);let r=await this.#e(pu,["clear",...this.attributes(t)],"",1e4);if(!(r.status===1&&!r.error&&r.stderr.trim()==="")&&(r.status!==0||r.error))throw this.refused(r)}};function Sf(e){if(!(0,Re.existsSync)(e)){(0,Re.mkdirSync)(e,{recursive:!0,mode:448}),process.platform!=="win32"&&(0,Re.chmodSync)(e,448);return}let t=(0,Re.lstatSync)(e);if(!t.isDirectory())throw new Error("custody_directory_invalid");if(process.platform!=="win32"&&(t.mode&63)!==0)throw new Error("custody_directory_not_private")}function $f(e,t){let r;try{r=(0,Re.openSync)(e,"wx",384)}catch(n){throw n.code==="EEXIST"?new Error("custody_handle_exists"):new Error("custody_create_failed")}let i=0;try{for(;i<t.length;)i+=(0,Re.writeSync)(r,t,i)}catch{throw(0,Re.closeSync)(r),(0,Re.rmSync)(e,{force:!0}),new Error("custody_create_failed")}(0,Re.closeSync)(r)}function yf(e){return new Error(e?.code==="ENOENT"?"custody_unavailable":"custody_store_unreadable")}function Of(e){let t;try{t=(0,Re.lstatSync)(e)}catch(r){throw yf(r)}if(!t.isFile()||t.size>Fi*2)throw new Error("custody_file_invalid");try{return(0,Re.readFileSync)(e)}catch(r){throw yf(r)}}var _u=class{constructor(t){this.directory=t}directory;path(t){return br(t),(0,go.join)(this.directory,`${t}.key`)}async create(t,r){let i=this.path(t);_o(r),Sf(this.directory),$f(i,r)}async read(t){let r=this.path(t);if(process.platform!=="win32"&&(0,Re.existsSync)(this.directory)){let n=(0,Re.lstatSync)(this.directory);if(!n.isDirectory()||(n.mode&63)!==0)throw new Error("custody_directory_not_private")}let i=Of(r);if(process.platform!=="win32"&&((0,Re.lstatSync)(r).mode&63)!==0)throw new Error("custody_file_invalid");if(i.length===0||i.length>Fi)throw new Error("custody_file_invalid");return i}async delete(t){(0,Re.rmSync)(this.path(t),{force:!0})}},Db="powershell.exe";function Mb(e,t){return br(t),["$ErrorActionPreference = 'Stop'","Add-Type -AssemblyName System.Security","$payload = [Convert]::FromBase64String(($input -join '').Trim())",`$entropy = [Text.Encoding]::UTF8.GetBytes('visa-agent-key:${t}')`,`$result = [System.Security.Cryptography.ProtectedData]::${e}($payload, $entropy, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)`,"[Console]::Out.Write([Convert]::ToBase64String($result))"].join("; ")}var hu=class{constructor(t,r={}){this.directory=t;this.#e=r.run??vu}directory;#e;path(t){return br(t),(0,go.join)(this.directory,`${t}.dpapi`)}async call(t,r,i){let n=await this.#e(Db,["-NoProfile","-NonInteractive","-InputFormat","Text","-Command",Mb(t,r)],Buffer.from(i).toString("base64")+`
85
85
  `,3e4),a=n.stdout.trim();if(n.status!==0||n.error||!/^[A-Za-z0-9+/]+={0,2}$/.test(a))throw new Error("dpapi_locked_or_unavailable");return Buffer.from(a,"base64")}async create(t,r){let i=this.path(t);if(_o(r),Sf(this.directory),(0,Re.existsSync)(i))throw new Error("custody_handle_exists");$f(i,await this.call("Protect",t,r))}async read(t){let r=Of(this.path(t)),i=await this.call("Unprotect",t,r);if(i.length===0||i.length>Fi)throw new Error("custody_record_invalid");return i}async delete(t){(0,Re.rmSync)(this.path(t),{force:!0})}};function bf(e=process.env){return(0,go.join)(fi(e),"agent-keys")}function If(e=process.env,t=process.platform){let r=e.VISA_RUNTIME_CUSTODY_PROFILE??"os";if(r==="headless")return new _u(bf(e));if(r!=="os")throw new Error("native_runtime_custody_profile_invalid");if(t==="darwin")return new mu;if(t==="win32")return new hu(bf(e));if(t==="linux")return new gu;throw new Error("custody_platform_unsupported")}var ia=je(Gl()),CD=Jl().version,Vh={policy_screening_blocked:{message:"Payments to this recipient are blocked by payment screening.",fix:"Do not retry, switch agents or switch payment methods; tell the owner."},policy_screening_not_configured:{message:"Payment screening is not available, so wallet payments are refused.",fix:"Retrying will not help until Visa restores screening; tell the owner."},connection_changed_while_reporting:{message:"This agent changed while connect was reporting it (the owner may have removed it), so nothing was reported as connected.",fix:"Do not repeat this call. Check status: if the owner removed the agent, ask whether to connect a new one with visa connect."},withdrawal_screening_blocked:{message:"Withdrawals to this address are blocked by payment screening.",fix:"Choose another address; do not retry this one."}},Te=class extends Error{constructor(r,i,n,a,o=null,s=null){super(Vh[i]?.message??ia.ERROR_FAMILIES[r]?.message??`Visa refused this request (${r}).`);this.code=r;this.detail=i;this.status=n;this.retryable=a;this.nextAction=o;this.retryAfterSeconds=s}code;detail;status;retryable;nextAction;retryAfterSeconds;name="AgentApiError";get fix(){return Vh[this.detail]?.fix??ia.ERROR_FAMILIES[this.code]?.fix??null}},Vt=class extends Error{constructor(r,i,n="response"){super(r);this.cause=i;this.kind=n}cause;kind;name="AgentTransportError"},Pc=class e{server;cliVersion;#e;#t=0;#i=!1;#c=new Map;#r=null;#o;#s;constructor(t){this.server=new URL(t.server).origin,this.#e=t.key??null,this.#o=t.fetch??fetch,this.cliVersion=t.cliVersion??CD,this.#s=t.timeoutMs??3e4}useKey(t){if(!(t&&this.#e?.jkt===t.jkt)){if(this.#i)throw new Error("agent_client_installation_bound");this.#e=t,this.#t+=1,this.#r=null}}forInstallation(t){let r=this.#c.get(t.jkt);return r||(r=new e({server:this.server,key:t,fetch:this.#o,cliVersion:this.cliVersion,timeoutMs:this.#s}),r.#i=!0,this.#c.set(t.jkt,r)),r}async#a(t,r,i={}){let n=i.body===void 0?void 0:JSON.stringify(i.body),a=ba(),o,s;try{o=await this.#o(`${this.server}${r}`,{method:t,headers:{accept:"application/json","x-visa-cli-version":this.cliVersion,...wa(a),...n!==void 0?{"content-type":"application/json"}:{},...i.headers},...n!==void 0?{body:n}:{},redirect:"error",signal:AbortSignal.timeout(i.timeoutMs??this.#s)})}catch(d){throw yr(new Vt(`Visa could not be reached at ${this.server}`,d,"outage"),a)}try{s=await o.text()}catch(d){throw yr(new Vt(`Visa answered ${o.status}, but its body could not be read`,d,o.ok?"outage":"response"),a,o.status)}let c=null;if(s)try{c=JSON.parse(s)}catch{throw yr(new Vt(`Visa answered ${o.status} with a non-JSON body`),a,o.status)}let u=c&&typeof c=="object"&&typeof c.code=="string"&&typeof c.detail=="string"&&!("id"in c);if(o.ok&&!u)return{status:o.status,body:c};if(u){let d=Number(o.headers.get("retry-after"));throw yr(new Te(c.code,String(c.detail??""),o.status,c.retryable===!0,c.continuation??c.next_action??null,Number.isFinite(d)&&d>=0?d:null),a,o.status)}throw yr(new Vt(`Visa answered ${o.status}`),a,o.status)}async startSetup(t){return(await this.#a("POST","/agent/v1/setups",{body:t})).body}async getSetup(t,r){return(await this.#a("GET",`/agent/v1/setups/${encodeURIComponent(t)}`,{headers:{authorization:`${ia.SETUP_AUTH_SCHEME} ${r}`}})).body}async claimSetup(t,r,i){return(await this.#a("POST",`/agent/v1/setups/${encodeURIComponent(t)}/claim`,{headers:{authorization:`${ia.SETUP_AUTH_SCHEME} ${r}`},body:{proof:i}})).body}async#u(){if(this.#r&&this.#r.expiresAt-3e4>Date.now())return this.#r.value;if(!this.#e)throw new Te("setup_required","not_connected",401,!1);let t=this.#t,r="/agent/v1/token",i="{}",n=this.#e.requestSignatureHeaders({method:"POST",targetUri:`${this.server}${r}`,body:i,cliVersion:this.cliVersion}),a=ba(),o;try{o=await this.#o(`${this.server}${r}`,{method:"POST",headers:{accept:"application/json","content-type":"application/json",...n,...wa(a)},body:i,redirect:"error",signal:AbortSignal.timeout(this.#s)})}catch(u){throw yr(new Vt(`Visa could not be reached at ${this.server}`,u,"outage"),a)}let s;try{s=await o.text()}catch(u){throw yr(new Vt(`Visa answered ${o.status}, but its body could not be read`,u,o.ok?"outage":"response"),a,o.status)}let c=null;try{c=JSON.parse(s)}catch{}if(!o.ok)throw yr(c&&typeof c.code=="string"?new Te(c.code,String(c.detail??""),o.status,!1):new Vt(`Visa answered ${o.status}`),a,o.status);if(typeof c?.access_token!="string")throw new Vt("Visa answered agent.token.create without a token");return t===this.#t&&(this.#r={value:c.access_token,expiresAt:Date.parse(String(c.expires_at))}),c.access_token}async#n(t,r,i={}){for(let n=0;;n+=1){let a=await this.#u();try{return(await this.#a(t,r,{...i,headers:{authorization:`Bearer ${a}`}})).body}catch(o){if(n===0&&o instanceof Te&&o.code==="setup_required"&&o.detail==="agent_token_required"){this.#r?.value===a&&(this.#r=null);continue}throw o}}}financialRuntimeRequest(t,r){return this.#n("POST",`/v1/financial-runtime/${t}`,{body:r})}status(){return this.#n("GET","/agent/v1/status")}createPayment(t){return this.#n("POST","/agent/v1/payments",{body:t,timeoutMs:9e4})}getPayment(t){return this.#n("GET",`/agent/v1/payments/${encodeURIComponent(t)}`)}listPayments(t={}){let r=new URLSearchParams;t.limit!==void 0&&r.set("limit",String(t.limit)),t.cursor&&r.set("cursor",t.cursor);let i=r.size?`?${r}`:"";return this.#n("GET",`/agent/v1/payments${i}`)}cancelPayment(t){return this.#n("POST",`/agent/v1/payments/${encodeURIComponent(t)}/cancel`)}reportPayment(t,r){return this.#n("POST",`/agent/v1/payments/${encodeURIComponent(t)}/report`,{body:r})}searchMerchants(t){let r=new URLSearchParams;return t.q&&r.set("q",t.q),t.target&&r.set("target",t.target),t.limit!==void 0&&r.set("limit",String(t.limit)),this.#n("GET",`/agent/v1/merchants?${r}`)}async sendEvents(t){let r=new Date().toISOString();await this.#n("POST","/agent/v1/events",{body:{events:t.map(i=>({...i,at:r}))}})}leaseForTap(t){return this.#n("POST","/agent/v1/keys/lease",{body:{operation:"tap_signature_base",request_id:t}})}tapSign(t){return this.#n("POST","/agent/v1/keys/tap-sign",{body:t})}async tapRegistryAgent(t){return(await this.#a("GET",`/v1/tap/registry/agents/${encodeURIComponent(t)}`)).body}};var zt=require("node:crypto"),ei=je(Gl()),qc=je(Bv()),k1="urn:visa:tvc:identity-gate",N1="visa-tempo-mpp-payment:v1",R1="visa-tempo-mpp-report:v1",C1=new Set([N1,R1,"visa-tempo-atum-sign:v1","visa-tempo-atum-read:v1","visa-tempo-atum-confirm:v1","visa-tempo-atum-settle:v1",k1]),D1=Buffer.from("302e020100300506032b657004220420","hex"),Gv=/^[0-9a-f]{64}$/;function M1(e){return(0,zt.createPrivateKey)({key:Buffer.concat([D1,e]),format:"der",type:"pkcs8"})}var Dr=class e{constructor(t,r,i){this.handle=t;this.now=i;this.#e=M1(r);let{x:n}=(0,zt.createPublicKey)(this.#e).export({format:"jwk"});this.publicJwk={kty:"OKP",crv:"Ed25519",x:n},this.jkt=(0,qc.computeJkt)(this.publicJwk)}handle;now;#e;publicJwk;jkt;static async create(t,r=Date.now){let i=(0,zt.randomBytes)(32).toString("hex"),n=(0,zt.randomBytes)(32),a={v:1,kind:"visa-installation-key",seed:n.toString("base64url")};return await t.create(i,Buffer.from(JSON.stringify(a),"utf8")),new e(i,n,r)}static async load(t,r,i=Date.now){if(!Gv.test(r))throw new Error("installation_key_handle_invalid");let n=await t.read(r),a;try{a=JSON.parse(Buffer.from(n).toString("utf8"))}catch{throw new Error("installation_key_unreadable")}let o=Buffer.from(String(a?.seed??""),"base64url");if(a?.v!==1||a.kind!=="visa-installation-key"||o.length!==32)throw new Error("installation_key_unreadable");return new e(r,o,i)}static async forget(t,r){Gv.test(r)&&await t.delete(r)}#t(t){return(0,zt.sign)(null,Buffer.from(t),this.#e)}claimProof(t){return this.#t((0,ei.setupClaimMessage)(t)).toString("base64url")}resumeProof(t){let r=(0,zt.randomBytes)(24).toString("base64url"),i=Math.floor(this.now()/1e3);return{signature:this.#t((0,ei.setupResumeMessage)({jkt:this.jkt,setupId:t,nonce:r,issuedAt:i})).toString("base64url"),setup_id:t,nonce:r,issued_at:i}}requestSignatureHeaders(t){let r={created:Math.floor(this.now()/1e3),nonce:(0,zt.randomUUID)(),keyid:this.jkt},i=t.body===void 0?void 0:`sha-256=:${(0,zt.createHash)("sha256").update(t.body,"utf8").digest("base64")}:`,n=(0,ei.agentSignatureBase)({method:t.method,targetUri:t.targetUri,...i?{contentDigest:i}:{},cliVersion:t.cliVersion},r);return{...i?{"content-digest":i}:{},"x-visa-cli-version":t.cliVersion,...(0,ei.agentSignatureHeaders)(i!==void 0,r,this.#t(n).toString("base64"))}}proofKey(){let t={kid:this.jkt,publicJwk:this.publicJwk,sign:async r=>new Uint8Array(this.#t(r))};return{publicJwk:this.publicJwk,jkt:this.jkt,createProof:async r=>{if(!C1.has(r.audience))throw new Error("proof_audience_refused");if(r.intentHash===void 0)throw new Error("proof_intent_required");return(0,qc.createPopProofWithSigner)(t,r)}}}turnkeyStamp(t){if(!/^[A-Za-z0-9_-]{1,128}$/.test(t.organizationId)||(t.action==="get_activity"?!/^[A-Za-z0-9_-]{1,256}$/.test(t.value):typeof t.value!="string"||t.value.length<1||t.value.length>1024))throw new Error("turnkey_request_invalid");let r=t.action==="get_activity"?{organizationId:t.organizationId,activityId:t.value}:{type:"ACTIVITY_TYPE_APPROVE_ACTIVITY",timestampMs:String(this.now()),organizationId:t.organizationId,parameters:{fingerprint:t.value}},i=JSON.stringify(r),n=Buffer.from(JSON.stringify({publicKey:Buffer.from(this.publicJwk.x,"base64url").toString("hex"),signature:this.#t(i).toString("hex"),scheme:"SIGNATURE_SCHEME_TK_API_ED25519"})).toString("base64url");return{body:i,stamp:n}}};var Di=je(require("fs")),zd=require("node:crypto");var Ci=je(require("path"));var Jv=require("node:crypto"),Wv=je(require("node:fs")),Ri=je(require("node:path")),Yv=require("node:util"),x1=1024*1024,Ha=class extends Error{constructor(t){super(t),this.name="PrivateStateSecurityError"}};function U1(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function it(e,t){return new Ha(`${e} ${t}`)}function Kv(e=process.platform){if(e==="win32")throw new Ha("owner-only identity files are not supported on Windows yet; protocol-v2 pairing is disabled until verified ACL storage is available")}function da(e,t,r,i){try{return r.lstatSync(e)}catch(n){if(i&&U1(n))return null;throw it(t,"could not be inspected safely")}}function L1(e,t){Kv(t);let r=e.expectedUid??process.geteuid?.();if(!Number.isSafeInteger(r)||r<0)throw new Ha("private state owner could not be verified against the process effective uid");return r}function fa(e,t,r){return!(r!=="win32"||e.dev!==0||t.dev!==0||e.ino!==0||t.ino!==0)||e.dev===t.dev&&e.ino===t.ino}function Ed(e,t,r,i){if(e.isSymbolicLink()||!e.isDirectory())throw it(t,"must be a real owner-only directory, not a symlink");if(r!=="win32"){if(e.uid!==i)throw it(t,"must be owned by the current effective user");if((e.mode&63)!==0)throw it(t,"must not grant access to group or other users (use mode 0700)")}}function Ka(e,t,r,i){if(e.isSymbolicLink()||!e.isFile())throw it(t,"must be a real owner-only regular file, not a symlink");if(r!=="win32"){if(e.uid!==i)throw it(t,"must be owned by the current effective user");if((e.mode&63)!==0)throw it(t,"must not grant access to group or other users (use mode 0600)")}}function Z1(e,t={}){let r=t.ops??Wv,i=t.platform??process.platform,n=t.maxBytes??x1;if(!Number.isSafeInteger(n)||n<1)throw new Error("private state maximum size must be a positive safe integer");let a=L1(t,i),o=Ri.dirname(e),s=da(o,"private state directory",r,!0);if(!s)return null;Ed(s,"private state directory",i,a);let c=da(e,"private state file",r,!0);if(!c)return null;Ka(c,"private state file",i,a);let u;try{try{u=r.openSync(e,r.constants.O_RDONLY|(r.constants.O_NOFOLLOW??0))}catch{throw it("private state file","changed or could not be opened safely")}let d=r.fstatSync(u);if(Ka(d,"private state file",i,a),!fa(c,d,i))throw it("private state file","changed while it was being opened");if(!Number.isSafeInteger(d.size)||d.size<0||d.size>n)throw it("private state file",`exceeds the ${n}-byte safety limit`);let p=da(e,"private state file",r,!1);if(Ka(p,"private state file",i,a),!fa(d,p,i))throw it("private state file","changed while it was being opened");let m=da(o,"private state directory",r,!1);if(Ed(m,"private state directory",i,a),!fa(s,m,i))throw it("private state directory","changed while private state was being opened");let b=[],y=0;for(;y<=n;){let Z=Buffer.allocUnsafe(Math.min(65536,n+1-y)),oe=r.readSync(u,Z,0,Z.length,null);if(oe===0)break;if(y+=oe,y>n)throw it("private state file",`exceeds the ${n}-byte safety limit`);b.push(Z.subarray(0,oe))}let O=r.fstatSync(u);if(Ka(O,"private state file",i,a),!fa(d,O,i)||O.size!==d.size||O.mtimeMs!==d.mtimeMs||O.ctimeMs!==d.ctimeMs||y!==O.size)throw it("private state file","changed while it was being read");let z=da(e,"private state file",r,!1);if(Ka(z,"private state file",i,a),!fa(O,z,i))throw it("private state file","changed while it was being read");let re=da(o,"private state directory",r,!1);if(Ed(re,"private state directory",i,a),!fa(s,re,i))throw it("private state directory","changed while private state was being read");let C;try{C=new Yv.TextDecoder("utf-8",{fatal:!0}).decode(Buffer.concat(b,y))}catch{throw it("private state file","must contain valid UTF-8")}return{contents:C,mtimeMs:O.mtimeMs}}finally{u!==void 0&&r.closeSync(u)}}function Fc(e,t={}){return Z1(e,t)?.contents??null}function Pd(e,t,r=Wv,i=process.platform){Kv(i);let n=Ri.dirname(e),a=Ri.join(n,`.${Ri.basename(e)}.${process.pid}.${(0,Jv.randomBytes)(8).toString("hex")}.tmp`),o=r.constants.O_NOFOLLOW??0,s,c=!1;try{s=r.openSync(a,r.constants.O_WRONLY|r.constants.O_CREAT|r.constants.O_EXCL|o,384),r.writeFileSync(s,t,{encoding:"utf8"}),r.fsyncSync(s),r.closeSync(s),s=void 0,r.renameSync(a,e),c=!0;let u;try{u=r.openSync(e,r.constants.O_RDONLY|o),r.fsyncSync(u)}finally{u!==void 0&&r.closeSync(u)}let d;try{let p=r.constants.O_DIRECTORY??0;d=r.openSync(n,r.constants.O_RDONLY|p|o),r.fsyncSync(d)}finally{d!==void 0&&r.closeSync(d)}}finally{s!==void 0&&r.closeSync(s),c||r.rmSync(a,{force:!0})}}var q1="agent.json",Hv="agents",Td="VISA_CLI_AGENT_SLOT",Xv=/^[a-z0-9]{8,32}$/;function Vc(e,t){let r={...e};if(t===null)delete r[Td];else{if(!Xv.test(t))throw new Error("agent_slot_invalid");r[Td]=t}return r}function Ad(e){return e[Td]??null}function jd(e,t=process.env){let r=fi(t),i=[null];try{for(let n of Di.readdirSync(Ci.join(r,Hv)).sort()){let a=/^([a-z0-9]{8,32})\.json$/.exec(n)?.[1];a&&i.push(a)}}catch{}return i.map(n=>({slot:n,state:Mr(e,Vc(t,n))})).filter(({slot:n,state:a})=>n===null||a.agent||a.setup||a.starting)}var kd=Symbol("observed-agent-home");function Qa(e=process.env){let t=Ad(e);if(t===null)return Ci.join(fi(e),q1);if(!Xv.test(t))throw new Error("agent_slot_invalid");return Ci.join(fi(e),Hv,`${t}.json`)}function Xa(e){return{v:1,server:e,key_handle:null,jkt:null,agent:null,setup:null}}function Mr(e,t=process.env){let r=Qa(t);if(!Di.existsSync(r))return Xa(e);let i=Fc(r);if(i===null)return Xa(e);let n;try{n=JSON.parse(i)}catch{throw new Error("agent_state_unreadable")}if(n?.v!==1)throw new Error("agent_state_unreadable");return n.server===e?n:Object.defineProperty(Xa(e),kd,{value:n})}function F1(e,t=process.env){let r=Qa(t);Di.mkdirSync(Ci.dirname(r),{recursive:!0,mode:448}),Pd(r,`${JSON.stringify(e,null,2)}
86
- `)}function eo(e,t){let r=i=>{let n=i[kd]??i;return JSON.stringify([n.server,n.generation,n.key_handle,n.jkt,n.agent,n.setup,n.starting])};return r(e)===r(t)}async function tn(e,t,r,i={}){let n=Qa(t);Di.mkdirSync(Ci.dirname(n),{recursive:!0,mode:448});let a=Date.now()+3e4,o;for(;!(o=ya({file:`${n}.lock`,staleMs:6e4}));){if(Date.now()>=a)throw new Te("conflict","agent_state_busy",409,!0);await new Promise(s=>setTimeout(s,25))}try{let s=Fc(n);if(s!==null&&JSON.parse(s).server!==e&&!i.adoptServer)throw new Te("conflict","agent_server_changed",409,!1);return await r(Mr(e,t),c=>{if(!o.held())throw new Te("conflict","agent_state_superseded",409,!1);if(c.server!==e)throw new Error("agent_state_server_mismatch");F1(c,t)})}finally{o()}}async function Qv(e,t,r=process.env,i){return tn(e,r,async(n,a)=>{let o=n[kd]??n;if(i?.(o)){if(o.setup||o.starting||o.pickup){a({...o,generation:(0,zd.randomUUID)(),setup:null,starting:void 0,pickup:void 0});for(let s of new Set([o.setup?.key_handle,o.starting?.key_handle]))s&&s!==o.key_handle&&await t.delete(s)}return o.agent}a({...Xa(e),generation:(0,zd.randomUUID)()});for(let s of new Set([o.key_handle,o.setup?.key_handle,o.starting?.key_handle]))s&&await t.delete(s);return o.agent},{adoptServer:!0})}var tU=je(Ly());var Z6=50*1024*1024,q6=1024*1024;var Zy=new Set(["open","claimed"]),qy=1e3;var aL=33*6e4,nU=1440*6e4,rU=60*6e4,iU=12e4,Vy=nU+rU+iU;function By(e,t){let r=Qa(e);return Kd.mkdirSync(Hd.dirname(r),{recursive:!0,mode:448}),{file:`${r}.${t}.lock`,staleMs:Vy+6e4}}function oi(e,t){if(!eo(e,t))throw new Te("conflict","setup_superseded",409,!1)}function Gy(e,t){let r=t.starting??t.setup;if(!r)return;let n=("mode"in r?r.mode:void 0)??(t.setup?.kind==="replacement"?"replace":"new");if(e.mode!==void 0&&e.mode!==n||e.setupKey!==void 0&&e.setupKey!==r.setup_key)throw new Te("conflict","setup_request_changed",409,!1)}function Jy(e,t=!0){return{state:"waiting_for_owner",owner_url:e.owner_url,code:e.code,expires_at:e.expires_at,setup_id:e.id,resumed:t}}function Wy(e,t){if(t.state==="cancelled"||t.state==="expired"||Zy.has(String(t.state))&&Date.parse(t.expires_at??e.expires_at)<=Date.now())return{state:"ended",reason:t.state==="cancelled"?"declined":"expired",setup_id:e.id};if(t.state==="approved"||t.state==="completed")return{state:"completing",setup_id:e.id};if(Zy.has(String(t.state)))return Jy({...e,expires_at:t.expires_at??e.expires_at});throw new Te("outcome_unknown","setup_state_unknown",202,!0)}async function aU(e,t){let r=t.env??process.env,i=Mr(t.client.server,r);if(Gy(e,i),t.generation&&t.generation!==i.generation)throw new Te("conflict","setup_superseded",409,!1);let n=ya(By(r,"connect"),Date.now(),process.pid,"connect");if(!n){if(i.setup){let a=await t.client.getSetup(i.setup.id,i.setup.secret);oi(Mr(t.client.server,r),i);let o=Wy(i.setup,a);if(o.state!=="completing")return o}throw new Te("conflict","setup_busy",409,!0)}try{return await oU(e,t,r)}finally{n()}}async function oU(e,t,r){let i=t.store??If(r),n=Mr(t.client.server,r);if(Gy(e,n),t.generation&&t.generation!==n.generation)throw new Te("conflict","setup_superseded",409,!1);if(t.pickupToken&&(!n.setup||n.pickup?.token!==t.pickupToken))throw new Te("conflict","setup_superseded",409,!1);let a=e.mode??n.starting?.mode??n.setup?.mode??"new";if(n.removed&&!n.setup&&!n.starting)throw new Te("agent_inactive","agent_revoked",403,!1);if(n.agent&&!n.setup&&!n.starting&&(a==="new"&&(!e.setupKey||e.setupKey===n.joined_setup_key)||t.generation)){t.client.useKey(await Dr.load(i,n.key_handle));let s=n.unreported===!0&&!t.pickupToken;return s&&await tn(n.server,r,(c,u)=>{if(!eo(c,n)||c.removed||!c.unreported)throw new Te("conflict","connection_changed_while_reporting",409,!1);u({...c,unreported:void 0})}),{state:"connected",agent:{id:n.agent.id,name:n.agent.name},installation_id:n.agent.installation_id,already:!s}}if(a==="replace"&&!n.agent&&!e.setupKey&&!n.setup&&!n.starting)throw new Te("setup_required","no_agent_to_replace",401,!1);if(n.setup){let s=n.setup,c=await Dr.load(i,s.key_handle);if(c.jkt!==s.jkt)throw new Te("conflict","setup_key_changed",409,!1);let u;try{u=await t.client.getSetup(s.id,s.secret)}catch(p){if(!t.pickupToken&&p instanceof Te&&["not_found","expired","setup_required"].includes(p.code))return Wd({mode:s.mode??a,setupKey:s.setup_key,client:s.client,...s.another?{another:!0}:{}},s.mode??a,n,c,t.client,r);throw p}if(await tn(n.server,r,p=>oi(p,n)),u.state==="approved"){let p=await t.client.claimSetup(s.id,s.secret,c.claimProof(s.id));return Fy(n,c,i,p.agent,p.installation_id,r,t.client,!!t.pickupToken)}if(u.state==="completed"){t.client.useKey(c);let p=await t.client.status();return Fy(n,c,i,p.agent,p.installation_id,r,t.client,!!t.pickupToken)}if(u.state==="cancelled"||u.state==="expired")return await tn(n.server,r,async(p,m)=>{oi(p,n),m({...p,setup:null,pickup:void 0}),s.key_handle!==p.key_handle&&await Dr.forget(i,s.key_handle)}),{state:"ended",reason:u.state==="cancelled"?"declined":"expired",setup_id:s.id};let d=Wy(s,u);if(d.state!=="completing")return d;throw new Te("conflict","setup_busy",409,!0)}if(t.pickupToken)throw new Te("conflict","setup_superseded",409,!1);if(n.starting){let s=n.starting,c=await Dr.load(i,s.key_handle);return Wd({mode:s.mode,setupKey:s.setup_key,client:s.client},s.mode,n,c,t.client,r)}let o=await tn(n.server,r,async(s,c)=>{oi(s,n);let u=await Dr.create(i),d={...s,generation:(0,Yd.randomUUID)(),pickup:void 0,starting:{key_handle:u.handle,mode:a,...e.setupKey?{setup_key:e.setupKey}:{},...e.client?{client:e.client}:{},...e.another&&!e.setupKey?{another:!0}:{}}};return c(d),{state:d,key:u}},{adoptServer:!0});return n=o.state,Wd(e,a,n,o.key,t.client,r)}async function Wd(e,t,r,i,n,a){let o=t==="replace"&&!e.setupKey?"replacement":"laptop",s=await tn(r.server,a,(d,p)=>{oi(d,r);let m={...d,generation:d.starting?d.generation:(0,Yd.randomUUID)(),setup:null,pickup:void 0,starting:{key_handle:i.handle,mode:t,...e.setupKey?{setup_key:e.setupKey}:{},...e.client?{client:e.client}:{},...e.another&&!e.setupKey||d.starting?.another?{another:!0}:{}}};return p(m),m}),c=await n.startSetup({kind:o,installation_key:i.publicJwk,client:{name:e.client??"visa-cli",version:n.cliVersion},...o==="replacement"?{agent_id:s.agent.id}:{},...e.setupKey?{setup_key:e.setupKey}:{},resume_proof:i.resumeProof(null)}),u={id:String(c.setup.id),secret:c.setup_secret,code:String(c.setup.code),owner_url:String(c.setup.owner_url),expires_at:String(c.setup.expires_at),kind:o,key_handle:i.handle,jkt:i.jkt,mode:t,...e.setupKey?{setup_key:e.setupKey}:{},...e.client?{client:e.client}:{},...s.starting?.another?{another:!0}:{}};return await tn(r.server,a,(d,p)=>{oi(d,s),p({...d,setup:u,starting:void 0})}),Jy(u,!1)}async function Fy(e,t,r,i,n,a,o,s=!1){if(!i||!n)throw new Error("setup_claim_answer_incomplete");await tn(e.server,a,async(u,d)=>{oi(u,e);let p=u.key_handle;d({...u,key_handle:t.handle,jkt:t.jkt,agent:{id:i.id,name:i.name,installation_id:n},setup:null,starting:void 0,pickup:void 0,joined_setup_key:e.setup?.setup_key,...s&&e.setup?.another?{unreported:!0}:{unreported:void 0}}),p&&p!==t.handle&&await Dr.forget(r,p)});let c=Ad(a);for(let u of jd(e.server,a))u.slot!==c&&u.state.agent?.id===i.id&&await Qv(e.server,r,Vc(a,u.slot));return o.useKey(t),{state:"connected",agent:{id:i.id,name:i.name},installation_id:n,already:!1}}async function Yy(e,t,r,i=process.env){let n=Mr(e,i);if(!n.setup||n.pickup?.token!==t)return;let a;for(;!(a=ya(By(i,`pickup-${n.generation??"saved"}`)));){let p=Mr(e,i);if(r()||p.pickup?.token!==t||Date.now()>=n.pickup.deadline_at)return;await new Promise(m=>setTimeout(m,qy))}let o=performance.now(),s=Math.min(Vy,Math.max(0,n.pickup.deadline_at-Date.now())),c=new Pc({server:e}),u="pickup_stopped",d="unavailable";try{for(await tn(e,i,(p,m)=>{if(oi(p,n),p.pickup?.token!==t)throw new Te("conflict","setup_superseded",409,!1);m({...p,pickup:{...p.pickup,state:"running"}})});!r()&&a.held()&&performance.now()-o<s&&Date.now()<n.pickup.deadline_at;){let p=Mr(e,i);if(!eo(p,n)||p.pickup?.token!==t)return;try{if((await aU({},{client:c,env:i,pickupToken:t})).state!=="waiting_for_owner")return}catch(m){if(!(m instanceof Vt)&&!(m instanceof Te&&m.retryable)){d=m instanceof Te?m.code:"unavailable",u=m instanceof Te?"pickup_refused":"custody_or_local_state_unavailable";return}}await new Promise(m=>setTimeout(m,qy))}r()||(u="pickup_deadline")}finally{try{await tn(e,i,(p,m)=>{!eo(p,n)||p.pickup?.token!==t||(m({...p,pickup:{...p.pickup,state:"interrupted",code:d,detail:u}}),Mt.info("agent:connect_pickup_interrupted",{correlation:t,code:d,detail:u}))})}finally{a()}}}var ha=je(require("node:fs")),nu=je(require("node:path"));function Xc(e,t,r,i){try{e[t](r,i)}catch{}}var tu=je(require("fs")),Qd=require("node:net"),Qy=je(require("os")),eb=je(require("path"));var eu=je(require("fs")),Xd=je(require("path")),Ky=je(require("os")),Qc=class{static ensureConfigDir(){let t=this.getConfigDir();eu.existsSync(t)||eu.mkdirSync(t,{recursive:!0,mode:448})}static getConfigDir(){let t=process.env.VISA_CLI_HOME;return typeof t=="string"&&t.trim().length>0?Xd.join(t,".visa-mcp"):Xd.join(Ky.homedir(),".visa-mcp")}};function Hy(e){let t=Qy.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}var sU="settings.json",cU="must use https unless it points at localhost/loopback for local development";function uU(){return eb.join(Qc.getConfigDir(),sU)}function tb(e){if((0,Qd.isIP)(e)!==4)return!1;let[t]=e.split(".").map(Number);return t===127}function lU(e){let t=e.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(!t)return!1;let r=Number.parseInt(t[1],16),i=Number.parseInt(t[2],16);if(!Number.isFinite(r)||!Number.isFinite(i))return!1;let n=[r>>8&255,r&255,i>>8&255,i&255].join(".");return tb(n)}function dU(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost")return!0;let r=(0,Qd.isIP)(t);return r===4?tb(t):r===6?t==="::1"||lU(t):!1}function Xy(e,t="auth.serverUrl"){let r;try{r=new URL(e)}catch{throw new Error(`${t} must be a valid URL (got: ${JSON.stringify(e)})`)}if(r.username||r.password)throw new Error(`${t} must not include username or password credentials`);if(r.protocol!=="https:"&&!(r.protocol==="http:"&&dU(r.hostname)))throw new Error(`${t} ${cU}`)}function fU(){let e=uU();if(!tu.existsSync(e))return{};try{let t=tu.readFileSync(e,"utf-8"),r=JSON.parse(t);return!r||typeof r!="object"||Array.isArray(r)?(Mt.warn("settings:corrupt",{path:Hy(e),reason:"not_object"}),{}):r}catch(t){return Mt.warn("settings:corrupt",{path:Hy(e),error:t?.message||String(t)}),{}}}function pU(e){let t=fU()[e];return typeof t=="string"?t:void 0}var nb="https://auth.visacli.sh",rb="https://auth-visa-code-preview.up.railway.app";function mU(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function gU(){try{let e=Jl();return mU(e.version)}catch{return!1}}function _U(e){return e.envVar!==void 0&&e.envVar!==""?(Xy(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(Xy(e.settingValue,"auth.serverUrl"),e.settingValue):e.isPrerelease?rb:nb}var hU="https://app.visacli.sh",vU="https://web-visa-code-preview.up.railway.app";function yU(e=process.env){let t=_U({envVar:e.VISA_AUTH_URL,settingValue:pU("auth.serverUrl"),isPrerelease:gU()}),r=new URL(t).origin,n=e.VISA_VERIFY_WEB_URL?.trim()||(r===rb?vU:r===nb?hU:r);for(;n.endsWith("/");)n=n.slice(0,-1);return{authUrl:t,webUrl:n}}function ib(){return yU().authUrl}var ab=je(require("fs")),ob=je(require("os")),_a=je(require("path"));function bU(e){return[["openclaw",_a.join(e,".openclaw")],["hermes",_a.join(e,".hermes")],["claude-code",_a.join(e,".claude")],["codex",_a.join(e,".codex")],["gemini",_a.join(e,".gemini")]]}function sb(e=process.env,t={}){if(e.VISA_CLI_RUNTIME&&e.VISA_CLI_RUNTIME.trim().length>0)return e.VISA_CLI_RUNTIME.trim();if(e.AGENT_RUNTIME&&e.AGENT_RUNTIME.trim().length>0)return e.AGENT_RUNTIME.trim();let r=o=>Object.entries(e).some(([s,c])=>s.startsWith(o)&&typeof c=="string"&&c.trim()!==""),i=new Set;if(r("CODEX_")&&i.add("codex"),(typeof e.CLAUDECODE=="string"&&e.CLAUDECODE.trim()!==""||r("CLAUDE_CODE_")||typeof e.CLAUDE_PROJECT_DIR=="string"&&e.CLAUDE_PROJECT_DIR.trim()!=="")&&i.add("claude-code"),r("OPENCLAW_")&&i.add("openclaw"),r("HERMES_")&&i.add("hermes"),(r("ANTIGRAVITY_")||r("GEMINI_"))&&i.add("gemini"),i.size>0)return i.size===1?i.values().next().value:void 0;let n=t.home??ob.homedir(),a=bU(n).filter(([,o])=>ab.existsSync(o));return a.length===1?a[0][0]:void 0}var ef="5.0.0-rc.411",wU="/v1/cli/failure-event",SU=2e3,$U=/^[a-z][a-z0-9_]{1,63}$/,OU=/^[0-9A-Za-z.+-]{1,40}$/,IU=new Set(["claude-code","codex","openclaw","hermes","gemini"]),EU={statusline:10*6e4},PU=new Set(["setup_declined","owner_declined"]);function zU(e=process.env){return e.NODE_ENV==="test"}function cb(e){return typeof e=="number"&&Number.isInteger(e)&&e>=100&&e<=599?e:void 0}function TU(e){return cb(e?.status)}function AU(){let e=process.platform;return e==="darwin"||e==="linux"||e==="win32"?e:"other"}function jU(e){try{let t=sb(e);return t&&IU.has(t)?t:void 0}catch{return}}function kU(e){return e instanceof Error?e.name:typeof e}function NU(e,t){let r=EU[e];if(!r)return!1;let i=nu.join(t,`failure-report-${e}.stamp`);try{if(Date.now()-ha.statSync(i).mtimeMs<r)return!0}catch{}try{ha.mkdirSync(t,{recursive:!0,mode:448}),ha.writeFileSync(i,"",{mode:384})}catch{}return!1}async function ub(e,t={}){try{let r=t.env??process.env,i=Zi(),n=e.step??i.step,a=$U.test(e.code)?e.code:"unspecified_error",o=cb(e.httpStatus),s=df(e.cause),c,u;e.failedRequestId&&uu.test(e.failedRequestId)?(c=e.failedRequestId,u=o):s?(c=s.requestId,u=o??s.httpStatus??void 0):e.cause!==void 0?u=o??TU(e.cause):(c=i.failedRequestId,u=o??(c?i.failedHttpStatus:void 0));let d=i.reference;if(Xc(Mt,i.surface==="mcp"?"warn":"info",i.surface==="mcp"?"tool:failed":"command:failed",{step:n,code:a,kind:e.kind,status:u??null,reference:d,failedRequestId:c??null}),PU.has(a)||!(t.enabled??!zU(r))||i.reported.has(a)||(i.reported.add(a),NU(n,t.stampDir??nu.dirname(mf()))))return;let p=Date.now(),m=jU(r),b={reference:d,...c?{failedRequestId:c}:{},surface:i.surface,step:n,code:a,kind:e.kind,...u!==void 0?{httpStatus:u}:{},cliVersion:OU.test(ef)?ef:"0.0.0",platform:AU(),...m?{harness:m}:{}},y=ba(),O=`${(t.authUrl??ib()).replace(/\/+$/,"")}${wU}`;try{let z=await(t.fetch??fetch)(O,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli","X-Visa-CLI-Version":ef,...wa(y)},body:JSON.stringify(b),redirect:"error",signal:AbortSignal.timeout(Math.max(1,SU-(Date.now()-p)))});z.body?.cancel().catch(()=>{}),Xc(Mt,"info","failure_report:sent",{reference:d,requestId:y,status:z.status})}catch(z){Xc(Mt,"info","failure_report:unsent",{reference:d,requestId:y,reason:kU(z)})}}catch{}}lf("mcp","enrollment_finisher");async function RU(){let e=process.argv.slice(2);if(e.length!==4||e[0]!=="--server"||e[2]!=="--pickup"||!/^[0-9a-f-]{36}$/.test(e[3])||new URL(e[1]).origin!==e[1])throw new Error("pickup_arguments_invalid");let t=sf({safeToExit:()=>!1,onStop:()=>Mt.info("agent:connect_pickup_stop_requested",{correlation:e[3]})});try{await Yy(e[1],e[3],t.stopRequested),t.stopRequested()&&(process.exitCode=143)}finally{t.dispose()}}RU().catch(async e=>{Mt.warn("agent:connect_pickup_stopped",{errorName:e instanceof Error?e.name:typeof e}),process.exitCode=1,await ub({code:"enrollment_finisher_crashed",kind:"unknown",cause:e})}).finally(()=>pf());
86
+ `)}function eo(e,t){let r=i=>{let n=i[kd]??i;return JSON.stringify([n.server,n.generation,n.key_handle,n.jkt,n.agent,n.setup,n.starting])};return r(e)===r(t)}async function tn(e,t,r,i={}){let n=Qa(t);Di.mkdirSync(Ci.dirname(n),{recursive:!0,mode:448});let a=Date.now()+3e4,o;for(;!(o=ya({file:`${n}.lock`,staleMs:6e4}));){if(Date.now()>=a)throw new Te("conflict","agent_state_busy",409,!0);await new Promise(s=>setTimeout(s,25))}try{let s=Fc(n);if(s!==null&&JSON.parse(s).server!==e&&!i.adoptServer)throw new Te("conflict","agent_server_changed",409,!1);return await r(Mr(e,t),c=>{if(!o.held())throw new Te("conflict","agent_state_superseded",409,!1);if(c.server!==e)throw new Error("agent_state_server_mismatch");F1(c,t)})}finally{o()}}async function Qv(e,t,r=process.env,i){return tn(e,r,async(n,a)=>{let o=n[kd]??n;if(i?.(o)){if(o.setup||o.starting||o.pickup){a({...o,generation:(0,zd.randomUUID)(),setup:null,starting:void 0,pickup:void 0});for(let s of new Set([o.setup?.key_handle,o.starting?.key_handle]))s&&s!==o.key_handle&&await t.delete(s)}return o.agent}a({...Xa(e),generation:(0,zd.randomUUID)()});for(let s of new Set([o.key_handle,o.setup?.key_handle,o.starting?.key_handle]))s&&await t.delete(s);return o.agent},{adoptServer:!0})}var tU=je(Ly());var Z6=50*1024*1024,q6=1024*1024;var Zy=new Set(["open","claimed"]),qy=1e3;var aL=33*6e4,nU=1440*6e4,rU=60*6e4,iU=12e4,Vy=nU+rU+iU;function By(e,t){let r=Qa(e);return Kd.mkdirSync(Hd.dirname(r),{recursive:!0,mode:448}),{file:`${r}.${t}.lock`,staleMs:Vy+6e4}}function oi(e,t){if(!eo(e,t))throw new Te("conflict","setup_superseded",409,!1)}function Gy(e,t){let r=t.starting??t.setup;if(!r)return;let n=("mode"in r?r.mode:void 0)??(t.setup?.kind==="replacement"?"replace":"new");if(e.mode!==void 0&&e.mode!==n||e.setupKey!==void 0&&e.setupKey!==r.setup_key)throw new Te("conflict","setup_request_changed",409,!1)}function Jy(e,t=!0){return{state:"waiting_for_owner",owner_url:e.owner_url,code:e.code,expires_at:e.expires_at,setup_id:e.id,resumed:t}}function Wy(e,t){if(t.state==="cancelled"||t.state==="expired"||Zy.has(String(t.state))&&Date.parse(t.expires_at??e.expires_at)<=Date.now())return{state:"ended",reason:t.state==="cancelled"?"declined":"expired",setup_id:e.id};if(t.state==="approved"||t.state==="completed")return{state:"completing",setup_id:e.id};if(Zy.has(String(t.state)))return Jy({...e,expires_at:t.expires_at??e.expires_at});throw new Te("outcome_unknown","setup_state_unknown",202,!0)}async function aU(e,t){let r=t.env??process.env,i=Mr(t.client.server,r);if(Gy(e,i),t.generation&&t.generation!==i.generation)throw new Te("conflict","setup_superseded",409,!1);let n=ya(By(r,"connect"),Date.now(),process.pid,"connect");if(!n){if(i.setup){let a=await t.client.getSetup(i.setup.id,i.setup.secret);oi(Mr(t.client.server,r),i);let o=Wy(i.setup,a);if(o.state!=="completing")return o}throw new Te("conflict","setup_busy",409,!0)}try{return await oU(e,t,r)}finally{n()}}async function oU(e,t,r){let i=t.store??If(r),n=Mr(t.client.server,r);if(Gy(e,n),t.generation&&t.generation!==n.generation)throw new Te("conflict","setup_superseded",409,!1);if(t.pickupToken&&(!n.setup||n.pickup?.token!==t.pickupToken))throw new Te("conflict","setup_superseded",409,!1);let a=e.mode??n.starting?.mode??n.setup?.mode??"new";if(n.removed&&!n.setup&&!n.starting)throw new Te("agent_inactive","agent_revoked",403,!1);if(n.agent&&!n.setup&&!n.starting&&(a==="new"&&(!e.setupKey||e.setupKey===n.joined_setup_key)||t.generation)){t.client.useKey(await Dr.load(i,n.key_handle));let s=n.unreported===!0&&!t.pickupToken;return s&&await tn(n.server,r,(c,u)=>{if(!eo(c,n)||c.removed||!c.unreported)throw new Te("conflict","connection_changed_while_reporting",409,!1);u({...c,unreported:void 0})}),{state:"connected",agent:{id:n.agent.id,name:n.agent.name},installation_id:n.agent.installation_id,already:!s}}if(a==="replace"&&!n.agent&&!e.setupKey&&!n.setup&&!n.starting)throw new Te("setup_required","no_agent_to_replace",401,!1);if(n.setup){let s=n.setup,c=await Dr.load(i,s.key_handle);if(c.jkt!==s.jkt)throw new Te("conflict","setup_key_changed",409,!1);let u;try{u=await t.client.getSetup(s.id,s.secret)}catch(p){if(!t.pickupToken&&p instanceof Te&&["not_found","expired","setup_required"].includes(p.code))return Wd({mode:s.mode??a,setupKey:s.setup_key,client:s.client,...s.another?{another:!0}:{}},s.mode??a,n,c,t.client,r);throw p}if(await tn(n.server,r,p=>oi(p,n)),u.state==="approved"){let p=await t.client.claimSetup(s.id,s.secret,c.claimProof(s.id));return Fy(n,c,i,p.agent,p.installation_id,r,t.client,!!t.pickupToken)}if(u.state==="completed"){t.client.useKey(c);let p=await t.client.status();return Fy(n,c,i,p.agent,p.installation_id,r,t.client,!!t.pickupToken)}if(u.state==="cancelled"||u.state==="expired")return await tn(n.server,r,async(p,m)=>{oi(p,n),m({...p,setup:null,pickup:void 0}),s.key_handle!==p.key_handle&&await Dr.forget(i,s.key_handle)}),{state:"ended",reason:u.state==="cancelled"?"declined":"expired",setup_id:s.id};let d=Wy(s,u);if(d.state!=="completing")return d;throw new Te("conflict","setup_busy",409,!0)}if(t.pickupToken)throw new Te("conflict","setup_superseded",409,!1);if(n.starting){let s=n.starting,c=await Dr.load(i,s.key_handle);return Wd({mode:s.mode,setupKey:s.setup_key,client:s.client},s.mode,n,c,t.client,r)}let o=await tn(n.server,r,async(s,c)=>{oi(s,n);let u=await Dr.create(i),d={...s,generation:(0,Yd.randomUUID)(),pickup:void 0,starting:{key_handle:u.handle,mode:a,...e.setupKey?{setup_key:e.setupKey}:{},...e.client?{client:e.client}:{},...e.another&&!e.setupKey?{another:!0}:{}}};return c(d),{state:d,key:u}},{adoptServer:!0});return n=o.state,Wd(e,a,n,o.key,t.client,r)}async function Wd(e,t,r,i,n,a){let o=t==="replace"&&!e.setupKey?"replacement":"laptop",s=await tn(r.server,a,(d,p)=>{oi(d,r);let m={...d,generation:d.starting?d.generation:(0,Yd.randomUUID)(),setup:null,pickup:void 0,starting:{key_handle:i.handle,mode:t,...e.setupKey?{setup_key:e.setupKey}:{},...e.client?{client:e.client}:{},...e.another&&!e.setupKey||d.starting?.another?{another:!0}:{}}};return p(m),m}),c=await n.startSetup({kind:o,installation_key:i.publicJwk,client:{name:e.client??"visa-cli",version:n.cliVersion},...o==="replacement"?{agent_id:s.agent.id}:{},...e.setupKey?{setup_key:e.setupKey}:{},resume_proof:i.resumeProof(null)}),u={id:String(c.setup.id),secret:c.setup_secret,code:String(c.setup.code),owner_url:String(c.setup.owner_url),expires_at:String(c.setup.expires_at),kind:o,key_handle:i.handle,jkt:i.jkt,mode:t,...e.setupKey?{setup_key:e.setupKey}:{},...e.client?{client:e.client}:{},...s.starting?.another?{another:!0}:{}};return await tn(r.server,a,(d,p)=>{oi(d,s),p({...d,setup:u,starting:void 0})}),Jy(u,!1)}async function Fy(e,t,r,i,n,a,o,s=!1){if(!i||!n)throw new Error("setup_claim_answer_incomplete");await tn(e.server,a,async(u,d)=>{oi(u,e);let p=u.key_handle;d({...u,key_handle:t.handle,jkt:t.jkt,agent:{id:i.id,name:i.name,installation_id:n},setup:null,starting:void 0,pickup:void 0,joined_setup_key:e.setup?.setup_key,...s&&e.setup?.another?{unreported:!0}:{unreported:void 0}}),p&&p!==t.handle&&await Dr.forget(r,p)});let c=Ad(a);for(let u of jd(e.server,a))u.slot!==c&&u.state.agent?.id===i.id&&await Qv(e.server,r,Vc(a,u.slot));return o.useKey(t),{state:"connected",agent:{id:i.id,name:i.name},installation_id:n,already:!1}}async function Yy(e,t,r,i=process.env){let n=Mr(e,i);if(!n.setup||n.pickup?.token!==t)return;let a;for(;!(a=ya(By(i,`pickup-${n.generation??"saved"}`)));){let p=Mr(e,i);if(r()||p.pickup?.token!==t||Date.now()>=n.pickup.deadline_at)return;await new Promise(m=>setTimeout(m,qy))}let o=performance.now(),s=Math.min(Vy,Math.max(0,n.pickup.deadline_at-Date.now())),c=new Pc({server:e}),u="pickup_stopped",d="unavailable";try{for(await tn(e,i,(p,m)=>{if(oi(p,n),p.pickup?.token!==t)throw new Te("conflict","setup_superseded",409,!1);m({...p,pickup:{...p.pickup,state:"running"}})});!r()&&a.held()&&performance.now()-o<s&&Date.now()<n.pickup.deadline_at;){let p=Mr(e,i);if(!eo(p,n)||p.pickup?.token!==t)return;try{if((await aU({},{client:c,env:i,pickupToken:t})).state!=="waiting_for_owner")return}catch(m){if(!(m instanceof Vt)&&!(m instanceof Te&&m.retryable)){d=m instanceof Te?m.code:"unavailable",u=m instanceof Te?"pickup_refused":"custody_or_local_state_unavailable";return}}await new Promise(m=>setTimeout(m,qy))}r()||(u="pickup_deadline")}finally{try{await tn(e,i,(p,m)=>{!eo(p,n)||p.pickup?.token!==t||(m({...p,pickup:{...p.pickup,state:"interrupted",code:d,detail:u}}),Mt.info("agent:connect_pickup_interrupted",{correlation:t,code:d,detail:u}))})}finally{a()}}}var ha=je(require("node:fs")),nu=je(require("node:path"));function Xc(e,t,r,i){try{e[t](r,i)}catch{}}var tu=je(require("fs")),Qd=require("node:net"),Qy=je(require("os")),eb=je(require("path"));var eu=je(require("fs")),Xd=je(require("path")),Ky=je(require("os")),Qc=class{static ensureConfigDir(){let t=this.getConfigDir();eu.existsSync(t)||eu.mkdirSync(t,{recursive:!0,mode:448})}static getConfigDir(){let t=process.env.VISA_CLI_HOME;return typeof t=="string"&&t.trim().length>0?Xd.join(t,".visa-mcp"):Xd.join(Ky.homedir(),".visa-mcp")}};function Hy(e){let t=Qy.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}var sU="settings.json",cU="must use https unless it points at localhost/loopback for local development";function uU(){return eb.join(Qc.getConfigDir(),sU)}function tb(e){if((0,Qd.isIP)(e)!==4)return!1;let[t]=e.split(".").map(Number);return t===127}function lU(e){let t=e.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(!t)return!1;let r=Number.parseInt(t[1],16),i=Number.parseInt(t[2],16);if(!Number.isFinite(r)||!Number.isFinite(i))return!1;let n=[r>>8&255,r&255,i>>8&255,i&255].join(".");return tb(n)}function dU(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost")return!0;let r=(0,Qd.isIP)(t);return r===4?tb(t):r===6?t==="::1"||lU(t):!1}function Xy(e,t="auth.serverUrl"){let r;try{r=new URL(e)}catch{throw new Error(`${t} must be a valid URL (got: ${JSON.stringify(e)})`)}if(r.username||r.password)throw new Error(`${t} must not include username or password credentials`);if(r.protocol!=="https:"&&!(r.protocol==="http:"&&dU(r.hostname)))throw new Error(`${t} ${cU}`)}function fU(){let e=uU();if(!tu.existsSync(e))return{};try{let t=tu.readFileSync(e,"utf-8"),r=JSON.parse(t);return!r||typeof r!="object"||Array.isArray(r)?(Mt.warn("settings:corrupt",{path:Hy(e),reason:"not_object"}),{}):r}catch(t){return Mt.warn("settings:corrupt",{path:Hy(e),error:t?.message||String(t)}),{}}}function pU(e){let t=fU()[e];return typeof t=="string"?t:void 0}var nb="https://auth.visacli.sh",rb="https://auth-visa-code-preview.up.railway.app";function mU(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function gU(){try{let e=Jl();return mU(e.version)}catch{return!1}}function _U(e){return e.envVar!==void 0&&e.envVar!==""?(Xy(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(Xy(e.settingValue,"auth.serverUrl"),e.settingValue):e.isPrerelease?rb:nb}var hU="https://app.visacli.sh",vU="https://web-visa-code-preview.up.railway.app";function yU(e=process.env){let t=_U({envVar:e.VISA_AUTH_URL,settingValue:pU("auth.serverUrl"),isPrerelease:gU()}),r=new URL(t).origin,n=e.VISA_VERIFY_WEB_URL?.trim()||(r===rb?vU:r===nb?hU:r);for(;n.endsWith("/");)n=n.slice(0,-1);return{authUrl:t,webUrl:n}}function ib(){return yU().authUrl}var ab=je(require("fs")),ob=je(require("os")),_a=je(require("path"));function bU(e){return[["openclaw",_a.join(e,".openclaw")],["hermes",_a.join(e,".hermes")],["claude-code",_a.join(e,".claude")],["codex",_a.join(e,".codex")],["gemini",_a.join(e,".gemini")]]}function sb(e=process.env,t={}){if(e.VISA_CLI_RUNTIME&&e.VISA_CLI_RUNTIME.trim().length>0)return e.VISA_CLI_RUNTIME.trim();if(e.AGENT_RUNTIME&&e.AGENT_RUNTIME.trim().length>0)return e.AGENT_RUNTIME.trim();let r=o=>Object.entries(e).some(([s,c])=>s.startsWith(o)&&typeof c=="string"&&c.trim()!==""),i=new Set;if(r("CODEX_")&&i.add("codex"),(typeof e.CLAUDECODE=="string"&&e.CLAUDECODE.trim()!==""||r("CLAUDE_CODE_")||typeof e.CLAUDE_PROJECT_DIR=="string"&&e.CLAUDE_PROJECT_DIR.trim()!=="")&&i.add("claude-code"),r("OPENCLAW_")&&i.add("openclaw"),r("HERMES_")&&i.add("hermes"),(r("ANTIGRAVITY_")||r("GEMINI_"))&&i.add("gemini"),i.size>0)return i.size===1?i.values().next().value:void 0;let n=t.home??ob.homedir(),a=bU(n).filter(([,o])=>ab.existsSync(o));return a.length===1?a[0][0]:void 0}var ef="5.0.0-rc.412",wU="/v1/cli/failure-event",SU=2e3,$U=/^[a-z][a-z0-9_]{1,63}$/,OU=/^[0-9A-Za-z.+-]{1,40}$/,IU=new Set(["claude-code","codex","openclaw","hermes","gemini"]),EU={statusline:10*6e4},PU=new Set(["setup_declined","owner_declined"]);function zU(e=process.env){return e.NODE_ENV==="test"}function cb(e){return typeof e=="number"&&Number.isInteger(e)&&e>=100&&e<=599?e:void 0}function TU(e){return cb(e?.status)}function AU(){let e=process.platform;return e==="darwin"||e==="linux"||e==="win32"?e:"other"}function jU(e){try{let t=sb(e);return t&&IU.has(t)?t:void 0}catch{return}}function kU(e){return e instanceof Error?e.name:typeof e}function NU(e,t){let r=EU[e];if(!r)return!1;let i=nu.join(t,`failure-report-${e}.stamp`);try{if(Date.now()-ha.statSync(i).mtimeMs<r)return!0}catch{}try{ha.mkdirSync(t,{recursive:!0,mode:448}),ha.writeFileSync(i,"",{mode:384})}catch{}return!1}async function ub(e,t={}){try{let r=t.env??process.env,i=Zi(),n=e.step??i.step,a=$U.test(e.code)?e.code:"unspecified_error",o=cb(e.httpStatus),s=df(e.cause),c,u;e.failedRequestId&&uu.test(e.failedRequestId)?(c=e.failedRequestId,u=o):s?(c=s.requestId,u=o??s.httpStatus??void 0):e.cause!==void 0?u=o??TU(e.cause):(c=i.failedRequestId,u=o??(c?i.failedHttpStatus:void 0));let d=i.reference;if(Xc(Mt,i.surface==="mcp"?"warn":"info",i.surface==="mcp"?"tool:failed":"command:failed",{step:n,code:a,kind:e.kind,status:u??null,reference:d,failedRequestId:c??null}),PU.has(a)||!(t.enabled??!zU(r))||i.reported.has(a)||(i.reported.add(a),NU(n,t.stampDir??nu.dirname(mf()))))return;let p=Date.now(),m=jU(r),b={reference:d,...c?{failedRequestId:c}:{},surface:i.surface,step:n,code:a,kind:e.kind,...u!==void 0?{httpStatus:u}:{},cliVersion:OU.test(ef)?ef:"0.0.0",platform:AU(),...m?{harness:m}:{}},y=ba(),O=`${(t.authUrl??ib()).replace(/\/+$/,"")}${wU}`;try{let z=await(t.fetch??fetch)(O,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli","X-Visa-CLI-Version":ef,...wa(y)},body:JSON.stringify(b),redirect:"error",signal:AbortSignal.timeout(Math.max(1,SU-(Date.now()-p)))});z.body?.cancel().catch(()=>{}),Xc(Mt,"info","failure_report:sent",{reference:d,requestId:y,status:z.status})}catch(z){Xc(Mt,"info","failure_report:unsent",{reference:d,requestId:y,reason:kU(z)})}}catch{}}lf("mcp","enrollment_finisher");async function RU(){let e=process.argv.slice(2);if(e.length!==4||e[0]!=="--server"||e[2]!=="--pickup"||!/^[0-9a-f-]{36}$/.test(e[3])||new URL(e[1]).origin!==e[1])throw new Error("pickup_arguments_invalid");let t=sf({safeToExit:()=>!1,onStop:()=>Mt.info("agent:connect_pickup_stop_requested",{correlation:e[3]})});try{await Yy(e[1],e[3],t.stopRequested),t.stopRequested()&&(process.exitCode=143)}finally{t.dispose()}}RU().catch(async e=>{Mt.warn("agent:connect_pickup_stopped",{errorName:e instanceof Error?e.name:typeof e}),process.exitCode=1,await ub({code:"enrollment_finisher_crashed",kind:"unknown",cause:e})}).finally(()=>pf());
87
87
  /*! Bundled license information:
88
88
 
89
89
  @noble/ed25519/index.js: