@catena/cli 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{a as e,i as t,n,r,t as i}from"./rolldown-runtime-B0Z9INg1.mjs";import{D as a,E as o,O as s}from"./dist-w03V0QPF.mjs";import{defineCommand as c,renderUsage as l,runMain as u}from"citty";import*as d from"valibot";import{ECDH as f,createECDH as p,createHash as m,createPrivateKey as h,randomBytes as g,sign as _}from"node:crypto";import{execFile as v,spawn as y}from"node:child_process";import{accessSync as b,chmodSync as x,constants as S,existsSync as C,mkdirSync as w,readFileSync as T,realpathSync as E,renameSync as D,rmSync as O,statSync as k,writeFileSync as A}from"node:fs";import{homedir as ee}from"node:os";import{dirname as j,isAbsolute as M,join as te,resolve as ne}from"node:path";import{createServer as re}from"node:http";import{constants as N,isUtf8 as ie}from"node:buffer";import ae from"semver";var P=`@catena/cli`,oe=`0.9.0`;function se(e){return e instanceof Error?e.message:String(e)}function ce(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function le(e){if(!ce(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}var F=class{container;constructor(e){this.container=e}};function ue(e,t){let n=Object.getOwnPropertyDescriptor(e,t);return n!==void 0&&n.enumerable===!0&&`value`in n}function de(e){if(Object.getOwnPropertySymbols(e).length>0)return null;let t=Object.getOwnPropertyNames(e);for(let n of t)if(!ue(e,n))return null;return t}function fe(e){if(Object.getPrototypeOf(e)!==Array.prototype||Object.getOwnPropertySymbols(e).length>0)return!1;let t=Object.getOwnPropertyNames(e);if(t.length!==e.length+1)return!1;for(let n=0;n<e.length;n++)if(t[n]!==String(n)||!ue(e,t[n]))return!1;return!0}function pe(e){let t=new Set,n=new Set,r=[e];for(;r.length>0;){let e=r.pop();if(e instanceof F){t.delete(e.container),n.add(e.container);continue}if(e===null||typeof e==`string`||typeof e==`boolean`)continue;if(typeof e==`number`){if(!Number.isFinite(e))return!1;continue}if(Array.isArray(e)){if(t.has(e))return!1;if(n.has(e))continue;if(!fe(e))return!1;t.add(e),r.push(new F(e));for(let t of e)r.push(t);continue}if(!le(e)||Object.hasOwn(e,`__proto__`)||t.has(e))return!1;if(n.has(e))continue;let i=de(e);if(i===null)return!1;t.add(e),r.push(new F(e));for(let t of i)r.push(e[t])}return!0}function me(e){return t=>{try{return e(t)}catch{return!1}}}d.custom(me(pe),`Expected a JSON value`),d.custom(me(e=>le(e)&&pe(e)),`Expected a JSON object`),d.custom(me(e=>Array.isArray(e)&&pe(e)),`Expected a JSON array`);function I(e){return ge(L(e))}function he(e,t){let n=e.padStart(Math.ceil(e.length/2)*2,`0`);return I(a(n,t).reduce((e,t)=>e+String.fromCharCode(t),``))}function ge(e){return e.replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=/g,``)}function L(e){if(arguments.length===0)throw TypeError(`1 argument required, but only 0 present.`);let t;for(e=`${e}`,t=0;t<e.length;t++)if(e.charCodeAt(t)>255)throw Error(`InvalidCharacterError: found code point greater than 255:${e.charCodeAt(t)} at position ${t}`);let n=``;for(t=0;t<e.length;t+=3){let r=[void 0,void 0,void 0,void 0];r[0]=e.charCodeAt(t)>>2,r[1]=(e.charCodeAt(t)&3)<<4,e.length>t+1&&(r[1]|=e.charCodeAt(t+1)>>4,r[2]=(e.charCodeAt(t+1)&15)<<2),e.length>t+2&&(r[2]|=e.charCodeAt(t+2)>>6,r[3]=e.charCodeAt(t+2)&63);for(let e=0;e<r.length;e++)r[e]===void 0?n+=`=`:n+=_e(r[e])}return n}function _e(e){if(e>=0&&e<64)return`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`[e]}var R=[`u8`,`u16`,`u32`,`u64`,`u128`,`i8`,`i16`,`i32`,`i64`,`i128`,`f32`,`f64`],ve=function(){function e(){this.offset=0,this.buffer_size=256,this.buffer=new ArrayBuffer(this.buffer_size),this.view=new DataView(this.buffer)}return e.prototype.resize_if_necessary=function(e){if(this.buffer_size-this.offset<e){this.buffer_size=Math.max(this.buffer_size*2,this.buffer_size+e);var t=new ArrayBuffer(this.buffer_size);new Uint8Array(t).set(new Uint8Array(this.buffer)),this.buffer=t,this.view=new DataView(t)}},e.prototype.get_used_buffer=function(){return new Uint8Array(this.buffer).slice(0,this.offset)},e.prototype.store_value=function(e,t){var n=t.substring(1),r=parseInt(n)/8;this.resize_if_necessary(r);var i=t[0]===`f`?`setFloat${n}`:t[0]===`i`?`setInt${n}`:`setUint${n}`;this.view[i](this.offset,e,!0),this.offset+=r},e.prototype.store_bytes=function(e){this.resize_if_necessary(e.length),new Uint8Array(this.buffer).set(new Uint8Array(e),this.offset),this.offset+=e.length},e}(),ye=function(){function e(e){this.offset=0,this.buffer_size=e.length,this.buffer=new ArrayBuffer(e.length),new Uint8Array(this.buffer).set(e),this.view=new DataView(this.buffer)}return e.prototype.assert_enough_buffer=function(e){if(this.offset+e>this.buffer.byteLength)throw Error(`Error in schema, the buffer is smaller than expected`)},e.prototype.consume_value=function(e){var t=e.substring(1),n=parseInt(t)/8;this.assert_enough_buffer(n);var r=e[0]===`f`?`getFloat${t}`:e[0]===`i`?`getInt${t}`:`getUint${t}`,i=this.view[r](this.offset,!0);return this.offset+=n,i},e.prototype.consume_bytes=function(e){this.assert_enough_buffer(e);var t=this.buffer.slice(this.offset,this.offset+e);return this.offset+=e,t},e}(),be=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},e(t,n)};return function(t,n){if(typeof n!=`function`&&n!==null)throw TypeError(`Class extends value `+String(n)+` is not a constructor or null`);e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})();function xe(e){return Array.isArray(e)||!!e&&typeof e==`object`&&`length`in e&&typeof e.length==`number`&&(e.length===0||e.length>0&&e.length-1 in e)}function Se(e,t,n){if(typeof e!==t)throw Error(`Expected ${t} not ${typeof e}(${e}) at ${n.join(`.`)}`)}function z(e,t){var n=[`number`,`string`,`bigint`,`boolean`].includes(typeof e),r=typeof e==`object`&&!!e&&`toString`in e;if(!n&&!r)throw Error(`Expected bigint, number, boolean or string not ${typeof e}(${e}) at ${t.join(`.`)}`)}function Ce(e,t,n){if(e!==t)throw Error(`Array length ${e} does not match schema length ${t} at ${n.join(`.`)}`)}function we(e,t){if(typeof e!=`object`||!e)throw Error(`Expected object not ${typeof e}(${e}) at ${t.join(`.`)}`)}R.concat([`bool`,`string`]),function(e){be(t,e);function t(t,n){var r=`Invalid schema: ${JSON.stringify(t)} expected ${n}`;return e.call(this,r)||this}return t}(Error),function(){function e(e){this.encoded=new ve,this.fieldPath=[`value`],this.checkTypes=e}return e.prototype.encode=function(e,t){return this.encode_value(e,t),this.encoded.get_used_buffer()},e.prototype.encode_value=function(e,t){if(typeof t==`string`){if(R.includes(t))return this.encode_integer(e,t);if(t===`string`)return this.encode_string(e);if(t===`bool`)return this.encode_boolean(e)}if(typeof t==`object`){if(`option`in t)return this.encode_option(e,t);if(`enum`in t)return this.encode_enum(e,t);if(`array`in t)return this.encode_array(e,t);if(`set`in t)return this.encode_set(e,t);if(`map`in t)return this.encode_map(e,t);if(`struct`in t)return this.encode_struct(e,t)}},e.prototype.encode_integer=function(e,t){var n=parseInt(t.substring(1));n<=32||t==`f64`?(this.checkTypes&&Se(e,`number`,this.fieldPath),this.encoded.store_value(e,t)):(this.checkTypes&&z(e,this.fieldPath),this.encode_bigint(BigInt(e),n))},e.prototype.encode_bigint=function(e,t){for(var n=t/8,r=new Uint8Array(n),i=0;i<n;i++)r[i]=Number(e&BigInt(255)),e>>=BigInt(8);this.encoded.store_bytes(new Uint8Array(r))},e.prototype.encode_string=function(e){this.checkTypes&&Se(e,`string`,this.fieldPath);for(var t=e,n=[],r=0;r<t.length;r++){var i=t.charCodeAt(r);i<128?n.push(i):i<2048?n.push(192|i>>6,128|i&63):i<55296||i>=57344?n.push(224|i>>12,128|i>>6&63,128|i&63):(r++,i=65536+((i&1023)<<10|t.charCodeAt(r)&1023),n.push(240|i>>18,128|i>>12&63,128|i>>6&63,128|i&63))}this.encoded.store_value(n.length,`u32`),this.encoded.store_bytes(new Uint8Array(n))},e.prototype.encode_boolean=function(e){this.checkTypes&&Se(e,`boolean`,this.fieldPath),this.encoded.store_value(+!!e,`u8`)},e.prototype.encode_option=function(e,t){e==null?this.encoded.store_value(0,`u8`):(this.encoded.store_value(1,`u8`),this.encode_value(e,t.option))},e.prototype.encode_enum=function(e,t){this.checkTypes&&we(e,this.fieldPath);for(var n=Object.keys(e)[0],r=0;r<t.enum.length;r++){var i=t.enum[r];if(n===Object.keys(i.struct)[0])return this.encoded.store_value(r,`u8`),this.encode_struct(e,i)}throw Error(`Enum key (${n}) not found in enum schema: ${JSON.stringify(t)} at ${this.fieldPath.join(`.`)}`)},e.prototype.encode_array=function(e,t){if(xe(e))return this.encode_arraylike(e,t);if(e instanceof ArrayBuffer)return this.encode_buffer(e,t);throw Error(`Expected Array-like not ${typeof e}(${e}) at ${this.fieldPath.join(`.`)}`)},e.prototype.encode_arraylike=function(e,t){t.array.len?Ce(e.length,t.array.len,this.fieldPath):this.encoded.store_value(e.length,`u32`);for(var n=0;n<e.length;n++)this.encode_value(e[n],t.array.type)},e.prototype.encode_buffer=function(e,t){t.array.len?Ce(e.byteLength,t.array.len,this.fieldPath):this.encoded.store_value(e.byteLength,`u32`),this.encoded.store_bytes(new Uint8Array(e))},e.prototype.encode_set=function(e,t){this.checkTypes&&Se(e,`object`,this.fieldPath);var n=e instanceof Set?Array.from(e.values()):Object.values(e);this.encoded.store_value(n.length,`u32`);for(var r=0,i=n;r<i.length;r++){var a=i[r];this.encode_value(a,t.set)}},e.prototype.encode_map=function(e,t){this.checkTypes&&Se(e,`object`,this.fieldPath);var n=e instanceof Map,r=n?Array.from(e.keys()):Object.keys(e);this.encoded.store_value(r.length,`u32`);for(var i=0,a=r;i<a.length;i++){var o=a[i];this.encode_value(o,t.map.key),this.encode_value(n?e.get(o):e[o],t.map.value)}},e.prototype.encode_struct=function(e,t){this.checkTypes&&Se(e,`object`,this.fieldPath);for(var n=0,r=Object.keys(t.struct);n<r.length;n++){var i=r[n];this.fieldPath.push(i),this.encode_value(e[i],t.struct[i]),this.fieldPath.pop()}},e}(),function(){function e(e){this.buffer=new ye(e)}return e.prototype.decode=function(e){return this.decode_value(e)},e.prototype.decode_value=function(e){if(typeof e==`string`){if(R.includes(e))return this.decode_integer(e);if(e===`string`)return this.decode_string();if(e===`bool`)return this.decode_boolean()}if(typeof e==`object`){if(`option`in e)return this.decode_option(e);if(`enum`in e)return this.decode_enum(e);if(`array`in e)return this.decode_array(e);if(`set`in e)return this.decode_set(e);if(`map`in e)return this.decode_map(e);if(`struct`in e)return this.decode_struct(e)}throw Error(`Unsupported type: ${e}`)},e.prototype.decode_integer=function(e){var t=parseInt(e.substring(1));return t<=32||e==`f64`?this.buffer.consume_value(e):this.decode_bigint(t,e.startsWith(`i`))},e.prototype.decode_bigint=function(e,t){t===void 0&&(t=!1);var n=e/8,r=new Uint8Array(this.buffer.consume_bytes(n)),i=r.reduceRight(function(e,t){return e+t.toString(16).padStart(2,`0`)},``);return t&&r[n-1]?BigInt.asIntN(e,BigInt(`0x${i}`)):BigInt(`0x${i}`)},e.prototype.decode_string=function(){for(var e=this.decode_integer(`u32`),t=new Uint8Array(this.buffer.consume_bytes(e)),n=[],r=0;r<e;++r){var i=t[r];if(i<128)n.push(i);else if(i<224)n.push((i&31)<<6|t[++r]&63);else if(i<240)n.push((i&15)<<12|(t[++r]&63)<<6|t[++r]&63);else{var a=(i&7)<<18|(t[++r]&63)<<12|(t[++r]&63)<<6|t[++r]&63;n.push(a)}}return String.fromCodePoint.apply(String,n)},e.prototype.decode_boolean=function(){return this.buffer.consume_value(`u8`)>0},e.prototype.decode_option=function(e){var t=this.buffer.consume_value(`u8`);if(t===1)return this.decode_value(e.option);if(t!==0)throw Error(`Invalid option ${t}`);return null},e.prototype.decode_enum=function(e){var t,n=this.buffer.consume_value(`u8`);if(n>e.enum.length)throw Error(`Enum option ${n} is not available`);var r=e.enum[n].struct,i=Object.keys(r)[0];return t={},t[i]=this.decode_value(r[i]),t},e.prototype.decode_array=function(e){for(var t=[],n=e.array.len?e.array.len:this.decode_integer(`u32`),r=0;r<n;++r)t.push(this.decode_value(e.array.type));return t},e.prototype.decode_set=function(e){for(var t=this.decode_integer(`u32`),n=new Set,r=0;r<t;++r)n.add(this.decode_value(e.set));return n},e.prototype.decode_map=function(e){for(var t=this.decode_integer(`u32`),n=new Map,r=0;r<t;++r){var i=this.decode_value(e.map.key),a=this.decode_value(e.map.value);n.set(i,a)}return n},e.prototype.decode_struct=function(e){var t={};for(var n in e.struct)t[n]=this.decode_value(e.struct[n]);return t},e}(),new Uint8Array([75,69,77,0,16]),new Uint8Array([72,80,75,69,0,16,0,1,0,2]),new Uint8Array([72,80,75,69,45,118,49]),new Uint8Array([115,101,99,114,101,116]),new Uint8Array([101,97,101,95,112,114,107]),new Uint8Array([115,104,97,114,101,100,95,115,101,99,114,101,116]),new Uint8Array([0,32,72,80,75,69,45,118,49,72,80,75,69,0,16,0,1,0,2,107,101,121,0,143,195,174,184,50,73,10,75,90,179,228,32,35,40,125,178,154,31,75,199,194,34,192,223,34,135,39,183,10,64,33,18,47,63,4,233,32,108,209,36,19,80,53,41,180,122,198,166,48,185,46,196,207,125,35,69,8,208,175,151,113,201,158,80]),new Uint8Array([0,12,72,80,75,69,45,118,49,72,80,75,69,0,16,0,1,0,2,98,97,115,101,95,110,111,110,99,101,0,143,195,174,184,50,73,10,75,90,179,228,32,35,40,125,178,154,31,75,199,194,34,192,223,34,135,39,183,10,64,33,18,47,63,4,233,32,108,209,36,19,80,53,41,180,122,198,166,48,185,46,196,207,125,35,69,8,208,175,151,113,201,158,80]),new Uint8Array([113,111,115,95,101,110,99,114,121,112,116,105,111,110,95,104,109,97,99,95,109,101,115,115,97,103,101]);const Te=e=>{let t=a(e);if(t.length<2)throw Error(`failed to convert DER-encoded signature: insufficient length`);if(t[0]!==48)throw Error(`failed to convert DER-encoded signature: invalid format (missing SEQUENCE tag)`);let n=1,r=t[n];if(r<=127){if(t.length<2+r)throw Error(`failed to convert DER-encoded signature: inconsistent message length header`);n+=1}else throw Error(`failed to convert DER-encoded signature: unexpectedly large or invalid signature length`);if(t[n]!==2)throw Error(`failed to convert DER-encoded signature: invalid tag for r`);n++;let i=t[n];if(i>33)throw Error(`failed to convert DER-encoded signature: unexpected length for r`);n++;let s=t.slice(n,n+i);if(n+=i,t[n]!==2)throw Error(`failed to convert DER-encoded signature: invalid tag for s`);n++;let c=t[n];if(c>33)throw Error(`failed to convert DER-encoded signature: unexpected length for s`);n++;let l=t.slice(n,n+c),u=o(s,32),d=o(l,32);return new Uint8Array([...u,...d])};var Ee;(function(e){e.NOTARIZER=`notarizer`,e.SIGNER=`signer`,e.EVM_PARSER=`evm-parser`,e.TLS_FETCHER=`tls-fetcher`,e.UMP=`ump`})(Ee||={});var De=i(((e,t)=>{(function(e,n){var r=2**-24,i=2**32,a=2**53;function o(e){var t=new ArrayBuffer(256),r=new DataView(t),o,s=0;function c(e){for(var n=t.byteLength,i=s+e;n<i;)n*=2;if(n!==t.byteLength){var a=r;t=new ArrayBuffer(n),r=new DataView(t);for(var c=s+3>>2,l=0;l<c;++l)r.setUint32(l*4,a.getUint32(l*4))}return o=e,r}function l(){s+=o}function u(e){l(c(8).setFloat64(s,e))}function d(e){l(c(1).setUint8(s,e))}function f(e){for(var t=c(e.length),n=0;n<e.length;++n)t.setUint8(s+n,e[n]);l()}function p(e){l(c(2).setUint16(s,e))}function m(e){l(c(4).setUint32(s,e))}function h(e){var t=e%i,n=(e-t)/i,r=c(8);r.setUint32(s,n),r.setUint32(s+4,t),l()}function g(e,t){t<24?d(e<<5|t):t<256?(d(e<<5|24),d(t)):t<65536?(d(e<<5|25),p(t)):t<4294967296?(d(e<<5|26),m(t)):(d(e<<5|27),h(t))}function _(e){var t;if(e===!1)return d(244);if(e===!0)return d(245);if(e===null)return d(246);if(e===n)return d(247);switch(typeof e){case`number`:if(Math.floor(e)===e){if(0<=e&&e<=a)return g(0,e);if(-a<=e&&e<0)return g(1,-(e+1))}return d(251),u(e);case`string`:var r=[];for(t=0;t<e.length;++t){var i=e.charCodeAt(t);i<128?r.push(i):i<2048?(r.push(192|i>>6),r.push(128|i&63)):i<55296?(r.push(224|i>>12),r.push(128|i>>6&63),r.push(128|i&63)):(i=(i&1023)<<10,i|=e.charCodeAt(++t)&1023,i+=65536,r.push(240|i>>18),r.push(128|i>>12&63),r.push(128|i>>6&63),r.push(128|i&63))}return g(3,r.length),f(r);default:var o;if(Array.isArray(e))for(o=e.length,g(4,o),t=0;t<o;++t)_(e[t]);else if(e instanceof Uint8Array)g(2,e.length),f(e);else{var s=Object.keys(e);for(o=s.length,g(5,o),t=0;t<o;++t){var c=s[t];_(c),_(e[c])}}}}if(_(e),`slice`in t)return t.slice(0,s);for(var v=new ArrayBuffer(s),y=new DataView(v),b=0;b<s;++b)y.setUint8(b,r.getUint8(b));return v}function s(e,t,a){var o=new DataView(e),s=0;typeof t!=`function`&&(t=function(e){return e}),typeof a!=`function`&&(a=function(){return n});function c(e,t){return s+=t,e}function l(t){return c(new Uint8Array(e,s,t),t)}function u(){var e=new DataView(new ArrayBuffer(4)),t=m(),n=t&32768,i=t&31744,a=t&1023;if(i===31744)i=261120;else if(i!==0)i+=114688;else if(a!==0)return a*r;return e.setUint32(0,n<<16|i<<13|a<<13),e.getFloat32(0)}function d(){return c(o.getFloat32(s),4)}function f(){return c(o.getFloat64(s),8)}function p(){return c(o.getUint8(s),1)}function m(){return c(o.getUint16(s),2)}function h(){return c(o.getUint32(s),4)}function g(){return h()*i+h()}function _(){return o.getUint8(s)===255&&(s+=1,!0)}function v(e){if(e<24)return e;if(e===24)return p();if(e===25)return m();if(e===26)return h();if(e===27)return g();if(e===31)return-1;throw`Invalid length encoding`}function y(e){var t=p();if(t===255)return-1;var n=v(t&31);if(n<0||t>>5!==e)throw`Invalid indefinite length element`;return n}function b(e,t){for(var n=0;n<t;++n){var r=p();r&128&&(r<224?(r=(r&31)<<6|p()&63,--t):r<240?(r=(r&15)<<12|(p()&63)<<6|p()&63,t-=2):(r=(r&15)<<18|(p()&63)<<12|(p()&63)<<6|p()&63,t-=3)),r<65536?e.push(r):(r-=65536,e.push(55296|r>>10),e.push(56320|r&1023))}}function x(){var e=p(),r=e>>5,i=e&31,o,s;if(r===7)switch(i){case 25:return u();case 26:return d();case 27:return f()}if(s=v(i),s<0&&(r<2||6<r))throw`Invalid length`;switch(r){case 0:return s;case 1:return-1-s;case 2:if(s<0){for(var c=[],m=0;(s=y(r))>=0;)m+=s,c.push(l(s));var h=new Uint8Array(m),g=0;for(o=0;o<c.length;++o)h.set(c[o],g),g+=c[o].length;return h}return l(s);case 3:var S=[];if(s<0)for(;(s=y(r))>=0;)b(S,s);else b(S,s);return String.fromCharCode.apply(null,S);case 4:var C;if(s<0)for(C=[];!_();)C.push(x());else for(C=Array(s),o=0;o<s;++o)C[o]=x();return C;case 5:var w={};for(o=0;o<s||s<0&&!_();++o){var T=x();w[T]=x()}return w;case 6:return t(x(),s);case 7:switch(s){case 20:return!1;case 21:return!0;case 22:return null;case 23:return n;default:return a(s)}}}var S=x();if(s!==e.byteLength)throw`Remaining bytes`;return S}var c={encode:o,decode:s};typeof define==`function`&&define.amd?define(`cbor/cbor`,c):t!==void 0&&t.exports?t.exports=c:e.CBOR||=c})(e)})),Oe=i((()=>{
2
+ import{a as e,i as t,n,r,t as i}from"./rolldown-runtime-B0Z9INg1.mjs";import{D as a,E as o,O as s}from"./dist-w03V0QPF.mjs";import{defineCommand as c,renderUsage as l,runMain as u}from"citty";import*as d from"valibot";import{ECDH as f,createECDH as p,createHash as m,createPrivateKey as h,randomBytes as g,sign as _}from"node:crypto";import{execFile as v,spawn as y}from"node:child_process";import{accessSync as b,chmodSync as x,constants as S,existsSync as C,mkdirSync as w,readFileSync as T,realpathSync as E,renameSync as D,rmSync as O,statSync as k,writeFileSync as A}from"node:fs";import{homedir as ee}from"node:os";import{dirname as j,isAbsolute as M,join as te,resolve as ne}from"node:path";import{createServer as re}from"node:http";import{constants as N,isUtf8 as ie}from"node:buffer";import ae from"semver";var P=`@catena/cli`,oe=`0.10.0`;function se(e){return e instanceof Error?e.message:String(e)}function ce(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function le(e){if(!ce(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}var F=class{container;constructor(e){this.container=e}};function ue(e,t){let n=Object.getOwnPropertyDescriptor(e,t);return n!==void 0&&n.enumerable===!0&&`value`in n}function de(e){if(Object.getOwnPropertySymbols(e).length>0)return null;let t=Object.getOwnPropertyNames(e);for(let n of t)if(!ue(e,n))return null;return t}function fe(e){if(Object.getPrototypeOf(e)!==Array.prototype||Object.getOwnPropertySymbols(e).length>0)return!1;let t=Object.getOwnPropertyNames(e);if(t.length!==e.length+1)return!1;for(let n=0;n<e.length;n++)if(t[n]!==String(n)||!ue(e,t[n]))return!1;return!0}function pe(e){let t=new Set,n=new Set,r=[e];for(;r.length>0;){let e=r.pop();if(e instanceof F){t.delete(e.container),n.add(e.container);continue}if(e===null||typeof e==`string`||typeof e==`boolean`)continue;if(typeof e==`number`){if(!Number.isFinite(e))return!1;continue}if(Array.isArray(e)){if(t.has(e))return!1;if(n.has(e))continue;if(!fe(e))return!1;t.add(e),r.push(new F(e));for(let t of e)r.push(t);continue}if(!le(e)||Object.hasOwn(e,`__proto__`)||t.has(e))return!1;if(n.has(e))continue;let i=de(e);if(i===null)return!1;t.add(e),r.push(new F(e));for(let t of i)r.push(e[t])}return!0}function me(e){return t=>{try{return e(t)}catch{return!1}}}d.custom(me(pe),`Expected a JSON value`),d.custom(me(e=>le(e)&&pe(e)),`Expected a JSON object`),d.custom(me(e=>Array.isArray(e)&&pe(e)),`Expected a JSON array`);function I(e){return ge(L(e))}function he(e,t){let n=e.padStart(Math.ceil(e.length/2)*2,`0`);return I(a(n,t).reduce((e,t)=>e+String.fromCharCode(t),``))}function ge(e){return e.replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=/g,``)}function L(e){if(arguments.length===0)throw TypeError(`1 argument required, but only 0 present.`);let t;for(e=`${e}`,t=0;t<e.length;t++)if(e.charCodeAt(t)>255)throw Error(`InvalidCharacterError: found code point greater than 255:${e.charCodeAt(t)} at position ${t}`);let n=``;for(t=0;t<e.length;t+=3){let r=[void 0,void 0,void 0,void 0];r[0]=e.charCodeAt(t)>>2,r[1]=(e.charCodeAt(t)&3)<<4,e.length>t+1&&(r[1]|=e.charCodeAt(t+1)>>4,r[2]=(e.charCodeAt(t+1)&15)<<2),e.length>t+2&&(r[2]|=e.charCodeAt(t+2)>>6,r[3]=e.charCodeAt(t+2)&63);for(let e=0;e<r.length;e++)r[e]===void 0?n+=`=`:n+=_e(r[e])}return n}function _e(e){if(e>=0&&e<64)return`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`[e]}var R=[`u8`,`u16`,`u32`,`u64`,`u128`,`i8`,`i16`,`i32`,`i64`,`i128`,`f32`,`f64`],ve=function(){function e(){this.offset=0,this.buffer_size=256,this.buffer=new ArrayBuffer(this.buffer_size),this.view=new DataView(this.buffer)}return e.prototype.resize_if_necessary=function(e){if(this.buffer_size-this.offset<e){this.buffer_size=Math.max(this.buffer_size*2,this.buffer_size+e);var t=new ArrayBuffer(this.buffer_size);new Uint8Array(t).set(new Uint8Array(this.buffer)),this.buffer=t,this.view=new DataView(t)}},e.prototype.get_used_buffer=function(){return new Uint8Array(this.buffer).slice(0,this.offset)},e.prototype.store_value=function(e,t){var n=t.substring(1),r=parseInt(n)/8;this.resize_if_necessary(r);var i=t[0]===`f`?`setFloat${n}`:t[0]===`i`?`setInt${n}`:`setUint${n}`;this.view[i](this.offset,e,!0),this.offset+=r},e.prototype.store_bytes=function(e){this.resize_if_necessary(e.length),new Uint8Array(this.buffer).set(new Uint8Array(e),this.offset),this.offset+=e.length},e}(),ye=function(){function e(e){this.offset=0,this.buffer_size=e.length,this.buffer=new ArrayBuffer(e.length),new Uint8Array(this.buffer).set(e),this.view=new DataView(this.buffer)}return e.prototype.assert_enough_buffer=function(e){if(this.offset+e>this.buffer.byteLength)throw Error(`Error in schema, the buffer is smaller than expected`)},e.prototype.consume_value=function(e){var t=e.substring(1),n=parseInt(t)/8;this.assert_enough_buffer(n);var r=e[0]===`f`?`getFloat${t}`:e[0]===`i`?`getInt${t}`:`getUint${t}`,i=this.view[r](this.offset,!0);return this.offset+=n,i},e.prototype.consume_bytes=function(e){this.assert_enough_buffer(e);var t=this.buffer.slice(this.offset,this.offset+e);return this.offset+=e,t},e}(),be=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},e(t,n)};return function(t,n){if(typeof n!=`function`&&n!==null)throw TypeError(`Class extends value `+String(n)+` is not a constructor or null`);e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})();function xe(e){return Array.isArray(e)||!!e&&typeof e==`object`&&`length`in e&&typeof e.length==`number`&&(e.length===0||e.length>0&&e.length-1 in e)}function Se(e,t,n){if(typeof e!==t)throw Error(`Expected ${t} not ${typeof e}(${e}) at ${n.join(`.`)}`)}function z(e,t){var n=[`number`,`string`,`bigint`,`boolean`].includes(typeof e),r=typeof e==`object`&&!!e&&`toString`in e;if(!n&&!r)throw Error(`Expected bigint, number, boolean or string not ${typeof e}(${e}) at ${t.join(`.`)}`)}function Ce(e,t,n){if(e!==t)throw Error(`Array length ${e} does not match schema length ${t} at ${n.join(`.`)}`)}function we(e,t){if(typeof e!=`object`||!e)throw Error(`Expected object not ${typeof e}(${e}) at ${t.join(`.`)}`)}R.concat([`bool`,`string`]),function(e){be(t,e);function t(t,n){var r=`Invalid schema: ${JSON.stringify(t)} expected ${n}`;return e.call(this,r)||this}return t}(Error),function(){function e(e){this.encoded=new ve,this.fieldPath=[`value`],this.checkTypes=e}return e.prototype.encode=function(e,t){return this.encode_value(e,t),this.encoded.get_used_buffer()},e.prototype.encode_value=function(e,t){if(typeof t==`string`){if(R.includes(t))return this.encode_integer(e,t);if(t===`string`)return this.encode_string(e);if(t===`bool`)return this.encode_boolean(e)}if(typeof t==`object`){if(`option`in t)return this.encode_option(e,t);if(`enum`in t)return this.encode_enum(e,t);if(`array`in t)return this.encode_array(e,t);if(`set`in t)return this.encode_set(e,t);if(`map`in t)return this.encode_map(e,t);if(`struct`in t)return this.encode_struct(e,t)}},e.prototype.encode_integer=function(e,t){var n=parseInt(t.substring(1));n<=32||t==`f64`?(this.checkTypes&&Se(e,`number`,this.fieldPath),this.encoded.store_value(e,t)):(this.checkTypes&&z(e,this.fieldPath),this.encode_bigint(BigInt(e),n))},e.prototype.encode_bigint=function(e,t){for(var n=t/8,r=new Uint8Array(n),i=0;i<n;i++)r[i]=Number(e&BigInt(255)),e>>=BigInt(8);this.encoded.store_bytes(new Uint8Array(r))},e.prototype.encode_string=function(e){this.checkTypes&&Se(e,`string`,this.fieldPath);for(var t=e,n=[],r=0;r<t.length;r++){var i=t.charCodeAt(r);i<128?n.push(i):i<2048?n.push(192|i>>6,128|i&63):i<55296||i>=57344?n.push(224|i>>12,128|i>>6&63,128|i&63):(r++,i=65536+((i&1023)<<10|t.charCodeAt(r)&1023),n.push(240|i>>18,128|i>>12&63,128|i>>6&63,128|i&63))}this.encoded.store_value(n.length,`u32`),this.encoded.store_bytes(new Uint8Array(n))},e.prototype.encode_boolean=function(e){this.checkTypes&&Se(e,`boolean`,this.fieldPath),this.encoded.store_value(+!!e,`u8`)},e.prototype.encode_option=function(e,t){e==null?this.encoded.store_value(0,`u8`):(this.encoded.store_value(1,`u8`),this.encode_value(e,t.option))},e.prototype.encode_enum=function(e,t){this.checkTypes&&we(e,this.fieldPath);for(var n=Object.keys(e)[0],r=0;r<t.enum.length;r++){var i=t.enum[r];if(n===Object.keys(i.struct)[0])return this.encoded.store_value(r,`u8`),this.encode_struct(e,i)}throw Error(`Enum key (${n}) not found in enum schema: ${JSON.stringify(t)} at ${this.fieldPath.join(`.`)}`)},e.prototype.encode_array=function(e,t){if(xe(e))return this.encode_arraylike(e,t);if(e instanceof ArrayBuffer)return this.encode_buffer(e,t);throw Error(`Expected Array-like not ${typeof e}(${e}) at ${this.fieldPath.join(`.`)}`)},e.prototype.encode_arraylike=function(e,t){t.array.len?Ce(e.length,t.array.len,this.fieldPath):this.encoded.store_value(e.length,`u32`);for(var n=0;n<e.length;n++)this.encode_value(e[n],t.array.type)},e.prototype.encode_buffer=function(e,t){t.array.len?Ce(e.byteLength,t.array.len,this.fieldPath):this.encoded.store_value(e.byteLength,`u32`),this.encoded.store_bytes(new Uint8Array(e))},e.prototype.encode_set=function(e,t){this.checkTypes&&Se(e,`object`,this.fieldPath);var n=e instanceof Set?Array.from(e.values()):Object.values(e);this.encoded.store_value(n.length,`u32`);for(var r=0,i=n;r<i.length;r++){var a=i[r];this.encode_value(a,t.set)}},e.prototype.encode_map=function(e,t){this.checkTypes&&Se(e,`object`,this.fieldPath);var n=e instanceof Map,r=n?Array.from(e.keys()):Object.keys(e);this.encoded.store_value(r.length,`u32`);for(var i=0,a=r;i<a.length;i++){var o=a[i];this.encode_value(o,t.map.key),this.encode_value(n?e.get(o):e[o],t.map.value)}},e.prototype.encode_struct=function(e,t){this.checkTypes&&Se(e,`object`,this.fieldPath);for(var n=0,r=Object.keys(t.struct);n<r.length;n++){var i=r[n];this.fieldPath.push(i),this.encode_value(e[i],t.struct[i]),this.fieldPath.pop()}},e}(),function(){function e(e){this.buffer=new ye(e)}return e.prototype.decode=function(e){return this.decode_value(e)},e.prototype.decode_value=function(e){if(typeof e==`string`){if(R.includes(e))return this.decode_integer(e);if(e===`string`)return this.decode_string();if(e===`bool`)return this.decode_boolean()}if(typeof e==`object`){if(`option`in e)return this.decode_option(e);if(`enum`in e)return this.decode_enum(e);if(`array`in e)return this.decode_array(e);if(`set`in e)return this.decode_set(e);if(`map`in e)return this.decode_map(e);if(`struct`in e)return this.decode_struct(e)}throw Error(`Unsupported type: ${e}`)},e.prototype.decode_integer=function(e){var t=parseInt(e.substring(1));return t<=32||e==`f64`?this.buffer.consume_value(e):this.decode_bigint(t,e.startsWith(`i`))},e.prototype.decode_bigint=function(e,t){t===void 0&&(t=!1);var n=e/8,r=new Uint8Array(this.buffer.consume_bytes(n)),i=r.reduceRight(function(e,t){return e+t.toString(16).padStart(2,`0`)},``);return t&&r[n-1]?BigInt.asIntN(e,BigInt(`0x${i}`)):BigInt(`0x${i}`)},e.prototype.decode_string=function(){for(var e=this.decode_integer(`u32`),t=new Uint8Array(this.buffer.consume_bytes(e)),n=[],r=0;r<e;++r){var i=t[r];if(i<128)n.push(i);else if(i<224)n.push((i&31)<<6|t[++r]&63);else if(i<240)n.push((i&15)<<12|(t[++r]&63)<<6|t[++r]&63);else{var a=(i&7)<<18|(t[++r]&63)<<12|(t[++r]&63)<<6|t[++r]&63;n.push(a)}}return String.fromCodePoint.apply(String,n)},e.prototype.decode_boolean=function(){return this.buffer.consume_value(`u8`)>0},e.prototype.decode_option=function(e){var t=this.buffer.consume_value(`u8`);if(t===1)return this.decode_value(e.option);if(t!==0)throw Error(`Invalid option ${t}`);return null},e.prototype.decode_enum=function(e){var t,n=this.buffer.consume_value(`u8`);if(n>e.enum.length)throw Error(`Enum option ${n} is not available`);var r=e.enum[n].struct,i=Object.keys(r)[0];return t={},t[i]=this.decode_value(r[i]),t},e.prototype.decode_array=function(e){for(var t=[],n=e.array.len?e.array.len:this.decode_integer(`u32`),r=0;r<n;++r)t.push(this.decode_value(e.array.type));return t},e.prototype.decode_set=function(e){for(var t=this.decode_integer(`u32`),n=new Set,r=0;r<t;++r)n.add(this.decode_value(e.set));return n},e.prototype.decode_map=function(e){for(var t=this.decode_integer(`u32`),n=new Map,r=0;r<t;++r){var i=this.decode_value(e.map.key),a=this.decode_value(e.map.value);n.set(i,a)}return n},e.prototype.decode_struct=function(e){var t={};for(var n in e.struct)t[n]=this.decode_value(e.struct[n]);return t},e}(),new Uint8Array([75,69,77,0,16]),new Uint8Array([72,80,75,69,0,16,0,1,0,2]),new Uint8Array([72,80,75,69,45,118,49]),new Uint8Array([115,101,99,114,101,116]),new Uint8Array([101,97,101,95,112,114,107]),new Uint8Array([115,104,97,114,101,100,95,115,101,99,114,101,116]),new Uint8Array([0,32,72,80,75,69,45,118,49,72,80,75,69,0,16,0,1,0,2,107,101,121,0,143,195,174,184,50,73,10,75,90,179,228,32,35,40,125,178,154,31,75,199,194,34,192,223,34,135,39,183,10,64,33,18,47,63,4,233,32,108,209,36,19,80,53,41,180,122,198,166,48,185,46,196,207,125,35,69,8,208,175,151,113,201,158,80]),new Uint8Array([0,12,72,80,75,69,45,118,49,72,80,75,69,0,16,0,1,0,2,98,97,115,101,95,110,111,110,99,101,0,143,195,174,184,50,73,10,75,90,179,228,32,35,40,125,178,154,31,75,199,194,34,192,223,34,135,39,183,10,64,33,18,47,63,4,233,32,108,209,36,19,80,53,41,180,122,198,166,48,185,46,196,207,125,35,69,8,208,175,151,113,201,158,80]),new Uint8Array([113,111,115,95,101,110,99,114,121,112,116,105,111,110,95,104,109,97,99,95,109,101,115,115,97,103,101]);const Te=e=>{let t=a(e);if(t.length<2)throw Error(`failed to convert DER-encoded signature: insufficient length`);if(t[0]!==48)throw Error(`failed to convert DER-encoded signature: invalid format (missing SEQUENCE tag)`);let n=1,r=t[n];if(r<=127){if(t.length<2+r)throw Error(`failed to convert DER-encoded signature: inconsistent message length header`);n+=1}else throw Error(`failed to convert DER-encoded signature: unexpectedly large or invalid signature length`);if(t[n]!==2)throw Error(`failed to convert DER-encoded signature: invalid tag for r`);n++;let i=t[n];if(i>33)throw Error(`failed to convert DER-encoded signature: unexpected length for r`);n++;let s=t.slice(n,n+i);if(n+=i,t[n]!==2)throw Error(`failed to convert DER-encoded signature: invalid tag for s`);n++;let c=t[n];if(c>33)throw Error(`failed to convert DER-encoded signature: unexpected length for s`);n++;let l=t.slice(n,n+c),u=o(s,32),d=o(l,32);return new Uint8Array([...u,...d])};var Ee;(function(e){e.NOTARIZER=`notarizer`,e.SIGNER=`signer`,e.EVM_PARSER=`evm-parser`,e.TLS_FETCHER=`tls-fetcher`,e.UMP=`ump`})(Ee||={});var De=i(((e,t)=>{(function(e,n){var r=2**-24,i=2**32,a=2**53;function o(e){var t=new ArrayBuffer(256),r=new DataView(t),o,s=0;function c(e){for(var n=t.byteLength,i=s+e;n<i;)n*=2;if(n!==t.byteLength){var a=r;t=new ArrayBuffer(n),r=new DataView(t);for(var c=s+3>>2,l=0;l<c;++l)r.setUint32(l*4,a.getUint32(l*4))}return o=e,r}function l(){s+=o}function u(e){l(c(8).setFloat64(s,e))}function d(e){l(c(1).setUint8(s,e))}function f(e){for(var t=c(e.length),n=0;n<e.length;++n)t.setUint8(s+n,e[n]);l()}function p(e){l(c(2).setUint16(s,e))}function m(e){l(c(4).setUint32(s,e))}function h(e){var t=e%i,n=(e-t)/i,r=c(8);r.setUint32(s,n),r.setUint32(s+4,t),l()}function g(e,t){t<24?d(e<<5|t):t<256?(d(e<<5|24),d(t)):t<65536?(d(e<<5|25),p(t)):t<4294967296?(d(e<<5|26),m(t)):(d(e<<5|27),h(t))}function _(e){var t;if(e===!1)return d(244);if(e===!0)return d(245);if(e===null)return d(246);if(e===n)return d(247);switch(typeof e){case`number`:if(Math.floor(e)===e){if(0<=e&&e<=a)return g(0,e);if(-a<=e&&e<0)return g(1,-(e+1))}return d(251),u(e);case`string`:var r=[];for(t=0;t<e.length;++t){var i=e.charCodeAt(t);i<128?r.push(i):i<2048?(r.push(192|i>>6),r.push(128|i&63)):i<55296?(r.push(224|i>>12),r.push(128|i>>6&63),r.push(128|i&63)):(i=(i&1023)<<10,i|=e.charCodeAt(++t)&1023,i+=65536,r.push(240|i>>18),r.push(128|i>>12&63),r.push(128|i>>6&63),r.push(128|i&63))}return g(3,r.length),f(r);default:var o;if(Array.isArray(e))for(o=e.length,g(4,o),t=0;t<o;++t)_(e[t]);else if(e instanceof Uint8Array)g(2,e.length),f(e);else{var s=Object.keys(e);for(o=s.length,g(5,o),t=0;t<o;++t){var c=s[t];_(c),_(e[c])}}}}if(_(e),`slice`in t)return t.slice(0,s);for(var v=new ArrayBuffer(s),y=new DataView(v),b=0;b<s;++b)y.setUint8(b,r.getUint8(b));return v}function s(e,t,a){var o=new DataView(e),s=0;typeof t!=`function`&&(t=function(e){return e}),typeof a!=`function`&&(a=function(){return n});function c(e,t){return s+=t,e}function l(t){return c(new Uint8Array(e,s,t),t)}function u(){var e=new DataView(new ArrayBuffer(4)),t=m(),n=t&32768,i=t&31744,a=t&1023;if(i===31744)i=261120;else if(i!==0)i+=114688;else if(a!==0)return a*r;return e.setUint32(0,n<<16|i<<13|a<<13),e.getFloat32(0)}function d(){return c(o.getFloat32(s),4)}function f(){return c(o.getFloat64(s),8)}function p(){return c(o.getUint8(s),1)}function m(){return c(o.getUint16(s),2)}function h(){return c(o.getUint32(s),4)}function g(){return h()*i+h()}function _(){return o.getUint8(s)===255&&(s+=1,!0)}function v(e){if(e<24)return e;if(e===24)return p();if(e===25)return m();if(e===26)return h();if(e===27)return g();if(e===31)return-1;throw`Invalid length encoding`}function y(e){var t=p();if(t===255)return-1;var n=v(t&31);if(n<0||t>>5!==e)throw`Invalid indefinite length element`;return n}function b(e,t){for(var n=0;n<t;++n){var r=p();r&128&&(r<224?(r=(r&31)<<6|p()&63,--t):r<240?(r=(r&15)<<12|(p()&63)<<6|p()&63,t-=2):(r=(r&15)<<18|(p()&63)<<12|(p()&63)<<6|p()&63,t-=3)),r<65536?e.push(r):(r-=65536,e.push(55296|r>>10),e.push(56320|r&1023))}}function x(){var e=p(),r=e>>5,i=e&31,o,s;if(r===7)switch(i){case 25:return u();case 26:return d();case 27:return f()}if(s=v(i),s<0&&(r<2||6<r))throw`Invalid length`;switch(r){case 0:return s;case 1:return-1-s;case 2:if(s<0){for(var c=[],m=0;(s=y(r))>=0;)m+=s,c.push(l(s));var h=new Uint8Array(m),g=0;for(o=0;o<c.length;++o)h.set(c[o],g),g+=c[o].length;return h}return l(s);case 3:var S=[];if(s<0)for(;(s=y(r))>=0;)b(S,s);else b(S,s);return String.fromCharCode.apply(null,S);case 4:var C;if(s<0)for(C=[];!_();)C.push(x());else for(C=Array(s),o=0;o<s;++o)C[o]=x();return C;case 5:var w={};for(o=0;o<s||s<0&&!_();++o){var T=x();w[T]=x()}return w;case 6:return t(x(),s);case 7:switch(s){case 20:return!1;case 21:return!0;case 22:return null;case 23:return n;default:return a(s)}}}var S=x();if(s!==e.byteLength)throw`Remaining bytes`;return S}var c={encode:o,decode:s};typeof define==`function`&&define.amd?define(`cbor/cbor`,c):t!==void 0&&t.exports?t.exports=c:e.CBOR||=c})(e)})),Oe=i((()=>{
3
3
  /*! *****************************************************************************
4
4
  Copyright (C) Microsoft. All rights reserved.
5
5
  Licensed under the Apache License, Version 2.0 (the "License"); you may not use
@@ -132,10 +132,10 @@ Oe();var n=q(),r=Y(),i=st(),a=_r(),o=wr(),s=Pr(),c=(K(),t(B)),l=zi(),u=ra(),d=sa
132
132
  `).replace(/\\0d/gi,`\r`).replace(/\\0g/gi,` `).replace(/\\(.)/g,`$1`)}toArrayBuffer(){return n.AsnConvert.serialize(this.asn)}async getThumbprint(...e){let t,n=`SHA-1`;return e.length>=1&&!e[0]?.subtle?(n=e[0]||n,t=e[1]||z.get()):t=e[0]||z.get(),await t.subtle.digest(n,this.toArrayBuffer())}};let Ae=`Cannot initialize GeneralName from ASN.1 data.`,je=`${Ae} Unsupported string format in use.`,Me=`${Ae} Value doesn't match to GUID regular expression.`,Ne=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,Pe=`1.3.6.1.4.1.311.25.1`,Fe=`1.3.6.1.4.1.311.20.2.3`,Ie=`email`,Le=`guid`;var Re=class extends ye{constructor(...e){let t;if(e.length===2)switch(e[0]){case`dn`:{let r=new V(e[1]).toArrayBuffer(),i=n.AsnConvert.parse(r,p.Name);t=new p.GeneralName({directoryName:i});break}case`dns`:t=new p.GeneralName({dNSName:e[1]});break;case Ie:t=new p.GeneralName({rfc822Name:e[1]});break;case Le:{let r=new RegExp(Ne,`i`).exec(e[1]);if(!r)throw Error(`Cannot parse GUID value. Value doesn't match to regular expression`);let a=r.slice(1).map((e,t)=>t<3?i.Convert.ToHex(new Uint8Array(i.Convert.FromHex(e)).reverse()):e).join(``);t=new p.GeneralName({otherName:new p.OtherName({typeId:Pe,value:n.AsnConvert.serialize(new n.OctetString(i.Convert.FromHex(a)))})});break}case`ip`:t=new p.GeneralName({iPAddress:e[1]});break;case`id`:t=new p.GeneralName({registeredID:e[1]});break;case`upn`:t=new p.GeneralName({otherName:new p.OtherName({typeId:Fe,value:n.AsnConvert.serialize(n.AsnUtf8StringConverter.toASN(e[1]))})});break;case`url`:t=new p.GeneralName({uniformResourceIdentifier:e[1]});break;default:throw Error(`Cannot create GeneralName. Unsupported type of the name`)}else t=i.BufferSourceConverter.isBufferSource(e[0])?n.AsnConvert.parse(e[0],p.GeneralName):e[0];super(t)}onInit(e){if(e.dNSName!=null)this.type=`dns`,this.value=e.dNSName;else if(e.rfc822Name!=null)this.type=Ie,this.value=e.rfc822Name;else if(e.iPAddress!=null)this.type=`ip`,this.value=e.iPAddress;else if(e.uniformResourceIdentifier!=null)this.type=`url`,this.value=e.uniformResourceIdentifier;else if(e.registeredID!=null)this.type=`id`,this.value=e.registeredID;else if(e.directoryName!=null)this.type=`dn`,this.value=new V(e.directoryName).toString();else if(e.otherName!=null){if(e.otherName.typeId===Pe){this.type=Le;let t=n.AsnConvert.parse(e.otherName.value,n.OctetString),r=new RegExp(Ne,`i`).exec(i.Convert.ToHex(t));if(!r)throw Error(Me);this.value=r.slice(1).map((e,t)=>t<3?i.Convert.ToHex(new Uint8Array(i.Convert.FromHex(e)).reverse()):e).join(`-`)}else if(e.otherName.typeId===Fe)this.type=`upn`,this.value=n.AsnConvert.parse(e.otherName.value,p.DirectoryString).toString();else throw Error(je)}else throw Error(je)}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let e;switch(this.type){case`dn`:case`dns`:case Le:case`ip`:case`id`:case`upn`:case`url`:e=this.type.toUpperCase();break;case Ie:e=`Email`;break;default:throw Error(`Unsupported GeneralName type`)}let t=this.value;return this.type===`id`&&(t=R.toString(t)),new L(e,void 0,t)}},ze=class extends ye{constructor(e){let t;if(e instanceof p.GeneralNames)t=e;else if(Array.isArray(e)){let r=[];for(let t of e)if(t instanceof p.GeneralName)r.push(t);else{let e=n.AsnConvert.parse(new Re(t.type,t.value).rawData,p.GeneralName);r.push(e)}t=new p.GeneralNames(r)}else if(i.BufferSourceConverter.isBufferSource(e))t=n.AsnConvert.parse(e,p.GeneralNames);else throw Error(`Cannot initialize GeneralNames. Incorrect incoming arguments`);super(t)}onInit(e){let t=[];for(let n of e){let e=null;try{e=new Re(n)}catch{continue}t.push(e)}this.items=t}toJSON(){return this.items.map(e=>e.toJSON())}toTextObject(){let e=super.toTextObjectEmpty();for(let t of this.items){let n=t.toTextObject(),r=e[n[L.NAME]];Array.isArray(r)||(r=[],e[n[L.NAME]]=r),r.push(n)}return e}};ze.NAME=`GeneralNames`;let H=`-{5}`,Be=`${`${H}BEGIN ([^\\n]+(?=${H}))${H}`}\\n(?:((?:[^:\\n]+: (?:[^\\n]+\\n(?: +[^\\n]+\\n)*))+))?\\n?((?:[a-zA-Z0-9=+/]+\\n)+)${`${H}END \\1${H}`}`;var U=class{static isPem(e){return typeof e==`string`&&new RegExp(Be,`g`).test(e)}static decodeWithHeaders(e){e=e.replace(/\r/g,``);let t=new RegExp(Be,`g`),n=[],r=null;for(;r=t.exec(e);){let e=r[3].replace(RegExp(`[\\n]+`,`g`),``),t={type:r[1],headers:[],rawData:i.Convert.FromBase64(e)},a=r[2];if(a){let e=a.split(RegExp(`\\n`,`g`)),n=null;for(let r of e){let[e,i]=r.split(/:(.*)/);if(i===void 0){if(!n)throw Error(`Cannot parse PEM string. Incorrect header value`);n.value+=e.trim()}else n&&t.headers.push(n),n={key:e,value:i.trim()}}n&&t.headers.push(n)}n.push(t)}return n}static decode(e){return this.decodeWithHeaders(e).map(e=>e.rawData)}static decodeFirst(e){let t=this.decode(e);if(!t.length)throw RangeError(`PEM string doesn't contain any objects`);return t[0]}static encode(e,t){if(Array.isArray(e)){let n=[];return t?e.forEach(e=>{if(!i.BufferSourceConverter.isBufferSource(e))throw TypeError(`Cannot encode array of BufferSource in PEM format. Not all items of the array are BufferSource`);n.push(this.encodeStruct({type:t,rawData:i.BufferSourceConverter.toArrayBuffer(e)}))}):e.forEach(e=>{if(!(`type`in e))throw TypeError(`Cannot encode array of PemStruct in PEM format. Not all items of the array are PemStrut`);n.push(this.encodeStruct(e))}),n.join(`
133
133
  `)}if(!t)throw Error(`Required argument 'tag' is missed`);return this.encodeStruct({type:t,rawData:i.BufferSourceConverter.toArrayBuffer(e)})}static encodeStruct(e){let t=e.type.toLocaleUpperCase(),n=[];if(n.push(`-----BEGIN ${t}-----`),e.headers?.length){for(let t of e.headers)n.push(`${t.key}: ${t.value}`);n.push(``)}let r=i.Convert.ToBase64(e.rawData),a,o=0,s=[];for(;o<r.length&&(r.length-o<64?a=r.substring(o):(a=r.substring(o,o+64),o+=64),a.length!==0)&&(s.push(a),!(a.length<64)););return n.push(...s),n.push(`-----END ${t}-----`),n.join(`
134
134
  `)}};U.CertificateTag=`CERTIFICATE`,U.CrlTag=`CRL`,U.CertificateRequestTag=`CERTIFICATE REQUEST`,U.PublicKeyTag=`PUBLIC KEY`,U.PrivateKeyTag=`PRIVATE KEY`;var W=class e extends ye{static isAsnEncoded(e){return i.BufferSourceConverter.isBufferSource(e)||typeof e==`string`}static toArrayBuffer(e){if(typeof e==`string`){if(U.isPem(e))return U.decode(e)[0];if(i.Convert.isHex(e))return i.Convert.FromHex(e);if(i.Convert.isBase64(e))return i.Convert.FromBase64(e);if(i.Convert.isBase64Url(e))return i.Convert.FromBase64Url(e);throw TypeError(`Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url`)}{let t=i.Convert.ToBinary(e);return U.isPem(t)?U.decode(t)[0]:i.Convert.isHex(t)?i.Convert.FromHex(t):i.Convert.isBase64(t)?i.Convert.FromBase64(t):i.Convert.isBase64Url(t)?i.Convert.FromBase64Url(t):i.BufferSourceConverter.toArrayBuffer(e)}}constructor(...t){e.isAsnEncoded(t[0])?super(e.toArrayBuffer(t[0]),t[1]):super(t[0])}toString(e=`pem`){switch(e){case`pem`:return U.encode(this.rawData,this.tag);default:return super.toString(e)}}},Ve=class e extends W{static async create(t,n=z.get()){if(t instanceof e)return t;if(Se.isCryptoKey(t)){if(t.type!==`public`)throw TypeError(`Public key is required`);let r=await n.subtle.exportKey(`spki`,t);return new e(r)}if(t.publicKey)return t.publicKey;if(i.BufferSourceConverter.isBufferSource(t))return new e(t);throw TypeError(`Unsupported PublicKeyType`)}constructor(e){W.isAsnEncoded(e)?super(e,r.SubjectPublicKeyInfo):super(e),this.tag=U.PublicKeyTag}async export(...e){let t,i=[`verify`],a={hash:`SHA-256`,...this.algorithm};e.length>1?(a=e[0]||a,i=e[1]||i,t=e[2]||z.get()):t=e[0]||z.get();let o=this.rawData,c=n.AsnConvert.parse(this.rawData,r.SubjectPublicKeyInfo);return c.algorithm.algorithm===s.id_RSASSA_PSS&&(o=He(c,o)),t.subtle.importKey(`spki`,o,a,!0,i)}onInit(e){let t=l.container.resolve(b),r=this.algorithm=t.toWebAlgorithm(e.algorithm);switch(e.algorithm.algorithm){case s.id_rsaEncryption:{let t=n.AsnConvert.parse(e.subjectPublicKey,s.RSAPublicKey),a=i.BufferSourceConverter.toUint8Array(t.modulus);r.publicExponent=i.BufferSourceConverter.toUint8Array(t.publicExponent),r.modulusLength=(a[0]?a:a.slice(1)).byteLength<<3;break}}}async getThumbprint(...e){let t,n=`SHA-1`;return e.length>=1&&!e[0]?.subtle?(n=e[0]||n,t=e[1]||z.get()):t=e[0]||z.get(),await t.subtle.digest(n,this.rawData)}async getKeyIdentifier(...e){let t,i=`SHA-1`;e.length===1?typeof e[0]==`string`?(i=e[0],t=z.get()):t=e[0]:e.length===2?(i=e[0],t=e[1]):t=z.get();let a=n.AsnConvert.parse(this.rawData,r.SubjectPublicKeyInfo);return await t.subtle.digest(i,a.subjectPublicKey)}toTextObject(){let e=this.toTextObjectEmpty(),t=n.AsnConvert.parse(this.rawData,r.SubjectPublicKeyInfo);switch(e.Algorithm=ve.serializeAlgorithm(t.algorithm),t.algorithm.algorithm){case o.id_ecPublicKey:e[`EC Point`]=t.subjectPublicKey;break;case s.id_rsaEncryption:default:e[`Raw Data`]=t.subjectPublicKey}return e}};function He(e,t){return e.algorithm=new r.AlgorithmIdentifier({algorithm:s.id_rsaEncryption,parameters:null}),t=n.AsnConvert.serialize(e),t}var Ue=class e extends be{static async create(t,n=!1,r=z.get()){if(`name`in t&&`serialNumber`in t)return new e(t,n);let a=await(await Ve.create(t,r)).getKeyIdentifier(r);return new e(i.Convert.ToHex(a),n)}constructor(...e){if(i.BufferSourceConverter.isBufferSource(e[0]))super(e[0]);else if(typeof e[0]==`string`){let t=new p.AuthorityKeyIdentifier({keyIdentifier:new p.KeyIdentifier(i.Convert.FromHex(e[0]))});super(p.id_ce_authorityKeyIdentifier,e[1],n.AsnConvert.serialize(t))}else{let t=e[0],r=t.name instanceof ze?n.AsnConvert.parse(t.name.rawData,p.GeneralNames):t.name,a=new p.AuthorityKeyIdentifier({authorityCertIssuer:r,authorityCertSerialNumber:i.Convert.FromHex(t.serialNumber)});super(p.id_ce_authorityKeyIdentifier,e[1],n.AsnConvert.serialize(a))}}onInit(e){super.onInit(e);let t=n.AsnConvert.parse(e.extnValue,p.AuthorityKeyIdentifier);t.keyIdentifier&&(this.keyId=i.Convert.ToHex(t.keyIdentifier)),(t.authorityCertIssuer||t.authorityCertSerialNumber)&&(this.certId={name:t.authorityCertIssuer||[],serialNumber:t.authorityCertSerialNumber?i.Convert.ToHex(t.authorityCertSerialNumber):``})}toTextObject(){let e=this.toTextObjectWithoutValue(),t=n.AsnConvert.parse(this.value,p.AuthorityKeyIdentifier);return t.authorityCertIssuer&&(e[`Authority Issuer`]=new ze(t.authorityCertIssuer).toTextObject()),t.authorityCertSerialNumber&&(e[`Authority Serial Number`]=t.authorityCertSerialNumber),t.keyIdentifier&&(e[``]=t.keyIdentifier),e}};Ue.NAME=`Authority Key Identifier`;var We=class extends be{constructor(...e){if(i.BufferSourceConverter.isBufferSource(e[0])){super(e[0]);let t=n.AsnConvert.parse(this.value,r.BasicConstraints);this.ca=t.cA,this.pathLength=t.pathLenConstraint}else{let t=new r.BasicConstraints({cA:e[0],pathLenConstraint:e[1]});super(r.id_ce_basicConstraints,e[2],n.AsnConvert.serialize(t)),this.ca=e[0],this.pathLength=e[1]}}toTextObject(){let e=this.toTextObjectWithoutValue();return this.ca&&(e.CA=this.ca),this.pathLength!==void 0&&(e[`Path Length`]=this.pathLength),e}};We.NAME=`Basic Constraints`,e.ExtendedKeyUsage=void 0,(function(e){e.serverAuth=`1.3.6.1.5.5.7.3.1`,e.clientAuth=`1.3.6.1.5.5.7.3.2`,e.codeSigning=`1.3.6.1.5.5.7.3.3`,e.emailProtection=`1.3.6.1.5.5.7.3.4`,e.timeStamping=`1.3.6.1.5.5.7.3.8`,e.ocspSigning=`1.3.6.1.5.5.7.3.9`})(e.ExtendedKeyUsage||={});var Ge=class extends be{constructor(...e){if(i.BufferSourceConverter.isBufferSource(e[0])){super(e[0]);let t=n.AsnConvert.parse(this.value,p.ExtendedKeyUsage);this.usages=t.map(e=>e)}else{let t=new p.ExtendedKeyUsage(e[0]);super(p.id_ce_extKeyUsage,e[1],n.AsnConvert.serialize(t)),this.usages=e[0]}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[``]=this.usages.map(e=>R.toString(e)).join(`, `),e}};Ge.NAME=`Extended Key Usages`,e.KeyUsageFlags=void 0,(function(e){e[e.digitalSignature=1]=`digitalSignature`,e[e.nonRepudiation=2]=`nonRepudiation`,e[e.keyEncipherment=4]=`keyEncipherment`,e[e.dataEncipherment=8]=`dataEncipherment`,e[e.keyAgreement=16]=`keyAgreement`,e[e.keyCertSign=32]=`keyCertSign`,e[e.cRLSign=64]=`cRLSign`,e[e.encipherOnly=128]=`encipherOnly`,e[e.decipherOnly=256]=`decipherOnly`})(e.KeyUsageFlags||={});var Ke=class extends be{constructor(...e){if(i.BufferSourceConverter.isBufferSource(e[0])){super(e[0]);let t=n.AsnConvert.parse(this.value,r.KeyUsage);this.usages=t.toNumber()}else{let t=new r.KeyUsage(e[0]);super(r.id_ce_keyUsage,e[1],n.AsnConvert.serialize(t)),this.usages=e[0]}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[``]=n.AsnConvert.parse(this.value,r.KeyUsage).toJSON().join(`, `),e}};Ke.NAME=`Key Usages`;var qe=class e extends be{static async create(t,n=!1,r=z.get()){let a=await(await Ve.create(t,r)).getKeyIdentifier(r);return new e(i.Convert.ToHex(a),n)}constructor(...e){if(i.BufferSourceConverter.isBufferSource(e[0])){super(e[0]);let t=n.AsnConvert.parse(this.value,p.SubjectKeyIdentifier);this.keyId=i.Convert.ToHex(t)}else{let t=typeof e[0]==`string`?i.Convert.FromHex(e[0]):e[0],r=new p.SubjectKeyIdentifier(t);super(p.id_ce_subjectKeyIdentifier,e[1],n.AsnConvert.serialize(r)),this.keyId=i.Convert.ToHex(t)}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[``]=n.AsnConvert.parse(this.value,p.SubjectKeyIdentifier),e}};qe.NAME=`Subject Key Identifier`;var Je=class extends be{constructor(...e){i.BufferSourceConverter.isBufferSource(e[0])?super(e[0]):super(p.id_ce_subjectAltName,e[1],new ze(e[0]||[]).rawData)}onInit(e){super.onInit(e);let t=n.AsnConvert.parse(e.extnValue,p.SubjectAlternativeName);this.names=new ze(t)}toTextObject(){let e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(let n in t)e[n]=t[n];return e}};Je.NAME=`Subject Alternative Name`;var G=class{static register(e,t){this.items.set(e,t)}static create(e){let t=new be(e),n=this.items.get(t.type);return n?new n(e):t}};G.items=new Map;var Ye=class extends be{constructor(...e){if(i.BufferSourceConverter.isBufferSource(e[0])){super(e[0]);let t=n.AsnConvert.parse(this.value,p.CertificatePolicies);this.policies=t.map(e=>e.policyIdentifier)}else{let t=e[0],r=e[1]??!1,i=new p.CertificatePolicies(t.map(e=>new p.PolicyInformation({policyIdentifier:e})));super(p.id_ce_certificatePolicies,r,n.AsnConvert.serialize(i)),this.policies=t}}toTextObject(){let e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map(e=>new L(``,{},R.toString(e))),e}};Ye.NAME=`Certificate Policies`,G.register(p.id_ce_certificatePolicies,Ye);var Xe=class extends be{constructor(...e){if(i.BufferSourceConverter.isBufferSource(e[0]))super(e[0]);else if(Array.isArray(e[0])&&typeof e[0][0]==`string`){let t=e[0].map(e=>new p.DistributionPoint({distributionPoint:new p.DistributionPointName({fullName:[new p.GeneralName({uniformResourceIdentifier:e})]})})),r=new p.CRLDistributionPoints(t);super(p.id_ce_cRLDistributionPoints,e[1],n.AsnConvert.serialize(r))}else{let t=new p.CRLDistributionPoints(e[0]);super(p.id_ce_cRLDistributionPoints,e[1],n.AsnConvert.serialize(t))}this.distributionPoints??=[]}onInit(e){super.onInit(e);let t=n.AsnConvert.parse(e.extnValue,p.CRLDistributionPoints);this.distributionPoints=t}toTextObject(){let e=this.toTextObjectWithoutValue();return e[`Distribution Point`]=this.distributionPoints.map(e=>{let t={};return e.distributionPoint&&(t[``]=e.distributionPoint.fullName?.map(e=>new Re(e).toString()).join(`, `)),e.reasons&&(t.Reasons=e.reasons.toString()),e.cRLIssuer&&(t[`CRL Issuer`]=e.cRLIssuer.map(e=>e.toString()).join(`, `)),t}),e}};Xe.NAME=`CRL Distribution Points`;var Ze=class extends be{constructor(...e){if(i.BufferSourceConverter.isBufferSource(e[0]))super(e[0]);else if(e[0]instanceof p.AuthorityInfoAccessSyntax){let t=new p.AuthorityInfoAccessSyntax(e[0]);super(p.id_pe_authorityInfoAccess,e[1],n.AsnConvert.serialize(t))}else{let t=e[0],r=new p.AuthorityInfoAccessSyntax;$e(r,t,p.id_ad_ocsp,`ocsp`),$e(r,t,p.id_ad_caIssuers,`caIssuers`),$e(r,t,p.id_ad_timeStamping,`timeStamping`),$e(r,t,p.id_ad_caRepository,`caRepository`),super(p.id_pe_authorityInfoAccess,e[1],n.AsnConvert.serialize(r))}this.ocsp??=[],this.caIssuers??=[],this.timeStamping??=[],this.caRepository??=[]}onInit(e){super.onInit(e),this.ocsp=[],this.caIssuers=[],this.timeStamping=[],this.caRepository=[],n.AsnConvert.parse(e.extnValue,p.AuthorityInfoAccessSyntax).forEach(e=>{switch(e.accessMethod){case p.id_ad_ocsp:this.ocsp.push(new Re(e.accessLocation));break;case p.id_ad_caIssuers:this.caIssuers.push(new Re(e.accessLocation));break;case p.id_ad_timeStamping:this.timeStamping.push(new Re(e.accessLocation));break;case p.id_ad_caRepository:this.caRepository.push(new Re(e.accessLocation))}})}toTextObject(){let e=this.toTextObjectWithoutValue();return this.ocsp.length&&Qe(e,`OCSP`,this.ocsp),this.caIssuers.length&&Qe(e,`CA Issuers`,this.caIssuers),this.timeStamping.length&&Qe(e,`Time Stamping`,this.timeStamping),this.caRepository.length&&Qe(e,`CA Repository`,this.caRepository),e}};Ze.NAME=`Authority Info Access`;function Qe(e,t,n){if(n.length===1)e[t]=n[0].toTextObject();else{let r=new L(``);n.forEach((e,t)=>{let n=e.toTextObject(),i=`${n[L.NAME]} ${t+1}`,a=r[i];Array.isArray(a)||(a=[],r[i]=a),a.push(n)}),e[t]=r}}function $e(e,t,r,i){let a=t[i];a&&(Array.isArray(a)?a:[a]).forEach(t=>{typeof t==`string`&&(t=new Re(`url`,t)),e.push(new p.AccessDescription({accessMethod:r,accessLocation:n.AsnConvert.parse(t.rawData,p.GeneralName)}))})}var et=class e extends ye{constructor(...e){let t;if(i.BufferSourceConverter.isBufferSource(e[0]))t=i.BufferSourceConverter.toArrayBuffer(e[0]);else{let a=e[0],o=Array.isArray(e[1])?e[1].map(e=>i.BufferSourceConverter.toArrayBuffer(e)):[];t=n.AsnConvert.serialize(new r.Attribute({type:a,values:o}))}super(t,r.Attribute)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){let e=this.toTextObjectWithoutValue();return e.Value=this.values.map(e=>new L(``,{"":e})),e}toTextObjectWithoutValue(){let t=this.toTextObjectEmpty();return t[L.NAME]===e.NAME&&(t[L.NAME]=R.toString(this.type)),t}};et.NAME=`Attribute`;var tt=class extends et{constructor(...e){if(i.BufferSourceConverter.isBufferSource(e[0]))super(e[0]);else{let t=new _.ChallengePassword({printableString:e[0]});super(_.id_pkcs9_at_challengePassword,[n.AsnConvert.serialize(t)])}this.password??=``}onInit(e){if(super.onInit(e),this.values[0]){let e=n.AsnConvert.parse(this.values[0],_.ChallengePassword);this.password=e.toString()}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[L.VALUE]=this.password,e}};tt.NAME=`Challenge Password`;var nt=class extends et{constructor(...e){if(i.BufferSourceConverter.isBufferSource(e[0]))super(e[0]);else{let t=e[0],r=new p.Extensions;for(let e of t)r.push(n.AsnConvert.parse(e.rawData,p.Extension));super(_.id_pkcs9_at_extensionRequest,[n.AsnConvert.serialize(r)])}this.items??=[]}onInit(e){if(super.onInit(e),this.values[0]){let e=n.AsnConvert.parse(this.values[0],p.Extensions);this.items=e.map(e=>G.create(n.AsnConvert.serialize(e)))}}toTextObject(){let e=this.toTextObjectWithoutValue(),t=this.items.map(e=>e.toTextObject());for(let n of t)e[n[L.NAME]]=n;return e}};nt.NAME=`Extensions`;var rt=class{static register(e,t){this.items.set(e,t)}static create(e){let t=new et(e),n=this.items.get(t.type);return n?new n(e):t}};rt.items=new Map;let it=`crypto.signatureFormatter`;var at=class{toAsnSignature(e,t){return i.BufferSourceConverter.toArrayBuffer(t)}toWebSignature(e,t){return i.BufferSourceConverter.toArrayBuffer(t)}},ot;e.RsaAlgorithm=ot=class{static createPssParams(e,t){let i=ot.getHashAlgorithm(e);return i?new g.RsaSaPssParams({hashAlgorithm:i,maskGenAlgorithm:new r.AlgorithmIdentifier({algorithm:g.id_mgf1,parameters:n.AsnConvert.serialize(i)}),saltLength:t}):null}static getHashAlgorithm(e){let t=l.container.resolve(b);return typeof e==`string`?t.toAsnAlgorithm({name:e}):typeof e==`object`&&e&&`name`in e?t.toAsnAlgorithm(e):null}toAsnAlgorithm(e){switch(e.name.toLowerCase()){case`rsassa-pkcs1-v1_5`:if(`hash`in e){let t;if(typeof e.hash==`string`)t=e.hash;else if(e.hash&&typeof e.hash==`object`&&`name`in e.hash&&typeof e.hash.name==`string`)t=e.hash.name.toUpperCase();else throw Error(`Cannot get hash algorithm name`);switch(t.toLowerCase()){case`sha-1`:return new r.AlgorithmIdentifier({algorithm:g.id_sha1WithRSAEncryption,parameters:null});case`sha-256`:return new r.AlgorithmIdentifier({algorithm:g.id_sha256WithRSAEncryption,parameters:null});case`sha-384`:return new r.AlgorithmIdentifier({algorithm:g.id_sha384WithRSAEncryption,parameters:null});case`sha-512`:return new r.AlgorithmIdentifier({algorithm:g.id_sha512WithRSAEncryption,parameters:null})}}else return new r.AlgorithmIdentifier({algorithm:g.id_rsaEncryption,parameters:null});break;case`rsa-pss`:if(`hash`in e){if(!(`saltLength`in e&&typeof e.saltLength==`number`))throw Error(`Cannot get 'saltLength' from 'alg' argument`);let t=ot.createPssParams(e.hash,e.saltLength);if(!t)throw Error(`Cannot create PSS parameters`);return new r.AlgorithmIdentifier({algorithm:g.id_RSASSA_PSS,parameters:n.AsnConvert.serialize(t)})}return new r.AlgorithmIdentifier({algorithm:g.id_RSASSA_PSS,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case g.id_rsaEncryption:return{name:`RSASSA-PKCS1-v1_5`};case g.id_sha1WithRSAEncryption:return{name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-1`}};case g.id_sha256WithRSAEncryption:return{name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-256`}};case g.id_sha384WithRSAEncryption:return{name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-384`}};case g.id_sha512WithRSAEncryption:return{name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-512`}};case g.id_RSASSA_PSS:if(e.parameters){let t=n.AsnConvert.parse(e.parameters,g.RsaSaPssParams);return{name:`RSA-PSS`,hash:l.container.resolve(b).toWebAlgorithm(t.hashAlgorithm),saltLength:t.saltLength}}return{name:`RSA-PSS`}}return null}},e.RsaAlgorithm=ot=c.__decorate([l.injectable()],e.RsaAlgorithm),l.container.registerSingleton(v,e.RsaAlgorithm),e.ShaAlgorithm=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case`sha-1`:return new r.AlgorithmIdentifier({algorithm:s.id_sha1});case`sha-256`:return new r.AlgorithmIdentifier({algorithm:s.id_sha256});case`sha-384`:return new r.AlgorithmIdentifier({algorithm:s.id_sha384});case`sha-512`:return new r.AlgorithmIdentifier({algorithm:s.id_sha512})}return null}toWebAlgorithm(e){switch(e.algorithm){case s.id_sha1:return{name:`SHA-1`};case s.id_sha256:return{name:`SHA-256`};case s.id_sha384:return{name:`SHA-384`};case s.id_sha512:return{name:`SHA-512`}}return null}},e.ShaAlgorithm=c.__decorate([l.injectable()],e.ShaAlgorithm),l.container.registerSingleton(v,e.ShaAlgorithm);var ct=class e{addPadding(e,t){let n=i.BufferSourceConverter.toUint8Array(t),r=new Uint8Array(e);return r.set(n,e-n.length),r}removePadding(e,t=!1){let n=i.BufferSourceConverter.toUint8Array(e);for(let e=0;e<n.length;e++)if(n[e]){n=n.slice(e);break}if(t&&n[0]>127){let e=new Uint8Array(n.length+1);return e.set(n,1),e.buffer}return n.buffer}toAsnSignature(t,r){if(t.name===`ECDSA`){let a=t.namedCurve,s=e.namedCurveSize.get(a)||e.defaultNamedCurveSize,c=new o.ECDSASigValue,l=i.BufferSourceConverter.toUint8Array(r);return c.r=this.removePadding(l.slice(0,s),!0),c.s=this.removePadding(l.slice(s,s+s),!0),n.AsnConvert.serialize(c)}return null}toWebSignature(t,r){if(t.name===`ECDSA`){let a=n.AsnConvert.parse(r,o.ECDSASigValue),s=t.namedCurve,c=e.namedCurveSize.get(s)||e.defaultNamedCurveSize,l=this.addPadding(c,this.removePadding(a.r)),u=this.addPadding(c,this.removePadding(a.s));return i.combine(l,u)}return null}};ct.namedCurveSize=new Map,ct.defaultNamedCurveSize=32;let lt=`1.3.101.110`,ut=`1.3.101.111`,dt=`1.3.101.112`,ft=`1.3.101.113`;e.EdAlgorithm=class{toAsnAlgorithm(e){let t=null;switch(e.name.toLowerCase()){case`ed25519`:t=dt;break;case`x25519`:t=lt;break;case`eddsa`:switch(e.namedCurve.toLowerCase()){case`ed25519`:t=dt;break;case`ed448`:t=ft}break;case`ecdh-es`:switch(e.namedCurve.toLowerCase()){case`x25519`:t=lt;break;case`x448`:t=ut}}return t?new r.AlgorithmIdentifier({algorithm:t}):null}toWebAlgorithm(e){switch(e.algorithm){case dt:return{name:`Ed25519`};case ft:return{name:`EdDSA`,namedCurve:`Ed448`};case lt:return{name:`X25519`};case ut:return{name:`ECDH-ES`,namedCurve:`X448`}}return null}},e.EdAlgorithm=c.__decorate([l.injectable()],e.EdAlgorithm),l.container.registerSingleton(v,e.EdAlgorithm);var pt=class extends W{constructor(e){W.isAsnEncoded(e)?super(e,d.CertificationRequest):super(e),this.tag=U.CertificateRequestTag}onInit(e){this.tbs=n.AsnConvert.serialize(e.certificationRequestInfo),this.publicKey=new Ve(e.certificationRequestInfo.subjectPKInfo);let t=l.container.resolve(b);this.signatureAlgorithm=t.toWebAlgorithm(e.signatureAlgorithm),this.signature=e.signature,this.attributes=e.certificationRequestInfo.attributes.map(e=>rt.create(n.AsnConvert.serialize(e)));let r=this.getAttribute(u.id_pkcs9_at_extensionRequest);this.extensions=[],r instanceof nt&&(this.extensions=r.items),this.subjectName=new V(e.certificationRequestInfo.subject),this.subject=this.subjectName.toString()}getAttribute(e){for(let t of this.attributes)if(t.type===e)return t;return null}getAttributes(e){return this.attributes.filter(t=>t.type===e)}getExtension(e){for(let t of this.extensions)if(t.type===e)return t;return null}getExtensions(e){return this.extensions.filter(t=>t.type===e)}async verify(e=z.get()){let t={...this.publicKey.algorithm,...this.signatureAlgorithm},n=await this.publicKey.export(t,[`verify`],e),r=l.container.resolveAll(it).reverse(),i=null;for(let e of r)if(i=e.toWebSignature(t,this.signature),i)break;if(!i)throw Error(`Cannot convert WebCrypto signature value to ASN.1 format`);return await e.subtle.verify(this.signatureAlgorithm,n,i,this.tbs)}toTextObject(){let e=this.toTextObjectEmpty(),t=n.AsnConvert.parse(this.rawData,d.CertificationRequest),i=t.certificationRequestInfo,a=new L(``,{Version:`${r.Version[i.version]} (${i.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){let e=new L(``);for(let t of this.attributes){let n=t.toTextObject();e[n[L.NAME]]=n}a.Attributes=e}return e.Data=a,e.Signature=new L(``,{Algorithm:ve.serializeAlgorithm(t.signatureAlgorithm),"":t.signature}),e}};pt.NAME=`PKCS#10 Certificate Request`;var mt=class{static async create(e,t=z.get()){if(!e.keys.privateKey)throw Error(`Bad field 'keys' in 'params' argument. 'privateKey' is empty`);if(!e.keys.publicKey)throw Error(`Bad field 'keys' in 'params' argument. 'publicKey' is empty`);let i=await t.subtle.exportKey(`spki`,e.keys.publicKey),a=new d.CertificationRequest({certificationRequestInfo:new d.CertificationRequestInfo({subjectPKInfo:n.AsnConvert.parse(i,r.SubjectPublicKeyInfo)})});if(e.name){let t=e.name instanceof V?e.name:new V(e.name);a.certificationRequestInfo.subject=n.AsnConvert.parse(t.toArrayBuffer(),r.Name)}if(e.attributes)for(let t of e.attributes)a.certificationRequestInfo.attributes.push(n.AsnConvert.parse(t.rawData,r.Attribute));if(e.extensions&&e.extensions.length){let t=new r.Attribute({type:u.id_pkcs9_at_extensionRequest}),i=new r.Extensions;for(let t of e.extensions)i.push(n.AsnConvert.parse(t.rawData,r.Extension));t.values.push(n.AsnConvert.serialize(i)),a.certificationRequestInfo.attributes.push(t)}let o={...e.signingAlgorithm,...e.keys.privateKey.algorithm};a.signatureAlgorithm=l.container.resolve(b).toAsnAlgorithm(o);let s=n.AsnConvert.serialize(a.certificationRequestInfo),c=await t.subtle.sign(o,e.keys.privateKey,s),f=l.container.resolveAll(it).reverse(),p=null;for(let e of f)if(p=e.toAsnSignature(o,c),p)break;if(!p)throw Error(`Cannot convert WebCrypto signature value to ASN.1 format`);return a.signature=p,new pt(n.AsnConvert.serialize(a))}},ht=class extends W{constructor(e){W.isAsnEncoded(e)?super(e,r.Certificate):super(e),this.tag=U.CertificateTag}onInit(e){let t=e.tbsCertificate;this.tbs=n.AsnConvert.serialize(t),this.serialNumber=i.Convert.ToHex(t.serialNumber),this.subjectName=new V(t.subject),this.subject=new V(t.subject).toString(),this.issuerName=new V(t.issuer),this.issuer=this.issuerName.toString();let r=l.container.resolve(b);this.signatureAlgorithm=r.toWebAlgorithm(e.signatureAlgorithm),this.signature=e.signatureValue;let a=t.validity.notBefore.utcTime||t.validity.notBefore.generalTime;if(!a)throw Error(`Cannot get 'notBefore' value`);this.notBefore=a;let o=t.validity.notAfter.utcTime||t.validity.notAfter.generalTime;if(!o)throw Error(`Cannot get 'notAfter' value`);this.notAfter=o,this.extensions=[],t.extensions&&(this.extensions=t.extensions.map(e=>G.create(n.AsnConvert.serialize(e)))),this.publicKey=new Ve(t.subjectPublicKeyInfo)}getExtension(e){for(let t of this.extensions)if(typeof e==`string`){if(t.type===e)return t}else if(t instanceof e)return t;return null}getExtensions(e){return this.extensions.filter(t=>typeof e==`string`?t.type===e:t instanceof e)}async verify(e={},t=z.get()){let n,r,a=e.publicKey;try{if(!a)n={...this.publicKey.algorithm,...this.signatureAlgorithm},r=await this.publicKey.export(n,[`verify`],t);else if(`publicKey`in a)n={...a.publicKey.algorithm,...this.signatureAlgorithm},r=await a.publicKey.export(n,[`verify`],t);else if(a instanceof Ve)n={...a.algorithm,...this.signatureAlgorithm},r=await a.export(n,[`verify`],t);else if(i.BufferSourceConverter.isBufferSource(a)){let e=new Ve(a);n={...e.algorithm,...this.signatureAlgorithm},r=await e.export(n,[`verify`],t)}else n={...a.algorithm,...this.signatureAlgorithm},r=a}catch{return!1}let o=l.container.resolveAll(it).reverse(),s=null;for(let e of o)if(s=e.toWebSignature(n,this.signature),s)break;if(!s)throw Error(`Cannot convert ASN.1 signature value to WebCrypto format`);let c=await t.subtle.verify(this.signatureAlgorithm,r,s,this.tbs);if(e.signatureOnly)return c;{let t=(e.date||new Date).getTime();return c&&this.notBefore.getTime()<t&&t<this.notAfter.getTime()}}async getThumbprint(...e){let t,n=`SHA-1`;return e[0]&&(e[0].subtle?t=e[0]:(n=e[0]||n,t=e[1])),t??=z.get(),await t.subtle.digest(n,this.rawData)}async isSelfSigned(e=z.get()){return this.subject===this.issuer&&await this.verify({signatureOnly:!0},e)}toTextObject(){let e=this.toTextObjectEmpty(),t=n.AsnConvert.parse(this.rawData,r.Certificate),i=t.tbsCertificate,a=new L(``,{Version:`${r.Version[i.version]} (${i.version})`,"Serial Number":i.serialNumber,"Signature Algorithm":ve.serializeAlgorithm(i.signature),Issuer:this.issuer,Validity:new L(``,{"Not Before":i.validity.notBefore.getTime(),"Not After":i.validity.notAfter.getTime()}),Subject:this.subject,"Subject Public Key Info":this.publicKey});if(i.issuerUniqueID&&(a[`Issuer Unique ID`]=i.issuerUniqueID),i.subjectUniqueID&&(a[`Subject Unique ID`]=i.subjectUniqueID),this.extensions.length){let e=new L(``);for(let t of this.extensions){let n=t.toTextObject();e[n[L.NAME]]=n}a.Extensions=e}return e.Data=a,e.Signature=new L(``,{Algorithm:ve.serializeAlgorithm(t.signatureAlgorithm),"":t.signatureValue}),e}};ht.NAME=`Certificate`;var gt=class extends Array{constructor(e){if(super(),W.isAsnEncoded(e))this.import(e);else if(e instanceof ht)this.push(e);else if(Array.isArray(e))for(let t of e)this.push(t)}export(e){let t=new m.SignedData;t.version=1,t.encapContentInfo.eContentType=m.id_data,t.encapContentInfo.eContent=new m.EncapsulatedContent({single:new n.OctetString}),t.certificates=new m.CertificateSet(this.map(e=>new m.CertificateChoices({certificate:n.AsnConvert.parse(e.rawData,r.Certificate)})));let i=new m.ContentInfo({contentType:m.id_signedData,content:n.AsnConvert.serialize(t)}),a=n.AsnConvert.serialize(i);return e===`raw`?a:this.toString(e)}import(e){let t=W.toArrayBuffer(e),r=n.AsnConvert.parse(t,m.ContentInfo);if(r.contentType!==m.id_signedData)throw TypeError(`Cannot parse CMS package. Incoming data is not a SignedData object.`);let i=n.AsnConvert.parse(r.content,m.SignedData);this.clear();for(let e of i.certificates||[])e.certificate&&this.push(new ht(e.certificate))}clear(){for(;this.pop(););}toString(e=`pem`){let t=this.export(`raw`);switch(e){case`pem`:return U.encode(t,`CMS`);case`pem-chain`:return this.map(e=>e.toString(`pem`)).join(`
135
- `);case`asn`:return n.AsnConvert.toString(t);case`hex`:return i.Convert.ToHex(t);case`base64`:return i.Convert.ToBase64(t);case`base64url`:return i.Convert.ToBase64Url(t);case`text`:return ve.serialize(this.toTextObject());default:throw TypeError(`Argument 'format' is unsupported value`)}}toTextObject(){let e=n.AsnConvert.parse(this.export(`raw`),m.ContentInfo),t=n.AsnConvert.parse(e.content,m.SignedData);return new L(`X509Certificates`,{"Content Type":R.toString(e.contentType),Content:new L(``,{Version:`${m.CMSVersion[t.version]} (${t.version})`,Certificates:new L(``,{Certificate:this.map(e=>e.toTextObject())})})})}},_t=class{constructor(e={}){this.certificates=[],e.certificates&&(this.certificates=e.certificates)}async build(e,t=z.get()){let n=new gt(e),r=e;for(;r=await this.findIssuer(r,t);){let e=await r.getThumbprint(t);for(let r of n){let n=await r.getThumbprint(t);if(i.isEqual(e,n))throw Error(`Cannot build a certificate chain. Circular dependency.`)}n.push(r)}return n}async findIssuer(e,t=z.get()){if(!await e.isSelfSigned(t)){let r=e.getExtension(p.id_ce_authorityKeyIdentifier);for(let a of this.certificates)if(a.subject===e.issuer){if(r){if(r.keyId){let e=a.getExtension(p.id_ce_subjectKeyIdentifier);if(e&&e.keyId!==r.keyId)continue}else if(r.certId){let e=a.getExtension(p.id_ce_subjectAltName);if(e&&!(r.certId.serialNumber===a.serialNumber&&i.isEqual(n.AsnConvert.serialize(r.certId.name),n.AsnConvert.serialize(e))))continue}}try{let n={...a.publicKey.algorithm,...e.signatureAlgorithm},r=await a.publicKey.export(n,[`verify`],t);if(!await e.verify({publicKey:r,signatureOnly:!0},t))continue}catch{continue}return a}}return null}},vt=class{static async createSelfSigned(e,t=z.get()){if(!e.keys.privateKey)throw Error(`Bad field 'keys' in 'params' argument. 'privateKey' is empty`);if(!e.keys.publicKey)throw Error(`Bad field 'keys' in 'params' argument. 'publicKey' is empty`);return this.create({serialNumber:e.serialNumber,subject:e.name,issuer:e.name,notBefore:e.notBefore,notAfter:e.notAfter,publicKey:e.keys.publicKey,signingKey:e.keys.privateKey,signingAlgorithm:e.signingAlgorithm,extensions:e.extensions},t)}static async create(e,t=z.get()){let r;r=e.publicKey instanceof Ve?e.publicKey.rawData:`publicKey`in e.publicKey?e.publicKey.publicKey.rawData:i.BufferSourceConverter.isBufferSource(e.publicKey)?e.publicKey:await t.subtle.exportKey(`spki`,e.publicKey);let a=e.serialNumber?i.BufferSourceConverter.toUint8Array(i.Convert.FromHex(e.serialNumber)):t.getRandomValues(new Uint8Array(16));a[0]>127&&(a[0]&=127),a.length>1&&a[0]===0&&(a[1]|=128);let o=e.notBefore||new Date,s=e.notAfter||new Date(o.getTime()+31536e6),c=new p.Certificate({tbsCertificate:new p.TBSCertificate({version:p.Version.v3,serialNumber:a,validity:new p.Validity({notBefore:o,notAfter:s}),extensions:new p.Extensions(e.extensions?.map(e=>n.AsnConvert.parse(e.rawData,p.Extension))||[]),subjectPublicKeyInfo:n.AsnConvert.parse(r,p.SubjectPublicKeyInfo)})});if(e.subject){let t=e.subject instanceof V?e.subject:new V(e.subject);c.tbsCertificate.subject=n.AsnConvert.parse(t.toArrayBuffer(),p.Name)}if(e.issuer){let t=e.issuer instanceof V?e.issuer:new V(e.issuer);c.tbsCertificate.issuer=n.AsnConvert.parse(t.toArrayBuffer(),p.Name)}let u={hash:`SHA-256`},d=`signingKey`in e?{...u,...e.signingAlgorithm,...e.signingKey.algorithm}:{...u,...e.signingAlgorithm},f=l.container.resolve(b);c.tbsCertificate.signature=c.signatureAlgorithm=f.toAsnAlgorithm(d);let m=n.AsnConvert.serialize(c.tbsCertificate),h=`signingKey`in e?await t.subtle.sign(d,e.signingKey,m):e.signature,g=l.container.resolveAll(it).reverse(),_=null;for(let e of g)if(_=e.toAsnSignature(d,h),_)break;if(!_)throw Error(`Cannot convert ASN.1 signature value to WebCrypto format`);return c.signatureValue=_,new ht(n.AsnConvert.serialize(c))}};e.X509CrlReason=void 0,(function(e){e[e.unspecified=0]=`unspecified`,e[e.keyCompromise=1]=`keyCompromise`,e[e.cACompromise=2]=`cACompromise`,e[e.affiliationChanged=3]=`affiliationChanged`,e[e.superseded=4]=`superseded`,e[e.cessationOfOperation=5]=`cessationOfOperation`,e[e.certificateHold=6]=`certificateHold`,e[e.removeFromCRL=8]=`removeFromCRL`,e[e.privilegeWithdrawn=9]=`privilegeWithdrawn`,e[e.aACompromise=10]=`aACompromise`})(e.X509CrlReason||={});var yt=class extends ye{constructor(...e){let t;t=i.BufferSourceConverter.isBufferSource(e[0])?i.BufferSourceConverter.toArrayBuffer(e[0]):n.AsnConvert.serialize(new r.RevokedCertificate({userCertificate:e[0],revocationDate:new r.Time(e[1]),crlEntryExtensions:e[2]})),super(t,r.RevokedCertificate)}onInit(e){this.serialNumber=i.Convert.ToHex(e.userCertificate),this.revocationDate=e.revocationDate.getTime(),this.extensions=[],e.crlEntryExtensions&&(this.extensions=e.crlEntryExtensions.map(e=>{let t=G.create(n.AsnConvert.serialize(e));switch(t.type){case r.id_ce_cRLReasons:this.reason=n.AsnConvert.parse(t.value,r.CRLReason).reason;break;case r.id_ce_invalidityDate:this.invalidity=n.AsnConvert.parse(t.value,r.InvalidityDate).value}return t}))}},bt=class extends W{constructor(e){W.isAsnEncoded(e)?super(e,r.CertificateList):super(e),this.tag=U.CrlTag}onInit(e){let t=e.tbsCertList;this.tbs=n.AsnConvert.serialize(t),this.version=t.version;let r=l.container.resolve(b);this.signatureAlgorithm=r.toWebAlgorithm(e.signatureAlgorithm),this.tbsCertListSignatureAlgorithm=t.signature,this.certListSignatureAlgorithm=e.signatureAlgorithm,this.signature=e.signature,this.issuerName=new V(t.issuer),this.issuer=this.issuerName.toString();let i=t.thisUpdate.getTime();if(!i)throw Error(`Cannot get 'thisUpdate' value`);this.thisUpdate=i;let a=t.nextUpdate?.getTime();this.nextUpdate=a,this.entries=t.revokedCertificates?.map(e=>new yt(n.AsnConvert.serialize(e)))||[],this.extensions=[],t.crlExtensions&&(this.extensions=t.crlExtensions.map(e=>G.create(n.AsnConvert.serialize(e))))}getExtension(e){for(let t of this.extensions)if(typeof e==`string`){if(t.type===e)return t}else if(t instanceof e)return t;return null}getExtensions(e){return this.extensions.filter(t=>typeof e==`string`?t.type===e:t instanceof e)}async verify(e,t=z.get()){if(!this.certListSignatureAlgorithm.isEqual(this.tbsCertListSignatureAlgorithm))throw Error(`algorithm identifier in the sequence tbsCertList and CertificateList mismatch`);let n,r,i=e.publicKey;try{i instanceof ht?(n={...i.publicKey.algorithm,...i.signatureAlgorithm},r=await i.publicKey.export(n,[`verify`])):i instanceof Ve?(n={...i.algorithm,...this.signature},r=await i.export(n,[`verify`])):(n={...i.algorithm,...this.signature},r=i)}catch{return!1}let a=l.container.resolveAll(it).reverse(),o=null;for(let e of a)if(o=e.toWebSignature(n,this.signature),o)break;if(!o)throw Error(`Cannot convert ASN.1 signature value to WebCrypto format`);return await t.subtle.verify(this.signatureAlgorithm,r,o,this.tbs)}async getThumbprint(...e){let t,n=`SHA-1`;return e[0]&&(e[0].subtle?t=e[0]:(n=e[0]||n,t=e[1])),t??=z.get(),await t.subtle.digest(n,this.rawData)}findRevoked(e){let t=typeof e==`string`?e:e.serialNumber;for(let e of this.entries)if(e.serialNumber===t)return e;return null}},xt=class{static async create(e,t=z.get()){let a=e.issuer instanceof V?e.issuer:new V(e.issuer),o=new p.CertificateList({tbsCertList:new p.TBSCertList({version:p.Version.v2,issuer:n.AsnConvert.parse(a.toArrayBuffer(),p.Name),thisUpdate:new r.Time(e.thisUpdate||new Date)})});if(e.nextUpdate&&(o.tbsCertList.nextUpdate=new r.Time(e.nextUpdate)),e.extensions&&e.extensions.length&&(o.tbsCertList.crlExtensions=new p.Extensions(e.extensions.map(e=>n.AsnConvert.parse(e.rawData,p.Extension))||[])),e.entries&&e.entries.length){o.tbsCertList.revokedCertificates=[];for(let t of e.entries){let a=W.toArrayBuffer(t.serialNumber);if(o.tbsCertList.revokedCertificates.findIndex(e=>i.isEqual(e.userCertificate,a))>-1)throw Error(`Certificate serial number ${t.serialNumber} already exists in tbsCertList`);let s=new r.RevokedCertificate({userCertificate:a,revocationDate:new r.Time(t.revocationDate||new Date)});if(s.crlEntryExtensions=`extensions`in t&&t.extensions?.length?t.extensions.map(e=>n.AsnConvert.parse(e.rawData,p.Extension)):[],!(t instanceof yt)&&(t.reason&&s.crlEntryExtensions.push(new p.Extension({extnID:p.id_ce_cRLReasons,critical:!1,extnValue:new n.OctetString(n.AsnConvert.serialize(new p.CRLReason(t.reason)))})),t.invalidity&&s.crlEntryExtensions.push(new p.Extension({extnID:p.id_ce_invalidityDate,critical:!1,extnValue:new n.OctetString(n.AsnConvert.serialize(new p.InvalidityDate(t.invalidity)))})),t.issuer)){let t=e.issuer instanceof V?e.issuer:new V(e.issuer);s.crlEntryExtensions.push(new p.Extension({extnID:p.id_ce_certificateIssuer,critical:!1,extnValue:new n.OctetString(n.AsnConvert.serialize(n.AsnConvert.parse(t.toArrayBuffer(),p.Name)))}))}o.tbsCertList.revokedCertificates.push(s)}}let s={...e.signingAlgorithm,...e.signingKey.algorithm},c=l.container.resolve(b);o.tbsCertList.signature=o.signatureAlgorithm=c.toAsnAlgorithm(s);let u=n.AsnConvert.serialize(o.tbsCertList),d=await t.subtle.sign(s,e.signingKey,u),f=l.container.resolveAll(it).reverse(),m=null;for(let e of f)if(m=e.toAsnSignature(s,d),m)break;if(!m)throw Error(`Cannot convert ASN.1 signature value to WebCrypto format`);return o.signature=m,new bt(n.AsnConvert.serialize(o))}};G.register(p.id_ce_basicConstraints,We),G.register(p.id_ce_extKeyUsage,Ge),G.register(p.id_ce_keyUsage,Ke),G.register(p.id_ce_subjectKeyIdentifier,qe),G.register(p.id_ce_authorityKeyIdentifier,Ue),G.register(p.id_ce_subjectAltName,Je),G.register(p.id_ce_cRLDistributionPoints,Xe),G.register(p.id_pe_authorityInfoAccess,Ze),rt.register(_.id_pkcs9_at_challengePassword,tt),rt.register(_.id_pkcs9_at_extensionRequest,nt),l.container.registerSingleton(it,at),l.container.registerSingleton(it,ct),ct.namedCurveSize.set(`P-256`,32),ct.namedCurveSize.set(`K-256`,32),ct.namedCurveSize.set(`P-384`,48),ct.namedCurveSize.set(`P-521`,66),e.AlgorithmProvider=y,e.AsnData=ye,e.AsnDefaultSignatureFormatter=at,e.AsnEcSignatureFormatter=ct,e.Attribute=et,e.AttributeFactory=rt,e.AuthorityInfoAccessExtension=Ze,e.AuthorityKeyIdentifierExtension=Ue,e.BasicConstraintsExtension=We,e.CRLDistributionPointsExtension=Xe,e.CertificatePolicyExtension=Ye,e.ChallengePasswordAttribute=tt,e.CryptoProvider=Se,e.DefaultAlgorithmSerializer=_e,e.ExtendedKeyUsageExtension=Ge,e.Extension=be,e.ExtensionFactory=G,e.ExtensionsAttribute=nt,e.GeneralName=Re,e.GeneralNames=ze,e.KeyUsagesExtension=Ke,e.Name=V,e.NameIdentifier=Te,e.OidSerializer=R,e.PemConverter=U,e.Pkcs10CertificateRequest=pt,e.Pkcs10CertificateRequestGenerator=mt,e.PublicKey=Ve,e.SubjectAlternativeNameExtension=Je,e.SubjectKeyIdentifierExtension=qe,e.TextConverter=ve,e.TextObject=L,e.X509Certificate=ht,e.X509CertificateGenerator=vt,e.X509Certificates=gt,e.X509ChainBuilder=_t,e.X509Crl=bt,e.X509CrlEntry=yt,e.X509CrlGenerator=xt,e.cryptoProvider=z,e.diAlgorithm=v,e.diAlgorithmProvider=b,e.diAsnSignatureFormatter=it,e.idEd25519=dt,e.idEd448=ft,e.idX25519=lt,e.idX448=ut}));De(),ca();var la;(function(e){e.Der=`der`,e.Raw=`raw`})(la||={});const ua=typeof window<`u`&&window.document!==void 0&&typeof crypto<`u`&&crypto.subtle!==void 0,da=typeof process<`u`&&process.versions!=null&&process.versions.node!=null,fa=()=>ua?`browser`:da?`node`:`purejs`,pa=async(e,t)=>{let n=t??fa();switch(n){case`browser`:return(await import(`./webcrypto-BeKbrVgs.mjs`)).signWithApiKey(e);case`node`:return(await import(`./nodecrypto-BSdTIm8T.mjs`)).signWithApiKey(e);case`purejs`:return(await import(`./purejs-xzcexc4T.mjs`)).signWithApiKey(e);default:throw Error(`Unsupported runtime: ${n}`)}};var ma=class{constructor(e){this.apiPublicKey=e.apiPublicKey,this.apiPrivateKey=e.apiPrivateKey,this.runtimeOverride=e.runtimeOverride}async stamp(e){let t=await pa({publicKey:this.apiPublicKey,privateKey:this.apiPrivateKey,content:e},this.runtimeOverride),n={publicKey:this.apiPublicKey,scheme:`SIGNATURE_SCHEME_TK_API_P256`,signature:t};return{stampHeaderName:`X-Stamp`,stampHeaderValue:I(JSON.stringify(n))}}async sign(e,t){switch(t){case la.Raw:{let t=await pa({publicKey:this.apiPublicKey,privateKey:this.apiPrivateKey,content:e},this.runtimeOverride),n=Te(t);return s(n)}case la.Der:return pa({publicKey:this.apiPublicKey,privateKey:this.apiPrivateKey,content:e},this.runtimeOverride);default:throw Error(`Unsupported signature format: ${t}`)}}},ha=class extends Error{constructor(e){super(e),this.name=`InvalidKeyError`}};function ga(){let e=p(`prime256v1`);return e.generateKeys(),va(e.getPrivateKey().toString(`hex`).padStart(64,`0`))}const _a=/^[0-9a-f]{64}$/i;function va(e){if(!_a.test(e))throw new ha(`P-256 private key must be 64 hex characters`);let t=e.toLowerCase(),n=p(`prime256v1`);try{n.setPrivateKey(Buffer.from(t,`hex`))}catch{throw new ha(`value is not a valid P-256 private key (scalar out of range)`)}return{algorithm:`p256`,privateKeyHex:t,publicKeyHex:n.getPublicKey(`hex`,`compressed`)}}function ya(e){try{let t=f.convertKey(e,`prime256v1`,`hex`,`hex`,`uncompressed`),n=Buffer.isBuffer(t)?t:Buffer.from(t,`hex`);return n.length===65?n:null}catch{return null}}function ba(e){let t=ya(e);if(t===null)throw new ha(`value is not a valid P-256 public key`);return xa(t)}function xa(e){let t=e.subarray(1,33).toString(`base64url`),n=e.subarray(33,65).toString(`base64url`);return m(`sha256`).update(`{"crv":"P-256","kty":"EC","x":"${t}","y":"${n}"}`,`utf8`).digest(`base64url`)}const Sa=/^https?:\/\/[\x21\x23-\x7e]{1,255}$/,Ca=/^[\x21\x23-\x3a\x3c-\x7e]{1,128}$/;function wa(e,t){return`${e.replace(/\/+$/,``)}/agent-keys/${t}`}function Ta(e){let t=Ea(e.keypair),n={...t,identityUrl:Da(e.identityUrl??wa(e.baseUrl,t.keyId))};return{sign:async e=>{let t=new Uint8Array(await e.clone().arrayBuffer()),r=Oa(n,{method:e.method,url:e.url,body:t},{nonce:g(16).toString(`base64url`),createdAt:new Date}),i=new Headers(e.headers);for(let[e,t]of Object.entries(r))i.set(e,t);return new Request(e,{headers:i})}}}function Ea(e){let t=ya(e.publicKeyHex);if(t===null)throw Error(`signer keypair has an invalid P-256 public key`);return{signingKey:Ma(t,e.privateKeyHex),keyId:xa(t)}}function Da(e){if(!Sa.test(e))throw Error(`identity URL is outside the signature profile: "${e}"`);return e}function Oa(e,t,n){if(!Ca.test(n.nonce))throw Error(`nonce is outside the signature profile`);let r=ka(t.body),i=`"${e.identityUrl}"`,a=`("@method" "@target-uri" "content-digest" "signature-agent");created=${Math.floor(n.createdAt.getTime()/1e3)};keyid="${e.keyId}";nonce="${n.nonce}";alg="ecdsa-p256-sha256"`,o=[`"@method": ${t.method.toUpperCase()}`,`"@target-uri": ${Aa(new URL(t.url))}`,`"content-digest": ${r}`,`"signature-agent": ${i}`,`"@signature-params": ${a}`].join(`
136
- `),s=_(`sha256`,Buffer.from(o,`utf8`),{key:e.signingKey,dsaEncoding:`ieee-p1363`});return{"Content-Digest":r,"Signature-Agent":i,"Signature-Input":`sig=${a}`,Signature:`sig=:${s.toString(`base64`)}:`}}function ka(e){return`sha-256=:${m(`sha256`).update(e??``).digest(`base64`)}:`}function Aa(e){return`${e.protocol}//${ja(e)}${e.pathname}${e.search}`}function ja(e){let t=e.host.toLowerCase();return e.protocol===`https:`&&e.port===`443`||e.protocol===`http:`&&e.port===`80`?e.hostname.toLowerCase():t}function Ma(e,t){return h({key:{kty:`EC`,crv:`P-256`,d:Buffer.from(t,`hex`).toString(`base64url`),x:e.subarray(1,33).toString(`base64url`),y:e.subarray(33,65).toString(`base64url`)},format:`jwk`})}var Na=`0.1.0`;const Pa=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Fa=Na;function Ia(e,t){if(!Pa.test(e))throw Error(`${t} must be a valid HTTP token`)}function La(e,t){let n=!1;for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r<32||r===127||r>255){n=!0;break}}if(n||/[()\\]/.test(e))throw Error(`${t} must not contain parentheses, backslashes, control characters, or characters outside Latin-1`)}function Ra(e){let t=`catena-agent-client/${Fa}`;if(!e)return t;Ia(e.name,`appInfo.name`),e.version!==void 0&&Ia(e.version,`appInfo.version`),e.url!==void 0&&La(e.url,`appInfo.url`);let n=e.version===void 0?e.name:`${e.name}/${e.version}`;return`${e.url===void 0?n:`${n} (${e.url})`} ${t}`}const za=d.object({paymentCredential:d.object({protocol:d.picklist([`mpp`,`x402`]),value:d.string()})});function Ba(e,t){let n=d.safeParse(za,e);return n.success&&n.output.paymentCredential.protocol===t?n.output.paymentCredential.value:void 0}const Va=`offer-receipt`,Ha=8192,Ua=d.pipe(d.string(),d.maxLength(Ha),d.regex(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,`Expected a JWS compact serialization`)),Wa=d.optional(d.pipe(d.number(),d.integer(),d.minValue(0))),Ga=d.pipe(d.string(),d.regex(/^0x[0-9a-fA-F]{130}$/,`Expected a 65-byte hex signature`)),Ka=d.variant(`format`,[d.looseObject({format:d.literal(`eip712`),acceptIndex:Wa,payload:d.record(d.string(),d.unknown()),signature:Ga}),d.looseObject({format:d.literal(`jws`),acceptIndex:Wa,signature:Ua})]),qa=d.variant(`format`,[d.looseObject({format:d.literal(`eip712`),payload:d.record(d.string(),d.unknown()),signature:Ga}),d.looseObject({format:d.literal(`jws`),signature:Ua})]),Ja=d.object({[Va]:d.object({info:d.object({offers:d.array(d.unknown())})})}),Ya=d.object({[Va]:d.object({info:d.object({receipt:d.unknown()})})}),Xa=d.looseObject({version:d.literal(1),resourceUrl:d.pipe(d.string(),d.maxLength(2048)),scheme:d.pipe(d.string(),d.maxLength(64)),network:d.pipe(d.string(),d.maxLength(64)),asset:d.pipe(d.string(),d.maxLength(128)),payTo:d.pipe(d.string(),d.maxLength(128)),amount:d.pipe(d.string(),d.regex(/^\d+$/),d.maxLength(78)),validUntil:d.optional(d.pipe(d.number(),d.integer(),d.minValue(0)))});function Za(e){let t=e.replaceAll(`-`,`+`).replaceAll(`_`,`/`),n=Uint8Array.from(atob(t),e=>e.charCodeAt(0));return JSON.parse(new TextDecoder().decode(n))}function Qa(e){if(e.format===`eip712`){let t=d.safeParse(Xa,e.payload);return t.success?t.output:void 0}let t=e.signature.split(`.`)[1];try{let e=d.safeParse(Xa,Za(t));return e.success?e.output:void 0}catch{return}}function $a(e,t){return e.toLowerCase()===t.toLowerCase()}function eo(e,t){return e.scheme===t.scheme&&e.network===t.network&&$a(e.asset,t.asset)&&$a(e.payTo,t.payTo)&&e.amount===t.amount}function to(e){return new TextEncoder().encode(JSON.stringify(e)).length<=Ha}function no(e,t){let n=d.safeParse(Ja,e);if(n.success)for(let e of n.output[Va].info.offers){let n=d.safeParse(Ka,e);if(!n.success)continue;let r=Qa(n.output);if(r!==void 0&&eo(r,t)&&to(n.output))return n.output}}function ro(e){let t=d.safeParse(Ya,e);if(!t.success)return;let n=d.safeParse(qa,t.output[Va].info.receipt);if(n.success&&to(n.output))return n.output}const io=d.pipe(d.string(),d.regex(/\S/,`Response enum values must not be blank`));function ao(e){return io}const oo=d.object({amount:d.string(),asset_id:d.string()}),so=d.pipe(d.string(),d.isoTimestamp()),co=d.object({success:d.literal(!0)}),lo=d.object({id:d.string(),name:d.string(),status:d.string(),organizationId:d.string()}),uo=d.object({agent:lo}),fo=[`per_transaction_amount`,`daily_amount`,`weekly_amount`,`monthly_amount`,`hourly_count`,`daily_count`],po=d.object({id:d.string(),ruleType:ao(fo),thresholdAmount:d.optional(oo),thresholdCount:d.optional(d.number()),action:ao([`block`,`require_approval`]),requiredApprovals:d.number(),accountAggregationScope:ao([`per_account`,`across_accounts`]),actorAggregationScope:ao([`per_agent`,`per_policy`]),displayOrder:d.number()}),mo=d.object({id:d.string(),organizationId:d.string(),policyId:d.string(),capability:ao([`query_balance`,`read`,`send`,`transfer`]),accountId:d.string(),rules:d.array(po),createdAt:so,updatedAt:so}),ho=[`allow`,`block`,`require_approval`],go=[`open`,`restricted`],_o=ao(ho),vo=d.object({mode:ao(go),allowedCounterparties:d.optional(d.array(d.string())),createAction:d.optional(_o),requestPaymentDetailsAction:d.optional(_o),allowCreate:d.optional(d.boolean())}),yo=d.object({id:d.optional(d.string()),description:d.optional(d.string()),version:d.optional(d.number()),name:d.string(),capabilities:d.array(d.string()),counterpartyRules:d.optional(vo),policyCapabilities:d.array(mo),kind:d.optional(d.picklist([`base`,`override`])),expiresAt:d.optional(d.string())}),bo=d.object({policy:yo}),xo=d.object({accounts:d.array(d.object({id:d.string(),name:d.string(),type:d.string(),currency:d.string()}))}),So=d.object({accountId:d.string(),balance:oo,balances:d.optional(d.object({total:oo,available:oo}))}),Co=[`operator-send`,`operator-transfer`,`operator-deposit`,`operator-refund`,`microdeposit`],wo=[`pending`,`processing`,`completed`,`failed`,`reversed`],To=[`initiated`,`provider_pending`,`processing`,`completed`,`failed`,`reversed`,`manual_review`],Eo=[`ach`,`wire`,`on-chain`],Do=d.object({id:d.string(),type:ao(Co),action:d.optional(d.string()),status:ao(wo),movementStatus:ao(To),direction:d.picklist([`incoming`,`outgoing`]),amount:oo,fee:oo,currency:d.string(),counterpartyName:d.optional(d.string()),method:d.optional(ao([`ach`,`wire`,`on-chain`])),memo:d.optional(d.string()),description:d.optional(d.string()),txHash:d.optional(d.string()),createdAt:so,completedAt:d.optional(so)}),Oo=d.object({accountId:d.string(),transactions:d.array(Do),total:d.number()}),ko=d.object({accountId:d.string(),address:d.string(),liquidationAddressId:d.optional(d.string()),source:ao([`wallet`,`liquidation`])}),Ao=d.object({id:d.string(),name:d.string(),status:d.optional(d.string()),rails:d.array(d.object({id:d.string(),type:d.string(),walletAddress:d.optional(d.string()),network:d.optional(d.string()),bankName:d.optional(d.string()),accountNumber:d.optional(d.string())}))}),jo=d.object({counterparties:d.array(Ao)}),Mo=d.picklist([`pending`,`processing`,`completed`,`blocked`,`failed`]),No=d.object({type:d.literal(`submit_stamp`),signingRequestId:d.string(),signer:d.object({algorithm:d.literal(`p256`),publicKeyHex:d.string()}),preparedBody:d.object({body:d.string(),bodyHash:d.string(),expiresAt:so,prepareToken:d.string()})}),Po=d.object({id:d.string(),accountId:d.optional(d.string()),type:ao([`send`,`transfer`,`create_counterparty`,`request_counterparty_details`,`x402`,`mpp`,`policy_override`]),status:Mo,reasons:d.array(d.string()),expiresAt:d.optional(d.nullable(so),null),replayed:d.optional(d.boolean(),!1),data:d.optional(d.nullable(d.record(d.string(),d.unknown())),null),metadata:d.optional(d.object({dataUrl:d.nullable(d.string())})),nextAction:d.optional(No)});function Fo(e){let{nextAction:t,...n}=e;return n}const Io=d.object({x402:d.object({paymentSignature:d.string()})});function Lo(e){let t=Ba(e,`x402`);if(t!==void 0)return t;let n=d.safeParse(Io,e);return n.success?n.output.x402.paymentSignature:void 0}const Ro=d.picklist(Eo),zo=d.object({type:d.literal(`send`),accountId:d.optional(d.pipe(d.string(),d.minLength(1))),counterpartyRailId:d.string(),amount:d.string(),method:Ro,memo:d.optional(d.string()),description:d.optional(d.string())}),Bo=d.object({type:d.literal(`transfer`),accountId:d.string(),toAccountId:d.string(),amount:d.string(),memo:d.optional(d.string()),description:d.optional(d.string())}),Vo={type:d.literal(`create_counterparty`),name:d.string()},Ho=d.union([d.object({...Vo,email:d.optional(d.string()),rail:d.nonOptional(d.unknown())}),d.object({...Vo,email:d.string()})]),Uo=d.object({type:d.literal(`request_counterparty_details`),counterpartyId:d.string(),methods:d.pipe(d.object({bank:d.boolean(),wallet:d.boolean()}),d.check(({bank:e,wallet:t})=>e||t,`Select at least one payment method to request`))}),Wo=d.looseObject({scheme:d.string(),network:d.string(),asset:d.string(),amount:d.string(),payTo:d.string(),maxTimeoutSeconds:d.number()}),Go=d.looseObject({url:d.string(),serviceName:d.fallback(d.optional(d.pipe(d.string(),d.maxLength(255))),void 0)}),Ko=d.pipe(d.string(),d.regex(/^0x[0-9a-fA-F]{40}$/,`Expected a 20-byte hex address`)),qo=d.pipe(d.string(),d.maxLength(78),d.regex(/^(0|[1-9]\d*)$/,`Expected a canonical decimal integer string`)),Jo=d.object({from:Ko,to:Ko,value:qo,validAfter:qo,validBefore:qo,nonce:d.pipe(d.string(),d.regex(/^0x[0-9a-fA-F]{64}$/,`Expected a 32-byte hex nonce`))}),Yo=d.object({type:d.literal(`x402`),accountId:d.string(),paymentRequirements:Wo,resource:d.optional(Go),authorization:d.optional(Jo),signedOffer:d.optional(Ka)}),Xo=d.object({id:d.string(),realm:d.string(),method:d.picklist([`evm`,`usdc`]),intent:d.literal(`charge`),request:d.string(),description:d.optional(d.string()),digest:d.optional(d.string()),expires:d.string(),header:d.optional(d.literal(`Payment-Authorization`)),opaque:d.optional(d.string())}),Zo=d.object({url:d.string(),serviceName:d.optional(d.string())}),Qo=d.object({type:d.literal(`mpp`),accountId:d.string(),challenge:Xo,resource:d.optional(Zo)}),$o=[`send`,`transfer`],es=d.strictObject({type:d.literal(`increase_limit`),accountId:d.pipe(d.string(),d.minLength(1)),capability:d.picklist($o),limitType:d.picklist([`per_transaction_amount`,`daily_amount`,`weekly_amount`,`monthly_amount`]),newLimit:d.strictObject({amount:d.pipe(d.string(),d.regex(/^\d+(\.\d{1,6})?$/),d.check(e=>Number(e)>0,`The amount must be greater than zero`)),assetId:d.literal(`USD`)})}),ts=d.strictObject({type:d.literal(`increase_limit`),accountId:d.pipe(d.string(),d.minLength(1)),capability:d.picklist($o),limitType:d.picklist([`hourly_count`,`daily_count`]),newLimit:d.strictObject({count:d.pipe(d.number(),d.integer(),d.minValue(1))})}),ns=d.pipe(d.array(d.union([es,ts])),d.minLength(1),d.maxLength(10),d.check(e=>new Set(e.map(e=>`${e.accountId}|${e.capability}|${e.limitType}`)).size===e.length,`Each account, capability, and limit type may appear only once`)),rs=d.object({type:d.literal(`policy_override`),operations:ns,durationSeconds:d.pipe(d.number(),d.integer(),d.minValue(60),d.maxValue(604800)),reason:d.pipe(d.string(),d.trim(),d.minLength(1),d.maxLength(280))}),is=d.union([zo,Bo,Ho,Uo,Yo,Qo,rs]);function as(e){let t=d.parse(is,e);return t.type===`send`||t.type===`transfer`?{...t,amount:{amount:t.amount,asset_id:`USD`}}:t.type===`policy_override`?{...t,schemaVersion:1}:t}const os=d.object({intent:Po});var ss=class extends Error{status;code;details;constructor(e,t,n,r){super(n?`API error ${e} [${n}]: ${t}`:`API error ${e}: ${t}`),this.name=`ApiError`,this.status=e,this.code=n,this.details=r}},cs=class extends Error{timeoutMs;constructor(e){super(`Request timed out after ${e}ms. The server may still have processed a state-changing request; follow that operation's documented recovery procedure before retrying.`),this.name=`TimeoutError`,this.timeoutMs=e}};const ls=d.object({error:d.nullish(d.string()),message:d.nullish(d.string()),code:d.nullish(d.string()),details:d.nullish(d.record(d.string(),d.unknown()))});async function us(e){let t=d.safeParse(ls,await e.json().catch(()=>void 0)),n=t.success?t.output:{};return n.error!=null&&n.message!=null?new ss(e.status,n.message,n.code??n.error,n.details??void 0):new ss(e.status,n.error??n.message??e.statusText,n.code??void 0,n.details??void 0)}async function ds(e,t){if(!e.ok)throw await us(e);return d.parse(t,await e.json())}var fs=class extends Error{intentId;outcome;constructor(e){let t=e.cause instanceof Error?e.cause.message:String(e.cause);super(e.outcome===`not-submitted`?`Intent ${e.intentId} was created but never submitted; no money moved: ${t}`:`Intent ${e.intentId} submission could not be confirmed: ${t}; poll getIntent("${e.intentId}") to a terminal status and resubmit only after blocked or failed`,{cause:e.cause}),this.name=`IntentSubmitError`,this.intentId=e.intentId,this.outcome=e.outcome}};const ps=2147483647;var ms=class{#e;#t;#n;#r;#i;#a;#o;constructor(e){let t=e.timeout===void 0?8e4:e.timeout;if(!Number.isInteger(t)||t<=0||t>ps)throw TypeError(`timeout must be a positive integer no greater than ${ps}`);this.#e=e.baseUrl??`https://api.catena.com`,this.#t=Ra(e.appInfo),this.#n=e.defaultHeaders??{},this.#r=va(e.privateKeyHex),this.#a=(e.fetch??globalThis.fetch).bind(globalThis),this.#o=t,this.#i=Ta({keypair:this.#r,baseUrl:this.#e,identityUrl:e.identityUrl})}#s(e){let t=new Headers({"Content-Type":`application/json`});for(let[e,n]of Object.entries(this.#n))t.set(e,n);for(let[n,r]of Object.entries(e??{}))t.set(n,r);return t.set(`User-Agent`,this.#t),t.delete(`Authorization`),t}async#c(e){let t=new URL(`${this.#e}/v1/agent-api${e.path}`);for(let[n,r]of Object.entries(e.query??{}))r!==void 0&&t.searchParams.set(n,r);let n=new Request(t,{method:e.method,headers:this.#s(e.headers),body:e.body===void 0?null:JSON.stringify(e.body)});return this.#i.sign(n)}async#l(e,t){return this.#u(await this.#c(e),t)}async#u(e,t){let n=new AbortController,r=new Request(e,{signal:n.signal}),i;try{let e=new Promise((e,t)=>{i=setTimeout(()=>{let e=new cs(this.#o);t(e),n.abort(e)},this.#o)}),a=this.#a(r).then(e=>ds(e,t));return await Promise.race([a,e])}finally{i!==void 0&&clearTimeout(i)}}async whoami(){return(await this.#l({method:`GET`,path:`/me`},uo)).agent}async submitFeedback(e){await this.#l({method:`POST`,path:`/feedback`,body:{body:e}},co)}async getPolicy(){return(await this.#l({method:`GET`,path:`/policy`},bo)).policy}async listAccounts(){return this.#l({method:`GET`,path:`/accounts`},xo)}async getAccountBalance(e){return this.#l({method:`GET`,path:`/accounts/${encodeURIComponent(e)}/balance`},So)}async listAccountTransactions(e,t={}){return this.#l({method:`GET`,path:`/accounts/${encodeURIComponent(e)}/transactions`,query:{start:t.start,end:t.end,limit:t.limit?.toString(),offset:t.offset?.toString()}},Oo)}async getAccountDepositAddress(e,t){return this.#l({method:`GET`,path:`/accounts/${encodeURIComponent(e)}/deposit-address`,query:{network:t.network,asset:t.asset}},ko)}async listCounterparties(e={}){return this.#l({method:`GET`,path:`/counterparties`,query:{address:e.address,network:e.network}},jo)}async submitIntent(e){let t=await this.#d({...e,idempotencyKey:e.idempotencyKey??crypto.randomUUID()}),n=t.nextAction;if(!n)return Fo(t);let r;try{let e=await this.#f(n);r=await this.#c({method:`POST`,path:`/intents/${encodeURIComponent(t.id)}/submit-stamp`,body:{preparedBody:n.preparedBody,stamp:e}})}catch(e){throw new fs({intentId:t.id,outcome:`not-submitted`,cause:e})}try{return await this.#p(r,t.replayed)}catch(e){throw new fs({intentId:t.id,outcome:`unknown`,cause:e})}}async#d(e){return this.#l({method:`POST`,path:`/intents`,body:{action:as(e.action)},headers:{"Idempotency-Key":e.idempotencyKey}},Po)}async#f(e){if(e.signer.publicKeyHex.toLowerCase()!==this.#r.publicKeyHex.toLowerCase())throw Error(`Local signer public key does not match requested signer ${e.signer.publicKeyHex}; linked credential has ${this.#r.publicKeyHex}`);let t=await new ma({apiPublicKey:this.#r.publicKeyHex,apiPrivateKey:this.#r.privateKeyHex}).stamp(e.preparedBody.body);return{publicKeyHex:this.#r.publicKeyHex,stampHeaderName:t.stampHeaderName,stampHeaderValue:t.stampHeaderValue}}async#p(e,t){let n=Fo((await this.#u(e,os)).intent);return t?{...n,replayed:!0}:n}async getIntent(e){return Fo(await this.#l({method:`GET`,path:`/intents/${encodeURIComponent(e)}`},Po))}async unlinkAgent(){await this.#l({method:`POST`,path:`/unlink`},co)}async reportSettlement(e){await this.#l({method:`POST`,path:`/intents/${encodeURIComponent(e.intentId)}/settlement-report`,body:{txHash:e.txHash,...e.receipt!==void 0&&{receipt:e.receipt}}},co)}};function hs(e={}){let t=e.privateKeyHex===void 0?process.env.CATENA_SECRET_KEY:e.privateKeyHex;if(t===void 0)throw new ha(`privateKeyHex is required; pass it explicitly or set CATENA_SECRET_KEY`);return new ms({...e,privateKeyHex:t})}function gs(e){let t=se(e);return e instanceof ss&&e.details!==void 0?`${t}\nDetails:\n${JSON.stringify(e.details,null,2)}`:t}function X(e){console.error(gs(e)),process.exit(1)}const _s=d.string(),vs=d.boolean();function ys(e){return e===void 0}function bs(e){return e.issues?.[0]?.message??`Invalid value`}function xs(e,t,n,r){return X(`${e}: ${t}${r?` (got: ${String(n)})`:``}`)}function Ss(e,t,n,r){let i=d.safeParse(e,t);return i.success?i.output:xs(n,bs(i),t,r)}function Cs(e,t){let n=t.schema??_s;return{type:e,description:t.description,negativeDescription:t.negativeDescription,required:t.required,default:t.default,parseValue(e,r){let i=ys(e)?t.default:e;if(ys(i)){t.required===!0&&X(`${r} is required`);return}return Ss(n,i,r,t.showValueInError===!0)}}}function Z(e){return Cs(`string`,e)}function ws(e){return Cs(`positional`,e)}function Ts(e){let t=e.schema??_s;return{type:`string`,description:e.description,repeatable:!0,parseValue(n,r){return(Array.isArray(n)?n:[]).map(n=>Ss(t,n,r,e.showValueInError===!0))}}}function Es(e){return{type:`boolean`,description:e.description,negativeDescription:e.negativeDescription,required:e.required,default:e.default,parseValue(t,n){let r=ys(t)?e.default:t;if(ys(r)){e.required===!0&&X(`${n} is required`);return}return Ss(vs,r,n,!1)}}}function Ds(e){return Os(`string`,e)}function Os(e,t){return Cs(e,{description:t.description,required:t.required,default:t.default,schema:d.picklist(t.choices,`must be one of ${t.choices.join(`|`)}`),showValueInError:!0})}function ks(e,t){return t.type===`positional`?`<${e}>`:`--${e}`}function As(e){return e.replace(/([a-z])([A-Z])/g,`$1 $2`).replace(/([A-Z0-9])([A-Z][a-z])/g,`$1 $2`).split(/[ _-]/).filter(e=>e.length>0)}function js(e){return As(e).join(`-`).toLowerCase()}function Ms(e){return As(e).map((e,t)=>t===0?e.charAt(0).toLowerCase()+e.slice(1):e.charAt(0).toUpperCase()+e.slice(1)).join(``)}function Ns(e){return[`--${e}`,`--${js(e)}`,`--${Ms(e)}`]}function Ps(e){let t=e.indexOf(`=`);return t===-1?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function Fs(e,t,n){let r=e.indexOf(`--`),i=r===-1?e.length:r,a=[...e.slice(0,i).filter(e=>!e.startsWith(`--no-`)),...e.slice(i)],o=new Set(Ns(t)),s=new Set(Object.entries(n).filter(([e,n])=>e!==t&&n.type===`string`).flatMap(([e])=>Ns(e))),c=[];for(let e=0;e<a.length;e++){let t=a[e];if(t===`--`)break;let[n,r]=Ps(t);if(o.has(n)){r===void 0?(c.push(a[e+1]??``),e++):c.push(r);continue}s.has(n)&&r===void 0&&e++}return c}function Is(e){let t=e.required??(e.type!==`positional`&&void 0);return e.type===`boolean`?{type:e.type,description:e.description,negativeDescription:e.negativeDescription,required:t,default:typeof e.default==`boolean`?e.default:void 0}:{type:e.type,description:e.description,required:t,default:typeof e.default==`string`?e.default:void 0}}function Q(e){return{args:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Is(t)])),label(t){return ks(t,e[t])},parse(t,n){let r=(r,i)=>{if(i.repeatable!==!0)return t[r];if(n===void 0)throw Error(`parse() needs the command's raw argv to collect the repeatable --${r} flag`);return Fs(n,r,e)};return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.parseValue(r(e,t),ks(e,t))]))}}}const Ls=Z({description:`Credential profile name`}),Rs=Es({description:`Print compact single-line JSON (for piping)`,default:!1}),zs=/^[a-zA-Z0-9_-]+$/,Bs=d.pipe(d.string(`ID must be a string`),d.minLength(1,`ID must not be empty`),d.maxLength(256,`ID is too long (max 256 characters)`),d.regex(zs,`ID may only contain letters, digits, hyphens, and underscores`));d.picklist([`base`,`base-sepolia`,`arc`,`solana`]),d.picklist([`usdc`]),d.picklist([`evm`,`svm`]);const Vs=/^0x[0-9a-fA-F]{40}$/;d.pipe(d.string(),d.trim(),d.regex(Vs,`Must be a 0x-prefixed hex wallet address`),d.brand(`EvmAddress`)),d.picklist([`always`,`testnet`,`preview`]),d.picklist([`bridge-internal-transfer`,`bridge-wallet-transfer`,`wallet-bridge-transfer`,`wallet-wallet-transfer`]);const Hs=[`bridge-internal-transfer`,`bridge-wallet-transfer`,`wallet-bridge-transfer`,`wallet-wallet-transfer`],Us=[`wallet-wallet-transfer`],Ws=[{network:`base`,networkLabel:`Base`,addressFamily:`evm`,blockExplorerUrl:`https://basescan.org`,blockExplorerName:`Basescan`,asset:`usdc`,assetLabel:`USDC`,assetDecimals:6,contractAddress:`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,caip2:`eip155:8453`,caip19:`eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,finality:`finalized`,gasTokenIsTrackedAsset:!1,availabilityGate:`always`,customerAccess:`enabled`,chainFeeUsd:`0`,walletTransferFeeUsd:`0`,transferRoutes:Hs,provider:{alchemyNetwork:`base`,alchemyDeposit:{transferEmitterAddress:`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,transferDecimals:6,webhook:`enabled`},bridgePaymentRail:`base`}},{network:`base-sepolia`,networkLabel:`Base Sepolia`,addressFamily:`evm`,isTestnet:!0,blockExplorerUrl:`https://sepolia.basescan.org`,blockExplorerName:`Sepolia Basescan`,asset:`usdc`,assetLabel:`USDC`,assetDecimals:6,contractAddress:`0x036CbD53842c5426634e7929541eC2318f3dCF7e`,caip2:`eip155:84532`,caip19:`eip155:84532/erc20:0x036CbD53842c5426634e7929541eC2318f3dCF7e`,finality:`finalized`,gasTokenIsTrackedAsset:!1,availabilityGate:`testnet`,customerAccess:`enabled`,chainFeeUsd:`0`,walletTransferFeeUsd:`0`,transferRoutes:Us,provider:{alchemyNetwork:`base-sepolia`,alchemyDeposit:{transferEmitterAddress:`0x036CbD53842c5426634e7929541eC2318f3dCF7e`,transferDecimals:6,webhook:`enabled`}}},{network:`arc`,networkLabel:`Arc`,addressFamily:`evm`,blockExplorerUrl:`https://arc-scan.org`,blockExplorerName:`ArcScan`,asset:`usdc`,assetLabel:`USDC`,assetDecimals:6,contractAddress:`0x3600000000000000000000000000000000000000`,caip2:`eip155:5042`,caip19:`eip155:5042/erc20:0x3600000000000000000000000000000000000000`,finality:`block-inclusion`,gasTokenIsTrackedAsset:!0,availabilityGate:`preview`,customerAccess:`enabled`,chainFeeUsd:`0`,walletTransferFeeUsd:`0`,transferRoutes:Us,provider:{alchemyNetwork:`arc`,alchemyDeposit:{transferEmitterAddress:`0xfffffffffffffffffffffffffffffffffffffffe`,transferDecimals:18,webhook:`disabled`},sendMode:`self-broadcast`}},{network:`solana`,networkLabel:`Solana`,addressFamily:`svm`,blockExplorerUrl:`https://solscan.io`,blockExplorerName:`Solscan`,asset:`usdc`,assetLabel:`USDC`,assetDecimals:6,contractAddress:`EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`,caip2:`solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp`,caip19:`solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp/token:EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`,finality:`finalized`,gasTokenIsTrackedAsset:!1,availabilityGate:`preview`,customerAccess:`enabled`,chainFeeUsd:`0`,walletTransferFeeUsd:`0`,transferRoutes:Hs,provider:{alchemyNotify:{webhook:`enabled`},bridgePaymentRail:`solana`}}];function Gs(e){if(typeof e==`object`&&e&&!Object.isFrozen(e)){for(let t of Object.values(e))Gs(t);Object.freeze(e)}}Gs(Ws);const Ks=Ws;function qs(e){return{id:e.network,label:e.networkLabel,addressFamily:e.addressFamily,blockExplorerUrl:e.blockExplorerUrl,blockExplorerName:e.blockExplorerName,...e.isTestnet?{isTestnet:!0}:{}}}function Js(e){return{id:e.asset,label:e.assetLabel,decimals:e.assetDecimals}}function Ys(e){return{network:e.network,asset:e.asset,contractAddress:e.contractAddress}}function Xs(e){return{id:`${e.network}-usdc`,label:`${e.networkLabel} USDC`,network:e.network,asset:`usdc`}}function Zs(e){let t=[];for(let n of e)t.some(e=>e.id===n.network)||t.push(qs(n));return t}function Qs(e){let t=[],n=new Set;for(let r of e)n.has(r.asset)||(n.add(r.asset),t.push(Js(r)));return t}function $s(e){return e.asset===`usdc`}const ec=Zs(Ks);Qs(Ks),Ks.map(Ys),Ks.filter($s).map(Xs);function tc(e,t){return`${e}:${t}`}new Map(Ks.map(e=>[tc(e.network,e.asset),e])),new Map(ec.map(e=>[e.id,e]));const nc=[`base`,`base-sepolia`],rc=[`usdc`],ic=`base`,ac=d.pipe(d.string(),d.trim(),d.guard(e=>Vs.test(e),`Must be a 0x-prefixed hex wallet address`));function oc(e){return Ds({description:e.description,choices:nc,...e.default===void 0?{}:{default:e.default}})}const sc=[`registered`,`already_registered`,`not_applicable`,`registration_failed`],cc=d.pipe(d.string(),d.regex(/^0[23][0-9a-f]{64}$/)),lc=d.pipe(d.string(),d.regex(/^[0-9a-f]{64}$/)),uc=d.object({status:d.picklist(sc),publicKeyHex:d.optional(cc),reason:d.optional(d.string())}),dc=d.object({algorithm:d.literal(`p256`),privateKeyHex:lc,publicKeyHex:cc,registration:uc}),fc=d.object({version:d.literal(`signer-1`),signer:dc}),pc=d.object({version:d.literal(1),refreshToken:d.pipe(d.string(),d.minLength(1)),sessionToken:d.pipe(d.string(),d.minLength(1)),expiresAt:d.pipe(d.string(),d.isoTimestamp())}),mc=d.object({version:d.literal(2),refreshToken:d.pipe(d.string(),d.minLength(1)),sessionToken:d.pipe(d.string(),d.minLength(1)),expiresAt:d.pipe(d.string(),d.isoTimestamp()),signer:dc}),hc=d.object({version:d.literal(3),signer:dc}),gc=d.variant(`version`,[pc,mc,hc]),_c=d.variant(`version`,[fc,pc,mc,hc]);function vc(e){return d.parse(gc,e)}function yc(e){return d.parse(_c,e)}function bc(e){let t=d.safeParse(_c,e);return t.success?t.output:null}function xc(e){return{version:`signer-1`,signer:{algorithm:e.algorithm,privateKeyHex:e.privateKeyHex,publicKeyHex:e.publicKeyHex,registration:{status:`not_applicable`,reason:`pending_claim`}}}}function Sc(e,t){try{return yc(JSON.parse(e))}catch(e){throw Error(`${t} credential has an unsupported format`,{cause:e})}}function Cc(e){return vc({version:3,signer:e})}function wc(e){return JSON.stringify(e)}function Tc(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Ec(e){return(t,n)=>Dc(e,t,n)}function Dc(e,t,n){return new Promise((r,i)=>{let a=y(e,[...t],{stdio:[`pipe`,`pipe`,`pipe`]}),o=[],s=[],c=!1,l=!1,u=null,d=null,f=null,p=e=>{c||(c=!0,d!==null&&clearTimeout(d),f!==null&&clearTimeout(f),r(e))},m=e=>{c||(c=!0,d!==null&&clearTimeout(d),f!==null&&clearTimeout(f),i(e))};d=setTimeout(()=>{l=!0,a.kill(`SIGTERM`),f=setTimeout(()=>{a.kill(`SIGKILL`),p({stdout:o.join(``),stderr:s.join(``),status:124})},1e3)},3e4),a.stdout.setEncoding(`utf8`),a.stderr.setEncoding(`utf8`),a.stdout.on(`data`,e=>o.push(e)),a.stderr.on(`data`,e=>s.push(e)),a.on(`error`,t=>{m(Error(`Unable to run ${e}: ${t.message}`))}),a.on(`close`,t=>{if(u!==null&&t===0){m(Error(`Unable to write to ${e} stdin: ${u.message}`));return}p({stdout:o.join(``),stderr:s.join(``),status:l?124:t})}),a.stdin.on(`error`,e=>{u=e});try{a.stdin.end(n)}catch(t){m(t instanceof Error?Error(`Unable to write to ${e} stdin: ${t.message}`):Error(`Unable to write to ${e} stdin`))}})}const Oc=`catena-agent`;function kc(e){if(!zs.test(e))throw Error(`Invalid credential location for credential storage: "${e}"`);return e}const Ac=Ec(`/usr/bin/secret-tool`);function jc(e){return e.status===1&&e.stdout===``&&e.stderr.trim()===``}function Mc(e,t){if(t.status===0)return;let n=Nc(t);throw Error(`Linux Secret Service credential ${e} failed (secret-tool exited ${t.status??`without status`}): ${n}`)}function Nc(e){let t=e.stderr.toLowerCase();return e.status===124?`secret service operation timed out`:t.includes(`cannot autolaunch`)||t.includes(`dbus`)||t.includes(`d-bus`)||t.includes(`org.freedesktop.secrets`)?`secret service session is unavailable`:/\blocked\b/.test(t)?`secret service keyring appears to be locked`:t.includes(`authorization`)||t.includes(`denied`)||t.includes(`not authorized`)?`secret service authorization was denied`:`secret service operation failed; ensure the Secret Service session is available and unlocked`}function Pc(e){return e instanceof Error?e.message.includes(`ENOENT`)?Error(`Linux Secret Service credential operation failed: /usr/bin/secret-tool was not found. Install libsecret-tools and ensure a Secret Service keyring is available.`,{cause:e}):e:Error(String(e))}var Fc=class{runSecretTool;constructor(e={}){if((e.platform??process.platform)!==`linux`)throw Error(`Linux Secret Service credential storage is only supported on Linux`);this.runSecretTool=e.runSecretTool??Ac}async save(e,t){let n=yc(t),r=kc(e);if(await this.savePassword(r,wc(n)),!Tc(await this.resolveDirectPassword(r),n))throw Error(`Linux Secret Service credential save verification failed`)}async resolve(e){return this.resolveDirectPassword(kc(e))}async delete(e){await this.deletePassword(kc(e))}async savePassword(e,t){Mc(`save`,await this.runSecretToolCommand([`store`,`--label`,`${Oc} ${e}`,`app`,Oc,`account`,e],t))}async resolvePassword(e){let t=await this.runSecretToolCommand([`lookup`,`app`,Oc,`account`,e]);return jc(t)?null:(Mc(`resolve`,t),t.stdout.replace(/\r?\n$/,``))}async resolveDirectPassword(e){let t=await this.resolvePassword(e);return t===null?null:Sc(t,`Linux Secret Service`)}async deletePassword(e){let t=await this.runSecretToolCommand([`clear`,`app`,Oc,`account`,e]);jc(t)||Mc(`delete`,t)}async runSecretToolCommand(e,t){try{return await this.runSecretTool(e,t)}catch(e){throw Pc(e)}}};const Ic=Ec(`/usr/bin/security`),Lc=d.object({version:d.literal(1),encoding:d.literal(`base64-json`),chunks:d.pipe(d.number(),d.integer(),d.minValue(1),d.maxValue(64)),sha256:d.pipe(d.string(),d.regex(/^[a-f0-9]{64}$/))});function Rc(e){return e.status===44}function zc(e,t){return`${e}:chunk:${t}`}function Bc(e){let t=JSON.parse(e),n=bc(t);if(n!==null)return{kind:`direct`,payload:n};let r=d.safeParse(Lc,t);if(r.success)return{kind:`legacy`,manifest:r.output};throw Error(`macOS Keychain credential has an unsupported format`)}function Vc(e,t){if(t.status===0)return;let n=Hc(t);throw Error(`macOS Keychain credential ${e} failed (security exited ${t.status??`without status`})${n===null?``:`: ${n}`}`)}function Hc(e){let t=e.stderr.toLowerCase();return e.status===124?`keychain operation timed out`:t.includes(`stdin isn't a terminal`)?`parent process has no terminal`:t.includes(`user interaction is not allowed`)?`keychain user interaction is not allowed`:t.includes(`authorization`)||t.includes(`denied`)?`keychain authorization was denied`:t.includes(`locked`)?`keychain appears to be locked`:null}function Uc(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32||n===127)throw Error(`macOS Keychain credential values cannot contain control characters`)}return`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function Wc(e,t){return[`add-generic-password`,`-s`,Uc(Oc),`-a`,Uc(e),`-w`,Uc(t),`-U`].join(` `)+`
137
- `}var Gc=class{runSecurity;constructor(e={}){if((e.platform??process.platform)!==`darwin`)throw Error(`macOS Keychain credential storage is only supported on macOS`);this.runSecurity=e.runSecurity??Ic}async save(e,t){let n=yc(t),r=kc(e),i=await this.resolveLegacyChunkCount(r,64);if(await this.savePassword(r,wc(n)),!Tc(await this.resolveDirectPassword(r),n))throw Error(`macOS Keychain credential save verification failed`);await this.deleteChunks(r,i)}async resolve(e){let t=kc(e),n=await this.resolveKeychainItem(t);return n===null?null:n.kind===`direct`?n.payload:this.resolveLegacyPayload(t,n.manifest)}async delete(e){let t=kc(e),n=await this.resolveLegacyChunkCount(t,64);await this.deleteChunks(t,n),await this.deletePassword(t)}async savePassword(e,t){Vc(`save`,await this.runSecurity([`-i`],Wc(e,t)))}async resolvePassword(e){let t=await this.runSecurity([`find-generic-password`,`-a`,e,`-s`,Oc,`-w`]);return Rc(t)?null:(Vc(`resolve`,t),t.stdout.replace(/\r?\n$/,``))}async resolveKeychainItem(e){let t=await this.resolvePassword(e);return t===null?null:Bc(t)}async resolveDirectPassword(e){let t=await this.resolveKeychainItem(e);if(t===null)return null;if(t.kind!==`direct`)throw Error(`macOS Keychain credential direct verification failed`);return t.payload}async resolveLegacyPayload(e,t){let n=[];for(let r=0;r<t.chunks;r++){let t=await this.resolvePassword(zc(e,r));if(t===null)throw Error(`macOS Keychain credential chunk is missing`);n.push(t)}let r=n.join(``);if(m(`sha256`).update(r).digest(`hex`)!==t.sha256)throw Error(`macOS Keychain credential checksum mismatch`);return yc(JSON.parse(Buffer.from(r,`base64`).toString(`utf8`)))}async resolveLegacyChunkCount(e,t){let n=await this.resolvePassword(e);if(n===null)return 0;try{let e=Bc(n);return e.kind===`legacy`?e.manifest.chunks:0}catch{return t}}async deleteChunks(e,t){for(let n=0;n<t;n++)await this.deletePassword(zc(e,n))}async deletePassword(e){let t=await this.runSecurity([`delete-generic-password`,`-a`,e,`-s`,Oc]);Rc(t)||Vc(`delete`,t)}};function Kc(e={}){let t=e.platform??process.platform;if(t===`darwin`)return new Gc({platform:t});if(t===`linux`)return new Fc({platform:t});throw Error(`Catena credential storage is only supported on macOS and Linux`)}const qc=/^127(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}$/;function Jc(e){let t=e.replace(/^\[|\]$/g,``);return t===`localhost`||t===`::1`||qc.test(t)}function Yc(e){let t;try{t=new URL(e)}catch{return!1}return t.protocol===`https:`||t.protocol===`http:`&&Jc(t.hostname)}function Xc(e,t){if(!Yc(e))throw Error(`${t} must be an https:// URL (http:// is allowed only for a loopback host): "${e}"`)}const Zc=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/,Qc=d.object({status:d.optional(d.literal(`linked`),`linked`),bank_url:d.pipe(d.string(),d.minLength(1)),agent_id:d.pipe(d.string(),d.minLength(1)),client_instance_id:d.pipe(d.string(),d.regex(zs))}),$c=d.object({status:d.literal(`pending_connection`),bank_url:d.pipe(d.string(),d.minLength(1)),client_instance_id:d.pipe(d.string(),d.regex(zs)),created_at:d.pipe(d.string(),d.isoTimestamp())}),el=d.variant(`status`,[Qc,$c]);d.object({version:d.literal(1),default_profile:d.optional(d.string()),profiles:d.record(d.string(),el),directories:d.optional(d.record(d.string(),d.string()))});const tl=d.object({version:d.literal(1),default_profile:d.optional(d.string()),profiles:d.record(d.string(),d.unknown()),directories:d.optional(d.record(d.string(),d.unknown()))});function nl(){return te(process.env.HOME??ee(),`.catena`)}function rl(){return te(nl(),`profiles.json`)}function il(e){return Zc.test(e)}function al(e){if(!il(e))throw Error(`invalid profile name "${e}" (expected [a-zA-Z0-9][a-zA-Z0-9._-]{0,63})`)}function ol(e){return typeof e!=`object`||!e||!(`code`in e)?!1:typeof e.code==`string`}function sl(e,t){let n;try{n=JSON.parse(e)}catch(e){throw Error(`profiles.json is not valid JSON: ${gs(e)}`,{cause:e})}if(typeof n==`object`&&n&&`version`in n){let e=n;if(e.version!==1)throw Error(`profiles.json version ${String(e.version)} is not supported (expected 1)`)}let r=d.parse(tl,n),i={};for(let[e,n]of Object.entries(r.profiles)){if(!il(e)){t?.(`profiles: dropping invalid profile name "${e}"`);continue}let r=d.safeParse(el,n);if(!r.success){t?.(`profiles: dropping malformed profile "${e}"`);continue}i[e]=r.output}if(r.default_profile!==void 0&&(al(r.default_profile),!Object.hasOwn(i,r.default_profile)))throw Error(`profiles.json default_profile "${r.default_profile}" is not linked`);let a={};for(let[e,n]of Object.entries(r.directories??{})){if(!M(e)){t?.(`profiles: dropping directory binding with relative path "${e}"`);continue}if(typeof n!=`string`||!il(n)){t?.(`profiles: dropping malformed directory binding "${e}"`);continue}a[e]=n}return{version:1,...r.default_profile===void 0?{}:{default_profile:r.default_profile},profiles:i,...Object.keys(a).length===0?{}:{directories:a}}}function cl(e){try{return sl(T(rl(),`utf-8`),e)}catch(e){if(e instanceof Error&&ol(e)&&e.code===`ENOENT`)return{version:1,profiles:{}};throw e}}function ll(){w(nl(),{recursive:!0,mode:448}),x(nl(),448)}function ul(e){ll();let t=rl(),n=`${t}.${g(6).toString(`hex`)}.tmp`;A(n,JSON.stringify(e,null,2)+`
138
- `,{encoding:`utf-8`,mode:384}),D(n,t)}function dl(e,t){al(e);let n=d.parse(el,t);Xc(n.bank_url,`profile "${e}" bank_url`);let r=cl();ul({...r,profiles:{...r.profiles,[e]:n}})}function fl(e){return e.status===`linked`}function pl(e,t){return e.replace(/\/+$/,``)===t.replace(/\/+$/,``)}function ml(e,t){let n=Object.entries(cl().profiles).toSorted(([e],[t])=>e.localeCompare(t)).find(([,n])=>fl(n)&&n.agent_id===e&&pl(n.bank_url,t));return n===void 0?null:n[0]}function hl(e,t){let n=Object.fromEntries(Object.entries(e??{}).filter(([,e])=>t(e)));return Object.keys(n).length===0?{}:{directories:n}}function gl(e){al(e);let t=cl(),{[e]:n,...r}=t.profiles;ul({version:1,...t.default_profile===e||t.default_profile===void 0?{}:{default_profile:t.default_profile},profiles:r,...hl(t.directories,t=>t!==e)})}function _l(e){try{return E(ne(e))}catch{return ne(e)}}function vl(e){return cl().directories?.[_l(e)]??null}function yl(e,t){al(t);let n=cl();if(!Object.hasOwn(n.profiles,t))throw Error(`Profile "${t}" is not linked. Run catena link --profile ${t} <agent-id>.`);let r=_l(e);return ul({...n,directories:{...n.directories,[r]:t}}),r}function bl(e){let t=cl(),n=_l(e);if(t.directories===void 0||!Object.hasOwn(t.directories,n))return{directory:n,removed:!1};let{[n]:r,...i}=t.directories,{directories:a,...o}=t;return ul({...o,...Object.keys(i).length===0?{}:{directories:i}}),{directory:n,removed:!0}}function xl(e){return al(e),cl().profiles[e]??null}function Sl(){return`client_${g(16).toString(`hex`)}`}function Cl(e,t){let n=xl(e);return t.agent_id===void 0?wl(e,t.bank_url,n):Tl(e,t.bank_url,t.agent_id,n)}function wl(e,t,n){if(n?.status===`linked`)throw Error(`Profile "${e}" is already linked. Choose a different profile name to start agent connection.`);let r=(n?.status===`pending_connection`&&pl(n.bank_url,t)?n.client_instance_id:null)??Sl();return dl(e,{status:`pending_connection`,bank_url:t,client_instance_id:r,created_at:n?.status===`pending_connection`?n.created_at:new Date().toISOString()}),r}function Tl(e,t,n,r){if(r?.status===`linked`){if(r.agent_id!==n)throw Error(`Profile "${e}" is already linked to a different agent (${r.agent_id}). Link ${n} under a different --profile, or run 'catena unlink --profile ${e}' first to repoint it (add --force if that agent's credential is missing or revoked).`);if(!pl(r.bank_url,t))throw Error(`Profile "${e}" is already linked to this agent on a different bank (${r.bank_url}). Link under a different --profile, or run 'catena unlink --profile ${e}' first (add --force if that credential is missing or revoked).`);return r.client_instance_id}let i=(r?.status===`pending_connection`&&pl(r.bank_url,t)?r.client_instance_id:null)??Sl();return dl(e,{status:`linked`,bank_url:t,agent_id:n,client_instance_id:i}),i}function El(e){al(e);let t=cl();if(!Object.hasOwn(t.profiles,e))throw Error(`Profile "${e}" is not linked. Run catena link --profile ${e} <agent-id>.`);ul({...t,default_profile:e})}function Dl(e){let t=e.toLowerCase().replace(/[^a-z0-9._-]+/g,`-`).replace(/^[^a-z0-9]+/,``).slice(0,64);return il(t)?t:`agent`}function Ol(e,t){if(!t(e))return e;for(let n=2;;n++){let r=`${e.slice(0,64-String(n).length-1)}-${n}`;if(!t(r))return r}}function kl(e){al(e.reservationName),al(e.profileName);let t=d.parse(el,e.profile);Xc(t.bank_url,`profile "${e.profileName}" bank_url`);let n=cl(),{[e.reservationName]:r,...i}=n.profiles;if(!Object.hasOwn(n.profiles,e.reservationName)||r.client_instance_id!==t.client_instance_id)throw Error(`Link reservation "${e.reservationName}" changed during setup (a concurrent link from this directory?). Re-run 'catena link'.`);if(e.profileName!==e.reservationName&&Object.hasOwn(i,e.profileName))throw Error(`Profile "${e.profileName}" already exists; cannot finalize link under that name.`);let a=Object.fromEntries(Object.entries(n.directories??{}).map(([t,n])=>[t,n===e.reservationName?e.profileName:n]));ul({version:1,...n.default_profile===void 0?{}:{default_profile:n.default_profile===e.reservationName?e.profileName:n.default_profile},profiles:{...i,[e.profileName]:t},...Object.keys(a).length===0?{}:{directories:a}})}function Al(e){return e??Kc()}async function jl(e,t){let n;try{n=xl(e.profileName)}catch(t){return{ok:!1,profileName:e.profileName,bankUrl:e.fallbackBankUrl,message:gs(t)}}if(n===null)return{ok:!1,profileName:e.profileName,bankUrl:e.fallbackBankUrl,message:`Profile "${e.profileName}" is not linked. Run 'catena link --profile ${e.profileName}' to authenticate.`};try{Xc(n.bank_url,`profile "${e.profileName}" bank_url`)}catch(t){return{ok:!1,profileName:e.profileName,bankUrl:e.fallbackBankUrl,message:gs(t)}}if(n.status===`pending_connection`)return{ok:!1,profileName:e.profileName,bankUrl:n.bank_url,message:`Profile "${e.profileName}" is waiting for agent connection approval. Run 'catena link --profile ${e.profileName}' to finish setup.`};let r;try{r=await Al(t).resolve(n.client_instance_id)}catch(t){return{ok:!1,profileName:e.profileName,bankUrl:n.bank_url,message:`Profile "${e.profileName}" credential unavailable for ${n.agent_id}: ${gs(t)}. Run 'catena link --profile ${e.profileName} ${n.agent_id}' to authenticate.`}}return r===null||r.version===`signer-1`?{ok:!1,profileName:e.profileName,bankUrl:n.bank_url,message:`Profile "${e.profileName}" credential unavailable for ${n.agent_id}. Run 'catena link --profile ${e.profileName} ${n.agent_id}' to authenticate.`}:r.version===1?{ok:!1,profileName:e.profileName,bankUrl:n.bank_url,message:`Profile "${e.profileName}" credential for ${n.agent_id} has no signing key. Run 'catena link --profile ${e.profileName} ${n.agent_id}' to authenticate.`}:{ok:!0,profileName:e.profileName,bankUrl:n.bank_url,agentId:n.agent_id,clientInstanceId:n.client_instance_id,signer:r.signer}}const Ml=`https://api.catena.com`,Nl=`CATENA_SECRET_KEY`;function Pl(e,t){let n=e[t]?.trim();return n===void 0||n.length===0?void 0:n}function Fl(e=process.env){return Pl(e,Nl)!==void 0}function Il(e=process.env){let t=Pl(e,Nl);if(t===void 0)return null;let n=Pl(e,`CATENA_API_URL`)??`https://api.catena.com`;return Xc(n,`CATENA_API_URL`),{bankUrl:n,privateKeyHex:t}}const Ll=`CATENA_PROFILE`;function Rl(e,t,n,r){if(e.directories===void 0)return null;let i;try{i=E(t)}catch{return null}let a=Object.entries(e.directories).map(([e,t])=>[e.replace(/\/+$/,``)||`/`,t]).filter(([e])=>i===e||i.startsWith(e===`/`?`/`:`${e}/`)).toSorted(([e],[t])=>t.length-e.length),o=null;for(let[t,n]of a){if(Object.hasOwn(e.profiles,n))return n;o??=`${t} -> "${n}"`}if(o===null)return null;if(n===`error`)throw Error(`This directory is bound to a profile that no longer exists (${o}). Run 'catena profiles unbind' here, bind it with 'catena profiles bind <name>', or run 'catena link' to re-establish it.`);return r?.(`profiles: ignoring stale directory binding ${o}`),null}function zl(e,t,n){if(e.flag!==void 0&&e.flag.length>0)return al(e.flag),{name:e.flag,source:`flag`};if(e.env!==void 0&&e.env.length>0){if(!il(e.env))throw Error(`${Ll} is set to an invalid profile name "${e.env}"`);return{name:e.env,source:`env`}}if(e.cwd!==void 0){let r=Rl(t,e.cwd,n,e.log);if(r!==null)return{name:r,source:`directory`}}return t.default_profile===void 0?null:{name:t.default_profile,source:`default`}}function Bl(e){return zl(e,cl(e.log),`ignore`)}function Vl(e){let t=cl(e.log),n=zl(e,t,`error`);if(n!==null)return n;let r=Object.keys(t.profiles),i=Object.entries(t.profiles).filter(([,e])=>fl(e)).map(([e])=>e);if(i.length===1){let[e]=i;return{name:e,source:`single`}}if(i.length===0){if(r.length===1){let[e]=r;return{name:e,source:`single`}}return r.length>1&&e.log?.(`profiles: ignoring ${r.length} pending profiles (${r.toSorted().join(`, `)}); none is linked`),{name:`default`,source:`fallback`}}throw Error(`Multiple profiles exist and none is selected (${i.toSorted().join(`, `)}). Pass --profile <name>, set ${Ll}, run 'catena profiles use <name>', or run 'catena link' from an agent directory to bind it.`)}function Hl(){try{return Object.entries(cl().profiles).filter(([,e])=>fl(e)).map(([e])=>e).toSorted()}catch{return[]}}function Ul(e=process.env){let t=e[Ll]?.trim();if(t!==void 0&&t.length>0)return`profiles: signing with ${Nl}; ${Ll}=${t} is ignored. Pass --profile ${t} to use that profile.`;let n=Hl();if(n.length===0)return null;let r=n.length===1?`profile`:`profiles`;return`profiles: signing with ${Nl}; ${n.length} linked ${r} ignored (${n.join(`, `)}). Pass --profile <name> to use one.`}const Wl={name:`catena-cli`,version:oe},Gl=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function Kl(e,t){if(!Gl.test(e))throw Error(`${t} must be a valid HTTP token`)}function ql(e,t){let n=!1;for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r<32||r===127||r>255){n=!0;break}}if(n||/[()\\]/.test(e))throw Error(`${t} must not contain parentheses, backslashes, control characters, or characters outside Latin-1`)}function Jl(e){Kl(e.name,`appInfo.name`),e.version!==void 0&&Kl(e.version,`appInfo.version`),e.url!==void 0&&ql(e.url,`appInfo.url`);let t=e.version===void 0?e.name:`${e.name}/${e.version}`;return{"User-Agent":e.url===void 0?t:`${t} (${e.url})`}}function Yl(e){return hs({baseUrl:e.bankUrl,privateKeyHex:e.signer.privateKeyHex,appInfo:Wl})}function Xl(){return Kc()}function Zl(e){try{return hs({baseUrl:e.bankUrl,privateKeyHex:e.privateKeyHex,appInfo:Wl})}catch(e){return X(`${Nl} is not usable: ${gs(e)}`)}}async function Ql(e){if(e===void 0){let e;try{e=Il()}catch(e){return X(e)}if(e!==null){let t=Ul();return t!==null&&console.error(t),Zl(e)}}let t;try{t=Vl({flag:e,env:process.env[Ll],cwd:process.cwd(),log:e=>console.error(e)}).name}catch(e){return X(e)}let n=await jl({profileName:t,fallbackBankUrl:Ml},void 0);return n.ok||X(n.message),Yl(n)}const $l=new Set([`unknown_key`,`key_revoked`,`client_unlinked`]),eu=new Set([`signature_auth_disabled`,`missing_auth`]);function tu(e,t,n=process.env){if(!(e instanceof ss)||e.code===void 0)return e;let r=t===void 0?`catena link`:`catena link --profile ${t}`;return $l.has(e.code)?t===void 0&&Fl(n)?Error(`The bank rejected the ${Nl} signing key (${e.code}). Create a secret key in the Catena console under the agent's Secret keys tab, then update ${Nl}.`):Error(`This machine's signing key was rejected by the bank (${e.code}). Run '${r}' to re-authenticate.`):e.code===`client_upgrade_required`?Error(`This CLI version (${Wl.version}) is no longer supported by the bank. Run 'npm i -g @catena/cli' and retry.`):eu.has(e.code)?Error(`This bank does not support key-based authentication (${e.code}). Upgrade the bank, or use an older CLI release that authenticates with session tokens.`):e.code===`invalid_signature`&&e.message.includes(`created_out_of_window`)?Error(`The bank rejected this request's timestamp (created_out_of_window). Check this machine's system clock and retry.`):e}function nu(e,t){console.log(t?.compact?JSON.stringify(e):JSON.stringify(e,null,2))}function ru(e){return e.profile===void 0||e.profile.length===0?void 0:e.profile}async function iu(e,t){try{return await t(await Ql(e))}catch(t){return X(tu(t,e))}}function au(e,t){return async(n,r)=>{let i=await iu(e,n);return nu(i,t),await new Promise(e=>{process.stdout.write(``,()=>e())}),process.exit(r?.exitCode?r.exitCode(i):0)}}function $(e){return au(ru(e),{compact:e.json===!0})}const ou=d.pipe(d.string(),d.regex(/^\d+$/,`must be a non-negative integer`),d.transform(Number),d.maxValue(2**53-1,`must be at most ${2**53-1}`)),su=d.pipe(ou,d.maxValue(200,`must be at most 200`)),cu={profile:Ls,json:Rs},lu=Q(cu),uu=Q({account:ws({description:`Account id`,required:!0,schema:Bs}),...cu}),du=Q({account:ws({description:`Account id`,required:!0,schema:Bs}),start:Z({description:`Only include transactions at or after this ISO 8601 time`}),end:Z({description:`Only include transactions at or before this ISO 8601 time`}),limit:Z({description:`Maximum transactions to return (default 50, max 200)`,schema:su}),offset:Z({description:`Number of transactions to skip for pagination`,schema:ou}),...cu}),fu=Q({account:ws({description:`Account id`,required:!0,schema:Bs}),network:oc({description:`Deposit network; defaults to ${ic}. Availability depends on the connected environment.`,default:ic}),asset:Ds({description:`Deposit asset (${rc.join(`|`)})`,choices:rc,default:`usdc`}),...cu}),pu=c({meta:{name:`list`,description:`List accounts accessible under the agent's policy`},args:lu.args,async run({args:e}){await $(lu.parse(e))(e=>e.listAccounts())}}),mu=c({meta:{name:`balance`,description:`Request an account balance through the policy engine`},args:uu.args,async run({args:e}){let t=uu.parse(e);await $(t)(e=>e.getAccountBalance(t.account))}}),hu=c({meta:{name:`transactions`,description:`Read an account's transaction history through the policy engine`},args:du.args,async run({args:e}){let t=du.parse(e);await $(t)(e=>e.listAccountTransactions(t.account,{start:t.start,end:t.end,limit:t.limit,offset:t.offset}))}}),gu=c({meta:{name:`deposit-address`,description:`Read an account deposit address through the policy engine`},args:fu.args,async run({args:e}){let t=fu.parse(e);await $(t)(e=>e.getAccountDepositAddress(t.account,{network:t.network,asset:t.asset}))}}),_u=c({meta:{name:`accounts`,description:`Inspect bank accounts`},subCommands:{list:pu,balance:mu,transactions:hu,"deposit-address":gu}}),vu=d.pipe(d.string(`Idempotency key must be a string`),d.minLength(1,`Idempotency key must not be empty`),d.maxLength(255,`Idempotency key is too long (max 255 characters)`)),yu=d.pipe(d.string(),d.minLength(1,`must not be empty`)),bu=d.pipe(d.string(),d.trim(),d.email(`must be a valid email address`)),xu={profile:Ls,json:Rs},Su=Q({address:Z({description:`Only counterparties with a wallet rail matching this address (0x…)`,schema:ac}),network:oc({description:`Only counterparties with a wallet rail on this network (e.g. base)`}),...xu}),Cu=Z({description:`Counterparty name`,required:!0,schema:yu}),wu=Z({description:`Optional contact email`,schema:bu}),Tu=Z({description:`Optional operation key. Reuse the same value only when retrying the same submission; omitted generates a fresh key for this invocation.`,schema:vu}),Eu=Q({name:Cu,email:Z({description:`Contact email; creating the counterparty sends no email`,required:!0,schema:bu}),"idempotency-key":Tu,...xu}),Du=Q({name:Z({description:`Counterparty name; required without a subcommand`,schema:yu}),email:Z({description:`Contact email; required without a subcommand; creating the counterparty sends no email`,schema:bu}),"idempotency-key":Tu,...xu}),Ou=Q({name:Cu,"bank-name":Z({description:`Receiving bank name`,required:!0,schema:yu}),"routing-number":Z({description:`9-digit ABA routing number`,required:!0,schema:yu}),"account-number":Z({description:`Receiving bank account number`,required:!0,schema:yu}),"account-type":Ds({description:`checking | savings (default checking)`,choices:[`checking`,`savings`]}),"address-street":Z({description:`Street address of the receiving bank account holder`,required:!0,schema:yu}),"address-city":Z({description:`City`,required:!0,schema:yu}),"address-state":Z({description:`State (e.g. NY)`,required:!0,schema:yu}),"address-postal-code":Z({description:`Postal code`,required:!0,schema:yu}),"address-country":Z({description:`Default USA`}),email:wu,"idempotency-key":Tu,...xu}),ku=Q({name:Cu,address:Z({description:`Wallet address (0x… or ENS name on EVM networks)`,required:!0,schema:yu}),network:oc({description:`Wallet network; defaults to ${ic}. Availability depends on the connected environment.`,default:ic}),email:wu,"idempotency-key":Tu,...xu}),Au=Q({counterparty:ws({description:`Counterparty id`,required:!0,schema:Bs}),bank:Es({description:`Request bank account details`,default:!1}),wallet:Es({description:`Request wallet details`,default:!1}),"idempotency-key":Tu,...xu}),ju=c({meta:{name:`list`,description:`List counterparties available under the agent's policy`},args:Su.args,async run({args:e}){let t=Su.parse(e);await $(t)(e=>e.listCounterparties({address:t.address,network:t.network}))}});function Mu(e){return e&&e.length>0?e:void 0}function Nu(e){let t=Mu(e.email);return{type:`create_counterparty`,name:e.name,email:t,rail:{type:`bank`,bankName:e[`bank-name`],routingNumber:e[`routing-number`],accountNumber:e[`account-number`],addressStreet:e[`address-street`],addressCity:e[`address-city`],addressState:e[`address-state`],addressPostalCode:e[`address-postal-code`],...e[`account-type`]?{accountType:e[`account-type`]}:{},...e[`address-country`]?{addressCountry:e[`address-country`]}:{}}}}function Pu(e){let t=Mu(e.email);return{type:`create_counterparty`,name:e.name,email:t,rail:{type:`wallet`,walletAddress:e.address,network:e.network}}}function Fu(e){return{type:`create_counterparty`,name:e.name,email:e.email}}const Iu=c({meta:{name:`email`,description:`Create a counterparty with an email and no payment details. Sends no email.`},args:Eu.args,async run({args:e}){let t=Eu.parse(e);await $(t)(e=>e.submitIntent({action:Fu(t),...t[`idempotency-key`]!==void 0&&{idempotencyKey:t[`idempotency-key`]}}))}}),Lu=c({meta:{name:`bank`,description:`Request bank counterparty creation through the policy engine. Prints an intent envelope.`},args:Ou.args,async run({args:e}){let t=Ou.parse(e),n=Nu(t);await $(t)(e=>e.submitIntent({action:n,...t[`idempotency-key`]!==void 0&&{idempotencyKey:t[`idempotency-key`]}}))}}),Ru=c({meta:{name:`wallet`,description:`Request wallet counterparty creation through the policy engine. Prints an intent envelope.`},args:ku.args,async run({args:e}){let t=ku.parse(e);await $(t)(e=>e.submitIntent({action:Pu(t),...t[`idempotency-key`]!==void 0&&{idempotencyKey:t[`idempotency-key`]}}))}}),zu=c({meta:{name:`create`,description:`Request counterparty creation through the policy engine. Without a subcommand, --name and --email create a record without payment details and send no email.`},args:Du.args,default:`email`,subCommands:{email:Iu,bank:Lu,wallet:Ru}}),Bu=c({meta:{name:`request-details`,description:`Ask a counterparty to provide bank details, wallet details, or both through the policy engine.`},args:Au.args,async run({args:e}){let t=Au.parse(e);!t.bank&&!t.wallet&&X(`Select at least one of --bank or --wallet`),await $(t)(e=>e.submitIntent({action:{type:`request_counterparty_details`,counterpartyId:t.counterparty,methods:{bank:t.bank,wallet:t.wallet}},...t[`idempotency-key`]?{idempotencyKey:t[`idempotency-key`]}:{}}))}}),Vu=c({meta:{name:`counterparties`,description:`Inspect, create, and request details from counterparties`},subCommands:{list:ju,create:zu,"request-details":Bu}}),Hu=4e3;async function Uu(){process.stdin.setEncoding(`utf8`);let e=``;for await(let t of process.stdin)e+=t;return e}async function Wu(e){return e===void 0?(process.stdin.isTTY&&X(`<message>: pass a quoted message or pipe it on stdin; a message starting with "-" needs -- before it (catena feedback -- "<message>") or stdin`),Uu()):e}const Gu=Q({message:ws({description:`Plain-text feedback (1-4000 chars); omit to pipe on stdin`}),profile:Ls,json:Rs}),Ku=c({meta:{name:`feedback`,description:`Send free-form feedback about Catena to the Catena team`},args:Gu.args,async run({args:e}){(Array.isArray(e._)?e._:[]).length>1&&X(`<message>: pass the message as a single quoted argument`);let t=Gu.parse(e),n=(await Wu(t.message)).trim();n.length===0&&X(`<message>: must not be empty`),n.length>Hu&&X(`<message>: must be at most ${Hu} characters (got: ${n.length})`),await $(t)(async e=>(await e.submitFeedback(n),{ok:!0}))}});function qu(e){return`# Catena CLI Agent Guide
135
+ `);case`asn`:return n.AsnConvert.toString(t);case`hex`:return i.Convert.ToHex(t);case`base64`:return i.Convert.ToBase64(t);case`base64url`:return i.Convert.ToBase64Url(t);case`text`:return ve.serialize(this.toTextObject());default:throw TypeError(`Argument 'format' is unsupported value`)}}toTextObject(){let e=n.AsnConvert.parse(this.export(`raw`),m.ContentInfo),t=n.AsnConvert.parse(e.content,m.SignedData);return new L(`X509Certificates`,{"Content Type":R.toString(e.contentType),Content:new L(``,{Version:`${m.CMSVersion[t.version]} (${t.version})`,Certificates:new L(``,{Certificate:this.map(e=>e.toTextObject())})})})}},_t=class{constructor(e={}){this.certificates=[],e.certificates&&(this.certificates=e.certificates)}async build(e,t=z.get()){let n=new gt(e),r=e;for(;r=await this.findIssuer(r,t);){let e=await r.getThumbprint(t);for(let r of n){let n=await r.getThumbprint(t);if(i.isEqual(e,n))throw Error(`Cannot build a certificate chain. Circular dependency.`)}n.push(r)}return n}async findIssuer(e,t=z.get()){if(!await e.isSelfSigned(t)){let r=e.getExtension(p.id_ce_authorityKeyIdentifier);for(let a of this.certificates)if(a.subject===e.issuer){if(r){if(r.keyId){let e=a.getExtension(p.id_ce_subjectKeyIdentifier);if(e&&e.keyId!==r.keyId)continue}else if(r.certId){let e=a.getExtension(p.id_ce_subjectAltName);if(e&&!(r.certId.serialNumber===a.serialNumber&&i.isEqual(n.AsnConvert.serialize(r.certId.name),n.AsnConvert.serialize(e))))continue}}try{let n={...a.publicKey.algorithm,...e.signatureAlgorithm},r=await a.publicKey.export(n,[`verify`],t);if(!await e.verify({publicKey:r,signatureOnly:!0},t))continue}catch{continue}return a}}return null}},vt=class{static async createSelfSigned(e,t=z.get()){if(!e.keys.privateKey)throw Error(`Bad field 'keys' in 'params' argument. 'privateKey' is empty`);if(!e.keys.publicKey)throw Error(`Bad field 'keys' in 'params' argument. 'publicKey' is empty`);return this.create({serialNumber:e.serialNumber,subject:e.name,issuer:e.name,notBefore:e.notBefore,notAfter:e.notAfter,publicKey:e.keys.publicKey,signingKey:e.keys.privateKey,signingAlgorithm:e.signingAlgorithm,extensions:e.extensions},t)}static async create(e,t=z.get()){let r;r=e.publicKey instanceof Ve?e.publicKey.rawData:`publicKey`in e.publicKey?e.publicKey.publicKey.rawData:i.BufferSourceConverter.isBufferSource(e.publicKey)?e.publicKey:await t.subtle.exportKey(`spki`,e.publicKey);let a=e.serialNumber?i.BufferSourceConverter.toUint8Array(i.Convert.FromHex(e.serialNumber)):t.getRandomValues(new Uint8Array(16));a[0]>127&&(a[0]&=127),a.length>1&&a[0]===0&&(a[1]|=128);let o=e.notBefore||new Date,s=e.notAfter||new Date(o.getTime()+31536e6),c=new p.Certificate({tbsCertificate:new p.TBSCertificate({version:p.Version.v3,serialNumber:a,validity:new p.Validity({notBefore:o,notAfter:s}),extensions:new p.Extensions(e.extensions?.map(e=>n.AsnConvert.parse(e.rawData,p.Extension))||[]),subjectPublicKeyInfo:n.AsnConvert.parse(r,p.SubjectPublicKeyInfo)})});if(e.subject){let t=e.subject instanceof V?e.subject:new V(e.subject);c.tbsCertificate.subject=n.AsnConvert.parse(t.toArrayBuffer(),p.Name)}if(e.issuer){let t=e.issuer instanceof V?e.issuer:new V(e.issuer);c.tbsCertificate.issuer=n.AsnConvert.parse(t.toArrayBuffer(),p.Name)}let u={hash:`SHA-256`},d=`signingKey`in e?{...u,...e.signingAlgorithm,...e.signingKey.algorithm}:{...u,...e.signingAlgorithm},f=l.container.resolve(b);c.tbsCertificate.signature=c.signatureAlgorithm=f.toAsnAlgorithm(d);let m=n.AsnConvert.serialize(c.tbsCertificate),h=`signingKey`in e?await t.subtle.sign(d,e.signingKey,m):e.signature,g=l.container.resolveAll(it).reverse(),_=null;for(let e of g)if(_=e.toAsnSignature(d,h),_)break;if(!_)throw Error(`Cannot convert ASN.1 signature value to WebCrypto format`);return c.signatureValue=_,new ht(n.AsnConvert.serialize(c))}};e.X509CrlReason=void 0,(function(e){e[e.unspecified=0]=`unspecified`,e[e.keyCompromise=1]=`keyCompromise`,e[e.cACompromise=2]=`cACompromise`,e[e.affiliationChanged=3]=`affiliationChanged`,e[e.superseded=4]=`superseded`,e[e.cessationOfOperation=5]=`cessationOfOperation`,e[e.certificateHold=6]=`certificateHold`,e[e.removeFromCRL=8]=`removeFromCRL`,e[e.privilegeWithdrawn=9]=`privilegeWithdrawn`,e[e.aACompromise=10]=`aACompromise`})(e.X509CrlReason||={});var yt=class extends ye{constructor(...e){let t;t=i.BufferSourceConverter.isBufferSource(e[0])?i.BufferSourceConverter.toArrayBuffer(e[0]):n.AsnConvert.serialize(new r.RevokedCertificate({userCertificate:e[0],revocationDate:new r.Time(e[1]),crlEntryExtensions:e[2]})),super(t,r.RevokedCertificate)}onInit(e){this.serialNumber=i.Convert.ToHex(e.userCertificate),this.revocationDate=e.revocationDate.getTime(),this.extensions=[],e.crlEntryExtensions&&(this.extensions=e.crlEntryExtensions.map(e=>{let t=G.create(n.AsnConvert.serialize(e));switch(t.type){case r.id_ce_cRLReasons:this.reason=n.AsnConvert.parse(t.value,r.CRLReason).reason;break;case r.id_ce_invalidityDate:this.invalidity=n.AsnConvert.parse(t.value,r.InvalidityDate).value}return t}))}},bt=class extends W{constructor(e){W.isAsnEncoded(e)?super(e,r.CertificateList):super(e),this.tag=U.CrlTag}onInit(e){let t=e.tbsCertList;this.tbs=n.AsnConvert.serialize(t),this.version=t.version;let r=l.container.resolve(b);this.signatureAlgorithm=r.toWebAlgorithm(e.signatureAlgorithm),this.tbsCertListSignatureAlgorithm=t.signature,this.certListSignatureAlgorithm=e.signatureAlgorithm,this.signature=e.signature,this.issuerName=new V(t.issuer),this.issuer=this.issuerName.toString();let i=t.thisUpdate.getTime();if(!i)throw Error(`Cannot get 'thisUpdate' value`);this.thisUpdate=i;let a=t.nextUpdate?.getTime();this.nextUpdate=a,this.entries=t.revokedCertificates?.map(e=>new yt(n.AsnConvert.serialize(e)))||[],this.extensions=[],t.crlExtensions&&(this.extensions=t.crlExtensions.map(e=>G.create(n.AsnConvert.serialize(e))))}getExtension(e){for(let t of this.extensions)if(typeof e==`string`){if(t.type===e)return t}else if(t instanceof e)return t;return null}getExtensions(e){return this.extensions.filter(t=>typeof e==`string`?t.type===e:t instanceof e)}async verify(e,t=z.get()){if(!this.certListSignatureAlgorithm.isEqual(this.tbsCertListSignatureAlgorithm))throw Error(`algorithm identifier in the sequence tbsCertList and CertificateList mismatch`);let n,r,i=e.publicKey;try{i instanceof ht?(n={...i.publicKey.algorithm,...i.signatureAlgorithm},r=await i.publicKey.export(n,[`verify`])):i instanceof Ve?(n={...i.algorithm,...this.signature},r=await i.export(n,[`verify`])):(n={...i.algorithm,...this.signature},r=i)}catch{return!1}let a=l.container.resolveAll(it).reverse(),o=null;for(let e of a)if(o=e.toWebSignature(n,this.signature),o)break;if(!o)throw Error(`Cannot convert ASN.1 signature value to WebCrypto format`);return await t.subtle.verify(this.signatureAlgorithm,r,o,this.tbs)}async getThumbprint(...e){let t,n=`SHA-1`;return e[0]&&(e[0].subtle?t=e[0]:(n=e[0]||n,t=e[1])),t??=z.get(),await t.subtle.digest(n,this.rawData)}findRevoked(e){let t=typeof e==`string`?e:e.serialNumber;for(let e of this.entries)if(e.serialNumber===t)return e;return null}},xt=class{static async create(e,t=z.get()){let a=e.issuer instanceof V?e.issuer:new V(e.issuer),o=new p.CertificateList({tbsCertList:new p.TBSCertList({version:p.Version.v2,issuer:n.AsnConvert.parse(a.toArrayBuffer(),p.Name),thisUpdate:new r.Time(e.thisUpdate||new Date)})});if(e.nextUpdate&&(o.tbsCertList.nextUpdate=new r.Time(e.nextUpdate)),e.extensions&&e.extensions.length&&(o.tbsCertList.crlExtensions=new p.Extensions(e.extensions.map(e=>n.AsnConvert.parse(e.rawData,p.Extension))||[])),e.entries&&e.entries.length){o.tbsCertList.revokedCertificates=[];for(let t of e.entries){let a=W.toArrayBuffer(t.serialNumber);if(o.tbsCertList.revokedCertificates.findIndex(e=>i.isEqual(e.userCertificate,a))>-1)throw Error(`Certificate serial number ${t.serialNumber} already exists in tbsCertList`);let s=new r.RevokedCertificate({userCertificate:a,revocationDate:new r.Time(t.revocationDate||new Date)});if(s.crlEntryExtensions=`extensions`in t&&t.extensions?.length?t.extensions.map(e=>n.AsnConvert.parse(e.rawData,p.Extension)):[],!(t instanceof yt)&&(t.reason&&s.crlEntryExtensions.push(new p.Extension({extnID:p.id_ce_cRLReasons,critical:!1,extnValue:new n.OctetString(n.AsnConvert.serialize(new p.CRLReason(t.reason)))})),t.invalidity&&s.crlEntryExtensions.push(new p.Extension({extnID:p.id_ce_invalidityDate,critical:!1,extnValue:new n.OctetString(n.AsnConvert.serialize(new p.InvalidityDate(t.invalidity)))})),t.issuer)){let t=e.issuer instanceof V?e.issuer:new V(e.issuer);s.crlEntryExtensions.push(new p.Extension({extnID:p.id_ce_certificateIssuer,critical:!1,extnValue:new n.OctetString(n.AsnConvert.serialize(n.AsnConvert.parse(t.toArrayBuffer(),p.Name)))}))}o.tbsCertList.revokedCertificates.push(s)}}let s={...e.signingAlgorithm,...e.signingKey.algorithm},c=l.container.resolve(b);o.tbsCertList.signature=o.signatureAlgorithm=c.toAsnAlgorithm(s);let u=n.AsnConvert.serialize(o.tbsCertList),d=await t.subtle.sign(s,e.signingKey,u),f=l.container.resolveAll(it).reverse(),m=null;for(let e of f)if(m=e.toAsnSignature(s,d),m)break;if(!m)throw Error(`Cannot convert ASN.1 signature value to WebCrypto format`);return o.signature=m,new bt(n.AsnConvert.serialize(o))}};G.register(p.id_ce_basicConstraints,We),G.register(p.id_ce_extKeyUsage,Ge),G.register(p.id_ce_keyUsage,Ke),G.register(p.id_ce_subjectKeyIdentifier,qe),G.register(p.id_ce_authorityKeyIdentifier,Ue),G.register(p.id_ce_subjectAltName,Je),G.register(p.id_ce_cRLDistributionPoints,Xe),G.register(p.id_pe_authorityInfoAccess,Ze),rt.register(_.id_pkcs9_at_challengePassword,tt),rt.register(_.id_pkcs9_at_extensionRequest,nt),l.container.registerSingleton(it,at),l.container.registerSingleton(it,ct),ct.namedCurveSize.set(`P-256`,32),ct.namedCurveSize.set(`K-256`,32),ct.namedCurveSize.set(`P-384`,48),ct.namedCurveSize.set(`P-521`,66),e.AlgorithmProvider=y,e.AsnData=ye,e.AsnDefaultSignatureFormatter=at,e.AsnEcSignatureFormatter=ct,e.Attribute=et,e.AttributeFactory=rt,e.AuthorityInfoAccessExtension=Ze,e.AuthorityKeyIdentifierExtension=Ue,e.BasicConstraintsExtension=We,e.CRLDistributionPointsExtension=Xe,e.CertificatePolicyExtension=Ye,e.ChallengePasswordAttribute=tt,e.CryptoProvider=Se,e.DefaultAlgorithmSerializer=_e,e.ExtendedKeyUsageExtension=Ge,e.Extension=be,e.ExtensionFactory=G,e.ExtensionsAttribute=nt,e.GeneralName=Re,e.GeneralNames=ze,e.KeyUsagesExtension=Ke,e.Name=V,e.NameIdentifier=Te,e.OidSerializer=R,e.PemConverter=U,e.Pkcs10CertificateRequest=pt,e.Pkcs10CertificateRequestGenerator=mt,e.PublicKey=Ve,e.SubjectAlternativeNameExtension=Je,e.SubjectKeyIdentifierExtension=qe,e.TextConverter=ve,e.TextObject=L,e.X509Certificate=ht,e.X509CertificateGenerator=vt,e.X509Certificates=gt,e.X509ChainBuilder=_t,e.X509Crl=bt,e.X509CrlEntry=yt,e.X509CrlGenerator=xt,e.cryptoProvider=z,e.diAlgorithm=v,e.diAlgorithmProvider=b,e.diAsnSignatureFormatter=it,e.idEd25519=dt,e.idEd448=ft,e.idX25519=lt,e.idX448=ut}));De(),ca();var la;(function(e){e.Der=`der`,e.Raw=`raw`})(la||={});const ua=typeof window<`u`&&window.document!==void 0&&typeof crypto<`u`&&crypto.subtle!==void 0,da=typeof process<`u`&&process.versions!=null&&process.versions.node!=null,fa=()=>ua?`browser`:da?`node`:`purejs`,pa=async(e,t)=>{let n=t??fa();switch(n){case`browser`:return(await import(`./webcrypto-CejAJWkk.mjs`)).signWithApiKey(e);case`node`:return(await import(`./nodecrypto-86590WN-.mjs`)).signWithApiKey(e);case`purejs`:return(await import(`./purejs-xzcexc4T.mjs`)).signWithApiKey(e);default:throw Error(`Unsupported runtime: ${n}`)}};var ma=class{constructor(e){this.apiPublicKey=e.apiPublicKey,this.apiPrivateKey=e.apiPrivateKey,this.runtimeOverride=e.runtimeOverride}async stamp(e){let t=await pa({publicKey:this.apiPublicKey,privateKey:this.apiPrivateKey,content:e},this.runtimeOverride),n={publicKey:this.apiPublicKey,scheme:`SIGNATURE_SCHEME_TK_API_P256`,signature:t};return{stampHeaderName:`X-Stamp`,stampHeaderValue:I(JSON.stringify(n))}}async sign(e,t){switch(t){case la.Raw:{let t=await pa({publicKey:this.apiPublicKey,privateKey:this.apiPrivateKey,content:e},this.runtimeOverride),n=Te(t);return s(n)}case la.Der:return pa({publicKey:this.apiPublicKey,privateKey:this.apiPrivateKey,content:e},this.runtimeOverride);default:throw Error(`Unsupported signature format: ${t}`)}}},ha=class extends Error{constructor(e){super(e),this.name=`InvalidKeyError`}};function ga(){let e=p(`prime256v1`);return e.generateKeys(),va(e.getPrivateKey().toString(`hex`).padStart(64,`0`))}const _a=/^[0-9a-f]{64}$/i;function va(e){if(!_a.test(e))throw new ha(`P-256 private key must be 64 hex characters`);let t=e.toLowerCase(),n=p(`prime256v1`);try{n.setPrivateKey(Buffer.from(t,`hex`))}catch{throw new ha(`value is not a valid P-256 private key (scalar out of range)`)}return{algorithm:`p256`,privateKeyHex:t,publicKeyHex:n.getPublicKey(`hex`,`compressed`)}}function ya(e){try{let t=f.convertKey(e,`prime256v1`,`hex`,`hex`,`uncompressed`),n=Buffer.isBuffer(t)?t:Buffer.from(t,`hex`);return n.length===65?n:null}catch{return null}}function ba(e){let t=ya(e);if(t===null)throw new ha(`value is not a valid P-256 public key`);return xa(t)}function xa(e){let t=e.subarray(1,33).toString(`base64url`),n=e.subarray(33,65).toString(`base64url`);return m(`sha256`).update(`{"crv":"P-256","kty":"EC","x":"${t}","y":"${n}"}`,`utf8`).digest(`base64url`)}const Sa=/^https?:\/\/[\x21\x23-\x7e]{1,255}$/,Ca=/^[\x21\x23-\x3a\x3c-\x7e]{1,128}$/;function wa(e,t){return`${e.replace(/\/+$/,``)}/agent-keys/${t}`}function Ta(e){let t=Ea(e.keypair),n={...t,identityUrl:Da(e.identityUrl??wa(e.baseUrl,t.keyId))};return{sign:async e=>{let t=new Uint8Array(await e.clone().arrayBuffer()),r=Oa(n,{method:e.method,url:e.url,body:t},{nonce:g(16).toString(`base64url`),createdAt:new Date}),i=new Headers(e.headers);for(let[e,t]of Object.entries(r))i.set(e,t);return new Request(e,{headers:i})}}}function Ea(e){let t=ya(e.publicKeyHex);if(t===null)throw Error(`signer keypair has an invalid P-256 public key`);return{signingKey:Ma(t,e.privateKeyHex),keyId:xa(t)}}function Da(e){if(!Sa.test(e))throw Error(`identity URL is outside the signature profile: "${e}"`);return e}function Oa(e,t,n){if(!Ca.test(n.nonce))throw Error(`nonce is outside the signature profile`);let r=ka(t.body),i=`"${e.identityUrl}"`,a=`("@method" "@target-uri" "content-digest" "signature-agent");created=${Math.floor(n.createdAt.getTime()/1e3)};keyid="${e.keyId}";nonce="${n.nonce}";alg="ecdsa-p256-sha256"`,o=[`"@method": ${t.method.toUpperCase()}`,`"@target-uri": ${Aa(new URL(t.url))}`,`"content-digest": ${r}`,`"signature-agent": ${i}`,`"@signature-params": ${a}`].join(`
136
+ `),s=_(`sha256`,Buffer.from(o,`utf8`),{key:e.signingKey,dsaEncoding:`ieee-p1363`});return{"Content-Digest":r,"Signature-Agent":i,"Signature-Input":`sig=${a}`,Signature:`sig=:${s.toString(`base64`)}:`}}function ka(e){return`sha-256=:${m(`sha256`).update(e??``).digest(`base64`)}:`}function Aa(e){return`${e.protocol}//${ja(e)}${e.pathname}${e.search}`}function ja(e){let t=e.host.toLowerCase();return e.protocol===`https:`&&e.port===`443`||e.protocol===`http:`&&e.port===`80`?e.hostname.toLowerCase():t}function Ma(e,t){return h({key:{kty:`EC`,crv:`P-256`,d:Buffer.from(t,`hex`).toString(`base64url`),x:e.subarray(1,33).toString(`base64url`),y:e.subarray(33,65).toString(`base64url`)},format:`jwk`})}var Na=`0.2.0`;const Pa=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Fa=Na;function Ia(e,t){if(!Pa.test(e))throw Error(`${t} must be a valid HTTP token`)}function La(e,t){let n=!1;for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r<32||r===127||r>255){n=!0;break}}if(n||/[()\\]/.test(e))throw Error(`${t} must not contain parentheses, backslashes, control characters, or characters outside Latin-1`)}function Ra(e){let t=`catena-agent-client/${Fa}`;if(!e)return t;Ia(e.name,`appInfo.name`),e.version!==void 0&&Ia(e.version,`appInfo.version`),e.url!==void 0&&La(e.url,`appInfo.url`);let n=e.version===void 0?e.name:`${e.name}/${e.version}`;return`${e.url===void 0?n:`${n} (${e.url})`} ${t}`}const za=d.object({paymentCredential:d.object({protocol:d.picklist([`mpp`,`x402`]),value:d.string()})});function Ba(e,t){let n=d.safeParse(za,e);return n.success&&n.output.paymentCredential.protocol===t?n.output.paymentCredential.value:void 0}const Va=`offer-receipt`,Ha=8192,Ua=d.pipe(d.string(),d.maxLength(Ha),d.regex(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,`Expected a JWS compact serialization`)),Wa=d.optional(d.pipe(d.number(),d.integer(),d.minValue(0))),Ga=d.pipe(d.string(),d.regex(/^0x[0-9a-fA-F]{130}$/,`Expected a 65-byte hex signature`)),Ka=d.variant(`format`,[d.looseObject({format:d.literal(`eip712`),acceptIndex:Wa,payload:d.record(d.string(),d.unknown()),signature:Ga}),d.looseObject({format:d.literal(`jws`),acceptIndex:Wa,signature:Ua})]),qa=d.variant(`format`,[d.looseObject({format:d.literal(`eip712`),payload:d.record(d.string(),d.unknown()),signature:Ga}),d.looseObject({format:d.literal(`jws`),signature:Ua})]),Ja=d.object({[Va]:d.object({info:d.object({offers:d.array(d.unknown())})})}),Ya=d.object({[Va]:d.object({info:d.object({receipt:d.unknown()})})}),Xa=d.looseObject({version:d.literal(1),resourceUrl:d.pipe(d.string(),d.maxLength(2048)),scheme:d.pipe(d.string(),d.maxLength(64)),network:d.pipe(d.string(),d.maxLength(64)),asset:d.pipe(d.string(),d.maxLength(128)),payTo:d.pipe(d.string(),d.maxLength(128)),amount:d.pipe(d.string(),d.regex(/^\d+$/),d.maxLength(78)),validUntil:d.optional(d.pipe(d.number(),d.integer(),d.minValue(0)))});function Za(e){let t=e.replaceAll(`-`,`+`).replaceAll(`_`,`/`),n=Uint8Array.from(atob(t),e=>e.charCodeAt(0));return JSON.parse(new TextDecoder().decode(n))}function Qa(e){if(e.format===`eip712`){let t=d.safeParse(Xa,e.payload);return t.success?t.output:void 0}let t=e.signature.split(`.`)[1];try{let e=d.safeParse(Xa,Za(t));return e.success?e.output:void 0}catch{return}}function $a(e,t){return e.toLowerCase()===t.toLowerCase()}function eo(e,t){return e.scheme===t.scheme&&e.network===t.network&&$a(e.asset,t.asset)&&$a(e.payTo,t.payTo)&&e.amount===t.amount}function to(e){return new TextEncoder().encode(JSON.stringify(e)).length<=Ha}function no(e,t){let n=d.safeParse(Ja,e);if(n.success)for(let e of n.output[Va].info.offers){let n=d.safeParse(Ka,e);if(!n.success)continue;let r=Qa(n.output);if(r!==void 0&&eo(r,t)&&to(n.output))return n.output}}function ro(e){let t=d.safeParse(Ya,e);if(!t.success)return;let n=d.safeParse(qa,t.output[Va].info.receipt);if(n.success&&to(n.output))return n.output}const io=d.pipe(d.string(),d.regex(/\S/,`Response enum values must not be blank`));function ao(e){return io}const oo=d.object({amount:d.string(),asset_id:d.string()}),so=d.pipe(d.string(),d.isoTimestamp()),co=d.object({success:d.literal(!0)}),lo=d.object({id:d.string(),name:d.string(),status:d.string(),organizationId:d.string()}),uo=d.object({agent:lo}),fo=[`per_transaction_amount`,`daily_amount`,`weekly_amount`,`monthly_amount`,`hourly_count`,`daily_count`],po=d.object({id:d.string(),ruleType:ao(fo),thresholdAmount:d.optional(oo),thresholdCount:d.optional(d.number()),action:ao([`block`,`require_approval`]),requiredApprovals:d.number(),accountAggregationScope:ao([`per_account`,`across_accounts`]),actorAggregationScope:ao([`per_agent`,`per_policy`]),displayOrder:d.number()}),mo=d.object({id:d.string(),organizationId:d.string(),policyId:d.string(),capability:ao([`query_balance`,`read`,`send`,`transfer`]),accountId:d.string(),rules:d.array(po),createdAt:so,updatedAt:so}),ho=[`allow`,`block`,`require_approval`],go=[`open`,`restricted`],_o=ao(ho),vo=d.object({mode:ao(go),allowedCounterparties:d.optional(d.array(d.string())),createAction:d.optional(_o),requestPaymentDetailsAction:d.optional(_o),allowCreate:d.optional(d.boolean())}),yo=d.object({id:d.optional(d.string()),description:d.optional(d.string()),version:d.optional(d.number()),name:d.string(),capabilities:d.array(d.string()),counterpartyRules:d.optional(vo),policyCapabilities:d.array(mo),kind:d.optional(d.picklist([`base`,`override`])),expiresAt:d.optional(d.string())}),bo=d.object({policy:yo}),xo=d.object({accounts:d.array(d.object({id:d.string(),name:d.string(),type:d.string(),currency:d.string()}))}),So=d.object({accountId:d.string(),balance:oo,balances:d.optional(d.object({total:oo,available:oo}))}),Co=[`operator-send`,`operator-transfer`,`operator-deposit`,`operator-refund`,`microdeposit`],wo=[`pending`,`processing`,`completed`,`failed`,`reversed`],To=[`initiated`,`provider_pending`,`processing`,`completed`,`failed`,`reversed`,`manual_review`],Eo=[`ach`,`wire`,`on-chain`],Do=d.object({id:d.string(),type:ao(Co),action:d.optional(d.string()),status:ao(wo),movementStatus:ao(To),direction:d.picklist([`incoming`,`outgoing`]),amount:oo,fee:oo,currency:d.string(),counterpartyName:d.optional(d.string()),method:d.optional(ao([`ach`,`wire`,`on-chain`])),memo:d.optional(d.string()),description:d.optional(d.string()),txHash:d.optional(d.string()),createdAt:so,completedAt:d.optional(so)}),Oo=d.object({accountId:d.string(),transactions:d.array(Do),total:d.number()}),ko=d.object({accountId:d.string(),address:d.string(),liquidationAddressId:d.optional(d.string()),source:ao([`wallet`,`liquidation`])}),Ao=d.object({type:d.literal(`wallet`),walletAddress:d.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{40}$/.test(e)),network:d.custom(e=>typeof e==`string`&&e.length>0)}),jo=d.object({id:d.string(),name:d.string(),status:d.optional(d.string()),rails:d.array(d.object({id:d.string(),type:d.string(),walletAddress:d.optional(d.string()),network:d.optional(d.string()),bankName:d.optional(d.string()),accountNumber:d.optional(d.string())}))}),Mo=d.object({counterparties:d.array(jo)}),No=d.picklist([`pending`,`processing`,`completed`,`blocked`,`failed`]),Po=d.object({type:d.literal(`submit_stamp`),signingRequestId:d.string(),signer:d.object({algorithm:d.literal(`p256`),publicKeyHex:d.string()}),preparedBody:d.object({body:d.string(),bodyHash:d.string(),expiresAt:so,prepareToken:d.string()})}),Fo=d.object({id:d.string(),accountId:d.optional(d.string()),type:ao([`send`,`transfer`,`create_counterparty`,`request_counterparty_details`,`x402`,`mpp`,`policy_override`]),status:No,reasons:d.array(d.string()),expiresAt:d.optional(d.nullable(so),null),replayed:d.optional(d.boolean(),!1),data:d.optional(d.nullable(d.record(d.string(),d.unknown())),null),metadata:d.optional(d.object({dataUrl:d.nullable(d.string())})),nextAction:d.optional(Po)});function Io(e){let{nextAction:t,...n}=e;return n}const Lo=d.object({x402:d.object({paymentSignature:d.string()})});function Ro(e){let t=Ba(e,`x402`);if(t!==void 0)return t;let n=d.safeParse(Lo,e);return n.success?n.output.x402.paymentSignature:void 0}const zo=d.picklist(Eo),Bo=d.object({type:d.literal(`send`),accountId:d.optional(d.pipe(d.string(),d.minLength(1))),counterpartyRailId:d.string(),amount:d.string(),method:zo,memo:d.optional(d.string()),description:d.optional(d.string())}),Vo=d.object({type:d.literal(`transfer`),accountId:d.string(),toAccountId:d.string(),amount:d.string(),memo:d.optional(d.string()),description:d.optional(d.string())}),Ho={type:d.literal(`create_counterparty`),name:d.string()},Uo=d.union([d.object({...Ho,email:d.optional(d.string()),rail:d.nonOptional(d.unknown())}),d.object({...Ho,email:d.string()})]),Wo=d.object({type:d.literal(`request_counterparty_details`),counterpartyId:d.string(),methods:d.pipe(d.object({bank:d.boolean(),wallet:d.boolean()}),d.check(({bank:e,wallet:t})=>e||t,`Select at least one payment method to request`))}),Go=d.looseObject({scheme:d.string(),network:d.string(),asset:d.string(),amount:d.string(),payTo:d.string(),maxTimeoutSeconds:d.number()}),Ko=d.looseObject({url:d.string(),serviceName:d.fallback(d.optional(d.pipe(d.string(),d.maxLength(255))),void 0)}),qo=d.pipe(d.string(),d.regex(/^0x[0-9a-fA-F]{40}$/,`Expected a 20-byte hex address`)),Jo=d.pipe(d.string(),d.maxLength(78),d.regex(/^(0|[1-9]\d*)$/,`Expected a canonical decimal integer string`)),Yo=d.object({from:qo,to:qo,value:Jo,validAfter:Jo,validBefore:Jo,nonce:d.pipe(d.string(),d.regex(/^0x[0-9a-fA-F]{64}$/,`Expected a 32-byte hex nonce`))}),Xo=d.object({type:d.literal(`x402`),accountId:d.string(),paymentRequirements:Go,resource:d.optional(Ko),authorization:d.optional(Yo),signedOffer:d.optional(Ka)}),Zo=d.object({id:d.string(),realm:d.string(),method:d.picklist([`evm`,`usdc`]),intent:d.literal(`charge`),request:d.string(),description:d.optional(d.string()),digest:d.optional(d.string()),expires:d.string(),header:d.optional(d.literal(`Payment-Authorization`)),opaque:d.optional(d.string())}),Qo=d.object({url:d.string(),serviceName:d.optional(d.string())}),$o=d.object({type:d.literal(`mpp`),accountId:d.string(),challenge:Zo,resource:d.optional(Qo)}),es=[`send`,`transfer`],ts=d.strictObject({type:d.literal(`increase_limit`),accountId:d.pipe(d.string(),d.minLength(1)),capability:d.picklist(es),limitType:d.picklist([`per_transaction_amount`,`daily_amount`,`weekly_amount`,`monthly_amount`]),newLimit:d.strictObject({amount:d.pipe(d.string(),d.regex(/^\d+(\.\d{1,6})?$/),d.check(e=>Number(e)>0,`The amount must be greater than zero`)),assetId:d.literal(`USD`)})}),ns=d.strictObject({type:d.literal(`increase_limit`),accountId:d.pipe(d.string(),d.minLength(1)),capability:d.picklist(es),limitType:d.picklist([`hourly_count`,`daily_count`]),newLimit:d.strictObject({count:d.pipe(d.number(),d.integer(),d.minValue(1))})}),rs=d.pipe(d.array(d.union([ts,ns])),d.minLength(1),d.maxLength(10),d.check(e=>new Set(e.map(e=>`${e.accountId}|${e.capability}|${e.limitType}`)).size===e.length,`Each account, capability, and limit type may appear only once`)),is=d.object({type:d.literal(`policy_override`),operations:rs,durationSeconds:d.pipe(d.number(),d.integer(),d.minValue(60),d.maxValue(604800)),reason:d.pipe(d.string(),d.trim(),d.minLength(1),d.maxLength(280))}),as=d.union([Bo,Vo,Uo,Wo,Xo,$o,is]);function os(e){let t=d.parse(as,e);return t.type===`send`||t.type===`transfer`?{...t,amount:{amount:t.amount,asset_id:`USD`}}:t.type===`policy_override`?{...t,schemaVersion:1}:t}const ss=d.object({intent:Fo});var cs=class extends Error{status;code;details;constructor(e,t,n,r){super(n?`API error ${e} [${n}]: ${t}`:`API error ${e}: ${t}`),this.name=`ApiError`,this.status=e,this.code=n,this.details=r}},ls=class extends Error{timeoutMs;constructor(e){super(`Request timed out after ${e}ms. The server may still have processed a state-changing request; follow that operation's documented recovery procedure before retrying.`),this.name=`TimeoutError`,this.timeoutMs=e}};const us=d.object({error:d.nullish(d.string()),message:d.nullish(d.string()),code:d.nullish(d.string()),details:d.nullish(d.record(d.string(),d.unknown()))});async function ds(e){let t=d.safeParse(us,await e.json().catch(()=>void 0)),n=t.success?t.output:{};return n.error!=null&&n.message!=null?new cs(e.status,n.message,n.code??n.error,n.details??void 0):new cs(e.status,n.error??n.message??e.statusText,n.code??void 0,n.details??void 0)}async function fs(e,t){if(!e.ok)throw await ds(e);return d.parse(t,await e.json())}var ps=class extends Error{intentId;outcome;constructor(e){let t=e.cause instanceof Error?e.cause.message:String(e.cause);super(e.outcome===`not-submitted`?`Intent ${e.intentId} was created but never submitted; no money moved: ${t}`:`Intent ${e.intentId} submission could not be confirmed: ${t}; poll getIntent("${e.intentId}") to a terminal status and resubmit only after blocked or failed`,{cause:e.cause}),this.name=`IntentSubmitError`,this.intentId=e.intentId,this.outcome=e.outcome}};const ms=2147483647;var hs=class{#e;#t;#n;#r;#i;#a;#o;constructor(e){let t=e.timeout===void 0?8e4:e.timeout;if(!Number.isInteger(t)||t<=0||t>ms)throw TypeError(`timeout must be a positive integer no greater than ${ms}`);this.#e=e.baseUrl??`https://api.catena.com`,this.#t=Ra(e.appInfo),this.#n=e.defaultHeaders??{},this.#r=va(e.privateKeyHex),this.#a=(e.fetch??globalThis.fetch).bind(globalThis),this.#o=t,this.#i=Ta({keypair:this.#r,baseUrl:this.#e,identityUrl:e.identityUrl})}#s(e){let t=new Headers({"Content-Type":`application/json`});for(let[e,n]of Object.entries(this.#n))t.set(e,n);for(let[n,r]of Object.entries(e??{}))t.set(n,r);return t.set(`User-Agent`,this.#t),t.delete(`Authorization`),t}async#c(e){let t=new URL(`${this.#e}/v1/agent-api${e.path}`);for(let[n,r]of Object.entries(e.query??{}))r!==void 0&&t.searchParams.set(n,r);let n=new Request(t,{method:e.method,headers:this.#s(e.headers),body:e.body===void 0?null:JSON.stringify(e.body)});return this.#i.sign(n)}async#l(e,t){return this.#u(await this.#c(e),t)}async#u(e,t){let n=new AbortController,r=new Request(e,{signal:n.signal}),i;try{let e=new Promise((e,t)=>{i=setTimeout(()=>{let e=new ls(this.#o);t(e),n.abort(e)},this.#o)}),a=this.#a(r).then(e=>fs(e,t));return await Promise.race([a,e])}finally{i!==void 0&&clearTimeout(i)}}async whoami(){return(await this.#l({method:`GET`,path:`/me`},uo)).agent}async submitFeedback(e){await this.#l({method:`POST`,path:`/feedback`,body:{body:e}},co)}async getPolicy(){return(await this.#l({method:`GET`,path:`/policy`},bo)).policy}async listAccounts(){return this.#l({method:`GET`,path:`/accounts`},xo)}async getAccountBalance(e){return this.#l({method:`GET`,path:`/accounts/${encodeURIComponent(e)}/balance`},So)}async listAccountTransactions(e,t={}){return this.#l({method:`GET`,path:`/accounts/${encodeURIComponent(e)}/transactions`,query:{start:t.start,end:t.end,limit:t.limit?.toString(),offset:t.offset?.toString()}},Oo)}async getAccountDepositAddress(e,t){return this.#l({method:`GET`,path:`/accounts/${encodeURIComponent(e)}/deposit-address`,query:{network:t.network,asset:t.asset}},ko)}async listCounterparties(e={}){return this.#l({method:`GET`,path:`/counterparties`,query:{address:e.address,network:e.network}},Mo)}async submitIntent(e){let t=await this.#d({...e,idempotencyKey:e.idempotencyKey??crypto.randomUUID()}),n=t.nextAction;if(!n)return Io(t);let r;try{let e=await this.#f(n);r=await this.#c({method:`POST`,path:`/intents/${encodeURIComponent(t.id)}/submit-stamp`,body:{preparedBody:n.preparedBody,stamp:e}})}catch(e){throw new ps({intentId:t.id,outcome:`not-submitted`,cause:e})}try{return await this.#p(r,t.replayed)}catch(e){throw new ps({intentId:t.id,outcome:`unknown`,cause:e})}}async#d(e){return this.#l({method:`POST`,path:`/intents`,body:{action:os(e.action)},headers:{"Idempotency-Key":e.idempotencyKey}},Fo)}async#f(e){if(e.signer.publicKeyHex.toLowerCase()!==this.#r.publicKeyHex.toLowerCase())throw Error(`Local signer public key does not match requested signer ${e.signer.publicKeyHex}; linked credential has ${this.#r.publicKeyHex}`);let t=await new ma({apiPublicKey:this.#r.publicKeyHex,apiPrivateKey:this.#r.privateKeyHex}).stamp(e.preparedBody.body);return{publicKeyHex:this.#r.publicKeyHex,stampHeaderName:t.stampHeaderName,stampHeaderValue:t.stampHeaderValue}}async#p(e,t){let n=Io((await this.#u(e,ss)).intent);return t?{...n,replayed:!0}:n}async getIntent(e){return Io(await this.#l({method:`GET`,path:`/intents/${encodeURIComponent(e)}`},Fo))}async unlinkAgent(){await this.#l({method:`POST`,path:`/unlink`},co)}async reportSettlement(e){await this.#l({method:`POST`,path:`/intents/${encodeURIComponent(e.intentId)}/settlement-report`,body:{txHash:e.txHash,...e.receipt!==void 0&&{receipt:e.receipt}}},co)}};function gs(e={}){let t=e.privateKeyHex===void 0?process.env.CATENA_SECRET_KEY:e.privateKeyHex;if(t===void 0)throw new ha(`privateKeyHex is required; pass it explicitly or set CATENA_SECRET_KEY`);return new hs({...e,privateKeyHex:t})}function _s(e){let t=se(e);return e instanceof cs&&e.details!==void 0?`${t}\nDetails:\n${JSON.stringify(e.details,null,2)}`:t}function X(e){console.error(_s(e)),process.exit(1)}const vs=d.string(),ys=d.boolean();function bs(e){return e===void 0}function xs(e){return e.issues?.[0]?.message??`Invalid value`}function Ss(e,t,n,r){return X(`${e}: ${t}${r?` (got: ${String(n)})`:``}`)}function Cs(e,t,n,r){let i=d.safeParse(e,t);return i.success?i.output:Ss(n,xs(i),t,r)}function ws(e,t){let n=t.schema??vs;return{type:e,description:t.description,negativeDescription:t.negativeDescription,required:t.required,default:t.default,parseValue(e,r){let i=bs(e)?t.default:e;if(bs(i)){t.required===!0&&X(`${r} is required`);return}return Cs(n,i,r,t.showValueInError===!0)}}}function Z(e){return ws(`string`,e)}function Ts(e){return ws(`positional`,e)}function Es(e){let t=e.schema??vs;return{type:`string`,description:e.description,repeatable:!0,parseValue(n,r){return(Array.isArray(n)?n:[]).map(n=>Cs(t,n,r,e.showValueInError===!0))}}}function Ds(e){return{type:`boolean`,description:e.description,negativeDescription:e.negativeDescription,required:e.required,default:e.default,parseValue(t,n){let r=bs(t)?e.default:t;if(bs(r)){e.required===!0&&X(`${n} is required`);return}return Cs(ys,r,n,!1)}}}function Os(e){return ks(`string`,e)}function ks(e,t){return ws(e,{description:t.description,required:t.required,default:t.default,schema:d.picklist(t.choices,`must be one of ${t.choices.join(`|`)}`),showValueInError:!0})}function As(e,t){return t.type===`positional`?`<${e}>`:`--${e}`}function js(e){return e.replace(/([a-z])([A-Z])/g,`$1 $2`).replace(/([A-Z0-9])([A-Z][a-z])/g,`$1 $2`).split(/[ _-]/).filter(e=>e.length>0)}function Ms(e){return js(e).join(`-`).toLowerCase()}function Ns(e){return js(e).map((e,t)=>t===0?e.charAt(0).toLowerCase()+e.slice(1):e.charAt(0).toUpperCase()+e.slice(1)).join(``)}function Ps(e){return[`--${e}`,`--${Ms(e)}`,`--${Ns(e)}`]}function Fs(e){let t=e.indexOf(`=`);return t===-1?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function Is(e,t,n){let r=e.indexOf(`--`),i=r===-1?e.length:r,a=[...e.slice(0,i).filter(e=>!e.startsWith(`--no-`)),...e.slice(i)],o=new Set(Ps(t)),s=new Set(Object.entries(n).filter(([e,n])=>e!==t&&n.type===`string`).flatMap(([e])=>Ps(e))),c=[];for(let e=0;e<a.length;e++){let t=a[e];if(t===`--`)break;let[n,r]=Fs(t);if(o.has(n)){r===void 0?(c.push(a[e+1]??``),e++):c.push(r);continue}s.has(n)&&r===void 0&&e++}return c}function Ls(e){let t=e.required??(e.type!==`positional`&&void 0);return e.type===`boolean`?{type:e.type,description:e.description,negativeDescription:e.negativeDescription,required:t,default:typeof e.default==`boolean`?e.default:void 0}:{type:e.type,description:e.description,required:t,default:typeof e.default==`string`?e.default:void 0}}function Q(e){return{args:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Ls(t)])),label(t){return As(t,e[t])},parse(t,n){let r=(r,i)=>{if(i.repeatable!==!0)return t[r];if(n===void 0)throw Error(`parse() needs the command's raw argv to collect the repeatable --${r} flag`);return Is(n,r,e)};return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.parseValue(r(e,t),As(e,t))]))}}}const Rs=Z({description:`Credential profile name`}),zs=Ds({description:`Print compact single-line JSON (for piping)`,default:!1}),Bs=/^[a-zA-Z0-9_-]+$/,Vs=d.pipe(d.string(`ID must be a string`),d.minLength(1,`ID must not be empty`),d.maxLength(256,`ID is too long (max 256 characters)`),d.regex(Bs,`ID may only contain letters, digits, hyphens, and underscores`));d.picklist([`base`,`base-sepolia`,`arc`,`solana`]),d.picklist([`usdc`]),d.picklist([`evm`,`svm`]);const Hs=/^0x[0-9a-fA-F]{40}$/;d.pipe(d.string(),d.trim(),d.regex(Hs,`Must be a 0x-prefixed hex wallet address`),d.brand(`EvmAddress`)),d.picklist([`always`,`testnet`,`preview`]),d.picklist([`bridge-internal-transfer`,`bridge-wallet-transfer`,`wallet-bridge-transfer`,`wallet-wallet-transfer`]);const Us=[`bridge-internal-transfer`,`bridge-wallet-transfer`,`wallet-bridge-transfer`,`wallet-wallet-transfer`],Ws=[`wallet-wallet-transfer`],Gs=[{network:`base`,networkLabel:`Base`,addressFamily:`evm`,blockExplorerUrl:`https://basescan.org`,blockExplorerName:`Basescan`,asset:`usdc`,assetLabel:`USDC`,assetDecimals:6,contractAddress:`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,caip2:`eip155:8453`,caip19:`eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,finality:`finalized`,gasTokenIsTrackedAsset:!1,availabilityGate:`always`,customerAccess:`enabled`,chainFeeUsd:`0`,walletTransferFeeUsd:`0`,transferRoutes:Us,provider:{alchemyNetwork:`base`,alchemyDeposit:{transferEmitterAddress:`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,transferDecimals:6,webhook:`enabled`},bridgePaymentRail:`base`}},{network:`base-sepolia`,networkLabel:`Base Sepolia`,addressFamily:`evm`,isTestnet:!0,blockExplorerUrl:`https://sepolia.basescan.org`,blockExplorerName:`Sepolia Basescan`,asset:`usdc`,assetLabel:`USDC`,assetDecimals:6,contractAddress:`0x036CbD53842c5426634e7929541eC2318f3dCF7e`,caip2:`eip155:84532`,caip19:`eip155:84532/erc20:0x036CbD53842c5426634e7929541eC2318f3dCF7e`,finality:`finalized`,gasTokenIsTrackedAsset:!1,availabilityGate:`testnet`,customerAccess:`enabled`,chainFeeUsd:`0`,walletTransferFeeUsd:`0`,transferRoutes:Ws,provider:{alchemyNetwork:`base-sepolia`,alchemyDeposit:{transferEmitterAddress:`0x036CbD53842c5426634e7929541eC2318f3dCF7e`,transferDecimals:6,webhook:`enabled`}}},{network:`arc`,networkLabel:`Arc`,addressFamily:`evm`,blockExplorerUrl:`https://arc-scan.org`,blockExplorerName:`ArcScan`,asset:`usdc`,assetLabel:`USDC`,assetDecimals:6,contractAddress:`0x3600000000000000000000000000000000000000`,caip2:`eip155:5042`,caip19:`eip155:5042/erc20:0x3600000000000000000000000000000000000000`,finality:`block-inclusion`,gasTokenIsTrackedAsset:!0,availabilityGate:`preview`,customerAccess:`enabled`,chainFeeUsd:`0`,walletTransferFeeUsd:`0`,transferRoutes:Ws,provider:{alchemyNetwork:`arc`,alchemyDeposit:{transferEmitterAddress:`0xfffffffffffffffffffffffffffffffffffffffe`,transferDecimals:18,webhook:`disabled`},sendMode:`self-broadcast`}},{network:`solana`,networkLabel:`Solana`,addressFamily:`svm`,blockExplorerUrl:`https://solscan.io`,blockExplorerName:`Solscan`,asset:`usdc`,assetLabel:`USDC`,assetDecimals:6,contractAddress:`EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`,caip2:`solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp`,caip19:`solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp/token:EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`,finality:`finalized`,gasTokenIsTrackedAsset:!1,availabilityGate:`preview`,customerAccess:`enabled`,chainFeeUsd:`0`,walletTransferFeeUsd:`0`,transferRoutes:Us,provider:{alchemyNotify:{webhook:`enabled`},bridgePaymentRail:`solana`}}];function Ks(e){if(typeof e==`object`&&e&&!Object.isFrozen(e)){for(let t of Object.values(e))Ks(t);Object.freeze(e)}}Ks(Gs);const qs=Gs;function Js(e){return{id:e.network,label:e.networkLabel,addressFamily:e.addressFamily,blockExplorerUrl:e.blockExplorerUrl,blockExplorerName:e.blockExplorerName,...e.isTestnet?{isTestnet:!0}:{}}}function Ys(e){return{id:e.asset,label:e.assetLabel,decimals:e.assetDecimals}}function Xs(e){return{network:e.network,asset:e.asset,contractAddress:e.contractAddress}}function Zs(e){return{id:`${e.network}-usdc`,label:`${e.networkLabel} USDC`,network:e.network,asset:`usdc`}}function Qs(e){let t=[];for(let n of e)t.some(e=>e.id===n.network)||t.push(Js(n));return t}function $s(e){let t=[],n=new Set;for(let r of e)n.has(r.asset)||(n.add(r.asset),t.push(Ys(r)));return t}function ec(e){return e.asset===`usdc`}const tc=Qs(qs);$s(qs),qs.map(Xs),qs.filter(ec).map(Zs);function nc(e,t){return`${e}:${t}`}new Map(qs.map(e=>[nc(e.network,e.asset),e])),new Map(tc.map(e=>[e.id,e]));const rc=[`usdc`],ic=`base`,ac=d.pipe(d.string(),d.trim(),d.guard(e=>Hs.test(e),`Must be a 0x-prefixed hex wallet address`));function oc(e){return Z({description:e.description,schema:d.pipe(d.string(),d.trim(),d.minLength(1)),...e.default===void 0?{}:{default:e.default}})}const sc=[`registered`,`already_registered`,`not_applicable`,`registration_failed`],cc=d.pipe(d.string(),d.regex(/^0[23][0-9a-f]{64}$/)),lc=d.pipe(d.string(),d.regex(/^[0-9a-f]{64}$/)),uc=d.object({status:d.picklist(sc),publicKeyHex:d.optional(cc),reason:d.optional(d.string())}),dc=d.object({algorithm:d.literal(`p256`),privateKeyHex:lc,publicKeyHex:cc,registration:uc}),fc=d.object({version:d.literal(`signer-1`),signer:dc}),pc=d.object({version:d.literal(1),refreshToken:d.pipe(d.string(),d.minLength(1)),sessionToken:d.pipe(d.string(),d.minLength(1)),expiresAt:d.pipe(d.string(),d.isoTimestamp())}),mc=d.object({version:d.literal(2),refreshToken:d.pipe(d.string(),d.minLength(1)),sessionToken:d.pipe(d.string(),d.minLength(1)),expiresAt:d.pipe(d.string(),d.isoTimestamp()),signer:dc}),hc=d.object({version:d.literal(3),signer:dc}),gc=d.variant(`version`,[pc,mc,hc]),_c=d.variant(`version`,[fc,pc,mc,hc]);function vc(e){return d.parse(gc,e)}function yc(e){return d.parse(_c,e)}function bc(e){let t=d.safeParse(_c,e);return t.success?t.output:null}function xc(e){return{version:`signer-1`,signer:{algorithm:e.algorithm,privateKeyHex:e.privateKeyHex,publicKeyHex:e.publicKeyHex,registration:{status:`not_applicable`,reason:`pending_claim`}}}}function Sc(e,t){try{return yc(JSON.parse(e))}catch(e){throw Error(`${t} credential has an unsupported format`,{cause:e})}}function Cc(e){return vc({version:3,signer:e})}function wc(e){return JSON.stringify(e)}function Tc(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Ec(e){return(t,n)=>Dc(e,t,n)}function Dc(e,t,n){return new Promise((r,i)=>{let a=y(e,[...t],{stdio:[`pipe`,`pipe`,`pipe`]}),o=[],s=[],c=!1,l=!1,u=null,d=null,f=null,p=e=>{c||(c=!0,d!==null&&clearTimeout(d),f!==null&&clearTimeout(f),r(e))},m=e=>{c||(c=!0,d!==null&&clearTimeout(d),f!==null&&clearTimeout(f),i(e))};d=setTimeout(()=>{l=!0,a.kill(`SIGTERM`),f=setTimeout(()=>{a.kill(`SIGKILL`),p({stdout:o.join(``),stderr:s.join(``),status:124})},1e3)},3e4),a.stdout.setEncoding(`utf8`),a.stderr.setEncoding(`utf8`),a.stdout.on(`data`,e=>o.push(e)),a.stderr.on(`data`,e=>s.push(e)),a.on(`error`,t=>{m(Error(`Unable to run ${e}: ${t.message}`))}),a.on(`close`,t=>{if(u!==null&&t===0){m(Error(`Unable to write to ${e} stdin: ${u.message}`));return}p({stdout:o.join(``),stderr:s.join(``),status:l?124:t})}),a.stdin.on(`error`,e=>{u=e});try{a.stdin.end(n)}catch(t){m(t instanceof Error?Error(`Unable to write to ${e} stdin: ${t.message}`):Error(`Unable to write to ${e} stdin`))}})}const Oc=`catena-agent`;function kc(e){if(!Bs.test(e))throw Error(`Invalid credential location for credential storage: "${e}"`);return e}const Ac=Ec(`/usr/bin/secret-tool`);function jc(e){return e.status===1&&e.stdout===``&&e.stderr.trim()===``}function Mc(e,t){if(t.status===0)return;let n=Nc(t);throw Error(`Linux Secret Service credential ${e} failed (secret-tool exited ${t.status??`without status`}): ${n}`)}function Nc(e){let t=e.stderr.toLowerCase();return e.status===124?`secret service operation timed out`:t.includes(`cannot autolaunch`)||t.includes(`dbus`)||t.includes(`d-bus`)||t.includes(`org.freedesktop.secrets`)?`secret service session is unavailable`:/\blocked\b/.test(t)?`secret service keyring appears to be locked`:t.includes(`authorization`)||t.includes(`denied`)||t.includes(`not authorized`)?`secret service authorization was denied`:`secret service operation failed; ensure the Secret Service session is available and unlocked`}function Pc(e){return e instanceof Error?e.message.includes(`ENOENT`)?Error(`Linux Secret Service credential operation failed: /usr/bin/secret-tool was not found. Install libsecret-tools and ensure a Secret Service keyring is available.`,{cause:e}):e:Error(String(e))}var Fc=class{runSecretTool;constructor(e={}){if((e.platform??process.platform)!==`linux`)throw Error(`Linux Secret Service credential storage is only supported on Linux`);this.runSecretTool=e.runSecretTool??Ac}async save(e,t){let n=yc(t),r=kc(e);if(await this.savePassword(r,wc(n)),!Tc(await this.resolveDirectPassword(r),n))throw Error(`Linux Secret Service credential save verification failed`)}async resolve(e){return this.resolveDirectPassword(kc(e))}async delete(e){await this.deletePassword(kc(e))}async savePassword(e,t){Mc(`save`,await this.runSecretToolCommand([`store`,`--label`,`${Oc} ${e}`,`app`,Oc,`account`,e],t))}async resolvePassword(e){let t=await this.runSecretToolCommand([`lookup`,`app`,Oc,`account`,e]);return jc(t)?null:(Mc(`resolve`,t),t.stdout.replace(/\r?\n$/,``))}async resolveDirectPassword(e){let t=await this.resolvePassword(e);return t===null?null:Sc(t,`Linux Secret Service`)}async deletePassword(e){let t=await this.runSecretToolCommand([`clear`,`app`,Oc,`account`,e]);jc(t)||Mc(`delete`,t)}async runSecretToolCommand(e,t){try{return await this.runSecretTool(e,t)}catch(e){throw Pc(e)}}};const Ic=Ec(`/usr/bin/security`),Lc=d.object({version:d.literal(1),encoding:d.literal(`base64-json`),chunks:d.pipe(d.number(),d.integer(),d.minValue(1),d.maxValue(64)),sha256:d.pipe(d.string(),d.regex(/^[a-f0-9]{64}$/))});function Rc(e){return e.status===44}function zc(e,t){return`${e}:chunk:${t}`}function Bc(e){let t=JSON.parse(e),n=bc(t);if(n!==null)return{kind:`direct`,payload:n};let r=d.safeParse(Lc,t);if(r.success)return{kind:`legacy`,manifest:r.output};throw Error(`macOS Keychain credential has an unsupported format`)}function Vc(e,t){if(t.status===0)return;let n=Hc(t);throw Error(`macOS Keychain credential ${e} failed (security exited ${t.status??`without status`})${n===null?``:`: ${n}`}`)}function Hc(e){let t=e.stderr.toLowerCase();return e.status===124?`keychain operation timed out`:t.includes(`stdin isn't a terminal`)?`parent process has no terminal`:t.includes(`user interaction is not allowed`)?`keychain user interaction is not allowed`:t.includes(`authorization`)||t.includes(`denied`)?`keychain authorization was denied`:t.includes(`locked`)?`keychain appears to be locked`:null}function Uc(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32||n===127)throw Error(`macOS Keychain credential values cannot contain control characters`)}return`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function Wc(e,t){return[`add-generic-password`,`-s`,Uc(Oc),`-a`,Uc(e),`-w`,Uc(t),`-U`].join(` `)+`
137
+ `}var Gc=class{runSecurity;constructor(e={}){if((e.platform??process.platform)!==`darwin`)throw Error(`macOS Keychain credential storage is only supported on macOS`);this.runSecurity=e.runSecurity??Ic}async save(e,t){let n=yc(t),r=kc(e),i=await this.resolveLegacyChunkCount(r,64);if(await this.savePassword(r,wc(n)),!Tc(await this.resolveDirectPassword(r),n))throw Error(`macOS Keychain credential save verification failed`);await this.deleteChunks(r,i)}async resolve(e){let t=kc(e),n=await this.resolveKeychainItem(t);return n===null?null:n.kind===`direct`?n.payload:this.resolveLegacyPayload(t,n.manifest)}async delete(e){let t=kc(e),n=await this.resolveLegacyChunkCount(t,64);await this.deleteChunks(t,n),await this.deletePassword(t)}async savePassword(e,t){Vc(`save`,await this.runSecurity([`-i`],Wc(e,t)))}async resolvePassword(e){let t=await this.runSecurity([`find-generic-password`,`-a`,e,`-s`,Oc,`-w`]);return Rc(t)?null:(Vc(`resolve`,t),t.stdout.replace(/\r?\n$/,``))}async resolveKeychainItem(e){let t=await this.resolvePassword(e);return t===null?null:Bc(t)}async resolveDirectPassword(e){let t=await this.resolveKeychainItem(e);if(t===null)return null;if(t.kind!==`direct`)throw Error(`macOS Keychain credential direct verification failed`);return t.payload}async resolveLegacyPayload(e,t){let n=[];for(let r=0;r<t.chunks;r++){let t=await this.resolvePassword(zc(e,r));if(t===null)throw Error(`macOS Keychain credential chunk is missing`);n.push(t)}let r=n.join(``);if(m(`sha256`).update(r).digest(`hex`)!==t.sha256)throw Error(`macOS Keychain credential checksum mismatch`);return yc(JSON.parse(Buffer.from(r,`base64`).toString(`utf8`)))}async resolveLegacyChunkCount(e,t){let n=await this.resolvePassword(e);if(n===null)return 0;try{let e=Bc(n);return e.kind===`legacy`?e.manifest.chunks:0}catch{return t}}async deleteChunks(e,t){for(let n=0;n<t;n++)await this.deletePassword(zc(e,n))}async deletePassword(e){let t=await this.runSecurity([`delete-generic-password`,`-a`,e,`-s`,Oc]);Rc(t)||Vc(`delete`,t)}};function Kc(e={}){let t=e.platform??process.platform;if(t===`darwin`)return new Gc({platform:t});if(t===`linux`)return new Fc({platform:t});throw Error(`Catena credential storage is only supported on macOS and Linux`)}const qc=/^127(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}$/;function Jc(e){let t=e.replace(/^\[|\]$/g,``);return t===`localhost`||t===`::1`||qc.test(t)}function Yc(e){let t;try{t=new URL(e)}catch{return!1}return t.protocol===`https:`||t.protocol===`http:`&&Jc(t.hostname)}function Xc(e,t){if(!Yc(e))throw Error(`${t} must be an https:// URL (http:// is allowed only for a loopback host): "${e}"`)}const Zc=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/,Qc=d.object({status:d.optional(d.literal(`linked`),`linked`),api_url:d.pipe(d.string(),d.minLength(1)),agent_id:d.pipe(d.string(),d.minLength(1)),client_instance_id:d.pipe(d.string(),d.regex(Bs))}),$c=d.object({status:d.literal(`pending_connection`),api_url:d.pipe(d.string(),d.minLength(1)),client_instance_id:d.pipe(d.string(),d.regex(Bs)),created_at:d.pipe(d.string(),d.isoTimestamp())}),el=d.variant(`status`,[Qc,$c]),tl=d.union([el,d.pipe(d.looseObject({api_url:d.optional(d.undefined()),bank_url:d.pipe(d.string(),d.minLength(1))}),d.transform(({bank_url:e,...t})=>({...t,api_url:e})),el)]);d.object({version:d.literal(1),default_profile:d.optional(d.string()),profiles:d.record(d.string(),el),directories:d.optional(d.record(d.string(),d.string()))});const nl=d.object({version:d.literal(1),default_profile:d.optional(d.string()),profiles:d.record(d.string(),d.unknown()),directories:d.optional(d.record(d.string(),d.unknown()))});function rl(){return te(process.env.HOME??ee(),`.catena`)}function il(){return te(rl(),`profiles.json`)}function al(e){return Zc.test(e)}function ol(e){if(!al(e))throw Error(`invalid profile name "${e}" (expected [a-zA-Z0-9][a-zA-Z0-9._-]{0,63})`)}function sl(e){return typeof e!=`object`||!e||!(`code`in e)?!1:typeof e.code==`string`}function cl(e,t){let n;try{n=JSON.parse(e)}catch(e){throw Error(`profiles.json is not valid JSON: ${_s(e)}`,{cause:e})}if(typeof n==`object`&&n&&`version`in n){let e=n;if(e.version!==1)throw Error(`profiles.json version ${String(e.version)} is not supported (expected 1)`)}let r=d.parse(nl,n),i={};for(let[e,n]of Object.entries(r.profiles)){if(!al(e)){t?.(`profiles: dropping invalid profile name "${e}"`);continue}let r=d.safeParse(tl,n);if(!r.success){t?.(`profiles: dropping malformed profile "${e}"`);continue}i[e]=r.output}if(r.default_profile!==void 0&&(ol(r.default_profile),!Object.hasOwn(i,r.default_profile)))throw Error(`profiles.json default_profile "${r.default_profile}" is not linked`);let a={};for(let[e,n]of Object.entries(r.directories??{})){if(!M(e)){t?.(`profiles: dropping directory binding with relative path "${e}"`);continue}if(typeof n!=`string`||!al(n)){t?.(`profiles: dropping malformed directory binding "${e}"`);continue}a[e]=n}return{version:1,...r.default_profile===void 0?{}:{default_profile:r.default_profile},profiles:i,...Object.keys(a).length===0?{}:{directories:a}}}function ll(e){try{return cl(T(il(),`utf-8`),e)}catch(e){if(e instanceof Error&&sl(e)&&e.code===`ENOENT`)return{version:1,profiles:{}};throw e}}function ul(){w(rl(),{recursive:!0,mode:448}),x(rl(),448)}function dl(e){ul();let t=il(),n=`${t}.${g(6).toString(`hex`)}.tmp`;A(n,JSON.stringify(e,null,2)+`
138
+ `,{encoding:`utf-8`,mode:384}),D(n,t)}function fl(e,t){ol(e);let n=d.parse(el,t);Xc(n.api_url,`profile "${e}" api_url`);let r=ll();dl({...r,profiles:{...r.profiles,[e]:n}})}function pl(e){return e.status===`linked`}function ml(e,t){return e.replace(/\/+$/,``)===t.replace(/\/+$/,``)}function hl(e,t){let n=Object.entries(ll().profiles).toSorted(([e],[t])=>e.localeCompare(t)).find(([,n])=>pl(n)&&n.agent_id===e&&ml(n.api_url,t));return n===void 0?null:n[0]}function gl(e,t){let n=Object.fromEntries(Object.entries(e??{}).filter(([,e])=>t(e)));return Object.keys(n).length===0?{}:{directories:n}}function _l(e){ol(e);let t=ll(),{[e]:n,...r}=t.profiles;dl({version:1,...t.default_profile===e||t.default_profile===void 0?{}:{default_profile:t.default_profile},profiles:r,...gl(t.directories,t=>t!==e)})}function vl(e){try{return E(ne(e))}catch{return ne(e)}}function yl(e){return ll().directories?.[vl(e)]??null}function bl(e,t){ol(t);let n=ll();if(!Object.hasOwn(n.profiles,t))throw Error(`Profile "${t}" is not linked. Run catena link --profile ${t} <agent-id>.`);let r=vl(e);return dl({...n,directories:{...n.directories,[r]:t}}),r}function xl(e){let t=ll(),n=vl(e);if(t.directories===void 0||!Object.hasOwn(t.directories,n))return{directory:n,removed:!1};let{[n]:r,...i}=t.directories,{directories:a,...o}=t;return dl({...o,...Object.keys(i).length===0?{}:{directories:i}}),{directory:n,removed:!0}}function Sl(e){return ol(e),ll().profiles[e]??null}function Cl(){return`client_${g(16).toString(`hex`)}`}function wl(e,t){let n=Sl(e);return t.agent_id===void 0?Tl(e,t.api_url,n):El(e,t.api_url,t.agent_id,n)}function Tl(e,t,n){if(n?.status===`linked`)throw Error(`Profile "${e}" is already linked. Choose a different profile name to start agent connection.`);let r=(n?.status===`pending_connection`&&ml(n.api_url,t)?n.client_instance_id:null)??Cl();return fl(e,{status:`pending_connection`,api_url:t,client_instance_id:r,created_at:n?.status===`pending_connection`?n.created_at:new Date().toISOString()}),r}function El(e,t,n,r){if(r?.status===`linked`){if(r.agent_id!==n)throw Error(`Profile "${e}" is already linked to a different agent (${r.agent_id}). Link ${n} under a different --profile, or run 'catena unlink --profile ${e}' first to repoint it (add --force if that agent's credential is missing or revoked).`);if(!ml(r.api_url,t))throw Error(`Profile "${e}" is already linked to this agent on a different Catena API (${r.api_url}). Link under a different --profile, or run 'catena unlink --profile ${e}' first (add --force if that credential is missing or revoked).`);return r.client_instance_id}let i=(r?.status===`pending_connection`&&ml(r.api_url,t)?r.client_instance_id:null)??Cl();return fl(e,{status:`linked`,api_url:t,agent_id:n,client_instance_id:i}),i}function Dl(e){ol(e);let t=ll();if(!Object.hasOwn(t.profiles,e))throw Error(`Profile "${e}" is not linked. Run catena link --profile ${e} <agent-id>.`);dl({...t,default_profile:e})}function Ol(e){let t=e.toLowerCase().replace(/[^a-z0-9._-]+/g,`-`).replace(/^[^a-z0-9]+/,``).slice(0,64);return al(t)?t:`agent`}function kl(e,t){if(!t(e))return e;for(let n=2;;n++){let r=`${e.slice(0,64-String(n).length-1)}-${n}`;if(!t(r))return r}}function Al(e){ol(e.reservationName),ol(e.profileName);let t=d.parse(el,e.profile);Xc(t.api_url,`profile "${e.profileName}" api_url`);let n=ll(),{[e.reservationName]:r,...i}=n.profiles;if(!Object.hasOwn(n.profiles,e.reservationName)||r.client_instance_id!==t.client_instance_id)throw Error(`Link reservation "${e.reservationName}" changed during setup (a concurrent link from this directory?). Re-run 'catena link'.`);if(e.profileName!==e.reservationName&&Object.hasOwn(i,e.profileName))throw Error(`Profile "${e.profileName}" already exists; cannot finalize link under that name.`);let a=Object.fromEntries(Object.entries(n.directories??{}).map(([t,n])=>[t,n===e.reservationName?e.profileName:n]));dl({version:1,...n.default_profile===void 0?{}:{default_profile:n.default_profile===e.reservationName?e.profileName:n.default_profile},profiles:{...i,[e.profileName]:t},...Object.keys(a).length===0?{}:{directories:a}})}function jl(e){return e??Kc()}async function Ml(e,t){let n;try{n=Sl(e.profileName)}catch(t){return{ok:!1,profileName:e.profileName,apiUrl:e.fallbackApiUrl,message:_s(t)}}if(n===null)return{ok:!1,profileName:e.profileName,apiUrl:e.fallbackApiUrl,message:`Profile "${e.profileName}" is not linked. Run 'catena link --profile ${e.profileName}' to authenticate.`};try{Xc(n.api_url,`profile "${e.profileName}" api_url`)}catch(t){return{ok:!1,profileName:e.profileName,apiUrl:e.fallbackApiUrl,message:_s(t)}}if(n.status===`pending_connection`)return{ok:!1,profileName:e.profileName,apiUrl:n.api_url,message:`Profile "${e.profileName}" is waiting for agent connection approval. Run 'catena link --profile ${e.profileName}' to finish setup.`};let r;try{r=await jl(t).resolve(n.client_instance_id)}catch(t){return{ok:!1,profileName:e.profileName,apiUrl:n.api_url,message:`Profile "${e.profileName}" credential unavailable for ${n.agent_id}: ${_s(t)}. Run 'catena link --profile ${e.profileName} ${n.agent_id}' to authenticate.`}}return r===null||r.version===`signer-1`?{ok:!1,profileName:e.profileName,apiUrl:n.api_url,message:`Profile "${e.profileName}" credential unavailable for ${n.agent_id}. Run 'catena link --profile ${e.profileName} ${n.agent_id}' to authenticate.`}:r.version===1?{ok:!1,profileName:e.profileName,apiUrl:n.api_url,message:`Profile "${e.profileName}" credential for ${n.agent_id} has no signing key. Run 'catena link --profile ${e.profileName} ${n.agent_id}' to authenticate.`}:{ok:!0,profileName:e.profileName,apiUrl:n.api_url,agentId:n.agent_id,clientInstanceId:n.client_instance_id,signer:r.signer}}const Nl=`https://api.catena.com`,Pl=`CATENA_SECRET_KEY`;function Fl(e,t){let n=e[t]?.trim();return n===void 0||n.length===0?void 0:n}function Il(e=process.env){return Fl(e,Pl)!==void 0}function Ll(e=process.env){let t=Fl(e,Pl);if(t===void 0)return null;let n=Fl(e,`CATENA_API_URL`)??`https://api.catena.com`;return Xc(n,`CATENA_API_URL`),{apiUrl:n,privateKeyHex:t}}const Rl=`CATENA_PROFILE`;function zl(e,t,n,r){if(e.directories===void 0)return null;let i;try{i=E(t)}catch{return null}let a=Object.entries(e.directories).map(([e,t])=>[e.replace(/\/+$/,``)||`/`,t]).filter(([e])=>i===e||i.startsWith(e===`/`?`/`:`${e}/`)).toSorted(([e],[t])=>t.length-e.length),o=null;for(let[t,n]of a){if(Object.hasOwn(e.profiles,n))return n;o??=`${t} -> "${n}"`}if(o===null)return null;if(n===`error`)throw Error(`This directory is bound to a profile that no longer exists (${o}). Run 'catena profiles unbind' here, bind it with 'catena profiles bind <name>', or run 'catena link' to re-establish it.`);return r?.(`profiles: ignoring stale directory binding ${o}`),null}function Bl(e,t,n){if(e.flag!==void 0&&e.flag.length>0)return ol(e.flag),{name:e.flag,source:`flag`};if(e.env!==void 0&&e.env.length>0){if(!al(e.env))throw Error(`${Rl} is set to an invalid profile name "${e.env}"`);return{name:e.env,source:`env`}}if(e.cwd!==void 0){let r=zl(t,e.cwd,n,e.log);if(r!==null)return{name:r,source:`directory`}}return t.default_profile===void 0?null:{name:t.default_profile,source:`default`}}function Vl(e){return Bl(e,ll(e.log),`ignore`)}function Hl(e){let t=ll(e.log),n=Bl(e,t,`error`);if(n!==null)return n;let r=Object.keys(t.profiles),i=Object.entries(t.profiles).filter(([,e])=>pl(e)).map(([e])=>e);if(i.length===1){let[e]=i;return{name:e,source:`single`}}if(i.length===0){if(r.length===1){let[e]=r;return{name:e,source:`single`}}return r.length>1&&e.log?.(`profiles: ignoring ${r.length} pending profiles (${r.toSorted().join(`, `)}); none is linked`),{name:`default`,source:`fallback`}}throw Error(`Multiple profiles exist and none is selected (${i.toSorted().join(`, `)}). Pass --profile <name>, set ${Rl}, run 'catena profiles use <name>', or run 'catena link' from an agent directory to bind it.`)}function Ul(){try{return Object.entries(ll().profiles).filter(([,e])=>pl(e)).map(([e])=>e).toSorted()}catch{return[]}}function Wl(e=process.env){let t=e[Rl]?.trim();if(t!==void 0&&t.length>0)return`profiles: signing with ${Pl}; ${Rl}=${t} is ignored. Pass --profile ${t} to use that profile.`;let n=Ul();if(n.length===0)return null;let r=n.length===1?`profile`:`profiles`;return`profiles: signing with ${Pl}; ${n.length} linked ${r} ignored (${n.join(`, `)}). Pass --profile <name> to use one.`}const Gl={name:`catena-cli`,version:oe},Kl=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function ql(e,t){if(!Kl.test(e))throw Error(`${t} must be a valid HTTP token`)}function Jl(e,t){let n=!1;for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r<32||r===127||r>255){n=!0;break}}if(n||/[()\\]/.test(e))throw Error(`${t} must not contain parentheses, backslashes, control characters, or characters outside Latin-1`)}function Yl(e){ql(e.name,`appInfo.name`),e.version!==void 0&&ql(e.version,`appInfo.version`),e.url!==void 0&&Jl(e.url,`appInfo.url`);let t=e.version===void 0?e.name:`${e.name}/${e.version}`;return{"User-Agent":e.url===void 0?t:`${t} (${e.url})`}}function Xl(e){return gs({baseUrl:e.apiUrl,privateKeyHex:e.signer.privateKeyHex,appInfo:Gl})}function Zl(){return Kc()}function Ql(e){try{return gs({baseUrl:e.apiUrl,privateKeyHex:e.privateKeyHex,appInfo:Gl})}catch(e){return X(`${Pl} is not usable: ${_s(e)}`)}}async function $l(e){if(e===void 0){let e;try{e=Ll()}catch(e){return X(e)}if(e!==null){let t=Wl();return t!==null&&console.error(t),Ql(e)}}let t;try{t=Hl({flag:e,env:process.env[Rl],cwd:process.cwd(),log:e=>console.error(e)}).name}catch(e){return X(e)}let n=await Ml({profileName:t,fallbackApiUrl:Nl},void 0);return n.ok||X(n.message),Xl(n)}const eu=new Set([`unknown_key`,`key_revoked`,`client_unlinked`]),tu=new Set([`signature_auth_disabled`,`missing_auth`]);function nu(e,t,n=process.env){if(!(e instanceof cs)||e.code===void 0)return e;let r=t===void 0?`catena link`:`catena link --profile ${t}`;return eu.has(e.code)?t===void 0&&Il(n)?Error(`Catena rejected the ${Pl} signing key (${e.code}). Create a secret key in the Catena console under the agent's Secret keys tab, then update ${Pl}.`):Error(`Catena rejected this machine's signing key (${e.code}). Run '${r}' to re-authenticate.`):e.code===`client_upgrade_required`?Error(`This CLI version (${Gl.version}) is no longer supported by the Catena API. Run 'npm i -g @catena/cli' and retry.`):tu.has(e.code)?Error(`This Catena API does not support key-based authentication (${e.code}). Upgrade it, or use an older CLI release that authenticates with session tokens.`):e.code===`invalid_signature`&&e.message.includes(`created_out_of_window`)?Error(`Catena rejected this request's timestamp (created_out_of_window). Check this machine's system clock and retry.`):e}function ru(e,t){console.log(t?.compact?JSON.stringify(e):JSON.stringify(e,null,2))}function iu(e){return e.profile===void 0||e.profile.length===0?void 0:e.profile}async function au(e,t){try{return await t(await $l(e))}catch(t){return X(nu(t,e))}}function ou(e,t){return async(n,r)=>{let i=await au(e,n);return ru(i,t),await new Promise(e=>{process.stdout.write(``,()=>e())}),process.exit(r?.exitCode?r.exitCode(i):0)}}function $(e){return ou(iu(e),{compact:e.json===!0})}const su=d.pipe(d.string(),d.regex(/^\d+$/,`must be a non-negative integer`),d.transform(Number),d.maxValue(2**53-1,`must be at most ${2**53-1}`)),cu=d.pipe(su,d.maxValue(200,`must be at most 200`)),lu={profile:Rs,json:zs},uu=Q(lu),du=Q({account:Ts({description:`Account id`,required:!0,schema:Vs}),...lu}),fu=Q({account:Ts({description:`Account id`,required:!0,schema:Vs}),start:Z({description:`Only include transactions at or after this ISO 8601 time`}),end:Z({description:`Only include transactions at or before this ISO 8601 time`}),limit:Z({description:`Maximum transactions to return (default 50, max 200)`,schema:cu}),offset:Z({description:`Number of transactions to skip for pagination`,schema:su}),...lu}),pu=Q({account:Ts({description:`Account id`,required:!0,schema:Vs}),network:oc({description:`Deposit network; defaults to ${ic}. Availability depends on the connected environment.`,default:ic}),asset:Z({description:`Deposit asset; known value: ${rc.join(`|`)}`,schema:d.pipe(d.string(),d.trim(),d.minLength(1)),default:`usdc`}),...lu}),mu=c({meta:{name:`list`,description:`List accounts accessible under the agent's policy`},args:uu.args,async run({args:e}){await $(uu.parse(e))(e=>e.listAccounts())}}),hu=c({meta:{name:`balance`,description:`Request an account balance through the policy engine`},args:du.args,async run({args:e}){let t=du.parse(e);await $(t)(e=>e.getAccountBalance(t.account))}}),gu=c({meta:{name:`transactions`,description:`Read an account's transaction history through the policy engine`},args:fu.args,async run({args:e}){let t=fu.parse(e);await $(t)(e=>e.listAccountTransactions(t.account,{start:t.start,end:t.end,limit:t.limit,offset:t.offset}))}}),_u=c({meta:{name:`deposit-address`,description:`Read an account deposit address through the policy engine`},args:pu.args,async run({args:e}){let t=pu.parse(e);await $(t)(e=>e.getAccountDepositAddress(t.account,{network:t.network,asset:t.asset}))}}),vu=c({meta:{name:`accounts`,description:`Inspect bank accounts`},subCommands:{list:mu,balance:hu,transactions:gu,"deposit-address":_u}}),yu=d.pipe(d.string(`Idempotency key must be a string`),d.minLength(1,`Idempotency key must not be empty`),d.maxLength(255,`Idempotency key is too long (max 255 characters)`)),bu=d.pipe(d.string(),d.minLength(1,`must not be empty`)),xu=d.pipe(d.string(),d.trim(),d.email(`must be a valid email address`)),Su={profile:Rs,json:zs},Cu=Q({address:Z({description:`Only counterparties with a wallet rail matching this address (0x…)`,schema:ac}),network:oc({description:`Only counterparties with a wallet rail on this network (e.g. base)`}),...Su}),wu=Z({description:`Counterparty name`,required:!0,schema:bu}),Tu=Z({description:`Optional contact email`,schema:xu}),Eu=Z({description:`Optional operation key. Reuse the same value only when retrying the same submission; omitted generates a fresh key for this invocation.`,schema:yu}),Du=Q({name:wu,email:Z({description:`Contact email; creating the counterparty sends no email`,required:!0,schema:xu}),"idempotency-key":Eu,...Su}),Ou=Q({name:Z({description:`Counterparty name; required without a subcommand`,schema:bu}),email:Z({description:`Contact email; required without a subcommand; creating the counterparty sends no email`,schema:xu}),"idempotency-key":Eu,...Su}),ku=Q({name:wu,"bank-name":Z({description:`Receiving bank name`,required:!0,schema:bu}),"routing-number":Z({description:`9-digit ABA routing number`,required:!0,schema:bu}),"account-number":Z({description:`Receiving bank account number`,required:!0,schema:bu}),"account-type":Os({description:`checking | savings (default checking)`,choices:[`checking`,`savings`]}),"address-street":Z({description:`Street address of the receiving bank account holder`,required:!0,schema:bu}),"address-city":Z({description:`City`,required:!0,schema:bu}),"address-state":Z({description:`State (e.g. NY)`,required:!0,schema:bu}),"address-postal-code":Z({description:`Postal code`,required:!0,schema:bu}),"address-country":Z({description:`Default USA`}),email:Tu,"idempotency-key":Eu,...Su}),Au=Q({name:wu,address:Z({description:`Wallet address (0x… or ENS name on EVM networks)`,required:!0,schema:bu}),network:oc({description:`Wallet network; defaults to ${ic}. Availability depends on the connected environment.`,default:ic}),email:Tu,"idempotency-key":Eu,...Su}),ju=Q({counterparty:Ts({description:`Counterparty id`,required:!0,schema:Vs}),bank:Ds({description:`Request bank account details`,default:!1}),wallet:Ds({description:`Request wallet details`,default:!1}),"idempotency-key":Eu,...Su}),Mu=c({meta:{name:`list`,description:`List counterparties available under the agent's policy`},args:Cu.args,async run({args:e}){let t=Cu.parse(e);await $(t)(e=>e.listCounterparties({address:t.address,network:t.network}))}});function Nu(e){return e&&e.length>0?e:void 0}function Pu(e){let t=Nu(e.email);return{type:`create_counterparty`,name:e.name,email:t,rail:{type:`bank`,bankName:e[`bank-name`],routingNumber:e[`routing-number`],accountNumber:e[`account-number`],addressStreet:e[`address-street`],addressCity:e[`address-city`],addressState:e[`address-state`],addressPostalCode:e[`address-postal-code`],...e[`account-type`]?{accountType:e[`account-type`]}:{},...e[`address-country`]?{addressCountry:e[`address-country`]}:{}}}}function Fu(e){let t=Nu(e.email);return{type:`create_counterparty`,name:e.name,email:t,rail:{type:`wallet`,walletAddress:e.address,network:e.network}}}function Iu(e){return{type:`create_counterparty`,name:e.name,email:e.email}}const Lu=c({meta:{name:`email`,description:`Create a counterparty with an email and no payment details. Sends no email.`},args:Du.args,async run({args:e}){let t=Du.parse(e);await $(t)(e=>e.submitIntent({action:Iu(t),...t[`idempotency-key`]!==void 0&&{idempotencyKey:t[`idempotency-key`]}}))}}),Ru=c({meta:{name:`bank`,description:`Request bank counterparty creation through the policy engine. Prints an intent envelope.`},args:ku.args,async run({args:e}){let t=ku.parse(e),n=Pu(t);await $(t)(e=>e.submitIntent({action:n,...t[`idempotency-key`]!==void 0&&{idempotencyKey:t[`idempotency-key`]}}))}}),zu=c({meta:{name:`wallet`,description:`Request wallet counterparty creation through the policy engine. Prints an intent envelope.`},args:Au.args,async run({args:e}){let t=Au.parse(e);await $(t)(e=>e.submitIntent({action:Fu(t),...t[`idempotency-key`]!==void 0&&{idempotencyKey:t[`idempotency-key`]}}))}}),Bu=c({meta:{name:`create`,description:`Request counterparty creation through the policy engine. Without a subcommand, --name and --email create a record without payment details and send no email.`},args:Ou.args,default:`email`,subCommands:{email:Lu,bank:Ru,wallet:zu}}),Vu=c({meta:{name:`request-details`,description:`Ask a counterparty to provide bank details, wallet details, or both through the policy engine.`},args:ju.args,async run({args:e}){let t=ju.parse(e);!t.bank&&!t.wallet&&X(`Select at least one of --bank or --wallet`),await $(t)(e=>e.submitIntent({action:{type:`request_counterparty_details`,counterpartyId:t.counterparty,methods:{bank:t.bank,wallet:t.wallet}},...t[`idempotency-key`]?{idempotencyKey:t[`idempotency-key`]}:{}}))}}),Hu=c({meta:{name:`counterparties`,description:`Inspect, create, and request details from counterparties`},subCommands:{list:Mu,create:Bu,"request-details":Vu}}),Uu=4e3;async function Wu(){process.stdin.setEncoding(`utf8`);let e=``;for await(let t of process.stdin)e+=t;return e}async function Gu(e){return e===void 0?(process.stdin.isTTY&&X(`<message>: pass a quoted message or pipe it on stdin; a message starting with "-" needs -- before it (catena feedback -- "<message>") or stdin`),Wu()):e}const Ku=Q({message:Ts({description:`Plain-text feedback (1-4000 chars); omit to pipe on stdin`}),profile:Rs,json:zs}),qu=c({meta:{name:`feedback`,description:`Send free-form feedback about Catena to the Catena team`},args:Ku.args,async run({args:e}){(Array.isArray(e._)?e._:[]).length>1&&X(`<message>: pass the message as a single quoted argument`);let t=Ku.parse(e),n=(await Gu(t.message)).trim();n.length===0&&X(`<message>: must not be empty`),n.length>Uu&&X(`<message>: must be at most ${Uu} characters (got: ${n.length})`),await $(t)(async e=>(await e.submitFeedback(n),{ok:!0}))}});function Ju(e){return`# Catena CLI Agent Guide
139
139
 
140
140
  CLI version: ${e}
141
141
 
@@ -150,7 +150,7 @@ instructions. An **operator** is a person who can sign in to the Catena console
150
150
  and approve requests. They are often the same person.
151
151
 
152
152
  The stored credential is one signing key for each profile. The CLI signs every
153
- request with that key. No session expires, and nothing refreshes. If the bank
153
+ request with that key. No session expires, and nothing refreshes. If Catena
154
154
  rejects the key, the error tells you to run \`catena link\`. Obey the error. Do
155
155
  not retry the command first. A host that sets \`CATENA_SECRET_KEY\` gets
156
156
  different guidance and must not run \`link\`. See Hosts Without a Keychain.
@@ -177,15 +177,15 @@ between commands, and how to read the results.
177
177
  the user approves from their own device.
178
178
 
179
179
  Run \`link\` again in three cases: after a denial or a revocation, after a
180
- command reports that the bank rejected this machine's signing key, and after a
180
+ command reports that Catena rejected this machine's signing key, and after a
181
181
  send or transfer fails with a local-signer error.
182
182
 
183
183
  Three failures do not improve after you run \`link\` again:
184
184
 
185
185
  - \`created_out_of_window\`. The clock on this machine is wrong.
186
- - The bank does not support key-based authentication. It needs an upgrade, or
187
- you need an older CLI release.
188
- - \`client_upgrade_required\`. The bank no longer accepts this CLI version. Run
186
+ - The Catena API does not support key-based authentication. It needs an
187
+ upgrade, or you need an older CLI release.
188
+ - \`client_upgrade_required\`. Catena no longer accepts this CLI version. Run
189
189
  \`npm i -g @catena/cli\`, then try again.
190
190
 
191
191
  \`link\` names the profile after the agent when no profile is selected. It also
@@ -221,13 +221,13 @@ Stdout keeps only the command result.
221
221
  must revoke the key in the Catena console. Only \`unlink --force\` still runs,
222
222
  because it clears a profile on this machine and never signs.
223
223
 
224
- If the bank rejects the key, the error names \`CATENA_SECRET_KEY\`. Ask an
224
+ If Catena rejects the key, the error names \`CATENA_SECRET_KEY\`. Ask an
225
225
  operator for a new key, then set the variable again. Do not run \`link\` to
226
226
  repair this credential.
227
227
 
228
228
  While the key is set, \`profiles current\` reports the credential and not a
229
229
  profile. \`.source\` is \`"secret-key"\`, \`.credential\` names the variable, and
230
- \`.bankUrl\` gives the target bank. The \`.profile\` and \`.agentId\` fields are
230
+ \`.apiUrl\` gives the Catena API URL. The \`.profile\` and \`.agentId\` fields are
231
231
  absent. \`profiles list\` adds \`.shadowedBy\` and reports \`current: false\`
232
232
  for every profile.
233
233
 
@@ -237,16 +237,16 @@ for every profile.
237
237
  such as Vercel, Cloudflare Workers, or a server. Approval registers a P-256
238
238
  public key. The flow makes no session token and writes nothing to this machine.
239
239
 
240
- The command prints the signing-key thumbprint before approval. It then prints
241
- \`CATENA_SECRET_KEY\` one time. That variable is the whole credential. The
242
- command also prints the public key as a record to keep, not as a variable to
243
- set. Add \`--public-key <hex>\` when the deployment already made its own
244
- keypair.
240
+ The command prints the signing-key thumbprint before approval. Check it against
241
+ the approval screen. It then prints \`CATENA_SECRET_KEY\` one time. That
242
+ variable is the whole credential. Add \`--public-key <hex>\` when the deployment
243
+ already made its own keypair.
245
244
 
246
- A second run with the same key is safe. It uses the existing link again, and it
247
- registers the wallet-send signer again. This is how you recover when the
248
- organization was not signing-ready at the time of the link. Give the linked
249
- agent ID as the final argument when you run the command for recovery.
245
+ The command also reports whether wallet sends are ready. They are not ready
246
+ when the organization cannot sign transfers yet. In that case the command
247
+ prints the exact command to run afterwards, with the agent ID and the public
248
+ key filled in. A second run with the same key is safe: it uses the existing
249
+ link again, and it registers the wallet-send signer again.
250
250
 
251
251
  This is a setup wizard for an operator. An agent that runs interactively
252
252
  through MCP, a CLI, or a terminal must use plain \`link\`. It must never use
@@ -316,8 +316,8 @@ that money moved. \`accounts deposit-address\` returns the on-chain funding
316
316
  address of the account on \`.address\`. Run \`policy show\` when the user asks
317
317
  what the agent can do.
318
318
 
319
- \`--network\` must match the network of the account. A bank does not always
320
- enable every network. A network that the bank does not enable fails with a
319
+ \`--network\` must match the network of the account. Catena does not always
320
+ enable every network. A network that Catena does not enable fails with a
321
321
  server error that lists the enabled networks. A network that the account is not
322
322
  on fails with a configured-network error. No command returns the network of an
323
323
  account. Use \`base\` by default. After either error, run the command again with
@@ -456,6 +456,9 @@ request again with the payment attached:
456
456
  catena x402 --url https://api.example.com/paid \\
457
457
  --account acct_... --max-amount 0.25
458
458
 
459
+ The CLI does not carry a network or token allowlist for x402. The connected
460
+ server decides which exact-scheme requirements are payable.
461
+
459
462
  \`x402\` manages its own keys. It makes a new key for each payment attempt. A
460
463
  second run after a success can pay a second time, even for the same URL and the
461
464
  same price.
@@ -492,8 +495,9 @@ You can check first with
492
495
  \`counterparties list --address <payTo> --network <network>\`, but you do not
493
496
  need the address before you start. If the address is not saved, the CLI charges
494
497
  nothing and exits non-zero. The result then carries \`.counterpartyNotFound\`
495
- with \`payTo\`, the \`network\` slug, \`networkId\`, \`serviceName\` when the
496
- endpoint gives one, \`.nameIsPlaceholder\`, and \`.createCommand\`.
498
+ with \`payTo\`, the server-resolved \`.requiredRail\`, the product \`network\`
499
+ slug, the protocol \`networkId\`, \`serviceName\` when the endpoint gives one,
500
+ \`.nameIsPlaceholder\`, and \`.createCommand\`.
497
501
  \`.createCommand\` holds the \`counterparties create wallet\` command to run, and
498
502
  \`.error\` holds the same command for a person to read.
499
503
 
@@ -551,10 +555,12 @@ non-custodial wallet account, then sends the request again:
551
555
  catena mpp --url https://api.example.com/paid \\
552
556
  --account acct_... --max-amount 0.25
553
557
 
554
- Support at this time covers \`evm/charge\` and \`usdc/charge\` only, for native
555
- USDC on Base and Base Sepolia. See \`mpp --help\` for the request-body, header,
556
- output, profile, and JSON flags. Always set \`--max-amount\` when the user gives
557
- a price ceiling. The CLI refuses a larger challenge before it makes an intent.
558
+ The CLI recognizes structurally valid EVM \`evm/charge\` and \`usdc/charge\`
559
+ challenges. The connected server decides which networks and canonical USDC
560
+ contracts are payable; current support includes Base and Base Sepolia. See
561
+ \`mpp --help\` for the request-body, header, output, profile, and JSON flags.
562
+ Always set \`--max-amount\` when the user gives a price ceiling. The CLI refuses
563
+ a larger challenge before it makes an intent.
558
564
 
559
565
  An MPP payment uses the same send capability, counterparty allowlist, spend
560
566
  limits, and operator approval flow as every other agent payment. The recipient
@@ -563,9 +569,9 @@ the challenge asks for.
563
569
 
564
570
  Three fields tell you what to do next:
565
571
 
566
- - **\`.counterpartyNotFound\`** — replace the \`<name>\` placeholder in
567
- \`.createCommand\`, make the counterparty, then run the SAME MPP command
568
- again.
572
+ - **\`.counterpartyNotFound\`** — inspect the server-resolved \`.requiredRail\`,
573
+ replace the \`<name>\` placeholder in \`.createCommand\`, make the
574
+ counterparty, then run the SAME MPP command again.
569
575
  - **\`.approvalPending\`** — ask an operator to approve the intent. Then run the
570
576
  SAME MPP command again, with no change.
571
577
  - **\`.networkMismatch\`** — the wallet account cannot pay on a network that the
@@ -699,13 +705,14 @@ need, or if it cannot express your operation:
699
705
 
700
706
  The message must have 1 to 4000 characters. You cannot read it again after you
701
707
  send it. Give a longer message on stdin instead of as an argument.
702
- `}const Ju=c({meta:{name:`guide`,description:`Print the Catena CLI agent operating guide`},run(){console.log(qu(oe))}}),Yu=Q({id:ws({description:`Intent id (e.g. int_…)`,required:!0,schema:Bs}),profile:Ls,json:Rs}),Xu=c({meta:{name:`get`,description:`Look up the current state of an intent created by this agent`},args:Yu.args,async run({args:e}){let t=Yu.parse(e);await $(t)(e=>e.getIntent(t.id))}}),Zu=c({meta:{name:`intents`,description:`Inspect intent receipts returned by governed operations`},subCommands:{get:Xu}});function Qu(e=process.env,t=process.platform){return!!(e.SSH_CONNECTION||e.SSH_TTY||t===`linux`&&!e.DISPLAY&&!e.WAYLAND_DISPLAY)}function $u(e){let t;try{t=E(ne(e))}catch{return!1}if(t===`/`)return!0;try{let e=E(process.env.HOME??ee());return t===e||e.startsWith(`${t}/`)}catch{return!0}}function ed(e){e&&process.stderr.write(`Failed to open browser: ${e.message}\n`)}function td(e){process.platform===`darwin`?v(`open`,[e],ed):process.platform===`win32`?v(`cmd`,[`/c`,`start`,``,e],ed):v(`xdg-open`,[e],ed)}function nd(e){if(typeof e!=`object`||!e)return;let t=e;return typeof t.message==`string`?t.message:typeof t.error==`string`?t.error:void 0}function rd(e){return typeof e!=`object`||!e||!(`access_token`in e)?!1:typeof e.access_token==`string`}function id(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.agentId==`string`&&typeof t.name==`string`&&typeof t.sessionToken==`string`&&(t.activated===void 0||typeof t.activated==`boolean`)}function ad(e){if(typeof e!=`object`||!e)return!1;let t=e;return sc.some(e=>e===t.status)&&(t.publicKeyHex===void 0||typeof t.publicKeyHex==`string`)&&(t.reason===void 0||typeof t.reason==`string`)}async function od(e){let{bankUrl:t,authCode:n,verifier:r,redirectUri:i,agentId:a,clientInstanceId:o,clientId:s,clientLabel:c,log:l=()=>{},appInfo:u,existingSigner:d,generateSignerKeypair:f=ga}=e,p=Jl(u);l(`Exchanging authorization code...`);let m=await fetch(`${t}/v1/auth/oauth2/token`,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,...p},body:new URLSearchParams({grant_type:`authorization_code`,code:n,code_verifier:r,client_id:s,redirect_uri:i}).toString()});if(!m.ok)return{ok:!1,message:nd(await m.json().catch(()=>({message:`Token exchange failed`})))??m.statusText};let h=await m.json();if(!rd(h))return{ok:!1,message:`Token exchange response missing access_token`};l(`Claiming agent...`);let g=d?{algorithm:d.algorithm,privateKeyHex:d.privateKeyHex,publicKeyHex:d.publicKeyHex}:f(),_=await fetch(`${t}/v1/agent-api/claim`,{method:`POST`,headers:{"Content-Type":`application/json`,...p,Authorization:`Bearer ${h.access_token}`},body:JSON.stringify({agentId:a,clientInstanceId:o,...c===void 0?{}:{clientLabel:c}})});if(!_.ok)return{ok:!1,message:nd(await _.json().catch(()=>({message:`Claim failed`})))??_.statusText};let v=await _.json();return id(v)?sd({bankUrl:t,claim:v,clientInstanceId:o,signerKeypair:g,identityHeaders:p,log:l}):{ok:!1,message:`Claim response missing required fields`}}async function sd(e){let{bankUrl:t,claim:n,clientInstanceId:r,signerKeypair:i,identityHeaders:a}=e;(e.log??(()=>{}))(`Registering signer...`);let o=await ld({bankUrl:t,sessionToken:n.sessionToken,keypair:i,identityHeaders:a});return o.status===`registration_failed`?(n.activated!==!1&&await ud({bankUrl:t,sessionToken:n.sessionToken,identityHeaders:a}),o.reason===`public_key_conflict`?{ok:!1,message:`This device's signing key conflicts with the one the bank already holds for this agent, or that key is already registered to another agent. Re-running link will not fix this; this agent's signing key cannot be reset automatically, so ask an operator or support to reset it before linking again.`}:{ok:!1,message:`Signer registration failed (${o.reason??`unknown`}). Run link again to retry.`}):{ok:!0,result:{agentId:n.agentId,clientInstanceId:r,agentName:n.name,signer:{...i,registration:o}}}}function cd(e){return typeof e!=`object`||!e||!(`signer`in e)?!1:ad(e.signer)}async function ld(e){let t;try{t=await fetch(`${e.bankUrl}/v1/agent-api/signer/register`,{method:`POST`,headers:{"Content-Type":`application/json`,...e.identityHeaders,Authorization:`Bearer ${e.sessionToken}`},body:JSON.stringify({signer:{algorithm:e.keypair.algorithm,publicKeyHex:e.keypair.publicKeyHex}})})}catch{return{status:`registration_failed`,reason:`registration_request_failed`}}if(t.status===409)return{status:`registration_failed`,reason:`public_key_conflict`};if(!t.ok)return{status:`registration_failed`,reason:`provider_registration_failed`};let n=await t.json().catch(()=>null);return cd(n)?n.signer:{status:`registration_failed`,reason:`registration_response_malformed`}}async function ud(e){try{await fetch(`${e.bankUrl}/v1/agent-api/unlink`,{method:`POST`,headers:{...e.identityHeaders,Authorization:`Bearer ${e.sessionToken}`}})}catch{}}function dd(e){return`${e}-signer`}async function fd(e,t){let n=await e.resolve(t);if(n!==null&&`signer`in n)return n.signer;let r=await e.resolve(dd(t));if(r!==null&&`signer`in r)return r.signer}async function pd(e,t,n=ga){let r=await fd(e,t);if(r!==void 0)return r;let i=xc(n());return await e.save(dd(t),i),i.signer}const md=[53682,53683,53684,53685,53686,53687];function hd(e){return new Promise((t,n)=>{let r=0,i=()=>{if(r>=md.length){n(Error(`No registered loopback callback ports are available`));return}let a=md[r],o=t=>{if(e.off(`error`,o),t.code===`EADDRINUSE`){r++,i();return}n(t)};e.once(`error`,o),e.listen(a,`127.0.0.1`,()=>{e.off(`error`,o),t(a)})};i()})}async function gd(e){let{bankUrl:t,agentId:n,clientInstanceId:r,clientId:i,clientLabel:a,timeoutMs:o=3e5,log:s=()=>{},appInfo:c,existingSigner:l}=e;Xc(t,`bankUrl`);let u=g(32).toString(`base64url`),d=m(`sha256`).update(u).digest(`base64url`),f=g(16).toString(`hex`),p=e=>{let n=new URL(`${t}/link-complete`);return n.searchParams.set(`linked`,e),n.toString()},h=e=>{let n=new URL(`${t}/link-complete`);return n.searchParams.set(`error`,e),n.toString()};return new Promise((e,m)=>{let g=0,_=!1,v=null,y=t=>{_||(_=!0,v&&clearTimeout(v),S.close(),e(t))},b=e=>{_||(_=!0,v&&clearTimeout(v),S.close(),m(e))},x=e=>{s(`Link failed: ${e}`),y(null)},S=re((e,t)=>{C(e,t).catch(e=>{let n=nd(e)??`Unexpected error`;t.headersSent||(t.writeHead(302,{Location:h(n)}),t.end()),s(`Link failed: ${n}`),y(null)})});async function C(e,o){let d=new URL(e.url??`/`,`http://localhost`);if(d.pathname!==`/callback`){o.writeHead(404),o.end(`Not found`);return}let m=d.searchParams.get(`error`);if(m){let e=d.searchParams.get(`error_description`)??m;o.writeHead(302,{Location:h(e)}),o.end(),x(`OAuth error: ${e}`);return}if(d.searchParams.get(`state`)!==f){o.writeHead(302,{Location:h(`State mismatch during OAuth callback`)}),o.end(),x(`State mismatch during OAuth callback`);return}let _=d.searchParams.get(`code`);if(!_){o.writeHead(302,{Location:h(`Missing authorization code`)}),o.end(),x(`Missing authorization code`);return}let v=`http://127.0.0.1:${g}/callback`,b=await od({bankUrl:t,authCode:_,verifier:u,redirectUri:v,agentId:n,clientInstanceId:r,clientId:i,clientLabel:a,log:s,appInfo:c,existingSigner:l});if(!b.ok){o.writeHead(302,{Location:h(b.message)}),o.end(),s(`Link failed: ${b.message}`),y(null);return}o.writeHead(302,{Location:p(b.result.agentId)}),o.end(),y(b.result)}hd(S).then(e=>{g=e;let n=`http://127.0.0.1:${g}/callback`,r=`${t}/v1/auth/oauth2/authorize?`+new URLSearchParams({response_type:`code`,client_id:i,redirect_uri:n,scope:`openid email profile offline_access`,code_challenge:d,code_challenge_method:`S256`,state:f}).toString();s(`Opening browser for authentication...`),td(r),s(`If browser didn't open, visit: ${r}`)}).catch(b),v=setTimeout(()=>{x(`Timed out waiting for authentication`)},o),v.unref()})}function _d(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.deviceCode==`string`&&typeof t.userCode==`string`&&typeof t.verificationUri==`string`&&typeof t.verificationUriComplete==`string`&&typeof t.expiresIn==`number`&&typeof t.interval==`number`}function vd(e){if(typeof e!=`object`||!e)return{};let t=e;return{code:typeof t.code==`string`?t.code:void 0,message:typeof t.error==`string`?t.error:void 0}}function yd(e){return new Promise(t=>{setTimeout(t,e)})}function bd(e){let t={clientInstanceId:e.clientInstanceId,...e.clientLabel===void 0?{}:{clientLabel:e.clientLabel}};return e.scope===`agent:connect`?{scope:`agent:connect`,...t,...e.suggestedAgentName===void 0?{}:{suggestedAgentName:e.suggestedAgentName}}:e.scope===`agent:link`?{scope:`agent:link`,agentId:e.agentId,...t}:{agentId:e.agentId,...t}}async function xd(e){let{bankUrl:t,clientInstanceId:n,onUserCode:r,log:i=()=>{},appInfo:a,existingSigner:o,generateSignerKeypair:s=ga,sleep:c=yd}=e;Xc(t,`bankUrl`);let l=Jl(a),u=e=>(i(`Link failed: ${e}`),null),d;try{d=await fetch(`${t}/v1/agent-link/device/code`,{method:`POST`,headers:{"Content-Type":`application/json`,...l},body:JSON.stringify(bd(e))})}catch{return u(`Could not reach the bank to start the device flow`)}if(!d.ok)return u(vd(await d.json().catch(()=>null)).message??d.statusText);let f=await d.json();if(!_d(f))return u(`Device authorization response missing required fields`);r({userCode:f.userCode,verificationUri:f.verificationUri,verificationUriComplete:f.verificationUriComplete,expiresInSeconds:f.expiresIn});let p=await Sd({bankUrl:t,grant:f,identityHeaders:l,sleep:c});if(!p.ok)return u(p.message);let m=p.body;if(!id(m))return u(`Device token response missing required fields`);i(`Approved. Claiming agent...`);let h=await sd({bankUrl:t,claim:m,clientInstanceId:n,signerKeypair:o?{algorithm:o.algorithm,privateKeyHex:o.privateKeyHex,publicKeyHex:o.publicKeyHex}:s(),identityHeaders:l,log:i});return h.ok?h.result:u(h.message)}async function Sd(e){let{bankUrl:t,grant:n,identityHeaders:r,sleep:i}=e,a=Date.now()+n.expiresIn*1e3,o=Math.max(n.interval,1)*1e3,s=o;for(;Date.now()+o<=a;){await i(o);let e;try{e=await fetch(`${t}/v1/agent-link/device/token`,{method:`POST`,headers:{"Content-Type":`application/json`,...r},body:JSON.stringify({deviceCode:n.deviceCode})})}catch{s=Math.min(s*2,6e4),o=Math.max(o,s);continue}if(s=o,e.ok){let t=await e.json().catch(()=>null);return t===null?{ok:!1,message:`The bank returned an unreadable token response`}:{ok:!0,body:t}}let a=vd(await e.json().catch(()=>null));if(a.code!==`authorization_pending`){if(a.code===`slow_down`){o+=5e3;continue}return a.code===`expired_token`?{ok:!1,message:`The device code expired before approval. Run link again`}:{ok:!1,message:a.message??`The request was denied`}}}return{ok:!1,message:`Timed out waiting for approval`}}function Cd(e){if(typeof e!=`object`||!e)return!1;let t=e,n=t.signer;return t.credential===`signing_key`&&typeof t.agentId==`string`&&typeof t.name==`string`&&typeof t.keyThumbprint==`string`&&typeof t.activated==`boolean`&&typeof n==`object`&&!!n&&typeof n.status==`string`}async function wd(e){let{bankUrl:t,clientInstanceId:n,onUserCode:r,log:i=()=>{},appInfo:a,sleep:o=yd}=e;Xc(t,`bankUrl`);let s=Jl(a),c=e=>(i(`Link failed: ${e}`),null),l={clientInstanceId:n,signer:{algorithm:`p256`,publicKeyHex:e.publicKeyHex},...e.clientLabel===void 0?{}:{clientLabel:e.clientLabel}},u=e.agentId===void 0?{scope:`agent:connect:service`,...l,...e.suggestedAgentName===void 0?{}:{suggestedAgentName:e.suggestedAgentName}}:{scope:`agent:link:service`,agentId:e.agentId,...l},d;try{d=await fetch(`${t}/v1/agent-link/device/code`,{method:`POST`,headers:{"Content-Type":`application/json`,...s},body:JSON.stringify(u)})}catch{return c(`Could not reach the bank to start the device flow`)}if(!d.ok){let e=vd(await d.json().catch(()=>null));return e.code===`validation_failed`?c(`The bank rejected the request, which usually means it does not support --service yet. Nothing was created. Upgrade the bank and retry`):c(e.message??d.statusText)}let f=await d.json();if(!_d(f))return c(`Device authorization response missing required fields`);r({userCode:f.userCode,verificationUri:f.verificationUri,verificationUriComplete:f.verificationUriComplete,expiresInSeconds:f.expiresIn});let p=await Sd({bankUrl:t,grant:f,identityHeaders:s,sleep:o});return p.ok?id(p.body)?c(`This bank does not support --service yet: it created a session link for agent ${p.body.agentId}. Unlink it in the console before retrying`):Cd(p.body)?(i(`Approved. Signing key registered.`),{agentId:p.body.agentId,agentName:p.body.name,keyThumbprint:p.body.keyThumbprint,activated:p.body.activated,signerStatus:p.body.signer.status,...p.body.signer.reason===void 0?{}:{signerReason:p.body.signer.reason}}):c(`Device token response missing required fields`):c(p.message)}const Td=Q({"agent-id":ws({description:`Optional agent ID shown in the Catena console; omit to create and link a new agent`,schema:Bs}),"bank-url":Z({description:`Bank API URL (defaults to $CATENA_API_URL or prod)`,default:process.env.CATENA_API_URL??`https://api.catena.com`}),browser:Es({description:`Open the browser PKCE flow (default)`,negativeDescription:`Skip the browser and link with a device code you approve from another machine`,default:!0}),name:Z({description:`Suggested name for an agent created from this link; only used when agent-id is omitted`}),service:Es({description:`Provision a deployed-service signing credential instead of linking this machine: approval registers a P-256 key, no session tokens are minted, and nothing is stored locally. Interactive agent hosts must NOT use this`,default:!1}),"public-key":Z({description:`With --service: register this existing compressed P-256 public key (the deployment already holds the private key) instead of generating a keypair`}),profile:Ls}),Ed=/^0[23][0-9a-f]{64}$/;function Dd(e){let t=Math.round(e.expiresInSeconds/60);console.log(`\n To approve this link, visit: ${e.verificationUri}`),console.log(` and enter the code: ${e.userCode}`),console.log(`\n Or open: ${e.verificationUriComplete}`),console.log(`\n Waiting for approval (expires in ${t} minutes)...`)}function Od(e){console.log(`
703
- Keep this generated keypair if the approval completed before the CLI failed:`),console.log(`\n ${Nl}=${e.privateKeyHex}`),console.log(`\nKeep this public key with your deployment notes. It is not an\nenvironment variable; signer recovery needs it:\n\n ${e.publicKeyHex}`)}function kd(e){switch(e){case`signer_key_conflict`:return` Wallet-send signer: not registered (signer key conflict); unlink the conflicting service link or re-run with the linked agent ID`;case`provider_registration_failed`:return` Wallet-send signer: not registered (provider registration failed); retry after the provider recovers`;case void 0:return` Wallet-send signer: not registered (registration failed); retry after checking the link status`;default:return` Wallet-send signer: not registered (${e}); retry after checking the link status`}}function Ad({agentId:e,suggestedAgentName:t,browserRequested:n,isHeadless:r}){return e===void 0?{kind:`device-connect`,deviceTarget:{scope:`agent:connect`,...t===void 0?{}:{suggestedAgentName:t}}}:n?r()?{kind:`device-link`,deviceTarget:{agentId:e},notice:`No browser available — using device code flow.`}:{kind:`pkce-link`,agentId:e}:{kind:`device-link`,deviceTarget:{agentId:e}}}function jd(e){let t=m(`sha256`).update(E(process.cwd())).digest(`hex`).slice(0,16);return`${Dl(e??`agent`).slice(0,47)}-${t}`}function Md(e){try{let t=process.cwd();if($u(t))return null;let n=vl(t);return{directory:yl(t,e),reboundFrom:n!==null&&n!==e?n:null}}catch{return console.error(`Warning: could not bind the current directory to profile "${e}".`),null}}const Nd=c({meta:{name:`link`,description:`Link an existing agent, or create and link a new agent when agent-id is omitted`},args:Td.args,async run({args:e}){let t=Td.parse(e),n=t[`bank-url`],r=t[`agent-id`],i=t.name;if(t.service){await Pd({bankUrl:n,agentId:r,suggestedAgentName:i,publicKeyHex:t[`public-key`]});return}let a,o,s;try{if(Xc(n,`--bank-url`),t[`public-key`]!==void 0)throw Error(`--public-key requires --service`);if(r!==void 0&&i!==void 0)throw Error(`--name can only be used when agent-id is omitted`);let e=Bl({flag:ru(t),cwd:process.cwd(),log:e=>console.error(e)});a=(e!==null&&e.source!=="default"?e.name:null)??(r===void 0?null:ml(r,n)),o=a??(r===void 0?jd(i):Dl(r)),s=Cl(o,{bank_url:n,agent_id:r})}catch(e){X(e)}console.log(`
704
- Catena — Agent Setup`),console.log(`─`.repeat(25));let c=Kc(),l=await pd(c,s),u={bankUrl:n,clientInstanceId:s,log:e=>console.log(` ${e}`),appInfo:Wl,existingSigner:l},d=Ad({agentId:r,suggestedAgentName:i,browserRequested:t.browser,isHeadless:Qu});d.kind===`device-link`&&d.notice!==void 0&&console.log(` ${d.notice}`);let f=d.kind===`pkce-link`?await gd({...u,agentId:d.agentId,clientId:`catena-cli`,timeoutMs:3e5}):await xd({...u,...d.deviceTarget,onUserCode:Dd});f||X(`
705
- Failed to link agent. Run the command again to try again.`),await c.save(s,Cc(f.signer));let p=a??Ol(Dl(f.agentName),e=>e!==o&&xl(e)!==null);try{p===o?dl(p,{bank_url:n,agent_id:f.agentId,client_instance_id:s}):kl({reservationName:o,profileName:p,profile:{bank_url:n,agent_id:f.agentId,client_instance_id:s}})}catch(e){X(e)}console.log(`\n Wrote profile "${p}"`);let m=Md(p);m!==null&&console.log(m.reboundFrom===null?` Bound ${m.directory} to profile "${p}"`:` Rebound ${m.directory} from profile "${m.reboundFrom}" to "${p}"`),console.log(` To pin this identity for an agent host, set ${Ll}=${p}`),Fl()&&console.log(` ${Nl} is set and outranks ${Ll}; unset it, or pass --profile ${p}, to use this profile`),console.log(`\nDone. Agent "${f.agentName}" linked.`),process.exit(0)}});async function Pd(e){try{if(Xc(e.bankUrl,`--bank-url`),e.agentId!==void 0&&e.suggestedAgentName!==void 0)throw Error(`--name can only be used when agent-id is omitted`);if(e.publicKeyHex!==void 0&&!Ed.test(e.publicKeyHex.toLowerCase()))throw Error(`--public-key must be compressed P-256 public key hex (66 chars)`)}catch(e){X(e)}console.log(`
706
- Catena — Deployed Service Setup`),console.log(`─`.repeat(31));let t=e.publicKeyHex===void 0?ga():null,n=t?.publicKeyHex??e.publicKeyHex?.toLowerCase()??``,r;try{r=ba(n)}catch(e){e instanceof ha||X(e),X(`Signing key public key is not a valid P-256 point`)}console.log(` Signing key (RFC 7638 thumbprint): ${r}`);let i=`service-${m(`sha256`).update(n).digest(`hex`).slice(0,32)}`,a=!1,o=()=>{t&&a&&Od({publicKeyHex:n,privateKeyHex:t.privateKeyHex})},s;try{s=await wd({bankUrl:e.bankUrl,clientInstanceId:i,publicKeyHex:n,...e.agentId===void 0?{}:{agentId:e.agentId},...e.suggestedAgentName===void 0?{}:{suggestedAgentName:e.suggestedAgentName},onUserCode:e=>{a=!0,Dd(e)},log:e=>console.log(` ${e}`),appInfo:Wl})}catch(e){o(),X(e)}s||(o(),X(`
707
- Failed to link the service. Run the command again to try again.`)),s.keyThumbprint!==r&&(o(),X(`The bank registered signing key thumbprint ${s.keyThumbprint}, which does not match the local key (${r}). Do not deploy this credential. Unlink the agent in the console and run link again`)),console.log(`\nDone. Agent "${s.agentName}" linked as a deployed service.`),console.log(` Agent ID: ${s.agentId}`),console.log(` Signing key (RFC 7638 thumbprint): ${s.keyThumbprint}`),s.signerStatus===`registered`||s.signerStatus===`already_registered`?console.log(` Wallet-send signer: registered`):s.signerStatus===`not_applicable`?console.log(` Wallet-send signer: deferred (${s.signerReason??`topology not ready`}); the org must be signing-ready before live sends`):s.signerStatus===`registration_failed`?console.log(kd(s.signerReason)):console.log(` Wallet-send signer: not registered (${s.signerReason??s.signerStatus}); retry after checking the link status`),console.log(`
708
- Set this in the deployment environment:`),console.log(t?`\n ${Nl}=${t.privateKeyHex}`:`\n ${Nl}=<the private key this deployment already holds>`),e.bankUrl!==`https://api.catena.com`&&console.log(` CATENA_API_URL=${e.bankUrl}`),console.log(`\nKeep the agent ID and this public key with your deployment notes. They\nare not environment variables; signer recovery needs them:\n\n ${n}`),t&&console.log(`
709
- The private key is shown once and is not stored on this machine.`),process.exit(0)}
708
+ `}const Yu=c({meta:{name:`guide`,description:`Print the Catena CLI agent operating guide`},run(){console.log(Ju(oe))}}),Xu=Q({id:Ts({description:`Intent id (e.g. int_…)`,required:!0,schema:Vs}),profile:Rs,json:zs}),Zu=c({meta:{name:`get`,description:`Look up the current state of an intent created by this agent`},args:Xu.args,async run({args:e}){let t=Xu.parse(e);await $(t)(e=>e.getIntent(t.id))}}),Qu=c({meta:{name:`intents`,description:`Inspect intent receipts returned by governed operations`},subCommands:{get:Zu}});function $u(e=process.env,t=process.platform){return!!(e.SSH_CONNECTION||e.SSH_TTY||t===`linux`&&!e.DISPLAY&&!e.WAYLAND_DISPLAY)}function ed(e){let t;try{t=E(ne(e))}catch{return!1}if(t===`/`)return!0;try{let e=E(process.env.HOME??ee());return t===e||e.startsWith(`${t}/`)}catch{return!0}}function td(e){e&&process.stderr.write(`Failed to open browser: ${e.message}\n`)}function nd(e){process.platform===`darwin`?v(`open`,[e],td):process.platform===`win32`?v(`cmd`,[`/c`,`start`,``,e],td):v(`xdg-open`,[e],td)}function rd(e){if(typeof e!=`object`||!e)return;let t=e;return typeof t.message==`string`?t.message:typeof t.error==`string`?t.error:void 0}function id(e){return typeof e!=`object`||!e||!(`access_token`in e)?!1:typeof e.access_token==`string`}function ad(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.agentId==`string`&&typeof t.name==`string`&&typeof t.sessionToken==`string`&&(t.activated===void 0||typeof t.activated==`boolean`)}function od(e){if(typeof e!=`object`||!e)return!1;let t=e;return sc.some(e=>e===t.status)&&(t.publicKeyHex===void 0||typeof t.publicKeyHex==`string`)&&(t.reason===void 0||typeof t.reason==`string`)}async function sd(e){let{apiUrl:t,authCode:n,verifier:r,redirectUri:i,agentId:a,clientInstanceId:o,clientId:s,clientLabel:c,log:l=()=>{},appInfo:u,existingSigner:d,generateSignerKeypair:f=ga}=e,p=Yl(u);l(`Exchanging authorization code...`);let m=await fetch(`${t}/v1/auth/oauth2/token`,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,...p},body:new URLSearchParams({grant_type:`authorization_code`,code:n,code_verifier:r,client_id:s,redirect_uri:i}).toString()});if(!m.ok)return{ok:!1,message:rd(await m.json().catch(()=>({message:`Token exchange failed`})))??m.statusText};let h=await m.json();if(!id(h))return{ok:!1,message:`Token exchange response missing access_token`};l(`Claiming agent...`);let g=d?{algorithm:d.algorithm,privateKeyHex:d.privateKeyHex,publicKeyHex:d.publicKeyHex}:f(),_=await fetch(`${t}/v1/agent-api/claim`,{method:`POST`,headers:{"Content-Type":`application/json`,...p,Authorization:`Bearer ${h.access_token}`},body:JSON.stringify({agentId:a,clientInstanceId:o,...c===void 0?{}:{clientLabel:c}})});if(!_.ok)return{ok:!1,message:rd(await _.json().catch(()=>({message:`Claim failed`})))??_.statusText};let v=await _.json();return ad(v)?cd({apiUrl:t,claim:v,clientInstanceId:o,signerKeypair:g,identityHeaders:p,log:l}):{ok:!1,message:`Claim response missing required fields`}}async function cd(e){let{apiUrl:t,claim:n,clientInstanceId:r,signerKeypair:i,identityHeaders:a}=e;(e.log??(()=>{}))(`Registering signer...`);let o=await ud({apiUrl:t,sessionToken:n.sessionToken,keypair:i,identityHeaders:a});return o.status===`registration_failed`?(n.activated!==!1&&await dd({apiUrl:t,sessionToken:n.sessionToken,identityHeaders:a}),o.reason===`public_key_conflict`?{ok:!1,message:`This device's signing key conflicts with the one Catena already holds for this agent, or that key is already registered to another agent. Re-running link will not fix this; this agent's signing key cannot be reset automatically, so ask an operator or support to reset it before linking again.`}:{ok:!1,message:`Signer registration failed (${o.reason??`unknown`}). Run link again to retry.`}):{ok:!0,result:{agentId:n.agentId,clientInstanceId:r,agentName:n.name,signer:{...i,registration:o}}}}function ld(e){return typeof e!=`object`||!e||!(`signer`in e)?!1:od(e.signer)}async function ud(e){let t;try{t=await fetch(`${e.apiUrl}/v1/agent-api/signer/register`,{method:`POST`,headers:{"Content-Type":`application/json`,...e.identityHeaders,Authorization:`Bearer ${e.sessionToken}`},body:JSON.stringify({signer:{algorithm:e.keypair.algorithm,publicKeyHex:e.keypair.publicKeyHex}})})}catch{return{status:`registration_failed`,reason:`registration_request_failed`}}if(t.status===409)return{status:`registration_failed`,reason:`public_key_conflict`};if(!t.ok)return{status:`registration_failed`,reason:`provider_registration_failed`};let n=await t.json().catch(()=>null);return ld(n)?n.signer:{status:`registration_failed`,reason:`registration_response_malformed`}}async function dd(e){try{await fetch(`${e.apiUrl}/v1/agent-api/unlink`,{method:`POST`,headers:{...e.identityHeaders,Authorization:`Bearer ${e.sessionToken}`}})}catch{}}function fd(e){return`${e}-signer`}async function pd(e,t){let n=await e.resolve(t);if(n!==null&&`signer`in n)return n.signer;let r=await e.resolve(fd(t));if(r!==null&&`signer`in r)return r.signer}async function md(e,t,n=ga){let r=await pd(e,t);if(r!==void 0)return r;let i=xc(n());return await e.save(fd(t),i),i.signer}const hd=[53682,53683,53684,53685,53686,53687];function gd(e){return new Promise((t,n)=>{let r=0,i=()=>{if(r>=hd.length){n(Error(`No registered loopback callback ports are available`));return}let a=hd[r],o=t=>{if(e.off(`error`,o),t.code===`EADDRINUSE`){r++,i();return}n(t)};e.once(`error`,o),e.listen(a,`127.0.0.1`,()=>{e.off(`error`,o),t(a)})};i()})}async function _d(e){let{apiUrl:t,agentId:n,clientInstanceId:r,clientId:i,clientLabel:a,timeoutMs:o=3e5,log:s=()=>{},appInfo:c,existingSigner:l}=e;Xc(t,`apiUrl`);let u=g(32).toString(`base64url`),d=m(`sha256`).update(u).digest(`base64url`),f=g(16).toString(`hex`),p=e=>{let n=new URL(`${t}/link-complete`);return n.searchParams.set(`linked`,e),n.toString()},h=e=>{let n=new URL(`${t}/link-complete`);return n.searchParams.set(`error`,e),n.toString()};return new Promise((e,m)=>{let g=0,_=!1,v=null,y=t=>{_||(_=!0,v&&clearTimeout(v),S.close(),e(t))},b=e=>{_||(_=!0,v&&clearTimeout(v),S.close(),m(e))},x=e=>{s(`Link failed: ${e}`),y(null)},S=re((e,t)=>{C(e,t).catch(e=>{let n=rd(e)??`Unexpected error`;t.headersSent||(t.writeHead(302,{Location:h(n)}),t.end()),s(`Link failed: ${n}`),y(null)})});async function C(e,o){let d=new URL(e.url??`/`,`http://localhost`);if(d.pathname!==`/callback`){o.writeHead(404),o.end(`Not found`);return}let m=d.searchParams.get(`error`);if(m){let e=d.searchParams.get(`error_description`)??m;o.writeHead(302,{Location:h(e)}),o.end(),x(`OAuth error: ${e}`);return}if(d.searchParams.get(`state`)!==f){o.writeHead(302,{Location:h(`State mismatch during OAuth callback`)}),o.end(),x(`State mismatch during OAuth callback`);return}let _=d.searchParams.get(`code`);if(!_){o.writeHead(302,{Location:h(`Missing authorization code`)}),o.end(),x(`Missing authorization code`);return}let v=`http://127.0.0.1:${g}/callback`,b=await sd({apiUrl:t,authCode:_,verifier:u,redirectUri:v,agentId:n,clientInstanceId:r,clientId:i,clientLabel:a,log:s,appInfo:c,existingSigner:l});if(!b.ok){o.writeHead(302,{Location:h(b.message)}),o.end(),s(`Link failed: ${b.message}`),y(null);return}o.writeHead(302,{Location:p(b.result.agentId)}),o.end(),y(b.result)}gd(S).then(e=>{g=e;let n=`http://127.0.0.1:${g}/callback`,r=`${t}/v1/auth/oauth2/authorize?`+new URLSearchParams({response_type:`code`,client_id:i,redirect_uri:n,scope:`openid email profile offline_access`,code_challenge:d,code_challenge_method:`S256`,state:f}).toString();s(`Opening browser for authentication...`),nd(r),s(`If browser didn't open, visit: ${r}`)}).catch(b),v=setTimeout(()=>{x(`Timed out waiting for authentication`)},o),v.unref()})}function vd(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.deviceCode==`string`&&typeof t.userCode==`string`&&typeof t.verificationUri==`string`&&typeof t.verificationUriComplete==`string`&&typeof t.expiresIn==`number`&&typeof t.interval==`number`}function yd(e){if(typeof e!=`object`||!e)return{};let t=e;return{code:typeof t.code==`string`?t.code:void 0,message:typeof t.error==`string`?t.error:void 0}}function bd(e){return new Promise(t=>{setTimeout(t,e)})}function xd(e){let t={clientInstanceId:e.clientInstanceId,...e.clientLabel===void 0?{}:{clientLabel:e.clientLabel}};return e.scope===`agent:connect`?{scope:`agent:connect`,...t,...e.suggestedAgentName===void 0?{}:{suggestedAgentName:e.suggestedAgentName}}:e.scope===`agent:link`?{scope:`agent:link`,agentId:e.agentId,...t}:{agentId:e.agentId,...t}}async function Sd(e){let{apiUrl:t,clientInstanceId:n,onUserCode:r,log:i=()=>{},appInfo:a,existingSigner:o,generateSignerKeypair:s=ga,sleep:c=bd}=e;Xc(t,`apiUrl`);let l=Yl(a),u=e=>(i(`Link failed: ${e}`),null),d;try{d=await fetch(`${t}/v1/agent-link/device/code`,{method:`POST`,headers:{"Content-Type":`application/json`,...l},body:JSON.stringify(xd(e))})}catch{return u(`Could not reach the Catena API to start the device flow`)}if(!d.ok)return u(yd(await d.json().catch(()=>null)).message??d.statusText);let f=await d.json();if(!vd(f))return u(`Device authorization response missing required fields`);r({userCode:f.userCode,verificationUri:f.verificationUri,verificationUriComplete:f.verificationUriComplete,expiresInSeconds:f.expiresIn});let p=await Cd({apiUrl:t,grant:f,identityHeaders:l,sleep:c});if(!p.ok)return u(p.message);let m=p.body;if(!ad(m))return u(`Device token response missing required fields`);i(`Approved. Claiming agent...`);let h=await cd({apiUrl:t,claim:m,clientInstanceId:n,signerKeypair:o?{algorithm:o.algorithm,privateKeyHex:o.privateKeyHex,publicKeyHex:o.publicKeyHex}:s(),identityHeaders:l,log:i});return h.ok?h.result:u(h.message)}async function Cd(e){let{apiUrl:t,grant:n,identityHeaders:r,sleep:i}=e,a=Date.now()+n.expiresIn*1e3,o=Math.max(n.interval,1)*1e3,s=o;for(;Date.now()+o<=a;){await i(o);let e;try{e=await fetch(`${t}/v1/agent-link/device/token`,{method:`POST`,headers:{"Content-Type":`application/json`,...r},body:JSON.stringify({deviceCode:n.deviceCode})})}catch{s=Math.min(s*2,6e4),o=Math.max(o,s);continue}if(s=o,e.ok){let t=await e.json().catch(()=>null);return t===null?{ok:!1,message:`The Catena API returned an unreadable token response`}:{ok:!0,body:t}}let a=yd(await e.json().catch(()=>null));if(a.code!==`authorization_pending`){if(a.code===`slow_down`){o+=5e3;continue}return a.code===`expired_token`?{ok:!1,message:`The device code expired before approval. Run link again`}:{ok:!1,message:a.message??`The request was denied`}}}return{ok:!1,message:`Timed out waiting for approval`}}function wd(e){if(typeof e!=`object`||!e)return!1;let t=e,n=t.signer;return t.credential===`signing_key`&&typeof t.agentId==`string`&&typeof t.name==`string`&&typeof t.keyThumbprint==`string`&&typeof t.activated==`boolean`&&typeof n==`object`&&!!n&&typeof n.status==`string`}async function Td(e){let{apiUrl:t,clientInstanceId:n,onUserCode:r,log:i=()=>{},appInfo:a,sleep:o=bd}=e;Xc(t,`apiUrl`);let s=Yl(a),c=e=>(i(`Link failed: ${e}`),null),l={clientInstanceId:n,signer:{algorithm:`p256`,publicKeyHex:e.publicKeyHex},...e.clientLabel===void 0?{}:{clientLabel:e.clientLabel}},u=e.agentId===void 0?{scope:`agent:connect:service`,...l,...e.suggestedAgentName===void 0?{}:{suggestedAgentName:e.suggestedAgentName}}:{scope:`agent:link:service`,agentId:e.agentId,...l},d;try{d=await fetch(`${t}/v1/agent-link/device/code`,{method:`POST`,headers:{"Content-Type":`application/json`,...s},body:JSON.stringify(u)})}catch{return c(`Could not reach the Catena API to start the device flow`)}if(!d.ok){let e=yd(await d.json().catch(()=>null));return e.code===`validation_failed`?c(`The Catena API rejected the request, which usually means it does not support --service yet. Nothing was created. Upgrade it and retry`):c(e.message??d.statusText)}let f=await d.json();if(!vd(f))return c(`Device authorization response missing required fields`);r({userCode:f.userCode,verificationUri:f.verificationUri,verificationUriComplete:f.verificationUriComplete,expiresInSeconds:f.expiresIn});let p=await Cd({apiUrl:t,grant:f,identityHeaders:s,sleep:o});return p.ok?ad(p.body)?c(`This Catena API does not support --service yet: it created a session link for agent ${p.body.agentId}. Unlink it in the console before retrying`):wd(p.body)?(i(`Approved. Signing key registered.`),{agentId:p.body.agentId,agentName:p.body.name,keyThumbprint:p.body.keyThumbprint,activated:p.body.activated,signerStatus:p.body.signer.status,...p.body.signer.reason===void 0?{}:{signerReason:p.body.signer.reason}}):c(`Device token response missing required fields`):c(p.message)}const Ed=Q({"agent-id":Ts({description:`Optional agent ID shown in the Catena console; omit to create and link a new agent`,schema:Vs}),"api-url":Z({description:`Catena API URL (defaults to $CATENA_API_URL)`,default:process.env.CATENA_API_URL??`https://api.catena.com`}),browser:Ds({description:`Open the browser PKCE flow (default)`,negativeDescription:`Skip the browser and link with a device code you approve from another machine`,default:!0}),name:Z({description:`Suggested name for an agent created from this link; only used when agent-id is omitted`}),service:Ds({description:`Provision a deployed-service signing credential instead of linking this machine: approval registers a P-256 key, no session tokens are minted, and nothing is stored locally. Interactive agent hosts must NOT use this`,default:!1}),"public-key":Z({description:`With --service: register this existing compressed P-256 public key (the deployment already holds the secret key) instead of generating a keypair`}),profile:Rs}),Dd=/^0[23][0-9a-f]{64}$/;function Od(e){let t=Math.round(e.expiresInSeconds/60);console.log(`\n To approve this link, visit: ${e.verificationUri}`),console.log(` and enter the code: ${e.userCode}`),console.log(`\n Or open: ${e.verificationUriComplete}`),console.log(`\n Waiting for approval (expires in ${t} minutes)...`)}function kd(e){console.log(`
709
+ This machine generated a key that the approval may already have registered.`),console.log(`Save both values before you run link again:`),console.log(`\n ${Pl}=${e.privateKeyHex}`),console.log(` Public key: ${e.publicKeyHex}`)}function Ad(e){let t=e.apiUrl===`https://api.catena.com`?``:` --api-url ${e.apiUrl}`;return` catena link --service ${e.agentId} --public-key ${e.publicKeyHex}${t}`}function jd(e){let t=t=>[...t,``,e.retryCommand];switch(e.signerStatus){case`registered`:case`already_registered`:return[];case`not_applicable`:return t([`Wallet sends are not ready yet. Your organization cannot sign`,`transfers until an admin finishes signing setup. Reads and payment`,`requests work now. Run this once that is done:`]);case`registration_failed`:return e.signerReason===`signer_key_conflict`?[`Wallet sends are not ready yet. Another link already uses this`,`signing key. Unlink that service in the Catena console, then run`,`link again.`]:t([`Wallet sends are not ready yet. The signing provider did not`,`register the key. Reads and payment requests work now. Run this`,`once it recovers:`]);default:return t([`Wallet sends are not ready yet. Catena reported "${e.signerReason??e.signerStatus}".`,`Reads and payment requests work now. Check the link in the Catena`,`console, then run this:`])}}function Md({agentId:e,suggestedAgentName:t,browserRequested:n,isHeadless:r}){return e===void 0?{kind:`device-connect`,deviceTarget:{scope:`agent:connect`,...t===void 0?{}:{suggestedAgentName:t}}}:n?r()?{kind:`device-link`,deviceTarget:{agentId:e},notice:`No browser available — using device code flow.`}:{kind:`pkce-link`,agentId:e}:{kind:`device-link`,deviceTarget:{agentId:e}}}function Nd(e){let t=m(`sha256`).update(E(process.cwd())).digest(`hex`).slice(0,16);return`${Ol(e??`agent`).slice(0,47)}-${t}`}function Pd(e){try{let t=process.cwd();if(ed(t))return null;let n=yl(t);return{directory:bl(t,e),reboundFrom:n!==null&&n!==e?n:null}}catch{return console.error(`Warning: could not bind the current directory to profile "${e}".`),null}}const Fd=c({meta:{name:`link`,description:`Link an existing agent, or create and link a new agent when agent-id is omitted`},args:Ed.args,async run({args:e}){let t=Ed.parse(e),n=t[`api-url`],r=t[`agent-id`],i=t.name;if(t.service){await Id({apiUrl:n,agentId:r,suggestedAgentName:i,publicKeyHex:t[`public-key`]});return}let a,o,s;try{if(Xc(n,`--api-url`),t[`public-key`]!==void 0)throw Error(`--public-key requires --service`);if(r!==void 0&&i!==void 0)throw Error(`--name can only be used when agent-id is omitted`);let e=Vl({flag:iu(t),cwd:process.cwd(),log:e=>console.error(e)});a=(e!==null&&e.source!=="default"?e.name:null)??(r===void 0?null:hl(r,n)),o=a??(r===void 0?Nd(i):Ol(r)),s=wl(o,{api_url:n,agent_id:r})}catch(e){X(e)}console.log(`
710
+ Catena — Agent Setup`),console.log(`─`.repeat(25));let c=Kc(),l=await md(c,s),u={apiUrl:n,clientInstanceId:s,log:e=>console.log(` ${e}`),appInfo:Gl,existingSigner:l},d=Md({agentId:r,suggestedAgentName:i,browserRequested:t.browser,isHeadless:$u});d.kind===`device-link`&&d.notice!==void 0&&console.log(` ${d.notice}`);let f=d.kind===`pkce-link`?await _d({...u,agentId:d.agentId,clientId:`catena-cli`,timeoutMs:3e5}):await Sd({...u,...d.deviceTarget,onUserCode:Od});f||X(`
711
+ Failed to link agent. Run the command again to try again.`),await c.save(s,Cc(f.signer));let p=a??kl(Ol(f.agentName),e=>e!==o&&Sl(e)!==null);try{p===o?fl(p,{api_url:n,agent_id:f.agentId,client_instance_id:s}):Al({reservationName:o,profileName:p,profile:{api_url:n,agent_id:f.agentId,client_instance_id:s}})}catch(e){X(e)}console.log(`\n Wrote profile "${p}"`);let m=Pd(p);m!==null&&console.log(m.reboundFrom===null?` Bound ${m.directory} to profile "${p}"`:` Rebound ${m.directory} from profile "${m.reboundFrom}" to "${p}"`),console.log(` To pin this identity for an agent host, set ${Rl}=${p}`),Il()&&console.log(` ${Pl} is set and outranks ${Rl}; unset it, or pass --profile ${p}, to use this profile`),console.log(`\nDone. Agent "${f.agentName}" linked.`),process.exit(0)}});async function Id(e){try{if(Xc(e.apiUrl,`--api-url`),e.agentId!==void 0&&e.suggestedAgentName!==void 0)throw Error(`--name can only be used when agent-id is omitted`);if(e.publicKeyHex!==void 0&&!Dd.test(e.publicKeyHex.toLowerCase()))throw Error(`--public-key must be compressed P-256 public key hex (66 chars)`)}catch(e){X(e)}console.log(`
712
+ Catena — Deployed Service Setup`),console.log(`─`.repeat(31));let t=e.publicKeyHex===void 0?ga():null,n=t?.publicKeyHex??e.publicKeyHex?.toLowerCase()??``,r;try{r=ba(n)}catch(e){e instanceof ha||X(e),X(`Signing key public key is not a valid P-256 point`)}console.log(` Signing key: ${r}`),console.log(` Check this matches the key on the approval screen.`);let i=`service-${m(`sha256`).update(n).digest(`hex`).slice(0,32)}`,a=!1,o=()=>{t&&a&&kd({publicKeyHex:n,privateKeyHex:t.privateKeyHex})},s;try{s=await Td({apiUrl:e.apiUrl,clientInstanceId:i,publicKeyHex:n,...e.agentId===void 0?{}:{agentId:e.agentId},...e.suggestedAgentName===void 0?{}:{suggestedAgentName:e.suggestedAgentName},onUserCode:e=>{a=!0,Od(e)},log:e=>console.log(` ${e}`),appInfo:Gl})}catch(e){o(),X(e)}s||(o(),X(`
713
+ Failed to link the service. Run the command again to try again.`)),s.keyThumbprint!==r&&(o(),X(`Catena registered signing key thumbprint ${s.keyThumbprint}, which does not match the local key (${r}). Do not deploy this credential. Unlink the agent in the console and run link again`));let c=jd({signerStatus:s.signerStatus,signerReason:s.signerReason,retryCommand:Ad({agentId:s.agentId,publicKeyHex:n,apiUrl:e.apiUrl})});console.log(`\nDone. Agent "${s.agentName}" is linked as a deployed service.`),console.log(` Agent ID: ${s.agentId}`),console.log(c.length===0?` Wallet sends: ready`:` Wallet sends: not ready yet`),console.log(`
714
+ Set this in the deployment environment:`),console.log(t?`\n ${Pl}=${t.privateKeyHex}`:`\n ${Pl}=<the secret key this deployment already holds>`),e.apiUrl!==`https://api.catena.com`&&console.log(` CATENA_API_URL=${e.apiUrl}`),t&&console.log(`
715
+ Save the secret key now. It is shown once and is not stored on this machine.`),c.length>0&&console.log(`\n${c.join(`
716
+ `)}`),process.exit(0)}
710
717
  /*! decimal.js-light v2.5.1 https://github.com/MikeMcl/decimal.js-light/LICENCE */
711
- const Fd=e(i(((e,t)=>{(function(e){var n=1e9,r={precision:20,rounding:4,toExpNeg:-7,toExpPos:21,LN10:`2.302585092994045684017991454684364207601101488628772976033327900967572609677352480235997205089598298341967784042286`},i=!0,a=`[DecimalError] `,o=a+`Invalid argument: `,s=a+`Exponent out of range: `,c=Math.floor,l=Math.pow,u=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,d,f=1e7,p=7,m=9007199254740991,h=c(m/p),g={};g.absoluteValue=g.abs=function(){var e=new this.constructor(this);return e.s&&=1,e},g.comparedTo=g.cmp=function(e){var t,n,r,i,a=this;if(e=new a.constructor(e),a.s!==e.s)return a.s||-e.s;if(a.e!==e.e)return a.e>e.e^a.s<0?1:-1;for(r=a.d.length,i=e.d.length,t=0,n=r<i?r:i;t<n;++t)if(a.d[t]!==e.d[t])return a.d[t]>e.d[t]^a.s<0?1:-1;return r===i?0:r>i^a.s<0?1:-1},g.decimalPlaces=g.dp=function(){var e=this,t=e.d.length-1,n=(t-e.e)*p;if(t=e.d[t],t)for(;t%10==0;t/=10)n--;return n<0?0:n},g.dividedBy=g.div=function(e){return b(this,new this.constructor(e))},g.dividedToIntegerBy=g.idiv=function(e){var t=this,n=t.constructor;return D(b(t,new n(e),0,1),n.precision)},g.equals=g.eq=function(e){return!this.cmp(e)},g.exponent=function(){return S(this)},g.greaterThan=g.gt=function(e){return this.cmp(e)>0},g.greaterThanOrEqualTo=g.gte=function(e){return this.cmp(e)>=0},g.isInteger=g.isint=function(){return this.e>this.d.length-2},g.isNegative=g.isneg=function(){return this.s<0},g.isPositive=g.ispos=function(){return this.s>0},g.isZero=function(){return this.s===0},g.lessThan=g.lt=function(e){return this.cmp(e)<0},g.lessThanOrEqualTo=g.lte=function(e){return this.cmp(e)<1},g.logarithm=g.log=function(e){var t,n=this,r=n.constructor,o=r.precision,s=o+5;if(e===void 0)e=new r(10);else if(e=new r(e),e.s<1||e.eq(d))throw Error(a+`NaN`);if(n.s<1)throw Error(a+(n.s?`NaN`:`-Infinity`));return n.eq(d)?new r(0):(i=!1,t=b(T(n,s),T(e,s),s),i=!0,D(t,o))},g.minus=g.sub=function(e){var t=this;return e=new t.constructor(e),t.s==e.s?O(t,e):_(t,(e.s=-e.s,e))},g.modulo=g.mod=function(e){var t,n=this,r=n.constructor,o=r.precision;if(e=new r(e),!e.s)throw Error(a+`NaN`);return n.s?(i=!1,t=b(n,e,0,1).times(e),i=!0,n.minus(t)):D(new r(n),o)},g.naturalExponential=g.exp=function(){return x(this)},g.naturalLogarithm=g.ln=function(){return T(this)},g.negated=g.neg=function(){var e=new this.constructor(this);return e.s=-e.s||0,e},g.plus=g.add=function(e){var t=this;return e=new t.constructor(e),t.s==e.s?_(t,e):O(t,(e.s=-e.s,e))},g.precision=g.sd=function(e){var t,n,r,i=this;if(e!==void 0&&e!==!!e&&e!==1&&e!==0)throw Error(o+e);if(t=S(i)+1,r=i.d.length-1,n=r*p+1,r=i.d[r],r){for(;r%10==0;r/=10)n--;for(r=i.d[0];r>=10;r/=10)n++}return e&&t>n?t:n},g.squareRoot=g.sqrt=function(){var e,t,n,r,o,s,l,u=this,d=u.constructor;if(u.s<1){if(!u.s)return new d(0);throw Error(a+`NaN`)}for(e=S(u),i=!1,o=Math.sqrt(+u),o==0||o==1/0?(t=y(u.d),(t.length+e)%2==0&&(t+=`0`),o=Math.sqrt(t),e=c((e+1)/2)-(e<0||e%2),o==1/0?t=`5e`+e:(t=o.toExponential(),t=t.slice(0,t.indexOf(`e`)+1)+e),r=new d(t)):r=new d(o.toString()),n=d.precision,o=l=n+3;;)if(s=r,r=s.plus(b(u,s,l+2)).times(.5),y(s.d).slice(0,l)===(t=y(r.d)).slice(0,l)){if(t=t.slice(l-3,l+1),o==l&&t==`4999`){if(D(s,n+1,0),s.times(s).eq(u)){r=s;break}}else if(t!=`9999`)break;l+=4}return i=!0,D(r,n)},g.times=g.mul=function(e){var t,n,r,a,o,s,c,l,u,d=this,p=d.constructor,m=d.d,h=(e=new p(e)).d;if(!d.s||!e.s)return new p(0);for(e.s*=d.s,n=d.e+e.e,l=m.length,u=h.length,l<u&&(o=m,m=h,h=o,s=l,l=u,u=s),o=[],s=l+u,r=s;r--;)o.push(0);for(r=u;--r>=0;){for(t=0,a=l+r;a>r;)c=o[a]+h[r]*m[a-r-1]+t,o[a--]=c%f|0,t=c/f|0;o[a]=(o[a]+t)%f|0}for(;!o[--s];)o.pop();return t?++n:o.shift(),e.d=o,e.e=n,i?D(e,p.precision):e},g.toDecimalPlaces=g.todp=function(e,t){var r=this,i=r.constructor;return r=new i(r),e===void 0?r:(v(e,0,n),t===void 0?t=i.rounding:v(t,0,8),D(r,e+S(r)+1,t))},g.toExponential=function(e,t){var r,i=this,a=i.constructor;return e===void 0?r=k(i,!0):(v(e,0,n),t===void 0?t=a.rounding:v(t,0,8),i=D(new a(i),e+1,t),r=k(i,!0,e+1)),r},g.toFixed=function(e,t){var r,i,a=this,o=a.constructor;return e===void 0?k(a):(v(e,0,n),t===void 0?t=o.rounding:v(t,0,8),i=D(new o(a),e+S(a)+1,t),r=k(i.abs(),!1,e+S(i)+1),a.isneg()&&!a.isZero()?`-`+r:r)},g.toInteger=g.toint=function(){var e=this,t=e.constructor;return D(new t(e),S(e)+1,t.rounding)},g.toNumber=function(){return+this},g.toPower=g.pow=function(e){var t,n,r,o,s,l,u=this,f=u.constructor,h=12,g=+(e=new f(e));if(!e.s)return new f(d);if(u=new f(u),!u.s){if(e.s<1)throw Error(a+`Infinity`);return u}if(u.eq(d))return u;if(r=f.precision,e.eq(d))return D(u,r);if(t=e.e,n=e.d.length-1,l=t>=n,s=u.s,!l){if(s<0)throw Error(a+`NaN`)}else if((n=g<0?-g:g)<=m){for(o=new f(d),t=Math.ceil(r/p+4),i=!1;n%2&&(o=o.times(u),A(o.d,t)),n=c(n/2),n!==0;)u=u.times(u),A(u.d,t);return i=!0,e.s<0?new f(d).div(o):D(o,r)}return s=s<0&&e.d[Math.max(t,n)]&1?-1:1,u.s=1,i=!1,o=e.times(T(u,r+h)),i=!0,o=x(o),o.s=s,o},g.toPrecision=function(e,t){var r,i,a=this,o=a.constructor;return e===void 0?(r=S(a),i=k(a,r<=o.toExpNeg||r>=o.toExpPos)):(v(e,1,n),t===void 0?t=o.rounding:v(t,0,8),a=D(new o(a),e,t),r=S(a),i=k(a,e<=r||r<=o.toExpNeg,e)),i},g.toSignificantDigits=g.tosd=function(e,t){var r=this,i=r.constructor;return e===void 0?(e=i.precision,t=i.rounding):(v(e,1,n),t===void 0?t=i.rounding:v(t,0,8)),D(new i(r),e,t)},g.toString=g.valueOf=g.val=g.toJSON=function(){var e=this,t=S(e),n=e.constructor;return k(e,t<=n.toExpNeg||t>=n.toExpPos)};function _(e,t){var n,r,a,o,s,c,l,u,d=e.constructor,m=d.precision;if(!e.s||!t.s)return t.s||(t=new d(e)),i?D(t,m):t;if(l=e.d,u=t.d,s=e.e,a=t.e,l=l.slice(),o=s-a,o){for(o<0?(r=l,o=-o,c=u.length):(r=u,a=s,c=l.length),s=Math.ceil(m/p),c=s>c?s+1:c+1,o>c&&(o=c,r.length=1),r.reverse();o--;)r.push(0);r.reverse()}for(c=l.length,o=u.length,c-o<0&&(o=c,r=u,u=l,l=r),n=0;o;)n=(l[--o]=l[o]+u[o]+n)/f|0,l[o]%=f;for(n&&(l.unshift(n),++a),c=l.length;l[--c]==0;)l.pop();return t.d=l,t.e=a,i?D(t,m):t}function v(e,t,n){if(e!==~~e||e<t||e>n)throw Error(o+e)}function y(e){var t,n,r,i=e.length-1,a=``,o=e[0];if(i>0){for(a+=o,t=1;t<i;t++)r=e[t]+``,n=p-r.length,n&&(a+=w(n)),a+=r;o=e[t],r=o+``,n=p-r.length,n&&(a+=w(n))}else if(o===0)return`0`;for(;o%10==0;)o/=10;return a+o}var b=(function(){function e(e,t){var n,r=0,i=e.length;for(e=e.slice();i--;)n=e[i]*t+r,e[i]=n%f|0,r=n/f|0;return r&&e.unshift(r),e}function t(e,t,n,r){var i,a;if(n!=r)a=n>r?1:-1;else for(i=a=0;i<n;i++)if(e[i]!=t[i]){a=e[i]>t[i]?1:-1;break}return a}function n(e,t,n){for(var r=0;n--;)e[n]-=r,r=+(e[n]<t[n]),e[n]=r*f+e[n]-t[n];for(;!e[0]&&e.length>1;)e.shift()}return function(r,i,o,s){var c,l,u,d,m,h,g,_,v,y,b,x,C,w,T,E,O,k,A=r.constructor,ee=r.s==i.s?1:-1,j=r.d,M=i.d;if(!r.s)return new A(r);if(!i.s)throw Error(a+`Division by zero`);for(l=r.e-i.e,O=M.length,T=j.length,g=new A(ee),_=g.d=[],u=0;M[u]==(j[u]||0);)++u;if(M[u]>(j[u]||0)&&--l,x=o==null?o=A.precision:s?o+(S(r)-S(i))+1:o,x<0)return new A(0);if(x=x/p+2|0,u=0,O==1)for(d=0,M=M[0],x++;(u<T||d)&&x--;u++)C=d*f+(j[u]||0),_[u]=C/M|0,d=C%M|0;else{for(d=f/(M[0]+1)|0,d>1&&(M=e(M,d),j=e(j,d),O=M.length,T=j.length),w=O,v=j.slice(0,O),y=v.length;y<O;)v[y++]=0;k=M.slice(),k.unshift(0),E=M[0],M[1]>=f/2&&++E;do d=0,c=t(M,v,O,y),c<0?(b=v[0],O!=y&&(b=b*f+(v[1]||0)),d=b/E|0,d>1?(d>=f&&(d=f-1),m=e(M,d),h=m.length,y=v.length,c=t(m,v,h,y),c==1&&(d--,n(m,O<h?k:M,h))):(d==0&&(c=d=1),m=M.slice()),h=m.length,h<y&&m.unshift(0),n(v,m,y),c==-1&&(y=v.length,c=t(M,v,O,y),c<1&&(d++,n(v,O<y?k:M,y))),y=v.length):c===0&&(d++,v=[0]),_[u++]=d,c&&v[0]?v[y++]=j[w]||0:(v=[j[w]],y=1);while((w++<T||v[0]!==void 0)&&x--)}return _[0]||_.shift(),g.e=l,D(g,s?o+S(g)+1:o)}})();function x(e,t){var n,r,a,o,c,u,f=0,p=0,m=e.constructor,h=m.precision;if(S(e)>16)throw Error(s+S(e));if(!e.s)return new m(d);for(t==null?(i=!1,u=h):u=t,c=new m(.03125);e.abs().gte(.1);)e=e.times(c),p+=5;for(r=Math.log(l(2,p))/Math.LN10*2+5|0,u+=r,n=a=o=new m(d),m.precision=u;;){if(a=D(a.times(e),u),n=n.times(++f),c=o.plus(b(a,n,u)),y(c.d).slice(0,u)===y(o.d).slice(0,u)){for(;p--;)o=D(o.times(o),u);return m.precision=h,t==null?(i=!0,D(o,h)):o}o=c}}function S(e){for(var t=e.e*p,n=e.d[0];n>=10;n/=10)t++;return t}function C(e,t,n){if(t>e.LN10.sd())throw i=!0,n&&(e.precision=n),Error(a+`LN10 precision limit exceeded`);return D(new e(e.LN10),t)}function w(e){for(var t=``;e--;)t+=`0`;return t}function T(e,t){var n,r,o,s,c,l,u,f,p,m=1,h=10,g=e,_=g.d,v=g.constructor,x=v.precision;if(g.s<1)throw Error(a+(g.s?`NaN`:`-Infinity`));if(g.eq(d))return new v(0);if(t==null?(i=!1,f=x):f=t,g.eq(10))return t??(i=!0),C(v,f);if(f+=h,v.precision=f,n=y(_),r=n.charAt(0),s=S(g),Math.abs(s)<0x5543df729c000){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)g=g.times(e),n=y(g.d),r=n.charAt(0),m++;s=S(g),r>1?(g=new v(`0.`+n),s++):g=new v(r+`.`+n.slice(1))}else return u=C(v,f+2,x).times(s+``),g=T(new v(r+`.`+n.slice(1)),f-h).plus(u),v.precision=x,t==null?(i=!0,D(g,x)):g;for(l=c=g=b(g.minus(d),g.plus(d),f),p=D(g.times(g),f),o=3;;){if(c=D(c.times(p),f),u=l.plus(b(c,new v(o),f)),y(u.d).slice(0,f)===y(l.d).slice(0,f))return l=l.times(2),s!==0&&(l=l.plus(C(v,f+2,x).times(s+``))),l=b(l,new v(m),f),v.precision=x,t==null?(i=!0,D(l,x)):l;l=u,o+=2}}function E(e,t){var n,r,a;for((n=t.indexOf(`.`))>-1&&(t=t.replace(`.`,``)),(r=t.search(/e/i))>0?(n<0&&(n=r),n+=+t.slice(r+1),t=t.substring(0,r)):n<0&&(n=t.length),r=0;t.charCodeAt(r)===48;)++r;for(a=t.length;t.charCodeAt(a-1)===48;)--a;if(t=t.slice(r,a),t){if(a-=r,n=n-r-1,e.e=c(n/p),e.d=[],r=(n+1)%p,n<0&&(r+=p),r<a){for(r&&e.d.push(+t.slice(0,r)),a-=p;r<a;)e.d.push(+t.slice(r,r+=p));t=t.slice(r),r=p-t.length}else r-=a;for(;r--;)t+=`0`;if(e.d.push(+t),i&&(e.e>h||e.e<-h))throw Error(s+n)}else e.s=0,e.e=0,e.d=[0];return e}function D(e,t,n){var r,a,o,u,d,m,g,_,v=e.d;for(u=1,o=v[0];o>=10;o/=10)u++;if(r=t-u,r<0)r+=p,a=t,g=v[_=0];else{if(_=Math.ceil((r+1)/p),o=v.length,_>=o)return e;for(g=o=v[_],u=1;o>=10;o/=10)u++;r%=p,a=r-p+u}if(n!==void 0&&(o=l(10,u-a-1),d=g/o%10|0,m=t<0||v[_+1]!==void 0||g%o,m=n<4?(d||m)&&(n==0||n==(e.s<0?3:2)):d>5||d==5&&(n==4||m||n==6&&(r>0?a>0?g/l(10,u-a):0:v[_-1])%10&1||n==(e.s<0?8:7))),t<1||!v[0])return m?(o=S(e),v.length=1,t=t-o-1,v[0]=l(10,(p-t%p)%p),e.e=c(-t/p)||0):(v.length=1,v[0]=e.e=e.s=0),e;if(r==0?(v.length=_,o=1,_--):(v.length=_+1,o=l(10,p-r),v[_]=a>0?(g/l(10,u-a)%l(10,a)|0)*o:0),m)for(;;)if(_==0){(v[0]+=o)==f&&(v[0]=1,++e.e);break}else{if(v[_]+=o,v[_]!=f)break;v[_--]=0,o=1}for(r=v.length;v[--r]===0;)v.pop();if(i&&(e.e>h||e.e<-h))throw Error(s+S(e));return e}function O(e,t){var n,r,a,o,s,c,l,u,d,m,h=e.constructor,g=h.precision;if(!e.s||!t.s)return t.s?t.s=-t.s:t=new h(e),i?D(t,g):t;if(l=e.d,m=t.d,r=t.e,u=e.e,l=l.slice(),s=u-r,s){for(d=s<0,d?(n=l,s=-s,c=m.length):(n=m,r=u,c=l.length),a=Math.max(Math.ceil(g/p),c)+2,s>a&&(s=a,n.length=1),n.reverse(),a=s;a--;)n.push(0);n.reverse()}else{for(a=l.length,c=m.length,d=a<c,d&&(c=a),a=0;a<c;a++)if(l[a]!=m[a]){d=l[a]<m[a];break}s=0}for(d&&(n=l,l=m,m=n,t.s=-t.s),c=l.length,a=m.length-c;a>0;--a)l[c++]=0;for(a=m.length;a>s;){if(l[--a]<m[a]){for(o=a;o&&l[--o]===0;)l[o]=f-1;--l[o],l[a]+=f}l[a]-=m[a]}for(;l[--c]===0;)l.pop();for(;l[0]===0;l.shift())--r;return l[0]?(t.d=l,t.e=r,i?D(t,g):t):new h(0)}function k(e,t,n){var r,i=S(e),a=y(e.d),o=a.length;return t?(n&&(r=n-o)>0?a=a.charAt(0)+`.`+a.slice(1)+w(r):o>1&&(a=a.charAt(0)+`.`+a.slice(1)),a=a+(i<0?`e`:`e+`)+i):i<0?(a=`0.`+w(-i-1)+a,n&&(r=n-o)>0&&(a+=w(r))):i>=o?(a+=w(i+1-o),n&&(r=n-i-1)>0&&(a=a+`.`+w(r))):((r=i+1)<o&&(a=a.slice(0,r)+`.`+a.slice(r)),n&&(r=n-o)>0&&(i+1===o&&(a+=`.`),a+=w(r))),e.s<0?`-`+a:a}function A(e,t){if(e.length>t)return e.length=t,!0}function ee(e){var t,n,r;function i(e){var t=this;if(!(t instanceof i))return new i(e);if(t.constructor=i,e instanceof i){t.s=e.s,t.e=e.e,t.d=(e=e.d)?e.slice():e;return}if(typeof e==`number`){if(e*0!=0)throw Error(o+e);if(e>0)t.s=1;else if(e<0)e=-e,t.s=-1;else{t.s=0,t.e=0,t.d=[0];return}if(e===~~e&&e<1e7){t.e=0,t.d=[e];return}return E(t,e.toString())}if(typeof e!=`string`)throw Error(o+e);if(e.charCodeAt(0)===45?(e=e.slice(1),t.s=-1):t.s=1,u.test(e))E(t,e);else throw Error(o+e)}if(i.prototype=g,i.ROUND_UP=0,i.ROUND_DOWN=1,i.ROUND_CEIL=2,i.ROUND_FLOOR=3,i.ROUND_HALF_UP=4,i.ROUND_HALF_DOWN=5,i.ROUND_HALF_EVEN=6,i.ROUND_HALF_CEIL=7,i.ROUND_HALF_FLOOR=8,i.clone=ee,i.config=i.set=j,e===void 0&&(e={}),e)for(r=[`precision`,`rounding`,`toExpNeg`,`toExpPos`,`LN10`],t=0;t<r.length;)e.hasOwnProperty(n=r[t++])||(e[n]=this[n]);return i.config(e),i}function j(e){if(!e||typeof e!=`object`)throw Error(a+`Object expected`);var t,r,i,s=[`precision`,1,n,`rounding`,0,8,`toExpNeg`,-1/0,0,`toExpPos`,0,1/0];for(t=0;t<s.length;t+=3)if((i=e[r=s[t]])!==void 0){if(c(i)===i&&i>=s[t+1]&&i<=s[t+2])this[r]=i;else throw Error(o+r+`: `+i)}if((i=e[r=`LN10`])!==void 0){if(i==Math.LN10)this[r]=new this(i);else throw Error(o+r+`: `+i)}return this}r=ee(r),r.default=r.Decimal=r,d=new r(1),typeof define==`function`&&define.amd?define(function(){return r}):t!==void 0&&t.exports?t.exports=r:(e||=typeof self<`u`&&self&&self.self==self?self:Function(`return this`)(),e.Decimal=r)})(e)}))(),1).default;Fd.set({rounding:Fd.ROUND_HALF_EVEN});const Id=new Map,Ld=/^[A-Z]{3}$/,Rd=/^[A-Z0-9]{2,6}$/;function zd(e,t,n,r){if(Id.has(e))throw Error(`duplicate asset id ${e}`);let i=new Fd(r);if(i.isNegative())throw Error(`dustThreshold must be a non-negative decimal`);if(i.decimalPlaces()>t)throw Error(`dustThreshold (${r}) must not be finer than the asset's ${t} decimals`);if(!Number.isInteger(t)||!Number.isInteger(n)||t<0||n<0)throw Error(`decimals and presentmentDecimals must be non-negative integers`);if(n>t)throw Error(`presentment decimals should be less than or equal to decimals`)}function Bd(e,t,n,r,i){if(!Ld.test(e))throw Error(`fiat asset ids must be 3-letter ISO-4217 codes`);zd(e,n,r,i.dustThreshold);let a=e;return Id.set(e,{id:a,symbol:e,name:t,kind:`fiat`,decimals:n,presentmentDecimals:r,denomination:e,valuation:{type:`par`},dustThreshold:i.dustThreshold}),a}function Vd(e,t,n,r,i){if(!Rd.test(e)||Ld.test(e))throw Error(`stablecoin tickers must be 2-6 uppercase alphanumerics and not a 3-letter ISO-4217 shape`);let a=Id.get(i.denomination);if(!a||a.kind!==`fiat`)throw Error(`stablecoin denomination must be a registered fiat asset, got ${i.denomination}`);if(n>a.decimals)throw Error(`par stablecoin decimals (${n}) must not exceed its denomination fiat's (${a.decimals})`);zd(e,n,r,i.dustThreshold);let o=e;return Id.set(e,{id:o,symbol:e,name:t,kind:`stablecoin`,decimals:n,presentmentDecimals:r,denomination:a.denomination,valuation:{type:`par`},dustThreshold:i.dustThreshold}),o}Vd(`USDC`,`USD Coin`,6,2,{denomination:Bd(`USD`,`US Dollar`,6,2,{dustThreshold:`0.01`}),dustThreshold:`0.01`}),new Fd(1e6),new Fd(1e3);const Hd=d.pipe(d.string(`Amount must be a string`),d.nonEmpty(`Amount must not be empty`),d.check(e=>e.trim()===e,`Amount must not have leading or trailing whitespace`),d.check(e=>!e.includes(`e`)&&!e.includes(`E`),`Scientific notation is not supported (e.g. use 1000000 instead of 1e6)`),d.check(e=>!e.startsWith(`+`),`Amount must not have a '+' prefix`),d.check(e=>!e.startsWith(`-`),`Amount must be non-negative`),d.check(e=>{try{return new Fd(e).gte(0)}catch{return!1}},`Amount must be a valid decimal (e.g. 100 or 100.50)`)),Ud=d.pipe(d.string(`Count must be a string`),d.transform(e=>e.trim()),d.check(e=>/^\d+$/.test(e),`Count must be a whole number of transactions (e.g. 20)`),d.transform(Number),d.check(e=>Number.isSafeInteger(e),`Count is too large`),d.check(e=>e>=1,`Count must be at least 1`)),Wd={s:1,m:60,h:3600,d:86400},Gd=d.pipe(d.string(`Duration must be a string`),d.transform(e=>e.trim()),d.check(e=>/^\d+[smhd]?$/.test(e),`Duration must be a number of seconds or a value with a unit (e.g. 90s, 30m, 4h, 2d)`),d.transform(e=>{let t=e.at(-1)??``;return t in Wd?Number(e.slice(0,-1))*Wd[t]:Number(e)}),d.check(e=>e>=60,`Duration must be at least 1 minute`),d.check(e=>e<=604800,`Duration must be at most 7 days`)),Kd=Q({profile:Ls,json:Rs}),qd=c({meta:{name:`show`,description:`Show the agent's assigned policy`},args:Kd.args,async run({args:e}){await $(Kd.parse(e))(e=>e.getPolicy())}}),Jd=Q({account:Z({description:`Account whose existing hard limit should increase. For a transfer limit, the source account funds move out of.`,required:!0}),capability:Ds({description:`Which capability's limit to increase: send (payments to counterparties) or transfer (between the user's own accounts)`,choices:$o,default:`send`}),rule:Ds({description:`Which limit to adjust`,choices:fo,default:`per_transaction_amount`}),amount:Z({description:`New threshold for an amount limit, as a decimal USD string (e.g. 500.00)`,schema:Hd,showValueInError:!0}),count:Z({description:`New threshold for a transaction-count limit (e.g. 20)`,schema:Ud,showValueInError:!0}),duration:Z({description:`How long the override should last once approved (e.g. 90s, 30m, 4h, 2d). One minute to seven days.`,required:!0,schema:Gd,showValueInError:!0}),reason:Z({description:`Why the task needs this, for the person who reviews the request`,required:!0}),idempotencyKey:Z({description:`Optional operation key. Reuse the same value only when retrying the same submission; omitted generates a fresh key for this invocation.`,schema:vu}),profile:Ls,json:Rs}),Yd=c({meta:{name:`request-override`,description:`Ask a person to approve a temporary change to this agent's limits`},args:Jd.args,async run({args:e}){let t=Jd.parse(e),n=$(t),r={type:`policy_override`,operations:[Xd(t)],durationSeconds:t.duration,reason:t.reason};await n(e=>e.submitIntent({action:r,...t.idempotencyKey!==void 0&&{idempotencyKey:t.idempotencyKey}}))}});function Xd(e){return e.rule===`hourly_count`||e.rule===`daily_count`?(e.amount!==void 0&&X(`--amount does not apply to ${e.rule}; use --count`),e.count===void 0&&X(`--count is required for ${e.rule}`),{type:`increase_limit`,accountId:e.account,capability:e.capability,limitType:e.rule,newLimit:{count:e.count}}):(e.count!==void 0&&X(`--count does not apply to ${e.rule}; use --amount`),e.amount===void 0&&X(`--amount is required for ${e.rule}`),{type:`increase_limit`,accountId:e.account,capability:e.capability,limitType:e.rule,newLimit:{amount:e.amount,assetId:`USD`}})}const Zd=c({meta:{name:`policy`,description:`Inspect the agent's policy`},subCommands:{show:qd,"request-override":Yd}}),Qd=Q({profile:ws({description:`Profile name`,required:!0})});function $d(){try{return Vl({env:process.env[Ll],cwd:process.cwd(),log:e=>console.error(e)})}catch(e){return X(e)}}const ef=c({meta:{name:`use`,description:`Set the default credential profile`},args:Qd.args,async run({args:e}){let t=Qd.parse(e);try{El(t.profile),nu({defaultProfile:t.profile})}catch(e){X(e)}}}),tf=c({meta:{name:`current`,description:`Show the selected credential profile and how it was chosen`},async run(){let e;try{e=Il()}catch(e){return X(e)}if(e!==null){nu({source:`secret-key`,credential:Nl,bankUrl:e.bankUrl});return}let t=$d(),n;try{n=xl(t.name)}catch(e){X(e)}n===null&&X(`Profile "${t.name}" is not linked.\nRun 'catena link --profile ${t.name} <agent-id>' to authenticate.`),nu({profile:t.name,source:t.source,bankUrl:n.bank_url,agentId:fl(n)?n.agent_id:void 0})}}),nf=c({meta:{name:`list`,description:`List credential profiles and their directory bindings`},async run(){let e;try{e=cl()}catch(e){X(e)}let t=Fl(),n;try{n=t?null:Vl({env:process.env[Ll],cwd:process.cwd()}).name}catch{n=null}let r=Object.entries(e.directories??{});nu({defaultProfile:e.default_profile,...t?{shadowedBy:Nl}:{},profiles:Object.entries(e.profiles).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>({name:e,bankUrl:t.bank_url,agentId:fl(t)?t.agent_id:void 0,directories:r.filter(([,t])=>t===e).map(([e])=>e).toSorted(),current:e===n}))})}}),rf=Q({profile:ws({description:`Profile name to bind`,required:!0}),path:ws({description:`Directory to bind (defaults to the current directory)`})}),af=c({meta:{name:`bind`,description:`Bind a directory to a profile for automatic selection`},args:rf.args,async run({args:e}){let t=rf.parse(e);try{let e=t.path??process.cwd();if($u(e))throw Error(`Refusing to bind the home directory or an ancestor of it — that would shadow the default profile for every directory beneath it. Bind a specific agent directory instead.`);let n=yl(e,t.profile);nu({profile:t.profile,directory:n})}catch(e){X(e)}}}),of=Q({path:ws({description:`Directory to unbind (defaults to the current directory)`})}),sf=c({meta:{name:`unbind`,description:`Remove a directory's profile binding`},args:of.args,async run({args:e}){let t=of.parse(e);try{nu(bl(t.path??process.cwd()))}catch(e){X(e)}}}),cf=c({meta:{name:`profiles`,description:`Manage credential profiles`},subCommands:{use:ef,current:tf,list:nf,bind:af,unbind:sf}}),lf=Q({account:Z({description:`Source account id; omit when the policy allows sends from exactly one account`,schema:Bs}),rail:Z({description:`Destination counterparty rail id (cprl_...)`,required:!0,schema:Bs}),amount:Z({description:`USD amount as a decimal string (e.g. 125.00)`,required:!0,schema:Hd,showValueInError:!0}),method:Ds({description:`ach | wire | on-chain; ach and wire require a bank rail, on-chain a wallet rail`,required:!0,choices:Eo}),memo:Z({description:`Memo on the underlying transfer`}),description:Z({description:`Operator-facing description`}),idempotencyKey:Z({description:`Optional operation key. Reuse the same value only when retrying the same submission; omitted generates a fresh key for this invocation.`,schema:vu}),profile:Ls,json:Rs}),uf=c({meta:{name:`send`,description:`Submit a USD send intent to a counterparty rail`},args:lf.args,async run({args:e}){let t=lf.parse(e),n=$(t),r={type:`send`,...t.account!==void 0&&{accountId:t.account},counterpartyRailId:t.rail,amount:t.amount,method:t.method,...t.memo?{memo:t.memo}:{},...t.description?{description:t.description}:{}};await n(e=>e.submitIntent({action:r,...t.idempotencyKey?{idempotencyKey:t.idempotencyKey}:{}}))}}),df=Q({from:Z({description:`Source account id`,required:!0,schema:Bs}),to:Z({description:`Destination account id`,required:!0,schema:Bs}),amount:Z({description:`USD amount as a decimal string (e.g. 125.00)`,required:!0,schema:Hd,showValueInError:!0}),memo:Z({description:`Memo on the underlying transfer`}),description:Z({description:`Operator-facing description`}),idempotencyKey:Z({description:`Optional operation key. Reuse the same value only when retrying the same submission; omitted generates a fresh key for this invocation.`,schema:vu}),profile:Ls,json:Rs}),ff=c({meta:{name:`transfer`,description:`Submit a USD transfer intent between two of this agent's accounts`},args:df.args,async run({args:e}){let t=df.parse(e),n=$(t),r={type:`transfer`,accountId:t.from,toAccountId:t.to,amount:t.amount,...t.memo?{memo:t.memo}:{},...t.description?{description:t.description}:{}};await n(e=>e.submitIntent({action:r,...t.idempotencyKey?{idempotencyKey:t.idempotencyKey}:{}}))}});function pf(){return`${Nl} is set, and this command removes only a linked profile. Revoke the key in the Catena console under the agent's Secret keys tab, or pass --profile <name> to target a profile on this machine.`}const mf=Q({profile:Ls,force:Es({description:`Remove the profile and its local credentials without contacting the server; use when the credential is missing, revoked, or a link was interrupted`,default:!1}),json:Rs}),hf=c({meta:{name:`unlink`,description:`Disconnect the selected agent profile`},args:mf.args,async run({args:e}){let t=mf.parse(e),n=Xl();!t.force&&ru(t)===void 0&&Fl()&&X(pf());let r;try{r=Vl({flag:ru(t),env:process.env[Ll],cwd:process.cwd(),log:e=>console.error(e)}).name}catch(e){X(e)}if(t.force){let e;try{if(e=xl(r),e===null)throw Error(Fl()?`Profile "${r}" not found, and this machine holds no profile to clear. Revoke the key in the Catena console under the agent's Secret keys tab.`:`Profile "${r}" not found`);await n.delete(e.client_instance_id),await n.delete(dd(e.client_instance_id)),gl(r)}catch(e){X(e)}nu({success:!0,profile:r,...fl(e)?{agentId:e.agent_id}:{},local:!0},{compact:t.json});return}let i=`To remove only this machine's copy, run 'catena unlink --profile ${r} --force'.`,a=await jl({profileName:r,fallbackBankUrl:Ml},n);a.ok||X(`${a.message} ${i}`);let o=Yl(a);try{await o.unlinkAgent(),await n.delete(a.clientInstanceId),await n.delete(dd(a.clientInstanceId)),gl(r)}catch(e){X(`${gs(tu(e,r))} ${i}`)}nu({success:!0,profile:r,agentId:a.agentId},{compact:t.json})}}),gf=Q({profile:Ls,json:Rs}),_f=c({meta:{name:`whoami`,description:`Show which agent you are currently acting as`},args:gf.args,async run({args:e}){await $(gf.parse(e))(e=>e.whoami())}});function vf(e){throw Error(`Unhandled case: ${String(e)}`)}function yf(e,t){return t?.body!==void 0&&t.body!==null&&typeof t.body!=`string`&&!(t.body instanceof URLSearchParams)&&!(t.body instanceof Blob)&&!(t.body instanceof ArrayBuffer)&&!ArrayBuffer.isView(t.body)?!1:typeof Request<`u`&&e instanceof Request?e.body===null&&!e.bodyUsed:!0}function bf(e,t){let n=new Headers(typeof Request<`u`&&e instanceof Request?e.headers:void 0);return new Headers(t?.headers).forEach((e,t)=>{n.set(t,e)}),n}const xf=/^0x[0-9a-fA-F]{64}$/;async function Sf(e,t,n,r){try{await e.reportSettlement({intentId:t,txHash:n,...r!==void 0&&{receipt:r}})}catch{return}}const Cf=[`PAYMENT-REQUIRED`,`X-Payment-Required`],wf=/^0x[0-9a-fA-F]{40}$/,Tf=d.looseObject({success:d.boolean(),transaction:d.string(),extensions:d.optional(d.unknown())}),Ef=d.looseObject({x402Version:d.literal(2),accepts:d.array(Wo),resource:d.optional(Go),extensions:d.optional(d.unknown())}),Df=`x402_network_mismatch`,Of=`x402_counterparty_rail_not_found`,kf=new Set([`x402_requirement_not_payable`,Df,Of]),Af={"eip155:8453":`Base`,"eip155:84532":`Base Sepolia`};function jf(e){let t=Object.hasOwn(Af,e)?Af[e]:void 0;return t?`${t} (${e})`:e}function Mf(e){let t=e.replaceAll(`-`,`+`).replaceAll(`_`,`/`),n=Uint8Array.from(atob(t),e=>e.charCodeAt(0));return JSON.parse(new TextDecoder().decode(n))}function Nf(e){let t=Cf.map(t=>e.headers.get(t)).find(e=>e!==null);if(t)try{let e=d.safeParse(Ef,Mf(t));return e.success?e.output:void 0}catch{return}}async function Pf(e,t,n){try{let r=n.headers.get(`PAYMENT-RESPONSE`);if(!r)return;let i=d.safeParse(Tf,Mf(r));if(!i.success||!i.output.success||!xf.test(i.output.transaction))return;let a=ro(i.output.extensions);await Sf(e,t,i.output.transaction,a)}catch{}}var Ff=class extends Error{reasons;constructor(e,t=[],n={}){super(t.length>0&&(n.appendReasonsToMessage??!0)?`${e}: ${t.join(`; `)}`:e),this.name=`X402PaymentError`,this.reasons=t}},If=class extends Ff{accountId;requiredNetworks;constructor(e,t,n=[]){super(`Account ${e} cannot fund this 402 challenge: it must be paid from a wallet account on ${t.map(jf).join(` or `)}`,n,{appendReasonsToMessage:!1}),this.name=`X402NetworkMismatchError`,this.accountId=e,this.requiredNetworks=t}},Lf=class extends Ff{payTo;network;serviceName;constructor(e,t,n,r=[]){super(`This 402 pays ${e} on ${jf(t)}, which is not a saved counterparty wallet rail; add it as a counterparty before paying`,r,{appendReasonsToMessage:!1}),this.name=`X402CounterpartyNotFoundError`,this.payTo=e,this.network=t,this.serviceName=n}},Rf=class extends Ff{intentId;expiresAt;constructor(e,t,n){super(`The payment is awaiting a human approval (intent ${e}); once an operator approves it, retry the request to complete the payment`,t),this.name=`X402ApprovalPendingError`,this.intentId=e,this.expiresAt=n}},zf=class extends Ff{receipt;constructor(e,t){super(`The payment settled (intent ${e.intentId}) but the post-payment continuation failed; retry the request with the PAYMENT-SIGNATURE header from the receipt (or getIntent("${e.intentId}") data.paymentCredential.value) instead of paying again`),this.name=`X402RetryFailedError`,this.receipt=e,this.cause=t}};async function Bf(e,t){try{return await t()}catch(t){throw new zf(e,t)}}var Vf=class extends Ff{intentId;requirements;constructor(e,t,n){super(`The payment could not be confirmed (intent ${e}); check getIntent("${e}") — completed: reuse its data.paymentCredential.value as the PAYMENT-SIGNATURE header; processing: poll until terminal; pay again only after blocked or failed`),this.name=`X402SubmitInterruptedError`,this.intentId=e,this.requirements=t,this.cause=n}};async function Hf(e,t){let n=t.paymentRequired.accepts.filter(e=>e.scheme===`exact`),r=n.filter(e=>t.maxAtomicAmount===void 0||/^\d+$/.test(e.amount)&&BigInt(e.amount)<=t.maxAtomicAmount).slice(0,5);if(r.length===0)throw new Ff(n.length>0&&t.maxAtomicAmount!==void 0?`Every requirement in the 402 challenge costs more than the caller's maximum amount`:`The 402 challenge offers no exact-scheme requirement Catena can pay`);let i=t.resource??t.paymentRequired.resource,a=[];for(let n of r){let r=await Uf(e,{accountId:t.accountId,requirements:n,resource:i,signedOffer:no(t.paymentRequired.extensions,n)}).catch(e=>{if(e instanceof ss&&e.code!==void 0&&kf.has(e.code)){a.push({error:e,requirement:n});return}throw e});if(r)return r}let o=a.filter(e=>e.error.code===Of),s=a.filter(e=>e.error.code===Df),c=a.filter(e=>e.error.code!==Of&&e.error.code!==Df),l=[...new Set([...o,...s,...c].map(e=>e.error.message))],u=o.find(e=>e.error.status===404&&wf.test(e.requirement.payTo));throw u?new Lf(u.requirement.payTo,u.requirement.network,i?.serviceName,l):s.length>0&&o.length===0?new If(t.accountId,[...new Set(s.map(e=>e.requirement.network))],l):new Ff(`No requirement in the 402 challenge is payable from this account`,l)}async function Uf(e,t){let n=await e.submitIntent({action:{type:`x402`,accountId:t.accountId,paymentRequirements:t.requirements,...t.resource!==void 0&&{resource:t.resource},...t.signedOffer!==void 0&&{signedOffer:t.signedOffer}},idempotencyKey:crypto.randomUUID()}).catch(e=>{throw e instanceof fs&&e.outcome===`unknown`?new Vf(e.intentId,t.requirements,e):e});if(n.status===`completed`){let e=Lo(n.data);if(e!==void 0)return{intentId:n.id,paymentSignature:e,requirements:t.requirements};throw new Ff(`The completed payment did not carry an x402 payment signature`)}switch(n.status){case`pending`:throw new Rf(n.id,n.reasons,n.expiresAt);case`processing`:throw new Ff(`The payment is still processing (intent ${n.id}); this client cannot resume an in-flight x402 settlement`);case`blocked`:case`failed`:throw new Ff(`Catena declined the payment`,n.reasons)}return vf(n.status)}function Wf(e,t){let n=(t.baseFetch??globalThis.fetch).bind(globalThis);return async(r,i)=>{let a=await n(r,i);if(a.status!==402)return a;let o=Nf(a);if(!o)return a;if(!yf(r,i))throw new Ff(`The request body cannot be replayed after payment; buffer the body (string, Blob, or ArrayBuffer) before using the x402 fetch wrapper`);let s=await Hf(e,{accountId:t.accountId,paymentRequired:o,...t.maxAtomicAmount!==void 0&&{maxAtomicAmount:t.maxAtomicAmount}});await Bf(s,()=>t.onPayment?.(s));let c=bf(r,i);c.set(`PAYMENT-SIGNATURE`,s.paymentSignature);let l=await Bf(s,()=>n(r,{...i,headers:c}));return Pf(e,s.intentId,l),l}}function Gf(e){if(e===`@-`)return Kf(0,`stdin`);if(e.startsWith(`@`)){let t=e.slice(1);return t===``?X(`--data @<path>: no file path given`):Kf(t,`@${t}`)}return e}function Kf(e,t){try{return T(e,`utf8`)}catch(e){return X(`--data ${t}: ${gs(e)}`)}}function qf(e){let[t,n=``]=e.split(`.`);return BigInt(`${t}${n.padEnd(6,`0`)}`)}const Jf=d.pipe(d.string(),d.check(e=>Gl.test(e.slice(0,Math.max(e.indexOf(`:`),0))),`must be "Name: Value" with a valid HTTP header name`),d.transform(e=>{let t=e.indexOf(`:`);return{name:e.slice(0,t),value:e.slice(t+1).trimStart()}}),d.check(e=>/^[\t\x20-\x7e\x80-\xff]*$/.test(e.value),`header value contains characters not allowed in an HTTP header`));function Yf(e,t){return e.some(e=>e.name.toLowerCase()===t)}function Xf(e,t){Yf(e,`content-type`)&&t!==void 0&&X(`--header "Content-Type: ..." conflicts with --content-type`)}function Zf(e,t,n){let r=[...n!==void 0&&!Yf(e,`content-type`)?[[`content-type`,t??`application/json`]]:[],...e.map(e=>[e.name,e.value])];return r.length>0?new Headers(r):void 0}const Qf={"eip155:8453":`base`,"eip155:84532":`base-sepolia`};function $f(e){return Object.hasOwn(Qf,e)?Qf[e]:void 0}function ep(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function tp(e){return e===void 0?``:` --profile ${ep(e)}`}function np(e,t){return`Payment submission could not be confirmed (intent ${e}). It may have succeeded. Before paying again, run \`catena intents get ${e}${tp(t)}\`.`}function rp(e,t,n,r){let i=$f(t)??ep(t);return`catena counterparties create wallet --name ${ep(n??`<name>`)} --address ${ep(e)} --network ${i}${tp(r)}`}function ip(e,t){try{w(e,{recursive:!0,mode:448}),x(e,448);let n=te(e,t);return w(n,{recursive:!0,mode:448}),x(n,448),n}catch{return}}const ap=4e3;function op(e){try{return k(e)}catch{return}}function sp(e,t,n){try{b(e,t)}catch{X(n)}}function cp(e){let t=ne(e),n=j(t),r=op(n);(r===void 0||!r.isDirectory())&&X(`--output ${e}: directory ${n} does not exist`);let i=op(t);return i===void 0?(sp(n,S.W_OK|S.X_OK,`--output ${e}: directory ${n} is not writable`),t):(i.isDirectory()&&X(`--output ${e}: destination is a directory`),i.isFile()||X(`--output ${e}: destination is not a regular file`),sp(t,S.W_OK,`--output ${e}: destination is not writable`),t)}const lp=/^(?:con|prn|aux|nul|com\d|lpt\d)$/i;function up(e){if(e!==void 0&&zs.test(e)&&!lp.test(e))return`${e}.body`;let t=`${Date.now()}-${g(4).toString(`hex`)}.body`;return e===void 0?`unpaid-${t}`:`paid-${t}`}function dp(e,t){let n=ip(nl(),`responses`);if(n===void 0)return;let r=te(n,up(t));try{return A(r,e,{mode:384}),r}catch{return}}function fp(e){let t=e.subarray(0,ap*4),n=t.toString(`utf8`);return{decoded:n,complete:t.length===e.length&&n.length<=ap&&ie(e)}}function pp({decoded:e,complete:t}){let n=e.slice(0,ap),r=n.charCodeAt(n.length-1);return{body:r>=55296&&r<=56319?n.slice(0,-1):n,...!t&&{bodyTruncated:!0}}}function mp(e,t){if(t.complete)return{body:t.decoded};if(e.length>268435456)return{...pp(t),error:`no writable location for the ${e.length}-byte body and it is too large to inline; only the .body preview survived`};if(ie(e)){let t=e.toString(`utf8`);if(6*t.length+2<=N.MAX_STRING_LENGTH)return{body:t};try{return JSON.stringify(t),{body:t}}catch{}}return{body:e.toString(`base64`),bodyEncoding:`base64`}}function hp(e){return e.error===void 0?e.bodyEncoding===void 0?`the full body is inlined in the result's .body field`:`the full body is inlined base64-encoded in the result's .body field`:e.error}function gp(e,t,n){let r=dp(e,t);return r===void 0?mp(e,n):{...pp(n),bodyPath:r}}function _p(e,t,n){let r=fp(e);if(n===void 0)return r.complete?{body:r.decoded}:gp(e,t,r);try{A(n,e,{mode:384})}catch(i){let a=gp(e,t,r),o=`--output ${n}: ${gs(i)}`;return`bodyPath`in a?{...a,error:`${o}; the full body was saved to ${a.bodyPath}`}:{...a,error:`${o}; ${hp(a)}`}}return{...pp(r),bodyPath:n}}function vp(e){return{intentId:e.intentId,amountAtomicUsdc:e.requirements.amount,payTo:e.requirements.payTo,network:e.requirements.network}}function yp(e){let t=e?.replaceAll(/[\p{C}\s]/gu,` `).replaceAll(/ {2,}/g,` `).trim();return t!==void 0&&t.length>0?t:void 0}function bp(e,t){Yf(e,`payment-signature`)&&X(`--header cannot set PAYMENT-SIGNATURE; the payment loop attaches it after paying`),Xf(e,t)}const xp=Q({url:Z({description:`The paywalled URL to fetch (an x402 v2 endpoint)`,required:!0,schema:d.pipe(d.string(),d.url())}),account:Z({description:`Source wallet account id the payment draws from`,required:!0,schema:Bs}),maxAmount:Z({description:`Refuse challenges above this USD amount (decimal string, e.g. 0.25). Policy limits still apply server-side.`,schema:d.pipe(d.string(),d.regex(/^\d+(\.\d{1,6})?$/))}),method:Ds({description:`HTTP method for the request`,choices:[`GET`,`POST`]}),data:Z({description:`Request body. Use @path to read a file or @- for stdin. Implies POST and a JSON content type unless overridden.`}),contentType:Z({description:`Content-Type header for the request body (default application/json when --data is set)`}),output:Z({description:`Write the full response body to this file (must be a regular file; written for any HTTP status — check .status). Without it .body is capped at 4000 characters; longer or non-UTF-8 bodies are saved to a file (path reported in .bodyPath)`}),header:Ts({description:`Request header as "Name: Value" (repeatable, like curl -H); sent on the initial request and the paid retry`,schema:Jf}),profile:Ls,json:Rs}),Sp=c({meta:{name:`x402`,description:`Fetch a URL, paying its x402 (HTTP 402) challenge via USDC`},args:xp.args,async run({args:e,rawArgs:t}){let n=xp.parse(e,t),r=n.method??(n.data===void 0?`GET`:`POST`);n.data!==void 0&&r!==`POST`&&X(`--data cannot be sent with --method ${r}; a body requires POST`),n.contentType!==void 0&&n.data===void 0&&X(`--content-type has no effect without --data`),bp(n.header,n.contentType);let i=n.output===void 0?void 0:cp(n.output),a=n.data===void 0?void 0:Gf(n.data),o=Zf(n.header,n.contentType,a);await $(n)(async e=>{let t,s=Wf(e,{accountId:n.account,...n.maxAmount!==void 0&&{maxAtomicAmount:qf(n.maxAmount)},onPayment:e=>{t=e}}),c;try{c=await s(n.url,{method:r,...a!==void 0&&{body:a},...o!==void 0&&{headers:o}})}catch(e){if(e instanceof Vf)throw Error(np(e.intentId,n.profile),{cause:e});if(e instanceof zf)return{status:null,paid:!0,retryFailed:!0,payment:vp(e.receipt),error:e.message};if(e instanceof If){let t=e.requiredNetworks.map(e=>$f(e)??e);return{status:null,paid:!1,retryFailed:!1,networkMismatch:{account:e.accountId,requiredNetworks:t,requiredNetworkIds:[...e.requiredNetworks]},error:`${e.message}. Re-run with --account set to a wallet account on ${t.join(` or `)} (your account ids are in \`catena accounts list${tp(n.profile)}\`).`}}if(e instanceof Lf){let t=yp(e.serviceName),r=t!==void 0&&t.length<=40?t:void 0,i=rp(e.payTo,e.network,r,n.profile),a=t===void 0?``:` The endpoint calls itself "${t.length>40?`${t.slice(0,40)}…`:t}" (unverified) — rename it if that is not a service you recognize.`;return{status:null,paid:!1,retryFailed:!1,counterpartyNotFound:{payTo:e.payTo,network:$f(e.network)??e.network,networkId:e.network,createCommand:i,nameIsPlaceholder:r===void 0,...t!==void 0&&{serviceName:t}},error:`${e.message}. Add it, then re-run:\n ${i}\n(counterparty creation may require approval per your policy)${a}`}}if(e instanceof Rf)return{status:null,paid:!1,retryFailed:!1,approvalPending:{intentId:e.intentId,expiresAt:e.expiresAt,reasons:[...e.reasons]},error:e.message};throw e}let l={status:c.status,paid:t!==void 0,retryFailed:!1,...t!==void 0&&{payment:vp(t)}},u;try{u=Buffer.from(await c.arrayBuffer())}catch(e){let r=t===void 0?``:`; the payment settled — re-read the PAYMENT-SIGNATURE with \`catena intents get ${t.intentId}${tp(n.profile)}\` to retry manually`;return{...l,error:`failed to read the response body: ${gs(e)}${r}`}}return{...l,..._p(u,t?.intentId,i)}},{exitCode:e=>+(`error`in e)})}}),Cp=d.object({version:d.literal(1),result:d.literal(`latest-version`),latestVersion:d.string(),checkedAt:d.pipe(d.string(),d.isoTimestamp())}),wp=d.object({version:d.literal(1),result:d.literal(`fetch-failure`),checkedAt:d.pipe(d.string(),d.isoTimestamp())}),Tp=d.variant(`result`,[Cp,wp]),Ep=d.object({"dist-tags":d.object({latest:d.string()})}),Dp=`cache`;function Op(){return te(nl(),Dp,`cli-version.json`)}function kp(e){return new URL(encodeURIComponent(e),`https://registry.npmjs.org/`).href}function Ap(e){try{let t=JSON.parse(T(e,`utf8`)),n=d.safeParse(Tp,t);return n.success?n.output:void 0}catch{return}}function jp(e){let t=Ap(e);if(!t)return;let n=Date.parse(t.checkedAt);if(!Number.isFinite(n))return;let r=Date.now()-n,i=t.result===`fetch-failure`?36e5:864e5;if(!(r<0||r>=i))return t}function Mp(e){try{return!C(e)||k(e).isFile()}catch{return!1}}function Np(e){let t=ip(nl(),Dp);if(t===void 0||!Mp(e))return!1;let n=te(t,`.cli-version-check-${g(6).toString(`hex`)}.tmp`);try{return A(n,``,{encoding:`utf8`,mode:384}),O(n,{force:!0}),!0}catch{try{O(n,{force:!0})}catch{}return!1}}function Pp(e,t){if(ip(nl(),Dp)===void 0)return!1;try{let n=`${e}.${g(6).toString(`hex`)}.tmp`;return A(n,`${JSON.stringify({version:1,...t,checkedAt:new Date().toISOString()},null,2)}\n`,{encoding:`utf8`,mode:384}),D(n,e),!0}catch{return!1}}async function Fp(e){let t=new AbortController,n=setTimeout(()=>t.abort(),750);n.unref();try{let n=await fetch(kp(e.packageName),{headers:{accept:`application/json`},signal:t.signal});if(!n.ok)return;let r=await n.json(),i=d.safeParse(Ep,r);return i.success?i.output[`dist-tags`].latest:void 0}catch{return}finally{clearTimeout(n)}}function Ip(e){let t=ae.valid(e.currentVersion),n=ae.valid(e.latestVersion);t!==null&&n!==null&&ae.gt(n,t)&&console.error(`A newer ${e.packageName} version is available: ${n} (current ${t}).`)}async function Lp({packageName:e,currentVersion:t}){let n=Op(),r=jp(n);if(r?.result===`latest-version`){Ip({packageName:e,currentVersion:t,latestVersion:r.latestVersion});return}if(r?.result===`fetch-failure`||!Np(n))return;let i=await Fp({packageName:e});if(i===void 0){Pp(n,{result:`fetch-failure`});return}Pp(n,{result:`latest-version`,latestVersion:i}),Ip({packageName:e,currentVersion:t,latestVersion:i})}async function Rp(e){return typeof e==`function`?await e():await e}async function zp(e){return typeof e==`function`?await e():await e}async function Bp(e){return typeof e==`function`?await e():await e}async function Vp(e,t,n=[]){if(e===t)return n;let r=await Bp(e.subCommands??{});return(await Promise.all(Object.entries(r).map(async([e,r])=>Vp(await Rp(r),t,[...n,e])))).find(e=>e!==void 0)}async function Hp(e,t){if(!e||!t||t.length<2)return e;let n=await zp(e.meta??{});return{...e,meta:{...n,name:t.slice(0,-1).join(` `)}}}function Up(e){return async(t,n)=>{let r=await l(t,await Hp(n,await Vp(e,t)));console.log(`${r}\n`)}}function Wp({shouldCheckCliVersionFreshness:e}){return c({meta:{name:`catena`,version:oe,description:`Catena CLI`},async setup({rawArgs:t}){e&&t.length!==0&&await Lp({packageName:P,currentVersion:oe})},subCommands:{link:Nd,unlink:hf,profiles:cf,whoami:_f,policy:Zd,accounts:_u,intents:Zu,send:uf,transfer:ff,mpp:()=>import(`./mpp-CZl4wkkp.mjs`).then(e=>e.mppCommand),x402:Sp,counterparties:Vu,feedback:Ku,guide:Ju}})}const Gp=Wp({shouldCheckCliVersionFreshness:!0});Wp({shouldCheckCliVersionFreshness:!1});function Kp(){u(Gp,{showUsage:Up(Gp)})}Kp();export{Ba as A,Q as C,gs as D,X as E,ss as O,Z as S,Ls as T,vf as _,rp as a,Ds as b,Jf as c,Gf as d,qf as f,yf as g,bf as h,Zf as i,he as j,fs as k,tp as l,Sf as m,cp as n,Yf as o,xf as p,Xf as r,$f as s,_p as t,np as u,$ as v,Rs as w,Ts as x,Bs as y};
718
+ const Ld=e(i(((e,t)=>{(function(e){var n=1e9,r={precision:20,rounding:4,toExpNeg:-7,toExpPos:21,LN10:`2.302585092994045684017991454684364207601101488628772976033327900967572609677352480235997205089598298341967784042286`},i=!0,a=`[DecimalError] `,o=a+`Invalid argument: `,s=a+`Exponent out of range: `,c=Math.floor,l=Math.pow,u=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,d,f=1e7,p=7,m=9007199254740991,h=c(m/p),g={};g.absoluteValue=g.abs=function(){var e=new this.constructor(this);return e.s&&=1,e},g.comparedTo=g.cmp=function(e){var t,n,r,i,a=this;if(e=new a.constructor(e),a.s!==e.s)return a.s||-e.s;if(a.e!==e.e)return a.e>e.e^a.s<0?1:-1;for(r=a.d.length,i=e.d.length,t=0,n=r<i?r:i;t<n;++t)if(a.d[t]!==e.d[t])return a.d[t]>e.d[t]^a.s<0?1:-1;return r===i?0:r>i^a.s<0?1:-1},g.decimalPlaces=g.dp=function(){var e=this,t=e.d.length-1,n=(t-e.e)*p;if(t=e.d[t],t)for(;t%10==0;t/=10)n--;return n<0?0:n},g.dividedBy=g.div=function(e){return b(this,new this.constructor(e))},g.dividedToIntegerBy=g.idiv=function(e){var t=this,n=t.constructor;return D(b(t,new n(e),0,1),n.precision)},g.equals=g.eq=function(e){return!this.cmp(e)},g.exponent=function(){return S(this)},g.greaterThan=g.gt=function(e){return this.cmp(e)>0},g.greaterThanOrEqualTo=g.gte=function(e){return this.cmp(e)>=0},g.isInteger=g.isint=function(){return this.e>this.d.length-2},g.isNegative=g.isneg=function(){return this.s<0},g.isPositive=g.ispos=function(){return this.s>0},g.isZero=function(){return this.s===0},g.lessThan=g.lt=function(e){return this.cmp(e)<0},g.lessThanOrEqualTo=g.lte=function(e){return this.cmp(e)<1},g.logarithm=g.log=function(e){var t,n=this,r=n.constructor,o=r.precision,s=o+5;if(e===void 0)e=new r(10);else if(e=new r(e),e.s<1||e.eq(d))throw Error(a+`NaN`);if(n.s<1)throw Error(a+(n.s?`NaN`:`-Infinity`));return n.eq(d)?new r(0):(i=!1,t=b(T(n,s),T(e,s),s),i=!0,D(t,o))},g.minus=g.sub=function(e){var t=this;return e=new t.constructor(e),t.s==e.s?O(t,e):_(t,(e.s=-e.s,e))},g.modulo=g.mod=function(e){var t,n=this,r=n.constructor,o=r.precision;if(e=new r(e),!e.s)throw Error(a+`NaN`);return n.s?(i=!1,t=b(n,e,0,1).times(e),i=!0,n.minus(t)):D(new r(n),o)},g.naturalExponential=g.exp=function(){return x(this)},g.naturalLogarithm=g.ln=function(){return T(this)},g.negated=g.neg=function(){var e=new this.constructor(this);return e.s=-e.s||0,e},g.plus=g.add=function(e){var t=this;return e=new t.constructor(e),t.s==e.s?_(t,e):O(t,(e.s=-e.s,e))},g.precision=g.sd=function(e){var t,n,r,i=this;if(e!==void 0&&e!==!!e&&e!==1&&e!==0)throw Error(o+e);if(t=S(i)+1,r=i.d.length-1,n=r*p+1,r=i.d[r],r){for(;r%10==0;r/=10)n--;for(r=i.d[0];r>=10;r/=10)n++}return e&&t>n?t:n},g.squareRoot=g.sqrt=function(){var e,t,n,r,o,s,l,u=this,d=u.constructor;if(u.s<1){if(!u.s)return new d(0);throw Error(a+`NaN`)}for(e=S(u),i=!1,o=Math.sqrt(+u),o==0||o==1/0?(t=y(u.d),(t.length+e)%2==0&&(t+=`0`),o=Math.sqrt(t),e=c((e+1)/2)-(e<0||e%2),o==1/0?t=`5e`+e:(t=o.toExponential(),t=t.slice(0,t.indexOf(`e`)+1)+e),r=new d(t)):r=new d(o.toString()),n=d.precision,o=l=n+3;;)if(s=r,r=s.plus(b(u,s,l+2)).times(.5),y(s.d).slice(0,l)===(t=y(r.d)).slice(0,l)){if(t=t.slice(l-3,l+1),o==l&&t==`4999`){if(D(s,n+1,0),s.times(s).eq(u)){r=s;break}}else if(t!=`9999`)break;l+=4}return i=!0,D(r,n)},g.times=g.mul=function(e){var t,n,r,a,o,s,c,l,u,d=this,p=d.constructor,m=d.d,h=(e=new p(e)).d;if(!d.s||!e.s)return new p(0);for(e.s*=d.s,n=d.e+e.e,l=m.length,u=h.length,l<u&&(o=m,m=h,h=o,s=l,l=u,u=s),o=[],s=l+u,r=s;r--;)o.push(0);for(r=u;--r>=0;){for(t=0,a=l+r;a>r;)c=o[a]+h[r]*m[a-r-1]+t,o[a--]=c%f|0,t=c/f|0;o[a]=(o[a]+t)%f|0}for(;!o[--s];)o.pop();return t?++n:o.shift(),e.d=o,e.e=n,i?D(e,p.precision):e},g.toDecimalPlaces=g.todp=function(e,t){var r=this,i=r.constructor;return r=new i(r),e===void 0?r:(v(e,0,n),t===void 0?t=i.rounding:v(t,0,8),D(r,e+S(r)+1,t))},g.toExponential=function(e,t){var r,i=this,a=i.constructor;return e===void 0?r=k(i,!0):(v(e,0,n),t===void 0?t=a.rounding:v(t,0,8),i=D(new a(i),e+1,t),r=k(i,!0,e+1)),r},g.toFixed=function(e,t){var r,i,a=this,o=a.constructor;return e===void 0?k(a):(v(e,0,n),t===void 0?t=o.rounding:v(t,0,8),i=D(new o(a),e+S(a)+1,t),r=k(i.abs(),!1,e+S(i)+1),a.isneg()&&!a.isZero()?`-`+r:r)},g.toInteger=g.toint=function(){var e=this,t=e.constructor;return D(new t(e),S(e)+1,t.rounding)},g.toNumber=function(){return+this},g.toPower=g.pow=function(e){var t,n,r,o,s,l,u=this,f=u.constructor,h=12,g=+(e=new f(e));if(!e.s)return new f(d);if(u=new f(u),!u.s){if(e.s<1)throw Error(a+`Infinity`);return u}if(u.eq(d))return u;if(r=f.precision,e.eq(d))return D(u,r);if(t=e.e,n=e.d.length-1,l=t>=n,s=u.s,!l){if(s<0)throw Error(a+`NaN`)}else if((n=g<0?-g:g)<=m){for(o=new f(d),t=Math.ceil(r/p+4),i=!1;n%2&&(o=o.times(u),A(o.d,t)),n=c(n/2),n!==0;)u=u.times(u),A(u.d,t);return i=!0,e.s<0?new f(d).div(o):D(o,r)}return s=s<0&&e.d[Math.max(t,n)]&1?-1:1,u.s=1,i=!1,o=e.times(T(u,r+h)),i=!0,o=x(o),o.s=s,o},g.toPrecision=function(e,t){var r,i,a=this,o=a.constructor;return e===void 0?(r=S(a),i=k(a,r<=o.toExpNeg||r>=o.toExpPos)):(v(e,1,n),t===void 0?t=o.rounding:v(t,0,8),a=D(new o(a),e,t),r=S(a),i=k(a,e<=r||r<=o.toExpNeg,e)),i},g.toSignificantDigits=g.tosd=function(e,t){var r=this,i=r.constructor;return e===void 0?(e=i.precision,t=i.rounding):(v(e,1,n),t===void 0?t=i.rounding:v(t,0,8)),D(new i(r),e,t)},g.toString=g.valueOf=g.val=g.toJSON=function(){var e=this,t=S(e),n=e.constructor;return k(e,t<=n.toExpNeg||t>=n.toExpPos)};function _(e,t){var n,r,a,o,s,c,l,u,d=e.constructor,m=d.precision;if(!e.s||!t.s)return t.s||(t=new d(e)),i?D(t,m):t;if(l=e.d,u=t.d,s=e.e,a=t.e,l=l.slice(),o=s-a,o){for(o<0?(r=l,o=-o,c=u.length):(r=u,a=s,c=l.length),s=Math.ceil(m/p),c=s>c?s+1:c+1,o>c&&(o=c,r.length=1),r.reverse();o--;)r.push(0);r.reverse()}for(c=l.length,o=u.length,c-o<0&&(o=c,r=u,u=l,l=r),n=0;o;)n=(l[--o]=l[o]+u[o]+n)/f|0,l[o]%=f;for(n&&(l.unshift(n),++a),c=l.length;l[--c]==0;)l.pop();return t.d=l,t.e=a,i?D(t,m):t}function v(e,t,n){if(e!==~~e||e<t||e>n)throw Error(o+e)}function y(e){var t,n,r,i=e.length-1,a=``,o=e[0];if(i>0){for(a+=o,t=1;t<i;t++)r=e[t]+``,n=p-r.length,n&&(a+=w(n)),a+=r;o=e[t],r=o+``,n=p-r.length,n&&(a+=w(n))}else if(o===0)return`0`;for(;o%10==0;)o/=10;return a+o}var b=(function(){function e(e,t){var n,r=0,i=e.length;for(e=e.slice();i--;)n=e[i]*t+r,e[i]=n%f|0,r=n/f|0;return r&&e.unshift(r),e}function t(e,t,n,r){var i,a;if(n!=r)a=n>r?1:-1;else for(i=a=0;i<n;i++)if(e[i]!=t[i]){a=e[i]>t[i]?1:-1;break}return a}function n(e,t,n){for(var r=0;n--;)e[n]-=r,r=+(e[n]<t[n]),e[n]=r*f+e[n]-t[n];for(;!e[0]&&e.length>1;)e.shift()}return function(r,i,o,s){var c,l,u,d,m,h,g,_,v,y,b,x,C,w,T,E,O,k,A=r.constructor,ee=r.s==i.s?1:-1,j=r.d,M=i.d;if(!r.s)return new A(r);if(!i.s)throw Error(a+`Division by zero`);for(l=r.e-i.e,O=M.length,T=j.length,g=new A(ee),_=g.d=[],u=0;M[u]==(j[u]||0);)++u;if(M[u]>(j[u]||0)&&--l,x=o==null?o=A.precision:s?o+(S(r)-S(i))+1:o,x<0)return new A(0);if(x=x/p+2|0,u=0,O==1)for(d=0,M=M[0],x++;(u<T||d)&&x--;u++)C=d*f+(j[u]||0),_[u]=C/M|0,d=C%M|0;else{for(d=f/(M[0]+1)|0,d>1&&(M=e(M,d),j=e(j,d),O=M.length,T=j.length),w=O,v=j.slice(0,O),y=v.length;y<O;)v[y++]=0;k=M.slice(),k.unshift(0),E=M[0],M[1]>=f/2&&++E;do d=0,c=t(M,v,O,y),c<0?(b=v[0],O!=y&&(b=b*f+(v[1]||0)),d=b/E|0,d>1?(d>=f&&(d=f-1),m=e(M,d),h=m.length,y=v.length,c=t(m,v,h,y),c==1&&(d--,n(m,O<h?k:M,h))):(d==0&&(c=d=1),m=M.slice()),h=m.length,h<y&&m.unshift(0),n(v,m,y),c==-1&&(y=v.length,c=t(M,v,O,y),c<1&&(d++,n(v,O<y?k:M,y))),y=v.length):c===0&&(d++,v=[0]),_[u++]=d,c&&v[0]?v[y++]=j[w]||0:(v=[j[w]],y=1);while((w++<T||v[0]!==void 0)&&x--)}return _[0]||_.shift(),g.e=l,D(g,s?o+S(g)+1:o)}})();function x(e,t){var n,r,a,o,c,u,f=0,p=0,m=e.constructor,h=m.precision;if(S(e)>16)throw Error(s+S(e));if(!e.s)return new m(d);for(t==null?(i=!1,u=h):u=t,c=new m(.03125);e.abs().gte(.1);)e=e.times(c),p+=5;for(r=Math.log(l(2,p))/Math.LN10*2+5|0,u+=r,n=a=o=new m(d),m.precision=u;;){if(a=D(a.times(e),u),n=n.times(++f),c=o.plus(b(a,n,u)),y(c.d).slice(0,u)===y(o.d).slice(0,u)){for(;p--;)o=D(o.times(o),u);return m.precision=h,t==null?(i=!0,D(o,h)):o}o=c}}function S(e){for(var t=e.e*p,n=e.d[0];n>=10;n/=10)t++;return t}function C(e,t,n){if(t>e.LN10.sd())throw i=!0,n&&(e.precision=n),Error(a+`LN10 precision limit exceeded`);return D(new e(e.LN10),t)}function w(e){for(var t=``;e--;)t+=`0`;return t}function T(e,t){var n,r,o,s,c,l,u,f,p,m=1,h=10,g=e,_=g.d,v=g.constructor,x=v.precision;if(g.s<1)throw Error(a+(g.s?`NaN`:`-Infinity`));if(g.eq(d))return new v(0);if(t==null?(i=!1,f=x):f=t,g.eq(10))return t??(i=!0),C(v,f);if(f+=h,v.precision=f,n=y(_),r=n.charAt(0),s=S(g),Math.abs(s)<0x5543df729c000){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)g=g.times(e),n=y(g.d),r=n.charAt(0),m++;s=S(g),r>1?(g=new v(`0.`+n),s++):g=new v(r+`.`+n.slice(1))}else return u=C(v,f+2,x).times(s+``),g=T(new v(r+`.`+n.slice(1)),f-h).plus(u),v.precision=x,t==null?(i=!0,D(g,x)):g;for(l=c=g=b(g.minus(d),g.plus(d),f),p=D(g.times(g),f),o=3;;){if(c=D(c.times(p),f),u=l.plus(b(c,new v(o),f)),y(u.d).slice(0,f)===y(l.d).slice(0,f))return l=l.times(2),s!==0&&(l=l.plus(C(v,f+2,x).times(s+``))),l=b(l,new v(m),f),v.precision=x,t==null?(i=!0,D(l,x)):l;l=u,o+=2}}function E(e,t){var n,r,a;for((n=t.indexOf(`.`))>-1&&(t=t.replace(`.`,``)),(r=t.search(/e/i))>0?(n<0&&(n=r),n+=+t.slice(r+1),t=t.substring(0,r)):n<0&&(n=t.length),r=0;t.charCodeAt(r)===48;)++r;for(a=t.length;t.charCodeAt(a-1)===48;)--a;if(t=t.slice(r,a),t){if(a-=r,n=n-r-1,e.e=c(n/p),e.d=[],r=(n+1)%p,n<0&&(r+=p),r<a){for(r&&e.d.push(+t.slice(0,r)),a-=p;r<a;)e.d.push(+t.slice(r,r+=p));t=t.slice(r),r=p-t.length}else r-=a;for(;r--;)t+=`0`;if(e.d.push(+t),i&&(e.e>h||e.e<-h))throw Error(s+n)}else e.s=0,e.e=0,e.d=[0];return e}function D(e,t,n){var r,a,o,u,d,m,g,_,v=e.d;for(u=1,o=v[0];o>=10;o/=10)u++;if(r=t-u,r<0)r+=p,a=t,g=v[_=0];else{if(_=Math.ceil((r+1)/p),o=v.length,_>=o)return e;for(g=o=v[_],u=1;o>=10;o/=10)u++;r%=p,a=r-p+u}if(n!==void 0&&(o=l(10,u-a-1),d=g/o%10|0,m=t<0||v[_+1]!==void 0||g%o,m=n<4?(d||m)&&(n==0||n==(e.s<0?3:2)):d>5||d==5&&(n==4||m||n==6&&(r>0?a>0?g/l(10,u-a):0:v[_-1])%10&1||n==(e.s<0?8:7))),t<1||!v[0])return m?(o=S(e),v.length=1,t=t-o-1,v[0]=l(10,(p-t%p)%p),e.e=c(-t/p)||0):(v.length=1,v[0]=e.e=e.s=0),e;if(r==0?(v.length=_,o=1,_--):(v.length=_+1,o=l(10,p-r),v[_]=a>0?(g/l(10,u-a)%l(10,a)|0)*o:0),m)for(;;)if(_==0){(v[0]+=o)==f&&(v[0]=1,++e.e);break}else{if(v[_]+=o,v[_]!=f)break;v[_--]=0,o=1}for(r=v.length;v[--r]===0;)v.pop();if(i&&(e.e>h||e.e<-h))throw Error(s+S(e));return e}function O(e,t){var n,r,a,o,s,c,l,u,d,m,h=e.constructor,g=h.precision;if(!e.s||!t.s)return t.s?t.s=-t.s:t=new h(e),i?D(t,g):t;if(l=e.d,m=t.d,r=t.e,u=e.e,l=l.slice(),s=u-r,s){for(d=s<0,d?(n=l,s=-s,c=m.length):(n=m,r=u,c=l.length),a=Math.max(Math.ceil(g/p),c)+2,s>a&&(s=a,n.length=1),n.reverse(),a=s;a--;)n.push(0);n.reverse()}else{for(a=l.length,c=m.length,d=a<c,d&&(c=a),a=0;a<c;a++)if(l[a]!=m[a]){d=l[a]<m[a];break}s=0}for(d&&(n=l,l=m,m=n,t.s=-t.s),c=l.length,a=m.length-c;a>0;--a)l[c++]=0;for(a=m.length;a>s;){if(l[--a]<m[a]){for(o=a;o&&l[--o]===0;)l[o]=f-1;--l[o],l[a]+=f}l[a]-=m[a]}for(;l[--c]===0;)l.pop();for(;l[0]===0;l.shift())--r;return l[0]?(t.d=l,t.e=r,i?D(t,g):t):new h(0)}function k(e,t,n){var r,i=S(e),a=y(e.d),o=a.length;return t?(n&&(r=n-o)>0?a=a.charAt(0)+`.`+a.slice(1)+w(r):o>1&&(a=a.charAt(0)+`.`+a.slice(1)),a=a+(i<0?`e`:`e+`)+i):i<0?(a=`0.`+w(-i-1)+a,n&&(r=n-o)>0&&(a+=w(r))):i>=o?(a+=w(i+1-o),n&&(r=n-i-1)>0&&(a=a+`.`+w(r))):((r=i+1)<o&&(a=a.slice(0,r)+`.`+a.slice(r)),n&&(r=n-o)>0&&(i+1===o&&(a+=`.`),a+=w(r))),e.s<0?`-`+a:a}function A(e,t){if(e.length>t)return e.length=t,!0}function ee(e){var t,n,r;function i(e){var t=this;if(!(t instanceof i))return new i(e);if(t.constructor=i,e instanceof i){t.s=e.s,t.e=e.e,t.d=(e=e.d)?e.slice():e;return}if(typeof e==`number`){if(e*0!=0)throw Error(o+e);if(e>0)t.s=1;else if(e<0)e=-e,t.s=-1;else{t.s=0,t.e=0,t.d=[0];return}if(e===~~e&&e<1e7){t.e=0,t.d=[e];return}return E(t,e.toString())}if(typeof e!=`string`)throw Error(o+e);if(e.charCodeAt(0)===45?(e=e.slice(1),t.s=-1):t.s=1,u.test(e))E(t,e);else throw Error(o+e)}if(i.prototype=g,i.ROUND_UP=0,i.ROUND_DOWN=1,i.ROUND_CEIL=2,i.ROUND_FLOOR=3,i.ROUND_HALF_UP=4,i.ROUND_HALF_DOWN=5,i.ROUND_HALF_EVEN=6,i.ROUND_HALF_CEIL=7,i.ROUND_HALF_FLOOR=8,i.clone=ee,i.config=i.set=j,e===void 0&&(e={}),e)for(r=[`precision`,`rounding`,`toExpNeg`,`toExpPos`,`LN10`],t=0;t<r.length;)e.hasOwnProperty(n=r[t++])||(e[n]=this[n]);return i.config(e),i}function j(e){if(!e||typeof e!=`object`)throw Error(a+`Object expected`);var t,r,i,s=[`precision`,1,n,`rounding`,0,8,`toExpNeg`,-1/0,0,`toExpPos`,0,1/0];for(t=0;t<s.length;t+=3)if((i=e[r=s[t]])!==void 0){if(c(i)===i&&i>=s[t+1]&&i<=s[t+2])this[r]=i;else throw Error(o+r+`: `+i)}if((i=e[r=`LN10`])!==void 0){if(i==Math.LN10)this[r]=new this(i);else throw Error(o+r+`: `+i)}return this}r=ee(r),r.default=r.Decimal=r,d=new r(1),typeof define==`function`&&define.amd?define(function(){return r}):t!==void 0&&t.exports?t.exports=r:(e||=typeof self<`u`&&self&&self.self==self?self:Function(`return this`)(),e.Decimal=r)})(e)}))(),1).default;Ld.set({rounding:Ld.ROUND_HALF_EVEN});const Rd=new Map,zd=/^[A-Z]{3}$/,Bd=/^[A-Z0-9]{2,6}$/;function Vd(e,t,n,r){if(Rd.has(e))throw Error(`duplicate asset id ${e}`);let i=new Ld(r);if(i.isNegative())throw Error(`dustThreshold must be a non-negative decimal`);if(i.decimalPlaces()>t)throw Error(`dustThreshold (${r}) must not be finer than the asset's ${t} decimals`);if(!Number.isInteger(t)||!Number.isInteger(n)||t<0||n<0)throw Error(`decimals and presentmentDecimals must be non-negative integers`);if(n>t)throw Error(`presentment decimals should be less than or equal to decimals`)}function Hd(e,t,n,r,i){if(!zd.test(e))throw Error(`fiat asset ids must be 3-letter ISO-4217 codes`);Vd(e,n,r,i.dustThreshold);let a=e;return Rd.set(e,{id:a,symbol:e,name:t,kind:`fiat`,decimals:n,presentmentDecimals:r,denomination:e,valuation:{type:`par`},dustThreshold:i.dustThreshold}),a}function Ud(e,t,n,r,i){if(!Bd.test(e)||zd.test(e))throw Error(`stablecoin tickers must be 2-6 uppercase alphanumerics and not a 3-letter ISO-4217 shape`);let a=Rd.get(i.denomination);if(!a||a.kind!==`fiat`)throw Error(`stablecoin denomination must be a registered fiat asset, got ${i.denomination}`);if(n>a.decimals)throw Error(`par stablecoin decimals (${n}) must not exceed its denomination fiat's (${a.decimals})`);Vd(e,n,r,i.dustThreshold);let o=e;return Rd.set(e,{id:o,symbol:e,name:t,kind:`stablecoin`,decimals:n,presentmentDecimals:r,denomination:a.denomination,valuation:{type:`par`},dustThreshold:i.dustThreshold}),o}Ud(`USDC`,`USD Coin`,6,2,{denomination:Hd(`USD`,`US Dollar`,6,2,{dustThreshold:`0.01`}),dustThreshold:`0.01`}),new Ld(1e6),new Ld(1e3);const Wd=d.pipe(d.string(`Amount must be a string`),d.nonEmpty(`Amount must not be empty`),d.check(e=>e.trim()===e,`Amount must not have leading or trailing whitespace`),d.check(e=>!e.includes(`e`)&&!e.includes(`E`),`Scientific notation is not supported (e.g. use 1000000 instead of 1e6)`),d.check(e=>!e.startsWith(`+`),`Amount must not have a '+' prefix`),d.check(e=>!e.startsWith(`-`),`Amount must be non-negative`),d.check(e=>{try{return new Ld(e).gte(0)}catch{return!1}},`Amount must be a valid decimal (e.g. 100 or 100.50)`)),Gd=d.pipe(d.string(`Count must be a string`),d.transform(e=>e.trim()),d.check(e=>/^\d+$/.test(e),`Count must be a whole number of transactions (e.g. 20)`),d.transform(Number),d.check(e=>Number.isSafeInteger(e),`Count is too large`),d.check(e=>e>=1,`Count must be at least 1`)),Kd={s:1,m:60,h:3600,d:86400},qd=d.pipe(d.string(`Duration must be a string`),d.transform(e=>e.trim()),d.check(e=>/^\d+[smhd]?$/.test(e),`Duration must be a number of seconds or a value with a unit (e.g. 90s, 30m, 4h, 2d)`),d.transform(e=>{let t=e.at(-1)??``;return t in Kd?Number(e.slice(0,-1))*Kd[t]:Number(e)}),d.check(e=>e>=60,`Duration must be at least 1 minute`),d.check(e=>e<=604800,`Duration must be at most 7 days`)),Jd=Q({profile:Rs,json:zs}),Yd=c({meta:{name:`show`,description:`Show the agent's assigned policy`},args:Jd.args,async run({args:e}){await $(Jd.parse(e))(e=>e.getPolicy())}}),Xd=Q({account:Z({description:`Account whose existing hard limit should increase. For a transfer limit, the source account funds move out of.`,required:!0}),capability:Os({description:`Which capability's limit to increase: send (payments to counterparties) or transfer (between the user's own accounts)`,choices:es,default:`send`}),rule:Os({description:`Which limit to adjust`,choices:fo,default:`per_transaction_amount`}),amount:Z({description:`New threshold for an amount limit, as a decimal USD string (e.g. 500.00)`,schema:Wd,showValueInError:!0}),count:Z({description:`New threshold for a transaction-count limit (e.g. 20)`,schema:Gd,showValueInError:!0}),duration:Z({description:`How long the override should last once approved (e.g. 90s, 30m, 4h, 2d). One minute to seven days.`,required:!0,schema:qd,showValueInError:!0}),reason:Z({description:`Why the task needs this, for the person who reviews the request`,required:!0}),idempotencyKey:Z({description:`Optional operation key. Reuse the same value only when retrying the same submission; omitted generates a fresh key for this invocation.`,schema:yu}),profile:Rs,json:zs}),Zd=c({meta:{name:`request-override`,description:`Ask a person to approve a temporary change to this agent's limits`},args:Xd.args,async run({args:e}){let t=Xd.parse(e),n=$(t),r={type:`policy_override`,operations:[Qd(t)],durationSeconds:t.duration,reason:t.reason};await n(e=>e.submitIntent({action:r,...t.idempotencyKey!==void 0&&{idempotencyKey:t.idempotencyKey}}))}});function Qd(e){return e.rule===`hourly_count`||e.rule===`daily_count`?(e.amount!==void 0&&X(`--amount does not apply to ${e.rule}; use --count`),e.count===void 0&&X(`--count is required for ${e.rule}`),{type:`increase_limit`,accountId:e.account,capability:e.capability,limitType:e.rule,newLimit:{count:e.count}}):(e.count!==void 0&&X(`--count does not apply to ${e.rule}; use --amount`),e.amount===void 0&&X(`--amount is required for ${e.rule}`),{type:`increase_limit`,accountId:e.account,capability:e.capability,limitType:e.rule,newLimit:{amount:e.amount,assetId:`USD`}})}const $d=c({meta:{name:`policy`,description:`Inspect the agent's policy`},subCommands:{show:Yd,"request-override":Zd}}),ef=Q({profile:Ts({description:`Profile name`,required:!0})});function tf(){try{return Hl({env:process.env[Rl],cwd:process.cwd(),log:e=>console.error(e)})}catch(e){return X(e)}}const nf=c({meta:{name:`use`,description:`Set the default credential profile`},args:ef.args,async run({args:e}){let t=ef.parse(e);try{Dl(t.profile),ru({defaultProfile:t.profile})}catch(e){X(e)}}}),rf=c({meta:{name:`current`,description:`Show the selected credential profile and how it was chosen`},async run(){let e;try{e=Ll()}catch(e){return X(e)}if(e!==null){ru({source:`secret-key`,credential:Pl,apiUrl:e.apiUrl});return}let t=tf(),n;try{n=Sl(t.name)}catch(e){X(e)}n===null&&X(`Profile "${t.name}" is not linked.\nRun 'catena link --profile ${t.name} <agent-id>' to authenticate.`),ru({profile:t.name,source:t.source,apiUrl:n.api_url,agentId:pl(n)?n.agent_id:void 0})}}),af=c({meta:{name:`list`,description:`List credential profiles and their directory bindings`},async run(){let e;try{e=ll()}catch(e){X(e)}let t=Il(),n;try{n=t?null:Hl({env:process.env[Rl],cwd:process.cwd()}).name}catch{n=null}let r=Object.entries(e.directories??{});ru({defaultProfile:e.default_profile,...t?{shadowedBy:Pl}:{},profiles:Object.entries(e.profiles).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>({name:e,apiUrl:t.api_url,agentId:pl(t)?t.agent_id:void 0,directories:r.filter(([,t])=>t===e).map(([e])=>e).toSorted(),current:e===n}))})}}),of=Q({profile:Ts({description:`Profile name to bind`,required:!0}),path:Ts({description:`Directory to bind (defaults to the current directory)`})}),sf=c({meta:{name:`bind`,description:`Bind a directory to a profile for automatic selection`},args:of.args,async run({args:e}){let t=of.parse(e);try{let e=t.path??process.cwd();if(ed(e))throw Error(`Refusing to bind the home directory or an ancestor of it — that would shadow the default profile for every directory beneath it. Bind a specific agent directory instead.`);let n=bl(e,t.profile);ru({profile:t.profile,directory:n})}catch(e){X(e)}}}),cf=Q({path:Ts({description:`Directory to unbind (defaults to the current directory)`})}),lf=c({meta:{name:`unbind`,description:`Remove a directory's profile binding`},args:cf.args,async run({args:e}){let t=cf.parse(e);try{ru(xl(t.path??process.cwd()))}catch(e){X(e)}}}),uf=c({meta:{name:`profiles`,description:`Manage credential profiles`},subCommands:{use:nf,current:rf,list:af,bind:sf,unbind:lf}}),df=Q({account:Z({description:`Source account id; omit when the policy allows sends from exactly one account`,schema:Vs}),rail:Z({description:`Destination counterparty rail id (cprl_...)`,required:!0,schema:Vs}),amount:Z({description:`USD amount as a decimal string (e.g. 125.00)`,required:!0,schema:Wd,showValueInError:!0}),method:Os({description:`ach | wire | on-chain; ach and wire require a bank rail, on-chain a wallet rail`,required:!0,choices:Eo}),memo:Z({description:`Memo on the underlying transfer`}),description:Z({description:`Operator-facing description`}),idempotencyKey:Z({description:`Optional operation key. Reuse the same value only when retrying the same submission; omitted generates a fresh key for this invocation.`,schema:yu}),profile:Rs,json:zs}),ff=c({meta:{name:`send`,description:`Submit a USD send intent to a counterparty rail`},args:df.args,async run({args:e}){let t=df.parse(e),n=$(t),r={type:`send`,...t.account!==void 0&&{accountId:t.account},counterpartyRailId:t.rail,amount:t.amount,method:t.method,...t.memo?{memo:t.memo}:{},...t.description?{description:t.description}:{}};await n(e=>e.submitIntent({action:r,...t.idempotencyKey?{idempotencyKey:t.idempotencyKey}:{}}))}}),pf=Q({from:Z({description:`Source account id`,required:!0,schema:Vs}),to:Z({description:`Destination account id`,required:!0,schema:Vs}),amount:Z({description:`USD amount as a decimal string (e.g. 125.00)`,required:!0,schema:Wd,showValueInError:!0}),memo:Z({description:`Memo on the underlying transfer`}),description:Z({description:`Operator-facing description`}),idempotencyKey:Z({description:`Optional operation key. Reuse the same value only when retrying the same submission; omitted generates a fresh key for this invocation.`,schema:yu}),profile:Rs,json:zs}),mf=c({meta:{name:`transfer`,description:`Submit a USD transfer intent between two of this agent's accounts`},args:pf.args,async run({args:e}){let t=pf.parse(e),n=$(t),r={type:`transfer`,accountId:t.from,toAccountId:t.to,amount:t.amount,...t.memo?{memo:t.memo}:{},...t.description?{description:t.description}:{}};await n(e=>e.submitIntent({action:r,...t.idempotencyKey?{idempotencyKey:t.idempotencyKey}:{}}))}});function hf(){return`${Pl} is set, and this command removes only a linked profile. Revoke the key in the Catena console under the agent's Secret keys tab, or pass --profile <name> to target a profile on this machine.`}const gf=Q({profile:Rs,force:Ds({description:`Remove the profile and its local credentials without contacting the server; use when the credential is missing, revoked, or a link was interrupted`,default:!1}),json:zs}),_f=c({meta:{name:`unlink`,description:`Disconnect the selected agent profile`},args:gf.args,async run({args:e}){let t=gf.parse(e),n=Zl();!t.force&&iu(t)===void 0&&Il()&&X(hf());let r;try{r=Hl({flag:iu(t),env:process.env[Rl],cwd:process.cwd(),log:e=>console.error(e)}).name}catch(e){X(e)}if(t.force){let e;try{if(e=Sl(r),e===null)throw Error(Il()?`Profile "${r}" not found, and this machine holds no profile to clear. Revoke the key in the Catena console under the agent's Secret keys tab.`:`Profile "${r}" not found`);await n.delete(e.client_instance_id),await n.delete(fd(e.client_instance_id)),_l(r)}catch(e){X(e)}ru({success:!0,profile:r,...pl(e)?{agentId:e.agent_id}:{},local:!0},{compact:t.json});return}let i=`To remove only this machine's copy, run 'catena unlink --profile ${r} --force'.`,a=await Ml({profileName:r,fallbackApiUrl:Nl},n);a.ok||X(`${a.message} ${i}`);let o=Xl(a);try{await o.unlinkAgent(),await n.delete(a.clientInstanceId),await n.delete(fd(a.clientInstanceId)),_l(r)}catch(e){X(`${_s(nu(e,r))} ${i}`)}ru({success:!0,profile:r,agentId:a.agentId},{compact:t.json})}}),vf=Q({profile:Rs,json:zs}),yf=c({meta:{name:`whoami`,description:`Show which agent you are currently acting as`},args:vf.args,async run({args:e}){await $(vf.parse(e))(e=>e.whoami())}});function bf(e){throw Error(`Unhandled case: ${String(e)}`)}const xf=d.object({requiredRail:Ao});function Sf(e,t){let n=d.safeParse(xf,e);if(n.success&&n.output.requiredRail.walletAddress.toLowerCase()===t.toLowerCase())return n.output.requiredRail}function Cf(e,t){return t?.body!==void 0&&t.body!==null&&typeof t.body!=`string`&&!(t.body instanceof URLSearchParams)&&!(t.body instanceof Blob)&&!(t.body instanceof ArrayBuffer)&&!ArrayBuffer.isView(t.body)?!1:typeof Request<`u`&&e instanceof Request?e.body===null&&!e.bodyUsed:!0}function wf(e,t){let n=new Headers(typeof Request<`u`&&e instanceof Request?e.headers:void 0);return new Headers(t?.headers).forEach((e,t)=>{n.set(t,e)}),n}const Tf=/^0x[0-9a-fA-F]{64}$/;async function Ef(e,t,n,r){try{await e.reportSettlement({intentId:t,txHash:n,...r!==void 0&&{receipt:r}})}catch{return}}const Df=[`PAYMENT-REQUIRED`,`X-Payment-Required`],Of=/^0x[0-9a-fA-F]{40}$/,kf=d.looseObject({success:d.boolean(),transaction:d.string(),extensions:d.optional(d.unknown())}),Af=d.looseObject({x402Version:d.literal(2),accepts:d.array(Go),resource:d.optional(Ko),extensions:d.optional(d.unknown())}),jf=`x402_network_mismatch`,Mf=`x402_counterparty_rail_not_found`,Nf=new Set([`x402_requirement_not_payable`,jf,Mf]),Pf={"eip155:8453":`Base`,"eip155:84532":`Base Sepolia`};function Ff(e){let t=Object.hasOwn(Pf,e)?Pf[e]:void 0;return t?`${t} (${e})`:e}function If(e){let t=e.replaceAll(`-`,`+`).replaceAll(`_`,`/`),n=Uint8Array.from(atob(t),e=>e.charCodeAt(0));return JSON.parse(new TextDecoder().decode(n))}function Lf(e){let t=Df.map(t=>e.headers.get(t)).find(e=>e!==null);if(t)try{let e=d.safeParse(Af,If(t));return e.success?e.output:void 0}catch{return}}async function Rf(e,t,n){try{let r=n.headers.get(`PAYMENT-RESPONSE`);if(!r)return;let i=d.safeParse(kf,If(r));if(!i.success||!i.output.success||!Tf.test(i.output.transaction))return;let a=ro(i.output.extensions);await Ef(e,t,i.output.transaction,a)}catch{}}var zf=class extends Error{reasons;constructor(e,t=[],n={}){super(t.length>0&&(n.appendReasonsToMessage??!0)?`${e}: ${t.join(`; `)}`:e),this.name=`X402PaymentError`,this.reasons=t}},Bf=class extends zf{accountId;requiredNetworks;constructor(e,t,n=[]){super(`Account ${e} cannot fund this 402 challenge: it must be paid from a wallet account on ${t.map(Ff).join(` or `)}`,n,{appendReasonsToMessage:!1}),this.name=`X402NetworkMismatchError`,this.accountId=e,this.requiredNetworks=t}},Vf=class extends zf{payTo;network;requiredRail;serviceName;constructor(e,t,n,r=[],i){super(`This 402 pays ${e} on ${Ff(t)}, which is not a saved counterparty wallet rail; add it as a counterparty before paying`,r,{appendReasonsToMessage:!1}),this.name=`X402CounterpartyNotFoundError`,this.payTo=e,this.network=t,this.serviceName=n,this.requiredRail=i}},Hf=class extends zf{intentId;expiresAt;constructor(e,t,n){super(`The payment is awaiting a human approval (intent ${e}); once an operator approves it, retry the request to complete the payment`,t),this.name=`X402ApprovalPendingError`,this.intentId=e,this.expiresAt=n}},Uf=class extends zf{receipt;constructor(e,t){super(`The payment settled (intent ${e.intentId}) but the post-payment continuation failed; retry the request with the PAYMENT-SIGNATURE header from the receipt (or getIntent("${e.intentId}") data.paymentCredential.value) instead of paying again`),this.name=`X402RetryFailedError`,this.receipt=e,this.cause=t}};async function Wf(e,t){try{return await t()}catch(t){throw new Uf(e,t)}}var Gf=class extends zf{intentId;requirements;constructor(e,t,n){super(`The payment could not be confirmed (intent ${e}); check getIntent("${e}") — completed: reuse its data.paymentCredential.value as the PAYMENT-SIGNATURE header; processing: poll until terminal; pay again only after blocked or failed`),this.name=`X402SubmitInterruptedError`,this.intentId=e,this.requirements=t,this.cause=n}};async function Kf(e,t){let n=t.paymentRequired.accepts.filter(e=>e.scheme===`exact`),r=n.filter(e=>t.maxAtomicAmount===void 0||/^\d+$/.test(e.amount)&&BigInt(e.amount)<=t.maxAtomicAmount).slice(0,5);if(r.length===0)throw new zf(n.length>0&&t.maxAtomicAmount!==void 0?`Every requirement in the 402 challenge costs more than the caller's maximum amount`:`The 402 challenge offers no exact-scheme requirement Catena can pay`);let i=t.resource??t.paymentRequired.resource,a=[];for(let n of r){let r=await qf(e,{accountId:t.accountId,requirements:n,resource:i,signedOffer:no(t.paymentRequired.extensions,n)}).catch(e=>{if(e instanceof cs&&e.code!==void 0&&Nf.has(e.code)){a.push({error:e,requirement:n});return}throw e});if(r)return r}let o=a.filter(e=>e.error.code===Mf),s=a.filter(e=>e.error.code===jf),c=a.filter(e=>e.error.code!==Mf&&e.error.code!==jf),l=[...new Set([...o,...s,...c].map(e=>e.error.message))],u=o.find(e=>e.error.status===404&&Of.test(e.requirement.payTo));throw u?new Vf(u.requirement.payTo,u.requirement.network,i?.serviceName,l,Sf(u.error.details,u.requirement.payTo)):s.length>0&&o.length===0?new Bf(t.accountId,[...new Set(s.map(e=>e.requirement.network))],l):new zf(`No requirement in the 402 challenge is payable from this account`,l)}async function qf(e,t){let n=await e.submitIntent({action:{type:`x402`,accountId:t.accountId,paymentRequirements:t.requirements,...t.resource!==void 0&&{resource:t.resource},...t.signedOffer!==void 0&&{signedOffer:t.signedOffer}},idempotencyKey:crypto.randomUUID()}).catch(e=>{throw e instanceof ps&&e.outcome===`unknown`?new Gf(e.intentId,t.requirements,e):e});if(n.status===`completed`){let e=Ro(n.data);if(e!==void 0)return{intentId:n.id,paymentSignature:e,requirements:t.requirements};throw new zf(`The completed payment did not carry an x402 payment signature`)}switch(n.status){case`pending`:throw new Hf(n.id,n.reasons,n.expiresAt);case`processing`:throw new zf(`The payment is still processing (intent ${n.id}); this client cannot resume an in-flight x402 settlement`);case`blocked`:case`failed`:throw new zf(`Catena declined the payment`,n.reasons)}return bf(n.status)}function Jf(e,t){let n=(t.baseFetch??globalThis.fetch).bind(globalThis);return async(r,i)=>{let a=await n(r,i);if(a.status!==402)return a;let o=Lf(a);if(!o)return a;if(!Cf(r,i))throw new zf(`The request body cannot be replayed after payment; buffer the body (string, Blob, or ArrayBuffer) before using the x402 fetch wrapper`);let s=await Kf(e,{accountId:t.accountId,paymentRequired:o,...t.maxAtomicAmount!==void 0&&{maxAtomicAmount:t.maxAtomicAmount}});await Wf(s,()=>t.onPayment?.(s));let c=wf(r,i);c.set(`PAYMENT-SIGNATURE`,s.paymentSignature);let l=await Wf(s,()=>n(r,{...i,headers:c}));return Rf(e,s.intentId,l),l}}function Yf(e){if(e===`@-`)return Xf(0,`stdin`);if(e.startsWith(`@`)){let t=e.slice(1);return t===``?X(`--data @<path>: no file path given`):Xf(t,`@${t}`)}return e}function Xf(e,t){try{return T(e,`utf8`)}catch(e){return X(`--data ${t}: ${_s(e)}`)}}function Zf(e){let[t,n=``]=e.split(`.`);return BigInt(`${t}${n.padEnd(6,`0`)}`)}const Qf=d.pipe(d.string(),d.check(e=>Kl.test(e.slice(0,Math.max(e.indexOf(`:`),0))),`must be "Name: Value" with a valid HTTP header name`),d.transform(e=>{let t=e.indexOf(`:`);return{name:e.slice(0,t),value:e.slice(t+1).trimStart()}}),d.check(e=>/^[\t\x20-\x7e\x80-\xff]*$/.test(e.value),`header value contains characters not allowed in an HTTP header`));function $f(e,t){return e.some(e=>e.name.toLowerCase()===t)}function ep(e,t){$f(e,`content-type`)&&t!==void 0&&X(`--header "Content-Type: ..." conflicts with --content-type`)}function tp(e,t,n){let r=[...n!==void 0&&!$f(e,`content-type`)?[[`content-type`,t??`application/json`]]:[],...e.map(e=>[e.name,e.value])];return r.length>0?new Headers(r):void 0}const np={"eip155:8453":`base`,"eip155:84532":`base-sepolia`};function rp(e){return Object.hasOwn(np,e)?np[e]:void 0}function ip(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function ap(e){return e===void 0?``:` --profile ${ip(e)}`}function op(e,t){return`Payment submission could not be confirmed (intent ${e}). It may have succeeded. Before paying again, run \`catena intents get ${e}${ap(t)}\`.`}function sp(e,t,n,r){let i=/^[a-z0-9][a-z0-9-]*$/.test(t)?t:ip(t);return`catena counterparties create wallet --name ${ip(n??`<name>`)} --address ${ip(e)} --network ${i}${ap(r)}`}function cp(e,t){try{w(e,{recursive:!0,mode:448}),x(e,448);let n=te(e,t);return w(n,{recursive:!0,mode:448}),x(n,448),n}catch{return}}const lp=4e3;function up(e){try{return k(e)}catch{return}}function dp(e,t,n){try{b(e,t)}catch{X(n)}}function fp(e){let t=ne(e),n=j(t),r=up(n);(r===void 0||!r.isDirectory())&&X(`--output ${e}: directory ${n} does not exist`);let i=up(t);return i===void 0?(dp(n,S.W_OK|S.X_OK,`--output ${e}: directory ${n} is not writable`),t):(i.isDirectory()&&X(`--output ${e}: destination is a directory`),i.isFile()||X(`--output ${e}: destination is not a regular file`),dp(t,S.W_OK,`--output ${e}: destination is not writable`),t)}const pp=/^(?:con|prn|aux|nul|com\d|lpt\d)$/i;function mp(e){if(e!==void 0&&Bs.test(e)&&!pp.test(e))return`${e}.body`;let t=`${Date.now()}-${g(4).toString(`hex`)}.body`;return e===void 0?`unpaid-${t}`:`paid-${t}`}function hp(e,t){let n=cp(rl(),`responses`);if(n===void 0)return;let r=te(n,mp(t));try{return A(r,e,{mode:384}),r}catch{return}}function gp(e){let t=e.subarray(0,lp*4),n=t.toString(`utf8`);return{decoded:n,complete:t.length===e.length&&n.length<=lp&&ie(e)}}function _p({decoded:e,complete:t}){let n=e.slice(0,lp),r=n.charCodeAt(n.length-1);return{body:r>=55296&&r<=56319?n.slice(0,-1):n,...!t&&{bodyTruncated:!0}}}function vp(e,t){if(t.complete)return{body:t.decoded};if(e.length>268435456)return{..._p(t),error:`no writable location for the ${e.length}-byte body and it is too large to inline; only the .body preview survived`};if(ie(e)){let t=e.toString(`utf8`);if(6*t.length+2<=N.MAX_STRING_LENGTH)return{body:t};try{return JSON.stringify(t),{body:t}}catch{}}return{body:e.toString(`base64`),bodyEncoding:`base64`}}function yp(e){return e.error===void 0?e.bodyEncoding===void 0?`the full body is inlined in the result's .body field`:`the full body is inlined base64-encoded in the result's .body field`:e.error}function bp(e,t,n){let r=hp(e,t);return r===void 0?vp(e,n):{..._p(n),bodyPath:r}}function xp(e,t,n){let r=gp(e);if(n===void 0)return r.complete?{body:r.decoded}:bp(e,t,r);try{A(n,e,{mode:384})}catch(i){let a=bp(e,t,r),o=`--output ${n}: ${_s(i)}`;return`bodyPath`in a?{...a,error:`${o}; the full body was saved to ${a.bodyPath}`}:{...a,error:`${o}; ${yp(a)}`}}return{..._p(r),bodyPath:n}}function Sp(e){return{intentId:e.intentId,amountAtomicUsdc:e.requirements.amount,payTo:e.requirements.payTo,network:e.requirements.network}}function Cp(e){let t=e?.replaceAll(/[\p{C}\s]/gu,` `).replaceAll(/ {2,}/g,` `).trim();return t!==void 0&&t.length>0?t:void 0}function wp(e,t){$f(e,`payment-signature`)&&X(`--header cannot set PAYMENT-SIGNATURE; the payment loop attaches it after paying`),ep(e,t)}const Tp=Q({url:Z({description:`The paywalled URL to fetch (an x402 v2 endpoint)`,required:!0,schema:d.pipe(d.string(),d.url())}),account:Z({description:`Source wallet account id the payment draws from`,required:!0,schema:Vs}),maxAmount:Z({description:`Refuse challenges above this USD amount (decimal string, e.g. 0.25). Policy limits still apply server-side.`,schema:d.pipe(d.string(),d.regex(/^\d+(\.\d{1,6})?$/))}),method:Os({description:`HTTP method for the request`,choices:[`GET`,`POST`]}),data:Z({description:`Request body. Use @path to read a file or @- for stdin. Implies POST and a JSON content type unless overridden.`}),contentType:Z({description:`Content-Type header for the request body (default application/json when --data is set)`}),output:Z({description:`Write the full response body to this file (must be a regular file; written for any HTTP status — check .status). Without it .body is capped at 4000 characters; longer or non-UTF-8 bodies are saved to a file (path reported in .bodyPath)`}),header:Es({description:`Request header as "Name: Value" (repeatable, like curl -H); sent on the initial request and the paid retry`,schema:Qf}),profile:Rs,json:zs}),Ep=c({meta:{name:`x402`,description:`Fetch a URL, paying its x402 (HTTP 402) challenge via USDC`},args:Tp.args,async run({args:e,rawArgs:t}){let n=Tp.parse(e,t),r=n.method??(n.data===void 0?`GET`:`POST`);n.data!==void 0&&r!==`POST`&&X(`--data cannot be sent with --method ${r}; a body requires POST`),n.contentType!==void 0&&n.data===void 0&&X(`--content-type has no effect without --data`),wp(n.header,n.contentType);let i=n.output===void 0?void 0:fp(n.output),a=n.data===void 0?void 0:Yf(n.data),o=tp(n.header,n.contentType,a);await $(n)(async e=>{let t,s=Jf(e,{accountId:n.account,...n.maxAmount!==void 0&&{maxAtomicAmount:Zf(n.maxAmount)},onPayment:e=>{t=e}}),c;try{c=await s(n.url,{method:r,...a!==void 0&&{body:a},...o!==void 0&&{headers:o}})}catch(e){if(e instanceof Gf)throw Error(op(e.intentId,n.profile),{cause:e});if(e instanceof Uf)return{status:null,paid:!0,retryFailed:!0,payment:Sp(e.receipt),error:e.message};if(e instanceof Bf){let t=e.requiredNetworks.map(e=>rp(e)??e);return{status:null,paid:!1,retryFailed:!1,networkMismatch:{account:e.accountId,requiredNetworks:t,requiredNetworkIds:[...e.requiredNetworks]},error:`${e.message}. Re-run with --account set to a wallet account on ${t.join(` or `)} (your account ids are in \`catena accounts list${ap(n.profile)}\`).`}}if(e instanceof Vf){let t=Cp(e.serviceName),r=e.requiredRail?.network??rp(e.network)??e.network,i=t!==void 0&&t.length<=40?t:void 0,a=sp(e.payTo,r,i,n.profile),o=t===void 0?``:` The endpoint calls itself "${t.length>40?`${t.slice(0,40)}…`:t}" (unverified) — rename it if that is not a service you recognize.`;return{status:null,paid:!1,retryFailed:!1,counterpartyNotFound:{payTo:e.payTo,network:r,networkId:e.network,...e.requiredRail!==void 0&&{requiredRail:e.requiredRail},createCommand:a,nameIsPlaceholder:i===void 0,...t!==void 0&&{serviceName:t}},error:`${e.message}. Add it, then re-run:\n ${a}\n(counterparty creation may require approval per your policy)${o}`}}if(e instanceof Hf)return{status:null,paid:!1,retryFailed:!1,approvalPending:{intentId:e.intentId,expiresAt:e.expiresAt,reasons:[...e.reasons]},error:e.message};throw e}let l={status:c.status,paid:t!==void 0,retryFailed:!1,...t!==void 0&&{payment:Sp(t)}},u;try{u=Buffer.from(await c.arrayBuffer())}catch(e){let r=t===void 0?``:`; the payment settled — re-read the PAYMENT-SIGNATURE with \`catena intents get ${t.intentId}${ap(n.profile)}\` to retry manually`;return{...l,error:`failed to read the response body: ${_s(e)}${r}`}}return{...l,...xp(u,t?.intentId,i)}},{exitCode:e=>+(`error`in e)})}}),Dp=d.object({version:d.literal(1),result:d.literal(`latest-version`),latestVersion:d.string(),checkedAt:d.pipe(d.string(),d.isoTimestamp())}),Op=d.object({version:d.literal(1),result:d.literal(`fetch-failure`),checkedAt:d.pipe(d.string(),d.isoTimestamp())}),kp=d.variant(`result`,[Dp,Op]),Ap=d.object({"dist-tags":d.object({latest:d.string()})}),jp=`cache`;function Mp(){return te(rl(),jp,`cli-version.json`)}function Np(e){return new URL(encodeURIComponent(e),`https://registry.npmjs.org/`).href}function Pp(e){try{let t=JSON.parse(T(e,`utf8`)),n=d.safeParse(kp,t);return n.success?n.output:void 0}catch{return}}function Fp(e){let t=Pp(e);if(!t)return;let n=Date.parse(t.checkedAt);if(!Number.isFinite(n))return;let r=Date.now()-n,i=t.result===`fetch-failure`?36e5:864e5;if(!(r<0||r>=i))return t}function Ip(e){try{return!C(e)||k(e).isFile()}catch{return!1}}function Lp(e){let t=cp(rl(),jp);if(t===void 0||!Ip(e))return!1;let n=te(t,`.cli-version-check-${g(6).toString(`hex`)}.tmp`);try{return A(n,``,{encoding:`utf8`,mode:384}),O(n,{force:!0}),!0}catch{try{O(n,{force:!0})}catch{}return!1}}function Rp(e,t){if(cp(rl(),jp)===void 0)return!1;try{let n=`${e}.${g(6).toString(`hex`)}.tmp`;return A(n,`${JSON.stringify({version:1,...t,checkedAt:new Date().toISOString()},null,2)}\n`,{encoding:`utf8`,mode:384}),D(n,e),!0}catch{return!1}}async function zp(e){let t=new AbortController,n=setTimeout(()=>t.abort(),750);n.unref();try{let n=await fetch(Np(e.packageName),{headers:{accept:`application/json`},signal:t.signal});if(!n.ok)return;let r=await n.json(),i=d.safeParse(Ap,r);return i.success?i.output[`dist-tags`].latest:void 0}catch{return}finally{clearTimeout(n)}}function Bp(e){let t=ae.valid(e.currentVersion),n=ae.valid(e.latestVersion);t!==null&&n!==null&&ae.gt(n,t)&&console.error(`A newer ${e.packageName} version is available: ${n} (current ${t}).`)}async function Vp({packageName:e,currentVersion:t}){let n=Mp(),r=Fp(n);if(r?.result===`latest-version`){Bp({packageName:e,currentVersion:t,latestVersion:r.latestVersion});return}if(r?.result===`fetch-failure`||!Lp(n))return;let i=await zp({packageName:e});if(i===void 0){Rp(n,{result:`fetch-failure`});return}Rp(n,{result:`latest-version`,latestVersion:i}),Bp({packageName:e,currentVersion:t,latestVersion:i})}const Hp=[{command:`link`,from:`--bank-url`,to:`--api-url`},{command:`link`,from:`--bankUrl`,to:`--api-url`}];function Up(e){return e.find(e=>!e.startsWith(`-`))??null}function Wp(e,t){let n=Hp.find(({command:n,from:r})=>n===t&&(e===r||e.startsWith(`${r}=`)));return n===void 0?null:{to:n.to+e.slice(n.from.length),notice:`${n.from} is deprecated; use ${n.to}`}}function Gp(e){let t=e.indexOf(`--`),n=t===-1?e.length:t,r=e.slice(0,n),i=Up(r),a=r.map(e=>({token:e,rename:Wp(e,i)}));return{rawArgs:[...a.map(({token:e,rename:t})=>t?.to??e),...e.slice(n)],notices:a.flatMap(({rename:e})=>e===null?[]:[e.notice])}}async function Kp(e){return typeof e==`function`?await e():await e}async function qp(e){return typeof e==`function`?await e():await e}async function Jp(e){return typeof e==`function`?await e():await e}async function Yp(e,t,n=[]){if(e===t)return n;let r=await Jp(e.subCommands??{});return(await Promise.all(Object.entries(r).map(async([e,r])=>Yp(await Kp(r),t,[...n,e])))).find(e=>e!==void 0)}async function Xp(e,t){if(!e||!t||t.length<2)return e;let n=await qp(e.meta??{});return{...e,meta:{...n,name:t.slice(0,-1).join(` `)}}}function Zp(e){return async(t,n)=>{let r=await l(t,await Xp(n,await Yp(e,t)));console.log(`${r}\n`)}}function Qp({shouldCheckCliVersionFreshness:e}){return c({meta:{name:`catena`,version:oe,description:`Catena CLI`},async setup({rawArgs:t}){e&&t.length!==0&&await Vp({packageName:P,currentVersion:oe})},subCommands:{link:Fd,unlink:_f,profiles:uf,whoami:yf,policy:$d,accounts:vu,intents:Qu,send:ff,transfer:mf,mpp:()=>import(`./mpp-C1N0QzFM.mjs`).then(e=>e.mppCommand),x402:Ep,counterparties:Hu,feedback:qu,guide:Yu}})}const $p=Qp({shouldCheckCliVersionFreshness:!0});Qp({shouldCheckCliVersionFreshness:!1});function em(e){let t=Gp(e);for(let e of t.notices)console.error(e);return[...t.rawArgs]}function tm(){u($p,{rawArgs:em(process.argv.slice(2)),showUsage:Zp($p)})}tm();export{ps as A,Z as C,X as D,Rs as E,he as M,_s as O,Es as S,zs as T,Sf as _,sp as a,Vs as b,Qf as c,Yf as d,Zf as f,Cf as g,wf as h,tp as i,Ba as j,cs as k,ap as l,Ef as m,fp as n,$f as o,Tf as p,ep as r,rp as s,xp as t,op as u,bf as v,Q as w,Os as x,$ as y};