@catena/cli 0.5.1 → 0.5.2

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.
Files changed (2) hide show
  1. package/dist/index.mjs +12 -12
  2. package/package.json +1 -1
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{C as e,S as t,_ as n,b as r,g as i,v as a,x as o,y as s}from"./dist-B0qgGwAq.mjs";import{n as c}from"./base64-WTSXTrii.mjs";import{defineCommand as l,renderUsage as u,runMain as d}from"citty";import*as f from"valibot";import{ECDH as p,createECDH as m,createHash as h,createPrivateKey as g,randomBytes as _,sign as v}from"node:crypto";import{execFile as y,spawn as b}from"node:child_process";import{accessSync as x,chmodSync as S,constants as C,existsSync as w,mkdirSync as T,readFileSync as ee,realpathSync as E,renameSync as D,rmSync as O,statSync as k,writeFileSync as A}from"node:fs";import{homedir as j}from"node:os";import{dirname as M,isAbsolute as te,join as ne,resolve as re}from"node:path";import{createServer as N}from"node:http";import{constants as ie,isUtf8 as ae}from"node:buffer";import P from"semver";var oe=`@catena/cli`,se=`0.5.1`,ce=[`u8`,`u16`,`u32`,`u64`,`u128`,`i8`,`i16`,`i32`,`i64`,`i128`,`f32`,`f64`],le=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}(),ue=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}(),de=(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 fe(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 pe(e,t,n){if(typeof e!==t)throw Error(`Expected ${t} not ${typeof e}(${e}) at ${n.join(`.`)}`)}function me(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 he(e,t,n){if(e!==t)throw Error(`Array length ${e} does not match schema length ${t} at ${n.join(`.`)}`)}function F(e,t){if(typeof e!=`object`||!e)throw Error(`Expected object not ${typeof e}(${e}) at ${t.join(`.`)}`)}ce.concat([`bool`,`string`]),function(e){de(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 le,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(ce.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&&pe(e,`number`,this.fieldPath),this.encoded.store_value(e,t)):(this.checkTypes&&me(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&&pe(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&&pe(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&&F(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(fe(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?he(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?he(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&&pe(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&&pe(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&&pe(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 ue(e)}return e.prototype.decode=function(e){return this.decode_value(e)},e.prototype.decode_value=function(e){if(typeof e==`string`){if(ce.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 ge=e=>{let t=n(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 r=1,a=t[r];if(a<=127){if(t.length<2+a)throw Error(`failed to convert DER-encoded signature: inconsistent message length header`);r+=1}else throw Error(`failed to convert DER-encoded signature: unexpectedly large or invalid signature length`);if(t[r]!==2)throw Error(`failed to convert DER-encoded signature: invalid tag for r`);r++;let o=t[r];if(o>33)throw Error(`failed to convert DER-encoded signature: unexpected length for r`);r++;let s=t.slice(r,r+o);if(r+=o,t[r]!==2)throw Error(`failed to convert DER-encoded signature: invalid tag for s`);r++;let c=t[r];if(c>33)throw Error(`failed to convert DER-encoded signature: unexpected length for s`);r++;let l=t.slice(r,r+c),u=i(s,32),d=i(l,32);return new Uint8Array([...u,...d])};var _e;(function(e){e.NOTARIZER=`notarizer`,e.SIGNER=`signer`,e.EVM_PARSER=`evm-parser`,e.TLS_FETCHER=`tls-fetcher`,e.UMP=`ump`})(_e||={});var I=s(((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)})),ve=s((()=>{
2
+ import{C as e,S as t,_ as n,b as r,g as i,v as a,x as o,y as s}from"./dist-B0qgGwAq.mjs";import{n as c}from"./base64-WTSXTrii.mjs";import{defineCommand as l,renderUsage as u,runMain as d}from"citty";import*as f from"valibot";import{ECDH as p,createECDH as m,createHash as h,createPrivateKey as g,randomBytes as _,sign as v}from"node:crypto";import{execFile as y,spawn as b}from"node:child_process";import{accessSync as x,chmodSync as S,constants as C,existsSync as w,mkdirSync as T,readFileSync as ee,realpathSync as E,renameSync as D,rmSync as O,statSync as k,writeFileSync as A}from"node:fs";import{homedir as j}from"node:os";import{dirname as M,isAbsolute as te,join as ne,resolve as re}from"node:path";import{createServer as N}from"node:http";import{constants as ie,isUtf8 as ae}from"node:buffer";import P from"semver";var oe=`@catena/cli`,se=`0.5.2`,ce=[`u8`,`u16`,`u32`,`u64`,`u128`,`i8`,`i16`,`i32`,`i64`,`i128`,`f32`,`f64`],le=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}(),ue=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}(),de=(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 fe(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 pe(e,t,n){if(typeof e!==t)throw Error(`Expected ${t} not ${typeof e}(${e}) at ${n.join(`.`)}`)}function me(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 he(e,t,n){if(e!==t)throw Error(`Array length ${e} does not match schema length ${t} at ${n.join(`.`)}`)}function F(e,t){if(typeof e!=`object`||!e)throw Error(`Expected object not ${typeof e}(${e}) at ${t.join(`.`)}`)}ce.concat([`bool`,`string`]),function(e){de(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 le,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(ce.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&&pe(e,`number`,this.fieldPath),this.encoded.store_value(e,t)):(this.checkTypes&&me(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&&pe(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&&pe(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&&F(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(fe(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?he(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?he(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&&pe(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&&pe(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&&pe(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 ue(e)}return e.prototype.decode=function(e){return this.decode_value(e)},e.prototype.decode_value=function(e){if(typeof e==`string`){if(ce.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 ge=e=>{let t=n(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 r=1,a=t[r];if(a<=127){if(t.length<2+a)throw Error(`failed to convert DER-encoded signature: inconsistent message length header`);r+=1}else throw Error(`failed to convert DER-encoded signature: unexpectedly large or invalid signature length`);if(t[r]!==2)throw Error(`failed to convert DER-encoded signature: invalid tag for r`);r++;let o=t[r];if(o>33)throw Error(`failed to convert DER-encoded signature: unexpected length for r`);r++;let s=t.slice(r,r+o);if(r+=o,t[r]!==2)throw Error(`failed to convert DER-encoded signature: invalid tag for s`);r++;let c=t[r];if(c>33)throw Error(`failed to convert DER-encoded signature: unexpected length for s`);r++;let l=t.slice(r,r+c),u=i(s,32),d=i(l,32);return new Uint8Array([...u,...d])};var _e;(function(e){e.NOTARIZER=`notarizer`,e.SIGNER=`signer`,e.EVM_PARSER=`evm-parser`,e.TLS_FETCHER=`tls-fetcher`,e.UMP=`ump`})(_e||={});var I=s(((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)})),ve=s((()=>{
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
@@ -133,9 +133,9 @@ ve();var n=J(),r=X(),i=Je(),a=rr(),o=ur(),s=br(),c=(K(),t(L)),l=Ti(),u=Ui(),d=qi
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
  `)}};W.CertificateTag=`CERTIFICATE`,W.CrlTag=`CRL`,W.CertificateRequestTag=`CERTIFICATE REQUEST`,W.PublicKeyTag=`PUBLIC KEY`,W.PrivateKeyTag=`PRIVATE KEY`;var G=class e extends xe{static isAsnEncoded(e){return i.BufferSourceConverter.isBufferSource(e)||typeof e==`string`}static toArrayBuffer(e){if(typeof e==`string`){if(W.isPem(e))return W.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 W.isPem(t)?W.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 W.encode(this.rawData,this.tag);default:return super.toString(e)}}},Be=class e extends G{static async create(t,n=B.get()){if(t instanceof e)return t;if(Ce.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){G.isAsnEncoded(e)?super(e,r.SubjectPublicKeyInfo):super(e),this.tag=W.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]||B.get()):t=e[0]||B.get();let o=this.rawData,c=n.AsnConvert.parse(this.rawData,r.SubjectPublicKeyInfo);return c.algorithm.algorithm===s.id_RSASSA_PSS&&(o=Ve(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]||B.get()):t=e[0]||B.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=B.get()):t=e[0]:e.length===2?(i=e[0],t=e[1]):t=B.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=be.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 Ve(e,t){return e.algorithm=new r.AlgorithmIdentifier({algorithm:s.id_rsaEncryption,parameters:null}),t=n.AsnConvert.serialize(e),t}var He=class e extends z{static async create(t,n=!1,r=B.get()){if(`name`in t&&`serialNumber`in t)return new e(t,n);let a=await(await Be.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 Re?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 Re(t.authorityCertIssuer).toTextObject()),t.authorityCertSerialNumber&&(e[`Authority Serial Number`]=t.authorityCertSerialNumber),t.keyIdentifier&&(e[``]=t.keyIdentifier),e}};He.NAME=`Authority Key Identifier`;var Ue=class extends z{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}};Ue.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 We=class extends z{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}};We.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 Ge=class extends z{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}};Ge.NAME=`Key Usages`;var Ke=class e extends z{static async create(t,n=!1,r=B.get()){let a=await(await Be.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}};Ke.NAME=`Subject Key Identifier`;var qe=class extends z{constructor(...e){i.BufferSourceConverter.isBufferSource(e[0])?super(e[0]):super(p.id_ce_subjectAltName,e[1],new Re(e[0]||[]).rawData)}onInit(e){super.onInit(e);let t=n.AsnConvert.parse(e.extnValue,p.SubjectAlternativeName);this.names=new Re(t)}toTextObject(){let e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(let n in t)e[n]=t[n];return e}};qe.NAME=`Subject Alternative Name`;var Ye=class{static register(e,t){this.items.set(e,t)}static create(e){let t=new z(e),n=this.items.get(t.type);return n?new n(e):t}};Ye.items=new Map;var Xe=class extends z{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 I(``,{},R.toString(e))),e}};Xe.NAME=`Certificate Policies`,Ye.register(p.id_ce_certificatePolicies,Xe);var Ze=class extends z{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 Le(e).toString()).join(`, `)),e.reasons&&(t.Reasons=e.reasons.toString()),e.cRLIssuer&&(t[`CRL Issuer`]=e.cRLIssuer.map(e=>e.toString()).join(`, `)),t}),e}};Ze.NAME=`CRL Distribution Points`;var Qe=class extends z{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;et(r,t,p.id_ad_ocsp,`ocsp`),et(r,t,p.id_ad_caIssuers,`caIssuers`),et(r,t,p.id_ad_timeStamping,`timeStamping`),et(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 Le(e.accessLocation));break;case p.id_ad_caIssuers:this.caIssuers.push(new Le(e.accessLocation));break;case p.id_ad_timeStamping:this.timeStamping.push(new Le(e.accessLocation));break;case p.id_ad_caRepository:this.caRepository.push(new Le(e.accessLocation))}})}toTextObject(){let e=this.toTextObjectWithoutValue();return this.ocsp.length&&$e(e,`OCSP`,this.ocsp),this.caIssuers.length&&$e(e,`CA Issuers`,this.caIssuers),this.timeStamping.length&&$e(e,`Time Stamping`,this.timeStamping),this.caRepository.length&&$e(e,`CA Repository`,this.caRepository),e}};Qe.NAME=`Authority Info Access`;function $e(e,t,n){if(n.length===1)e[t]=n[0].toTextObject();else{let r=new I(``);n.forEach((e,t)=>{let n=e.toTextObject(),i=`${n[I.NAME]} ${t+1}`,a=r[i];Array.isArray(a)||(a=[],r[i]=a),a.push(n)}),e[t]=r}}function et(e,t,r,i){let a=t[i];a&&(Array.isArray(a)?a:[a]).forEach(t=>{typeof t==`string`&&(t=new Le(`url`,t)),e.push(new p.AccessDescription({accessMethod:r,accessLocation:n.AsnConvert.parse(t.rawData,p.GeneralName)}))})}var q=class e extends xe{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 I(``,{"":e})),e}toTextObjectWithoutValue(){let t=this.toTextObjectEmpty();return t[I.NAME]===e.NAME&&(t[I.NAME]=R.toString(this.type)),t}};q.NAME=`Attribute`;var tt=class extends q{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[I.VALUE]=this.password,e}};tt.NAME=`Challenge Password`;var nt=class extends q{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=>Ye.create(n.AsnConvert.serialize(e)))}}toTextObject(){let e=this.toTextObjectWithoutValue(),t=this.items.map(e=>e.toTextObject());for(let n of t)e[n[I.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 q(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 st=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}};st.namedCurveSize=new Map,st.defaultNamedCurveSize=32;let ct=`1.3.101.110`,lt=`1.3.101.111`,ut=`1.3.101.112`,dt=`1.3.101.113`;e.EdAlgorithm=class{toAsnAlgorithm(e){let t=null;switch(e.name.toLowerCase()){case`ed25519`:t=ut;break;case`x25519`:t=ct;break;case`eddsa`:switch(e.namedCurve.toLowerCase()){case`ed25519`:t=ut;break;case`ed448`:t=dt}break;case`ecdh-es`:switch(e.namedCurve.toLowerCase()){case`x25519`:t=ct;break;case`x448`:t=lt}}return t?new r.AlgorithmIdentifier({algorithm:t}):null}toWebAlgorithm(e){switch(e.algorithm){case ut:return{name:`Ed25519`};case dt:return{name:`EdDSA`,namedCurve:`Ed448`};case ct:return{name:`X25519`};case lt:return{name:`ECDH-ES`,namedCurve:`X448`}}return null}},e.EdAlgorithm=c.__decorate([l.injectable()],e.EdAlgorithm),l.container.registerSingleton(v,e.EdAlgorithm);var ft=class extends G{constructor(e){G.isAsnEncoded(e)?super(e,d.CertificationRequest):super(e),this.tag=W.CertificateRequestTag}onInit(e){this.tbs=n.AsnConvert.serialize(e.certificationRequestInfo),this.publicKey=new Be(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 H(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=B.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 I(``,{Version:`${r.Version[i.version]} (${i.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){let e=new I(``);for(let t of this.attributes){let n=t.toTextObject();e[n[I.NAME]]=n}a.Attributes=e}return e.Data=a,e.Signature=new I(``,{Algorithm:be.serializeAlgorithm(t.signatureAlgorithm),"":t.signature}),e}};ft.NAME=`PKCS#10 Certificate Request`;var pt=class{static async create(e,t=B.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 H?e.name:new H(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 ft(n.AsnConvert.serialize(a))}},mt=class extends G{constructor(e){G.isAsnEncoded(e)?super(e,r.Certificate):super(e),this.tag=W.CertificateTag}onInit(e){let t=e.tbsCertificate;this.tbs=n.AsnConvert.serialize(t),this.serialNumber=i.Convert.ToHex(t.serialNumber),this.subjectName=new H(t.subject),this.subject=new H(t.subject).toString(),this.issuerName=new H(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=>Ye.create(n.AsnConvert.serialize(e)))),this.publicKey=new Be(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=B.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 Be)n={...a.algorithm,...this.signatureAlgorithm},r=await a.export(n,[`verify`],t);else if(i.BufferSourceConverter.isBufferSource(a)){let e=new Be(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??=B.get(),await t.subtle.digest(n,this.rawData)}async isSelfSigned(e=B.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 I(``,{Version:`${r.Version[i.version]} (${i.version})`,"Serial Number":i.serialNumber,"Signature Algorithm":be.serializeAlgorithm(i.signature),Issuer:this.issuer,Validity:new I(``,{"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 I(``);for(let t of this.extensions){let n=t.toTextObject();e[n[I.NAME]]=n}a.Extensions=e}return e.Data=a,e.Signature=new I(``,{Algorithm:be.serializeAlgorithm(t.signatureAlgorithm),"":t.signatureValue}),e}};mt.NAME=`Certificate`;var ht=class extends Array{constructor(e){if(super(),G.isAsnEncoded(e))this.import(e);else if(e instanceof mt)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=G.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 mt(e.certificate))}clear(){for(;this.pop(););}toString(e=`pem`){let t=this.export(`raw`);switch(e){case`pem`:return W.encode(t,`CMS`);case`pem-chain`:return this.map(e=>e.toString(`pem`)).join(`
135
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 be.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 I(`X509Certificates`,{"Content Type":R.toString(e.contentType),Content:new I(``,{Version:`${m.CMSVersion[t.version]} (${t.version})`,Certificates:new I(``,{Certificate:this.map(e=>e.toTextObject())})})})}},gt=class{constructor(e={}){this.certificates=[],e.certificates&&(this.certificates=e.certificates)}async build(e,t=B.get()){let n=new ht(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=B.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}},_t=class{static async createSelfSigned(e,t=B.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=B.get()){let r;r=e.publicKey instanceof Be?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 H?e.subject:new H(e.subject);c.tbsCertificate.subject=n.AsnConvert.parse(t.toArrayBuffer(),p.Name)}if(e.issuer){let t=e.issuer instanceof H?e.issuer:new H(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 mt(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 vt=class extends xe{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=Ye.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}))}},yt=class extends G{constructor(e){G.isAsnEncoded(e)?super(e,r.CertificateList):super(e),this.tag=W.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 H(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 vt(n.AsnConvert.serialize(e)))||[],this.extensions=[],t.crlExtensions&&(this.extensions=t.crlExtensions.map(e=>Ye.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=B.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 mt?(n={...i.publicKey.algorithm,...i.signatureAlgorithm},r=await i.publicKey.export(n,[`verify`])):i instanceof Be?(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??=B.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}},bt=class{static async create(e,t=B.get()){let a=e.issuer instanceof H?e.issuer:new H(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=G.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 vt)&&(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 H?e.issuer:new H(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 yt(n.AsnConvert.serialize(o))}};Ye.register(p.id_ce_basicConstraints,Ue),Ye.register(p.id_ce_extKeyUsage,We),Ye.register(p.id_ce_keyUsage,Ge),Ye.register(p.id_ce_subjectKeyIdentifier,Ke),Ye.register(p.id_ce_authorityKeyIdentifier,He),Ye.register(p.id_ce_subjectAltName,qe),Ye.register(p.id_ce_cRLDistributionPoints,Ze),Ye.register(p.id_pe_authorityInfoAccess,Qe),rt.register(_.id_pkcs9_at_challengePassword,tt),rt.register(_.id_pkcs9_at_extensionRequest,nt),l.container.registerSingleton(it,at),l.container.registerSingleton(it,st),st.namedCurveSize.set(`P-256`,32),st.namedCurveSize.set(`K-256`,32),st.namedCurveSize.set(`P-384`,48),st.namedCurveSize.set(`P-521`,66),e.AlgorithmProvider=y,e.AsnData=xe,e.AsnDefaultSignatureFormatter=at,e.AsnEcSignatureFormatter=st,e.Attribute=q,e.AttributeFactory=rt,e.AuthorityInfoAccessExtension=Qe,e.AuthorityKeyIdentifierExtension=He,e.BasicConstraintsExtension=Ue,e.CRLDistributionPointsExtension=Ze,e.CertificatePolicyExtension=Xe,e.ChallengePasswordAttribute=tt,e.CryptoProvider=Ce,e.DefaultAlgorithmSerializer=ye,e.ExtendedKeyUsageExtension=We,e.Extension=z,e.ExtensionFactory=Ye,e.ExtensionsAttribute=nt,e.GeneralName=Le,e.GeneralNames=Re,e.KeyUsagesExtension=Ge,e.Name=H,e.NameIdentifier=Ee,e.OidSerializer=R,e.PemConverter=W,e.Pkcs10CertificateRequest=ft,e.Pkcs10CertificateRequestGenerator=pt,e.PublicKey=Be,e.SubjectAlternativeNameExtension=qe,e.SubjectKeyIdentifierExtension=Ke,e.TextConverter=be,e.TextObject=I,e.X509Certificate=mt,e.X509CertificateGenerator=_t,e.X509Certificates=ht,e.X509ChainBuilder=gt,e.X509Crl=yt,e.X509CrlEntry=vt,e.X509CrlGenerator=bt,e.cryptoProvider=B,e.diAlgorithm=v,e.diAlgorithmProvider=b,e.diAsnSignatureFormatter=it,e.idEd25519=ut,e.idEd448=dt,e.idX25519=ct,e.idX448=lt}));I(),Ji();var Yi;(function(e){e.Der=`der`,e.Raw=`raw`})(Yi||={});const Xi=typeof window<`u`&&window.document!==void 0&&typeof crypto<`u`&&crypto.subtle!==void 0,Zi=typeof process<`u`&&process.versions!=null&&process.versions.node!=null,Qi=()=>Xi?`browser`:Zi?`node`:`purejs`,$i=async(e,t)=>{let n=t??Qi();switch(n){case`browser`:return(await import(`./webcrypto-CRLL4ptE.mjs`)).signWithApiKey(e);case`node`:return(await import(`./nodecrypto-CIGSbdQh.mjs`)).signWithApiKey(e);case`purejs`:return(await import(`./purejs-CZxWHjtN.mjs`)).signWithApiKey(e);default:throw Error(`Unsupported runtime: ${n}`)}};var ea=class{constructor(e){this.apiPublicKey=e.apiPublicKey,this.apiPrivateKey=e.apiPrivateKey,this.runtimeOverride=e.runtimeOverride}async stamp(e){let t=await $i({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:c(JSON.stringify(n))}}async sign(e,t){switch(t){case Yi.Raw:{let t=await $i({publicKey:this.apiPublicKey,privateKey:this.apiPrivateKey,content:e},this.runtimeOverride),n=ge(t);return a(n)}case Yi.Der:return $i({publicKey:this.apiPublicKey,privateKey:this.apiPrivateKey,content:e},this.runtimeOverride);default:throw Error(`Unsupported signature format: ${t}`)}}},ta=class extends Error{constructor(e){super(e),this.name=`InvalidKeyError`}};function na(){let e=m(`prime256v1`);return e.generateKeys(),ia(e.getPrivateKey().toString(`hex`).padStart(64,`0`))}const ra=/^[0-9a-f]{64}$/i;function ia(e){if(!ra.test(e))throw new ta(`P-256 private key must be 64 hex characters`);let t=e.toLowerCase(),n=m(`prime256v1`);try{n.setPrivateKey(Buffer.from(t,`hex`))}catch{throw new ta(`value is not a valid P-256 private key (scalar out of range)`)}return{algorithm:`p256`,privateKeyHex:t,publicKeyHex:n.getPublicKey(`hex`,`compressed`)}}function aa(e){try{let t=p.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 oa(e){let t=aa(e);if(t===null)throw new ta(`value is not a valid P-256 public key`);return sa(t)}function sa(e){let t=e.subarray(1,33).toString(`base64url`),n=e.subarray(33,65).toString(`base64url`);return h(`sha256`).update(`{"crv":"P-256","kty":"EC","x":"${t}","y":"${n}"}`,`utf8`).digest(`base64url`)}const ca=/^https?:\/\/[\x21\x23-\x7e]{1,255}$/,la=/^[\x21\x23-\x3a\x3c-\x7e]{1,128}$/;function ua(e,t){return`${e.replace(/\/+$/,``)}/agent-keys/${t}`}function da(e){let t=fa(e.keypair),n={...t,identityUrl:pa(e.identityUrl??ua(e.baseUrl,t.keyId))};return{sign:async e=>{let t=new Uint8Array(await e.clone().arrayBuffer()),r=ma(n,{method:e.method,url:e.url,body:t},{nonce:_(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 fa(e){let t=aa(e.publicKeyHex);if(t===null)throw Error(`signer keypair has an invalid P-256 public key`);return{signingKey:va(t,e.privateKeyHex),keyId:sa(t)}}function pa(e){if(!ca.test(e))throw Error(`identity URL is outside the signature profile: "${e}"`);return e}function ma(e,t,n){if(!la.test(n.nonce))throw Error(`nonce is outside the signature profile`);let r=ha(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": ${ga(new URL(t.url))}`,`"content-digest": ${r}`,`"signature-agent": ${i}`,`"@signature-params": ${a}`].join(`
136
- `),s=v(`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 ha(e){return`sha-256=:${h(`sha256`).update(e??``).digest(`base64`)}:`}function ga(e){return`${e.protocol}//${_a(e)}${e.pathname}${e.search}`}function _a(e){let t=e.host.toLowerCase();return e.protocol===`https:`&&e.port===`443`||e.protocol===`http:`&&e.port===`80`?e.hostname.toLowerCase():t}function va(e,t){return g({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 ya=`0.1.0`;const ba=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,xa=ya;function Sa(e,t){if(!ba.test(e))throw Error(`${t} must be a valid HTTP token`)}function Ca(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 wa(e){let t=`catena-agent-client/${xa}`;if(!e)return t;Sa(e.name,`appInfo.name`),e.version!==void 0&&Sa(e.version,`appInfo.version`),e.url!==void 0&&Ca(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 Ta=f.object({amount:f.string(),asset_id:f.string()}),Ea=f.pipe(f.string(),f.isoTimestamp()),Da=f.object({success:f.literal(!0)}),Oa=f.object({id:f.string(),name:f.string(),status:f.string(),organizationId:f.string()}),ka=f.object({agent:Oa}),Aa=f.object({id:f.string(),ruleType:f.picklist([`per_transaction_amount`,`daily_amount`,`weekly_amount`,`monthly_amount`,`hourly_count`,`daily_count`]),thresholdAmount:f.optional(Ta),thresholdCount:f.optional(f.number()),action:f.picklist([`block`,`require_approval`]),requiredApprovals:f.number(),accountAggregationScope:f.picklist([`per_account`,`across_accounts`]),actorAggregationScope:f.picklist([`per_agent`,`per_policy`]),displayOrder:f.number()}),ja=f.object({id:f.string(),organizationId:f.string(),policyId:f.string(),capability:f.picklist([`query_balance`,`read`,`send`,`transfer`]),accountId:f.string(),rules:f.array(Aa),createdAt:Ea,updatedAt:Ea}),Ma=f.picklist([`allow`,`block`,`require_approval`]),Na=f.object({mode:f.picklist([`open`,`restricted`]),allowedCounterparties:f.optional(f.array(f.string())),createAction:f.optional(Ma),requestPaymentDetailsAction:f.optional(Ma),allowCreate:f.optional(f.boolean())}),Pa=f.object({id:f.optional(f.string()),description:f.optional(f.string()),version:f.optional(f.number()),name:f.string(),capabilities:f.array(f.string()),counterpartyRules:f.optional(Na),policyCapabilities:f.array(ja)}),Fa=f.object({policy:Pa}),Ia=f.object({accounts:f.array(f.object({id:f.string(),name:f.string(),type:f.string(),currency:f.string()}))}),La=f.object({accountId:f.string(),balance:Ta,balances:f.optional(f.object({total:Ta,available:Ta}))}),Ra=f.object({id:f.string(),type:f.picklist([`operator-send`,`operator-transfer`,`operator-deposit`,`operator-refund`,`microdeposit`]),action:f.optional(f.string()),status:f.picklist([`pending`,`processing`,`completed`,`failed`,`reversed`]),movementStatus:f.picklist([`initiated`,`provider_pending`,`processing`,`completed`,`failed`,`reversed`,`manual_review`]),direction:f.picklist([`incoming`,`outgoing`]),amount:Ta,fee:Ta,currency:f.string(),counterpartyName:f.optional(f.string()),method:f.optional(f.picklist([`ach`,`wire`,`on-chain`])),memo:f.optional(f.string()),description:f.optional(f.string()),txHash:f.optional(f.string()),createdAt:Ea,completedAt:f.optional(Ea)}),za=f.object({accountId:f.string(),transactions:f.array(Ra),total:f.number()}),Ba=f.object({accountId:f.string(),address:f.string(),liquidationAddressId:f.optional(f.string()),source:f.picklist([`wallet`,`liquidation`])}),Va=f.object({id:f.string(),name:f.string(),status:f.optional(f.string()),rails:f.array(f.object({id:f.string(),type:f.string(),walletAddress:f.optional(f.string()),network:f.optional(f.string()),bankName:f.optional(f.string()),accountNumber:f.optional(f.string())}))}),Ha=f.object({counterparties:f.array(Va)}),Ua=f.picklist([`pending`,`processing`,`completed`,`blocked`,`failed`]),Wa=f.object({type:f.literal(`submit_stamp`),signingRequestId:f.string(),signer:f.object({algorithm:f.literal(`p256`),publicKeyHex:f.string()}),preparedBody:f.object({body:f.string(),bodyHash:f.string(),expiresAt:Ea,prepareToken:f.string()})}),Ga=f.object({id:f.string(),type:f.picklist([`send`,`transfer`,`create_counterparty`,`request_counterparty_details`,`x402`]),status:Ua,reasons:f.array(f.string()),expiresAt:f.optional(f.nullable(Ea),null),replayed:f.optional(f.boolean(),!1),data:f.optional(f.nullable(f.record(f.string(),f.unknown())),null),metadata:f.optional(f.object({dataUrl:f.nullable(f.string())})),nextAction:f.optional(Wa)});function Ka(e){let{nextAction:t,...n}=e;return n}const qa=[`ach`,`wire`,`on-chain`],Ja=f.picklist(qa),Ya=f.object({type:f.literal(`send`),accountId:f.string(),counterpartyRailId:f.string(),amount:f.string(),method:Ja,memo:f.optional(f.string()),description:f.optional(f.string())}),Xa=f.object({type:f.literal(`transfer`),accountId:f.string(),toAccountId:f.string(),amount:f.string(),memo:f.optional(f.string()),description:f.optional(f.string())}),Za={type:f.literal(`create_counterparty`),name:f.string()},Qa=f.union([f.object({...Za,email:f.optional(f.string()),rail:f.nonOptional(f.unknown())}),f.object({...Za,email:f.string()})]),$a=f.object({type:f.literal(`request_counterparty_details`),counterpartyId:f.string(),methods:f.pipe(f.object({bank:f.boolean(),wallet:f.boolean()}),f.check(({bank:e,wallet:t})=>e||t,`Select at least one payment method to request`))}),eo=f.looseObject({scheme:f.string(),network:f.string(),asset:f.string(),amount:f.string(),payTo:f.string(),maxTimeoutSeconds:f.number()}),to=f.looseObject({url:f.string(),serviceName:f.fallback(f.optional(f.pipe(f.string(),f.maxLength(255))),void 0)}),no=f.object({type:f.literal(`x402`),accountId:f.string(),paymentRequirements:eo,resource:f.optional(to)}),ro=f.union([Ya,Xa,Qa,$a,no]);function io(e){let t=f.parse(ro,e);return t.type===`send`||t.type===`transfer`?{...t,amount:{amount:t.amount,asset_id:`USD`}}:t}const ao=f.object({intent:Ga});var oo=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}},so=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 co=f.object({error:f.nullish(f.string()),message:f.nullish(f.string()),code:f.nullish(f.string()),details:f.nullish(f.record(f.string(),f.unknown()))});async function lo(e){let t=f.safeParse(co,await e.json().catch(()=>void 0)),n=t.success?t.output:{};return n.error!=null&&n.message!=null?new oo(e.status,n.message,n.code??n.error,n.details??void 0):new oo(e.status,n.error??n.message??e.statusText,n.code??void 0,n.details??void 0)}async function uo(e,t){if(!e.ok)throw await lo(e);return f.parse(t,await e.json())}var fo=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 po=2147483647;var mo=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>po)throw TypeError(`timeout must be a positive integer no greater than ${po}`);this.#e=e.baseUrl??`https://api.catena.com`,this.#t=wa(e.appInfo),this.#n=e.defaultHeaders??{},this.#r=ia(e.privateKeyHex),this.#a=(e.fetch??globalThis.fetch).bind(globalThis),this.#o=t,this.#i=da({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 so(this.#o);t(e),n.abort(e)},this.#o)}),a=this.#a(r).then(e=>uo(e,t));return await Promise.race([a,e])}finally{i!==void 0&&clearTimeout(i)}}async whoami(){return(await this.#l({method:`GET`,path:`/me`},ka)).agent}async submitFeedback(e){await this.#l({method:`POST`,path:`/feedback`,body:{body:e}},Da)}async getPolicy(){return(await this.#l({method:`GET`,path:`/policy`},Fa)).policy}async listAccounts(){return this.#l({method:`GET`,path:`/accounts`},Ia)}async getAccountBalance(e){return this.#l({method:`GET`,path:`/accounts/${encodeURIComponent(e)}/balance`},La)}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()}},za)}async getAccountDepositAddress(e,t){return this.#l({method:`GET`,path:`/accounts/${encodeURIComponent(e)}/deposit-address`,query:{network:t.network,asset:t.asset}},Ba)}async listCounterparties(e={}){return this.#l({method:`GET`,path:`/counterparties`,query:{address:e.address,network:e.network}},Ha)}async submitIntent(e){let t=await this.#d(e),n=t.nextAction;if(!n)return Ka(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 fo({intentId:t.id,outcome:`not-submitted`,cause:e})}try{return await this.#p(r,t.replayed)}catch(e){throw new fo({intentId:t.id,outcome:`unknown`,cause:e})}}async#d(e){return this.#l({method:`POST`,path:`/intents`,body:{action:io(e.action)},...e.idempotencyKey!==void 0&&{headers:{"Idempotency-Key":e.idempotencyKey}}},Ga)}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 ea({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=Ka((await this.#u(e,ao)).intent);return t?{...n,replayed:!0}:n}async getIntent(e){return Ka(await this.#l({method:`GET`,path:`/intents/${encodeURIComponent(e)}`},Ga))}async unlinkAgent(){await this.#l({method:`POST`,path:`/unlink`},Da)}async reportSettlement(e){await this.#l({method:`POST`,path:`/intents/${encodeURIComponent(e.intentId)}/settlement-report`,body:{txHash:e.txHash}},Da)}};function ho(e={}){let t=e.privateKeyHex===void 0?process.env.CATENA_SECRET_KEY:e.privateKeyHex;if(t===void 0)throw new ta(`privateKeyHex is required; pass it explicitly or set CATENA_SECRET_KEY`);return new mo({...e,privateKeyHex:t})}function go(e){let t=e instanceof Error?e.message:String(e);return e instanceof oo&&e.details!==void 0?`${t}\nDetails:\n${JSON.stringify(e.details,null,2)}`:t}function Z(e){console.error(go(e)),process.exit(1)}const _o=f.string(),vo=f.boolean();function yo(e){return e===void 0}function bo(e){return e.issues?.[0]?.message??`Invalid value`}function xo(e,t,n,r){return Z(`${e}: ${t}${r?` (got: ${String(n)})`:``}`)}function So(e,t,n,r){let i=f.safeParse(e,t);return i.success?i.output:xo(n,bo(i),t,r)}function Co(e,t){let n=t.schema??_o;return{type:e,description:t.description,negativeDescription:t.negativeDescription,required:t.required,default:t.default,parseValue(e,r){let i=yo(e)?t.default:e;if(yo(i)){t.required===!0&&Z(`${r} is required`);return}return So(n,i,r,t.showValueInError===!0)}}}function Q(e){return Co(`string`,e)}function wo(e){return Co(`positional`,e)}function To(e){let t=e.schema??_o;return{type:`string`,description:e.description,repeatable:!0,parseValue(n,r){return(Array.isArray(n)?n:[]).map(n=>So(t,n,r,e.showValueInError===!0))}}}function Eo(e){return{type:`boolean`,description:e.description,negativeDescription:e.negativeDescription,required:e.required,default:e.default,parseValue(t,n){let r=yo(t)?e.default:t;if(yo(r)){e.required===!0&&Z(`${n} is required`);return}return So(vo,r,n,!1)}}}function Do(e){return Oo(`string`,e)}function Oo(e,t){return Co(e,{description:t.description,required:t.required,default:t.default,schema:f.picklist(t.choices,`must be one of ${t.choices.join(`|`)}`),showValueInError:!0})}function ko(e,t){return t.type===`positional`?`<${e}>`:`--${e}`}function Ao(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 jo(e){return Ao(e).join(`-`).toLowerCase()}function Mo(e){return Ao(e).map((e,t)=>t===0?e.charAt(0).toLowerCase()+e.slice(1):e.charAt(0).toUpperCase()+e.slice(1)).join(``)}function No(e){return[`--${e}`,`--${jo(e)}`,`--${Mo(e)}`]}function Po(e){let t=e.indexOf(`=`);return t===-1?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function Fo(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(No(t)),s=new Set(Object.entries(n).filter(([e,n])=>e!==t&&n.type===`string`).flatMap(([e])=>No(e))),c=[];for(let e=0;e<a.length;e++){let t=a[e];if(t===`--`)break;let[n,r]=Po(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 Io(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 $(e){return{args:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Io(t)])),label(t){return ko(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 Fo(n,r,e)};return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.parseValue(r(e,t),ko(e,t))]))}}}const Lo=Q({description:`Credential profile name`}),Ro=Eo({description:`Print compact single-line JSON (for piping)`,default:!1}),zo=/^[a-zA-Z0-9_-]+$/,Bo=f.pipe(f.string(`ID must be a string`),f.minLength(1,`ID must not be empty`),f.maxLength(256,`ID is too long (max 256 characters)`),f.regex(zo,`ID may only contain letters, digits, hyphens, and underscores`)),Vo=[`base`,`base-sepolia`],Ho=[`usdc`],Uo=`base`,Wo=f.pipe(f.string(),f.trim(),f.guard(e=>/^0x[0-9a-fA-F]{40}$/.test(e),`Must be a 0x-prefixed hex wallet address`));function Go(e){return Do({description:e.description,choices:Vo,...e.default===void 0?{}:{default:e.default}})}const Ko=[`registered`,`already_registered`,`not_applicable`,`registration_failed`],qo=f.pipe(f.string(),f.regex(/^0[23][0-9a-f]{64}$/)),Jo=f.pipe(f.string(),f.regex(/^[0-9a-f]{64}$/)),Yo=f.object({status:f.picklist(Ko),publicKeyHex:f.optional(qo),reason:f.optional(f.string())}),Xo=f.object({algorithm:f.literal(`p256`),privateKeyHex:Jo,publicKeyHex:qo,registration:Yo}),Zo=f.object({version:f.literal(`signer-1`),signer:Xo}),Qo=f.object({version:f.literal(1),refreshToken:f.pipe(f.string(),f.minLength(1)),sessionToken:f.pipe(f.string(),f.minLength(1)),expiresAt:f.pipe(f.string(),f.isoTimestamp())}),$o=f.object({version:f.literal(2),refreshToken:f.pipe(f.string(),f.minLength(1)),sessionToken:f.pipe(f.string(),f.minLength(1)),expiresAt:f.pipe(f.string(),f.isoTimestamp()),signer:Xo}),es=f.object({version:f.literal(3),signer:Xo}),ts=f.variant(`version`,[Qo,$o,es]),ns=f.variant(`version`,[Zo,Qo,$o,es]);function rs(e){return f.parse(ts,e)}function is(e){return f.parse(ns,e)}function as(e){let t=f.safeParse(ns,e);return t.success?t.output:null}function os(e){return{version:`signer-1`,signer:{algorithm:e.algorithm,privateKeyHex:e.privateKeyHex,publicKeyHex:e.publicKeyHex,registration:{status:`not_applicable`,reason:`pending_claim`}}}}function ss(e,t){try{return is(JSON.parse(e))}catch(e){throw Error(`${t} credential has an unsupported format`,{cause:e})}}function cs(e){return rs({version:3,signer:e})}function ls(e){return JSON.stringify(e)}function us(e,t){return JSON.stringify(e)===JSON.stringify(t)}function ds(e){return(t,n)=>fs(e,t,n)}function fs(e,t,n){return new Promise((r,i)=>{let a=b(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 ps=`catena-agent`;function ms(e){if(!zo.test(e))throw Error(`Invalid credential location for credential storage: "${e}"`);return e}const hs=ds(`/usr/bin/secret-tool`);function gs(e){return e.status===1&&e.stdout===``&&e.stderr.trim()===``}function _s(e,t){if(t.status===0)return;let n=vs(t);throw Error(`Linux Secret Service credential ${e} failed (secret-tool exited ${t.status??`without status`}): ${n}`)}function vs(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 ys(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 bs=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??hs}async save(e,t){let n=is(t),r=ms(e);if(await this.savePassword(r,ls(n)),!us(await this.resolveDirectPassword(r),n))throw Error(`Linux Secret Service credential save verification failed`)}async resolve(e){return this.resolveDirectPassword(ms(e))}async delete(e){await this.deletePassword(ms(e))}async savePassword(e,t){_s(`save`,await this.runSecretToolCommand([`store`,`--label`,`${ps} ${e}`,`app`,ps,`account`,e],t))}async resolvePassword(e){let t=await this.runSecretToolCommand([`lookup`,`app`,ps,`account`,e]);return gs(t)?null:(_s(`resolve`,t),t.stdout.replace(/\r?\n$/,``))}async resolveDirectPassword(e){let t=await this.resolvePassword(e);return t===null?null:ss(t,`Linux Secret Service`)}async deletePassword(e){let t=await this.runSecretToolCommand([`clear`,`app`,ps,`account`,e]);gs(t)||_s(`delete`,t)}async runSecretToolCommand(e,t){try{return await this.runSecretTool(e,t)}catch(e){throw ys(e)}}};const xs=ds(`/usr/bin/security`),Ss=f.object({version:f.literal(1),encoding:f.literal(`base64-json`),chunks:f.pipe(f.number(),f.integer(),f.minValue(1),f.maxValue(64)),sha256:f.pipe(f.string(),f.regex(/^[a-f0-9]{64}$/))});function Cs(e){return e.status===44}function ws(e,t){return`${e}:chunk:${t}`}function Ts(e){let t=JSON.parse(e),n=as(t);if(n!==null)return{kind:`direct`,payload:n};let r=f.safeParse(Ss,t);if(r.success)return{kind:`legacy`,manifest:r.output};throw Error(`macOS Keychain credential has an unsupported format`)}function Es(e,t){if(t.status===0)return;let n=Ds(t);throw Error(`macOS Keychain credential ${e} failed (security exited ${t.status??`without status`})${n===null?``:`: ${n}`}`)}function Ds(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 Os(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 ks(e,t){return[`add-generic-password`,`-s`,Os(ps),`-a`,Os(e),`-w`,Os(t),`-U`].join(` `)+`
137
- `}var As=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??xs}async save(e,t){let n=is(t),r=ms(e),i=await this.resolveLegacyChunkCount(r,64);if(await this.savePassword(r,ls(n)),!us(await this.resolveDirectPassword(r),n))throw Error(`macOS Keychain credential save verification failed`);await this.deleteChunks(r,i)}async resolve(e){let t=ms(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=ms(e),n=await this.resolveLegacyChunkCount(t,64);await this.deleteChunks(t,n),await this.deletePassword(t)}async savePassword(e,t){Es(`save`,await this.runSecurity([`-i`],ks(e,t)))}async resolvePassword(e){let t=await this.runSecurity([`find-generic-password`,`-a`,e,`-s`,ps,`-w`]);return Cs(t)?null:(Es(`resolve`,t),t.stdout.replace(/\r?\n$/,``))}async resolveKeychainItem(e){let t=await this.resolvePassword(e);return t===null?null:Ts(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(ws(e,r));if(t===null)throw Error(`macOS Keychain credential chunk is missing`);n.push(t)}let r=n.join(``);if(h(`sha256`).update(r).digest(`hex`)!==t.sha256)throw Error(`macOS Keychain credential checksum mismatch`);return is(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=Ts(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(ws(e,n))}async deletePassword(e){let t=await this.runSecurity([`delete-generic-password`,`-a`,e,`-s`,ps]);Cs(t)||Es(`delete`,t)}};function js(e={}){let t=e.platform??process.platform;if(t===`darwin`)return new As({platform:t});if(t===`linux`)return new bs({platform:t});throw Error(`Catena credential storage is only supported on macOS and Linux`)}const Ms=/^127(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}$/;function Ns(e){let t=e.replace(/^\[|\]$/g,``);return t===`localhost`||t===`::1`||Ms.test(t)}function Ps(e){let t;try{t=new URL(e)}catch{return!1}return t.protocol===`https:`||t.protocol===`http:`&&Ns(t.hostname)}function Fs(e,t){if(!Ps(e))throw Error(`${t} must be an https:// URL (http:// is allowed only for a loopback host): "${e}"`)}const Is=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/,Ls=f.object({status:f.optional(f.literal(`linked`),`linked`),bank_url:f.pipe(f.string(),f.minLength(1)),agent_id:f.pipe(f.string(),f.minLength(1)),client_instance_id:f.pipe(f.string(),f.regex(zo))}),Rs=f.object({status:f.literal(`pending_connection`),bank_url:f.pipe(f.string(),f.minLength(1)),client_instance_id:f.pipe(f.string(),f.regex(zo)),created_at:f.pipe(f.string(),f.isoTimestamp())}),zs=f.variant(`status`,[Ls,Rs]);f.object({version:f.literal(1),default_profile:f.optional(f.string()),profiles:f.record(f.string(),zs),directories:f.optional(f.record(f.string(),f.string()))});const Bs=f.object({version:f.literal(1),default_profile:f.optional(f.string()),profiles:f.record(f.string(),f.unknown()),directories:f.optional(f.record(f.string(),f.unknown()))});function Vs(){return ne(process.env.HOME??j(),`.catena`)}function Hs(){return ne(Vs(),`profiles.json`)}function Us(e){return Is.test(e)}function Ws(e){if(!Us(e))throw Error(`invalid profile name "${e}" (expected [a-zA-Z0-9][a-zA-Z0-9._-]{0,63})`)}function Gs(e){return typeof e!=`object`||!e||!(`code`in e)?!1:typeof e.code==`string`}function Ks(e,t){let n;try{n=JSON.parse(e)}catch(e){throw Error(`profiles.json is not valid JSON: ${go(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=f.parse(Bs,n),i={};for(let[e,n]of Object.entries(r.profiles)){if(!Us(e)){t?.(`profiles: dropping invalid profile name "${e}"`);continue}let r=f.safeParse(zs,n);if(!r.success){t?.(`profiles: dropping malformed profile "${e}"`);continue}i[e]=r.output}if(r.default_profile!==void 0&&(Ws(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(!te(e)){t?.(`profiles: dropping directory binding with relative path "${e}"`);continue}if(typeof n!=`string`||!Us(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 qs(e){try{return Ks(ee(Hs(),`utf-8`),e)}catch(e){if(e instanceof Error&&Gs(e)&&e.code===`ENOENT`)return{version:1,profiles:{}};throw e}}function Js(){T(Vs(),{recursive:!0,mode:448}),S(Vs(),448)}function Ys(e){Js();let t=Hs(),n=`${t}.${_(6).toString(`hex`)}.tmp`;A(n,JSON.stringify(e,null,2)+`
138
- `,{encoding:`utf-8`,mode:384}),D(n,t)}function Xs(e,t){Ws(e);let n=f.parse(zs,t);Fs(n.bank_url,`profile "${e}" bank_url`);let r=qs();Ys({...r,profiles:{...r.profiles,[e]:n}})}function Zs(e){return e.status===`linked`}function Qs(e,t){return e.replace(/\/+$/,``)===t.replace(/\/+$/,``)}function $s(e,t){let n=Object.entries(qs().profiles).toSorted(([e],[t])=>e.localeCompare(t)).find(([,n])=>Zs(n)&&n.agent_id===e&&Qs(n.bank_url,t));return n===void 0?null:n[0]}function ec(e,t){let n=Object.fromEntries(Object.entries(e??{}).filter(([,e])=>t(e)));return Object.keys(n).length===0?{}:{directories:n}}function tc(e){Ws(e);let t=qs(),{[e]:n,...r}=t.profiles;Ys({version:1,...t.default_profile===e||t.default_profile===void 0?{}:{default_profile:t.default_profile},profiles:r,...ec(t.directories,t=>t!==e)})}function nc(e){try{return E(re(e))}catch{return re(e)}}function rc(e){return qs().directories?.[nc(e)]??null}function ic(e,t){Ws(t);let n=qs();if(!Object.hasOwn(n.profiles,t))throw Error(`Profile "${t}" is not linked. Run catena link --profile ${t} <agent-id>.`);let r=nc(e);return Ys({...n,directories:{...n.directories,[r]:t}}),r}function ac(e){let t=qs(),n=nc(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 Ys({...o,...Object.keys(i).length===0?{}:{directories:i}}),{directory:n,removed:!0}}function oc(e){return Ws(e),qs().profiles[e]??null}function sc(){return`client_${_(16).toString(`hex`)}`}function cc(e,t){let n=oc(e);return t.agent_id===void 0?lc(e,t.bank_url,n):uc(e,t.bank_url,t.agent_id,n)}function lc(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`&&Qs(n.bank_url,t)?n.client_instance_id:null)??sc();return Xs(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 uc(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(!Qs(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`&&Qs(r.bank_url,t)?r.client_instance_id:null)??sc();return Xs(e,{status:`linked`,bank_url:t,agent_id:n,client_instance_id:i}),i}function dc(e){Ws(e);let t=qs();if(!Object.hasOwn(t.profiles,e))throw Error(`Profile "${e}" is not linked. Run catena link --profile ${e} <agent-id>.`);Ys({...t,default_profile:e})}function fc(e){let t=e.toLowerCase().replace(/[^a-z0-9._-]+/g,`-`).replace(/^[^a-z0-9]+/,``).slice(0,64);return Us(t)?t:`agent`}function pc(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 mc(e){Ws(e.reservationName),Ws(e.profileName);let t=f.parse(zs,e.profile);Fs(t.bank_url,`profile "${e.profileName}" bank_url`);let n=qs(),{[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]));Ys({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 hc(e){return e??js()}async function gc(e,t){let n;try{n=oc(e.profileName)}catch(t){return{ok:!1,profileName:e.profileName,bankUrl:e.fallbackBankUrl,message:go(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{Fs(n.bank_url,`profile "${e.profileName}" bank_url`)}catch(t){return{ok:!1,profileName:e.profileName,bankUrl:e.fallbackBankUrl,message:go(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 hc(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}: ${go(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 _c={name:`catena-cli`,version:se},vc=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function yc(e,t){if(!vc.test(e))throw Error(`${t} must be a valid HTTP token`)}function bc(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 xc(e){yc(e.name,`appInfo.name`),e.version!==void 0&&yc(e.version,`appInfo.version`),e.url!==void 0&&bc(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})`}}const Sc=`https://api.catena.com`,Cc=`CATENA_PROFILE`;function wc(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 Tc(e,t,n){if(e.flag!==void 0&&e.flag.length>0)return Ws(e.flag),{name:e.flag,source:`flag`};if(e.env!==void 0&&e.env.length>0){if(!Us(e.env))throw Error(`${Cc} is set to an invalid profile name "${e.env}"`);return{name:e.env,source:`env`}}if(e.cwd!==void 0){let r=wc(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 Ec(e){return Tc(e,qs(e.log),`ignore`)}function Dc(e){let t=qs(e.log),n=Tc(e,t,`error`);if(n!==null)return n;let r=Object.keys(t.profiles),i=Object.entries(t.profiles).filter(([,e])=>Zs(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 ${Cc}, run 'catena profiles use <name>', or run 'catena link' from an agent directory to bind it.`)}function Oc(e){return ho({baseUrl:e.bankUrl,privateKeyHex:e.signer.privateKeyHex,appInfo:_c})}function kc(){return js()}async function Ac(e){let t;try{t=Dc({flag:e,env:process.env[Cc],cwd:process.cwd(),log:e=>console.error(e)}).name}catch(e){return Z(e)}let n=await gc({profileName:t,fallbackBankUrl:Sc},void 0);return n.ok||Z(n.message),Oc(n)}const jc=new Set([`unknown_key`,`key_revoked`,`client_unlinked`]),Mc=new Set([`signature_auth_disabled`,`missing_auth`]);function Nc(e,t){if(!(e instanceof oo)||e.code===void 0)return e;let n=t===void 0?`catena link`:`catena link --profile ${t}`;return jc.has(e.code)?Error(`This machine's signing key was rejected by the bank (${e.code}). Run '${n}' to re-authenticate.`):e.code===`client_upgrade_required`?Error(`This CLI version (${_c.version}) is no longer supported by the bank. Run 'npm i -g @catena/cli' and retry.`):Mc.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 Pc(e,t){console.log(t?.compact?JSON.stringify(e):JSON.stringify(e,null,2))}function Fc(e){return e.profile===void 0||e.profile.length===0?void 0:e.profile}async function Ic(e,t){try{return await t(await Ac(e))}catch(t){return Z(Nc(t,e))}}function Lc(e,t){return async(n,r)=>{let i=await Ic(e,n);return Pc(i,t),await new Promise(e=>{process.stdout.write(``,()=>e())}),process.exit(r?.exitCode?r.exitCode(i):0)}}function Rc(e){return Lc(Fc(e),{compact:e.json===!0})}const zc=f.pipe(f.string(),f.regex(/^\d+$/,`must be a non-negative integer`),f.transform(Number),f.maxValue(2**53-1,`must be at most ${2**53-1}`)),Bc=f.pipe(zc,f.maxValue(200,`must be at most 200`)),Vc={profile:Lo,json:Ro},Hc=$(Vc),Uc=$({account:wo({description:`Account id`,required:!0,schema:Bo}),...Vc}),Wc=$({account:wo({description:`Account id`,required:!0,schema:Bo}),start:Q({description:`Only include transactions at or after this ISO 8601 time`}),end:Q({description:`Only include transactions at or before this ISO 8601 time`}),limit:Q({description:`Maximum transactions to return (default 50, max 200)`,schema:Bc}),offset:Q({description:`Number of transactions to skip for pagination`,schema:zc}),...Vc}),Gc=$({account:wo({description:`Account id`,required:!0,schema:Bo}),network:Go({description:`Deposit network; defaults to ${Uo}. Availability depends on the connected environment.`,default:Uo}),asset:Do({description:`Deposit asset (${Ho.join(`|`)})`,choices:Ho,default:`usdc`}),...Vc}),Kc=l({meta:{name:`list`,description:`List accounts accessible under the agent's policy`},args:Hc.args,async run({args:e}){await Rc(Hc.parse(e))(e=>e.listAccounts())}}),qc=l({meta:{name:`balance`,description:`Request an account balance through the policy engine`},args:Uc.args,async run({args:e}){let t=Uc.parse(e);await Rc(t)(e=>e.getAccountBalance(t.account))}}),Jc=l({meta:{name:`transactions`,description:`Read an account's transaction history through the policy engine`},args:Wc.args,async run({args:e}){let t=Wc.parse(e);await Rc(t)(e=>e.listAccountTransactions(t.account,{start:t.start,end:t.end,limit:t.limit,offset:t.offset}))}}),Yc=l({meta:{name:`deposit-address`,description:`Read an account deposit address through the policy engine`},args:Gc.args,async run({args:e}){let t=Gc.parse(e);await Rc(t)(e=>e.getAccountDepositAddress(t.account,{network:t.network,asset:t.asset}))}}),Xc=l({meta:{name:`accounts`,description:`Inspect bank accounts`},subCommands:{list:Kc,balance:qc,transactions:Jc,"deposit-address":Yc}}),Zc=f.pipe(f.string(`Idempotency key must be a string`),f.minLength(1,`Idempotency key must not be empty`),f.maxLength(255,`Idempotency key is too long (max 255 characters)`)),Qc=f.pipe(f.string(),f.minLength(1,`must not be empty`)),$c=f.pipe(f.string(),f.trim(),f.email(`must be a valid email address`)),el={profile:Lo,json:Ro},tl=$({address:Q({description:`Only counterparties with a wallet rail matching this address (0x…)`,schema:Wo}),network:Go({description:`Only counterparties with a wallet rail on this network (e.g. base)`}),...el}),nl=Q({description:`Counterparty name`,required:!0,schema:Qc}),rl=Q({description:`Optional contact email`,schema:$c}),il=$({name:nl,email:Q({description:`Contact email; creating the counterparty sends no email`,required:!0,schema:$c}),...el}),al=$({name:Q({description:`Counterparty name; required without a subcommand`,schema:Qc}),email:Q({description:`Contact email; required without a subcommand; creating the counterparty sends no email`,schema:$c}),...el}),ol=$({name:nl,"bank-name":Q({description:`Receiving bank name`,required:!0,schema:Qc}),"routing-number":Q({description:`9-digit ABA routing number`,required:!0,schema:Qc}),"account-number":Q({description:`Receiving bank account number`,required:!0,schema:Qc}),"account-type":Do({description:`checking | savings (default checking)`,choices:[`checking`,`savings`]}),"address-street":Q({description:`Street address of the receiving bank account holder`,required:!0,schema:Qc}),"address-city":Q({description:`City`,required:!0,schema:Qc}),"address-state":Q({description:`State (e.g. NY)`,required:!0,schema:Qc}),"address-postal-code":Q({description:`Postal code`,required:!0,schema:Qc}),"address-country":Q({description:`Default USA`}),email:rl,...el}),sl=$({name:nl,address:Q({description:`Wallet address (0x… or ENS name on EVM networks)`,required:!0,schema:Qc}),network:Go({description:`Wallet network; defaults to ${Uo}. Availability depends on the connected environment.`,default:Uo}),email:rl,...el}),cl=$({counterparty:wo({description:`Counterparty id`,required:!0,schema:Bo}),bank:Eo({description:`Request bank account details`,default:!1}),wallet:Eo({description:`Request wallet details`,default:!1}),"idempotency-key":Q({description:`Optional key to replay this exact submission`,schema:Zc}),...el}),ll=l({meta:{name:`list`,description:`List counterparties available under the agent's policy`},args:tl.args,async run({args:e}){let t=tl.parse(e);await Rc(t)(e=>e.listCounterparties({address:t.address,network:t.network}))}});function ul(e){return e&&e.length>0?e:void 0}function dl(e){let t=ul(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 fl(e){let t=ul(e.email);return{type:`create_counterparty`,name:e.name,email:t,rail:{type:`wallet`,walletAddress:e.address,network:e.network}}}function pl(e){return{type:`create_counterparty`,name:e.name,email:e.email}}const ml=l({meta:{name:`email`,description:`Create a counterparty with an email and no payment details. Sends no email.`},args:il.args,async run({args:e}){let t=il.parse(e);await Rc(t)(e=>e.submitIntent({action:pl(t)}))}}),hl=l({meta:{name:`bank`,description:`Request bank counterparty creation through the policy engine. Prints an intent envelope.`},args:ol.args,async run({args:e}){let t=ol.parse(e),n=dl(t);await Rc(t)(e=>e.submitIntent({action:n}))}}),gl=l({meta:{name:`wallet`,description:`Request wallet counterparty creation through the policy engine. Prints an intent envelope.`},args:sl.args,async run({args:e}){let t=sl.parse(e);await Rc(t)(e=>e.submitIntent({action:fl(t)}))}}),_l=l({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:al.args,default:`email`,subCommands:{email:ml,bank:hl,wallet:gl}}),vl=l({meta:{name:`request-details`,description:`Ask a counterparty to provide bank details, wallet details, or both through the policy engine.`},args:cl.args,async run({args:e}){let t=cl.parse(e);!t.bank&&!t.wallet&&Z(`Select at least one of --bank or --wallet`),await Rc(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`]}:{}}))}}),yl=l({meta:{name:`counterparties`,description:`Inspect, create, and request details from counterparties`},subCommands:{list:ll,create:_l,"request-details":vl}}),bl=4e3;async function xl(){process.stdin.setEncoding(`utf8`);let e=``;for await(let t of process.stdin)e+=t;return e}async function Sl(e){return e===void 0?(process.stdin.isTTY&&Z(`<message>: pass a quoted message or pipe it on stdin; a message starting with "-" needs -- before it (catena feedback -- "<message>") or stdin`),xl()):e}const Cl=$({message:wo({description:`Plain-text feedback (1-4000 chars); omit to pipe on stdin`}),profile:Lo,json:Ro}),wl=l({meta:{name:`feedback`,description:`Send free-form feedback about Catena to the Catena team`},args:Cl.args,async run({args:e}){(Array.isArray(e._)?e._:[]).length>1&&Z(`<message>: pass the message as a single quoted argument`);let t=Cl.parse(e),n=(await Sl(t.message)).trim();n.length===0&&Z(`<message>: must not be empty`),n.length>bl&&Z(`<message>: must be at most ${bl} characters (got: ${n.length})`),await Rc(t)(async e=>(await e.submitFeedback(n),{ok:!0}))}});function Tl(e){return`# Catena CLI Agent Guide
136
+ `),s=v(`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 ha(e){return`sha-256=:${h(`sha256`).update(e??``).digest(`base64`)}:`}function ga(e){return`${e.protocol}//${_a(e)}${e.pathname}${e.search}`}function _a(e){let t=e.host.toLowerCase();return e.protocol===`https:`&&e.port===`443`||e.protocol===`http:`&&e.port===`80`?e.hostname.toLowerCase():t}function va(e,t){return g({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 ya=`0.1.0`;const ba=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,xa=ya;function Sa(e,t){if(!ba.test(e))throw Error(`${t} must be a valid HTTP token`)}function Ca(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 wa(e){let t=`catena-agent-client/${xa}`;if(!e)return t;Sa(e.name,`appInfo.name`),e.version!==void 0&&Sa(e.version,`appInfo.version`),e.url!==void 0&&Ca(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 Ta=f.pipe(f.string(),f.regex(/\S/,`Response enum values must not be blank`));function Ea(e){return Ta}const Da=f.object({amount:f.string(),asset_id:f.string()}),Oa=f.pipe(f.string(),f.isoTimestamp()),ka=f.object({success:f.literal(!0)}),Aa=f.object({id:f.string(),name:f.string(),status:f.string(),organizationId:f.string()}),ja=f.object({agent:Aa}),Ma=f.object({id:f.string(),ruleType:Ea([`per_transaction_amount`,`daily_amount`,`weekly_amount`,`monthly_amount`,`hourly_count`,`daily_count`]),thresholdAmount:f.optional(Da),thresholdCount:f.optional(f.number()),action:Ea([`block`,`require_approval`]),requiredApprovals:f.number(),accountAggregationScope:Ea([`per_account`,`across_accounts`]),actorAggregationScope:Ea([`per_agent`,`per_policy`]),displayOrder:f.number()}),Na=f.object({id:f.string(),organizationId:f.string(),policyId:f.string(),capability:Ea([`query_balance`,`read`,`send`,`transfer`]),accountId:f.string(),rules:f.array(Ma),createdAt:Oa,updatedAt:Oa}),Pa=[`allow`,`block`,`require_approval`],Fa=[`open`,`restricted`],Ia=Ea(Pa),La=f.object({mode:Ea(Fa),allowedCounterparties:f.optional(f.array(f.string())),createAction:f.optional(Ia),requestPaymentDetailsAction:f.optional(Ia),allowCreate:f.optional(f.boolean())}),Ra=f.object({id:f.optional(f.string()),description:f.optional(f.string()),version:f.optional(f.number()),name:f.string(),capabilities:f.array(f.string()),counterpartyRules:f.optional(La),policyCapabilities:f.array(Na)}),za=f.object({policy:Ra}),Ba=f.object({accounts:f.array(f.object({id:f.string(),name:f.string(),type:f.string(),currency:f.string()}))}),Va=f.object({accountId:f.string(),balance:Da,balances:f.optional(f.object({total:Da,available:Da}))}),Ha=[`operator-send`,`operator-transfer`,`operator-deposit`,`operator-refund`,`microdeposit`],Ua=[`pending`,`processing`,`completed`,`failed`,`reversed`],Wa=[`initiated`,`provider_pending`,`processing`,`completed`,`failed`,`reversed`,`manual_review`],Ga=[`ach`,`wire`,`on-chain`],Ka=f.object({id:f.string(),type:Ea(Ha),action:f.optional(f.string()),status:Ea(Ua),movementStatus:Ea(Wa),direction:f.picklist([`incoming`,`outgoing`]),amount:Da,fee:Da,currency:f.string(),counterpartyName:f.optional(f.string()),method:f.optional(Ea([`ach`,`wire`,`on-chain`])),memo:f.optional(f.string()),description:f.optional(f.string()),txHash:f.optional(f.string()),createdAt:Oa,completedAt:f.optional(Oa)}),qa=f.object({accountId:f.string(),transactions:f.array(Ka),total:f.number()}),Ja=f.object({accountId:f.string(),address:f.string(),liquidationAddressId:f.optional(f.string()),source:Ea([`wallet`,`liquidation`])}),Ya=f.object({id:f.string(),name:f.string(),status:f.optional(f.string()),rails:f.array(f.object({id:f.string(),type:f.string(),walletAddress:f.optional(f.string()),network:f.optional(f.string()),bankName:f.optional(f.string()),accountNumber:f.optional(f.string())}))}),Xa=f.object({counterparties:f.array(Ya)}),Za=f.picklist([`pending`,`processing`,`completed`,`blocked`,`failed`]),Qa=f.object({type:f.literal(`submit_stamp`),signingRequestId:f.string(),signer:f.object({algorithm:f.literal(`p256`),publicKeyHex:f.string()}),preparedBody:f.object({body:f.string(),bodyHash:f.string(),expiresAt:Oa,prepareToken:f.string()})}),$a=f.object({id:f.string(),type:Ea([`send`,`transfer`,`create_counterparty`,`request_counterparty_details`,`x402`]),status:Za,reasons:f.array(f.string()),expiresAt:f.optional(f.nullable(Oa),null),replayed:f.optional(f.boolean(),!1),data:f.optional(f.nullable(f.record(f.string(),f.unknown())),null),metadata:f.optional(f.object({dataUrl:f.nullable(f.string())})),nextAction:f.optional(Qa)});function eo(e){let{nextAction:t,...n}=e;return n}const to=f.picklist(Ga),no=f.object({type:f.literal(`send`),accountId:f.string(),counterpartyRailId:f.string(),amount:f.string(),method:to,memo:f.optional(f.string()),description:f.optional(f.string())}),ro=f.object({type:f.literal(`transfer`),accountId:f.string(),toAccountId:f.string(),amount:f.string(),memo:f.optional(f.string()),description:f.optional(f.string())}),io={type:f.literal(`create_counterparty`),name:f.string()},ao=f.union([f.object({...io,email:f.optional(f.string()),rail:f.nonOptional(f.unknown())}),f.object({...io,email:f.string()})]),oo=f.object({type:f.literal(`request_counterparty_details`),counterpartyId:f.string(),methods:f.pipe(f.object({bank:f.boolean(),wallet:f.boolean()}),f.check(({bank:e,wallet:t})=>e||t,`Select at least one payment method to request`))}),so=f.looseObject({scheme:f.string(),network:f.string(),asset:f.string(),amount:f.string(),payTo:f.string(),maxTimeoutSeconds:f.number()}),co=f.looseObject({url:f.string(),serviceName:f.fallback(f.optional(f.pipe(f.string(),f.maxLength(255))),void 0)}),lo=f.object({type:f.literal(`x402`),accountId:f.string(),paymentRequirements:so,resource:f.optional(co)}),uo=f.union([no,ro,ao,oo,lo]);function fo(e){let t=f.parse(uo,e);return t.type===`send`||t.type===`transfer`?{...t,amount:{amount:t.amount,asset_id:`USD`}}:t}const po=f.object({intent:$a});var mo=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}},ho=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 go=f.object({error:f.nullish(f.string()),message:f.nullish(f.string()),code:f.nullish(f.string()),details:f.nullish(f.record(f.string(),f.unknown()))});async function _o(e){let t=f.safeParse(go,await e.json().catch(()=>void 0)),n=t.success?t.output:{};return n.error!=null&&n.message!=null?new mo(e.status,n.message,n.code??n.error,n.details??void 0):new mo(e.status,n.error??n.message??e.statusText,n.code??void 0,n.details??void 0)}async function vo(e,t){if(!e.ok)throw await _o(e);return f.parse(t,await e.json())}var yo=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 bo=2147483647;var xo=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>bo)throw TypeError(`timeout must be a positive integer no greater than ${bo}`);this.#e=e.baseUrl??`https://api.catena.com`,this.#t=wa(e.appInfo),this.#n=e.defaultHeaders??{},this.#r=ia(e.privateKeyHex),this.#a=(e.fetch??globalThis.fetch).bind(globalThis),this.#o=t,this.#i=da({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 ho(this.#o);t(e),n.abort(e)},this.#o)}),a=this.#a(r).then(e=>vo(e,t));return await Promise.race([a,e])}finally{i!==void 0&&clearTimeout(i)}}async whoami(){return(await this.#l({method:`GET`,path:`/me`},ja)).agent}async submitFeedback(e){await this.#l({method:`POST`,path:`/feedback`,body:{body:e}},ka)}async getPolicy(){return(await this.#l({method:`GET`,path:`/policy`},za)).policy}async listAccounts(){return this.#l({method:`GET`,path:`/accounts`},Ba)}async getAccountBalance(e){return this.#l({method:`GET`,path:`/accounts/${encodeURIComponent(e)}/balance`},Va)}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()}},qa)}async getAccountDepositAddress(e,t){return this.#l({method:`GET`,path:`/accounts/${encodeURIComponent(e)}/deposit-address`,query:{network:t.network,asset:t.asset}},Ja)}async listCounterparties(e={}){return this.#l({method:`GET`,path:`/counterparties`,query:{address:e.address,network:e.network}},Xa)}async submitIntent(e){let t=await this.#d(e),n=t.nextAction;if(!n)return eo(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 yo({intentId:t.id,outcome:`not-submitted`,cause:e})}try{return await this.#p(r,t.replayed)}catch(e){throw new yo({intentId:t.id,outcome:`unknown`,cause:e})}}async#d(e){return this.#l({method:`POST`,path:`/intents`,body:{action:fo(e.action)},...e.idempotencyKey!==void 0&&{headers:{"Idempotency-Key":e.idempotencyKey}}},$a)}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 ea({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=eo((await this.#u(e,po)).intent);return t?{...n,replayed:!0}:n}async getIntent(e){return eo(await this.#l({method:`GET`,path:`/intents/${encodeURIComponent(e)}`},$a))}async unlinkAgent(){await this.#l({method:`POST`,path:`/unlink`},ka)}async reportSettlement(e){await this.#l({method:`POST`,path:`/intents/${encodeURIComponent(e.intentId)}/settlement-report`,body:{txHash:e.txHash}},ka)}};function So(e={}){let t=e.privateKeyHex===void 0?process.env.CATENA_SECRET_KEY:e.privateKeyHex;if(t===void 0)throw new ta(`privateKeyHex is required; pass it explicitly or set CATENA_SECRET_KEY`);return new xo({...e,privateKeyHex:t})}function Co(e){let t=e instanceof Error?e.message:String(e);return e instanceof mo&&e.details!==void 0?`${t}\nDetails:\n${JSON.stringify(e.details,null,2)}`:t}function Z(e){console.error(Co(e)),process.exit(1)}const wo=f.string(),To=f.boolean();function Eo(e){return e===void 0}function Do(e){return e.issues?.[0]?.message??`Invalid value`}function Oo(e,t,n,r){return Z(`${e}: ${t}${r?` (got: ${String(n)})`:``}`)}function ko(e,t,n,r){let i=f.safeParse(e,t);return i.success?i.output:Oo(n,Do(i),t,r)}function Ao(e,t){let n=t.schema??wo;return{type:e,description:t.description,negativeDescription:t.negativeDescription,required:t.required,default:t.default,parseValue(e,r){let i=Eo(e)?t.default:e;if(Eo(i)){t.required===!0&&Z(`${r} is required`);return}return ko(n,i,r,t.showValueInError===!0)}}}function Q(e){return Ao(`string`,e)}function jo(e){return Ao(`positional`,e)}function Mo(e){let t=e.schema??wo;return{type:`string`,description:e.description,repeatable:!0,parseValue(n,r){return(Array.isArray(n)?n:[]).map(n=>ko(t,n,r,e.showValueInError===!0))}}}function No(e){return{type:`boolean`,description:e.description,negativeDescription:e.negativeDescription,required:e.required,default:e.default,parseValue(t,n){let r=Eo(t)?e.default:t;if(Eo(r)){e.required===!0&&Z(`${n} is required`);return}return ko(To,r,n,!1)}}}function Po(e){return Fo(`string`,e)}function Fo(e,t){return Ao(e,{description:t.description,required:t.required,default:t.default,schema:f.picklist(t.choices,`must be one of ${t.choices.join(`|`)}`),showValueInError:!0})}function Io(e,t){return t.type===`positional`?`<${e}>`:`--${e}`}function Lo(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 Ro(e){return Lo(e).join(`-`).toLowerCase()}function zo(e){return Lo(e).map((e,t)=>t===0?e.charAt(0).toLowerCase()+e.slice(1):e.charAt(0).toUpperCase()+e.slice(1)).join(``)}function Bo(e){return[`--${e}`,`--${Ro(e)}`,`--${zo(e)}`]}function Vo(e){let t=e.indexOf(`=`);return t===-1?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function Ho(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(Bo(t)),s=new Set(Object.entries(n).filter(([e,n])=>e!==t&&n.type===`string`).flatMap(([e])=>Bo(e))),c=[];for(let e=0;e<a.length;e++){let t=a[e];if(t===`--`)break;let[n,r]=Vo(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 Uo(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 $(e){return{args:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Uo(t)])),label(t){return Io(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 Ho(n,r,e)};return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.parseValue(r(e,t),Io(e,t))]))}}}const Wo=Q({description:`Credential profile name`}),Go=No({description:`Print compact single-line JSON (for piping)`,default:!1}),Ko=/^[a-zA-Z0-9_-]+$/,qo=f.pipe(f.string(`ID must be a string`),f.minLength(1,`ID must not be empty`),f.maxLength(256,`ID is too long (max 256 characters)`),f.regex(Ko,`ID may only contain letters, digits, hyphens, and underscores`)),Jo=[`base`,`base-sepolia`],Yo=[`usdc`],Xo=`base`,Zo=f.pipe(f.string(),f.trim(),f.guard(e=>/^0x[0-9a-fA-F]{40}$/.test(e),`Must be a 0x-prefixed hex wallet address`));function Qo(e){return Po({description:e.description,choices:Jo,...e.default===void 0?{}:{default:e.default}})}const $o=[`registered`,`already_registered`,`not_applicable`,`registration_failed`],es=f.pipe(f.string(),f.regex(/^0[23][0-9a-f]{64}$/)),ts=f.pipe(f.string(),f.regex(/^[0-9a-f]{64}$/)),ns=f.object({status:f.picklist($o),publicKeyHex:f.optional(es),reason:f.optional(f.string())}),rs=f.object({algorithm:f.literal(`p256`),privateKeyHex:ts,publicKeyHex:es,registration:ns}),is=f.object({version:f.literal(`signer-1`),signer:rs}),as=f.object({version:f.literal(1),refreshToken:f.pipe(f.string(),f.minLength(1)),sessionToken:f.pipe(f.string(),f.minLength(1)),expiresAt:f.pipe(f.string(),f.isoTimestamp())}),os=f.object({version:f.literal(2),refreshToken:f.pipe(f.string(),f.minLength(1)),sessionToken:f.pipe(f.string(),f.minLength(1)),expiresAt:f.pipe(f.string(),f.isoTimestamp()),signer:rs}),ss=f.object({version:f.literal(3),signer:rs}),cs=f.variant(`version`,[as,os,ss]),ls=f.variant(`version`,[is,as,os,ss]);function us(e){return f.parse(cs,e)}function ds(e){return f.parse(ls,e)}function fs(e){let t=f.safeParse(ls,e);return t.success?t.output:null}function ps(e){return{version:`signer-1`,signer:{algorithm:e.algorithm,privateKeyHex:e.privateKeyHex,publicKeyHex:e.publicKeyHex,registration:{status:`not_applicable`,reason:`pending_claim`}}}}function ms(e,t){try{return ds(JSON.parse(e))}catch(e){throw Error(`${t} credential has an unsupported format`,{cause:e})}}function hs(e){return us({version:3,signer:e})}function gs(e){return JSON.stringify(e)}function _s(e,t){return JSON.stringify(e)===JSON.stringify(t)}function vs(e){return(t,n)=>ys(e,t,n)}function ys(e,t,n){return new Promise((r,i)=>{let a=b(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 bs=`catena-agent`;function xs(e){if(!Ko.test(e))throw Error(`Invalid credential location for credential storage: "${e}"`);return e}const Ss=vs(`/usr/bin/secret-tool`);function Cs(e){return e.status===1&&e.stdout===``&&e.stderr.trim()===``}function ws(e,t){if(t.status===0)return;let n=Ts(t);throw Error(`Linux Secret Service credential ${e} failed (secret-tool exited ${t.status??`without status`}): ${n}`)}function Ts(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 Es(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 Ds=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??Ss}async save(e,t){let n=ds(t),r=xs(e);if(await this.savePassword(r,gs(n)),!_s(await this.resolveDirectPassword(r),n))throw Error(`Linux Secret Service credential save verification failed`)}async resolve(e){return this.resolveDirectPassword(xs(e))}async delete(e){await this.deletePassword(xs(e))}async savePassword(e,t){ws(`save`,await this.runSecretToolCommand([`store`,`--label`,`${bs} ${e}`,`app`,bs,`account`,e],t))}async resolvePassword(e){let t=await this.runSecretToolCommand([`lookup`,`app`,bs,`account`,e]);return Cs(t)?null:(ws(`resolve`,t),t.stdout.replace(/\r?\n$/,``))}async resolveDirectPassword(e){let t=await this.resolvePassword(e);return t===null?null:ms(t,`Linux Secret Service`)}async deletePassword(e){let t=await this.runSecretToolCommand([`clear`,`app`,bs,`account`,e]);Cs(t)||ws(`delete`,t)}async runSecretToolCommand(e,t){try{return await this.runSecretTool(e,t)}catch(e){throw Es(e)}}};const Os=vs(`/usr/bin/security`),ks=f.object({version:f.literal(1),encoding:f.literal(`base64-json`),chunks:f.pipe(f.number(),f.integer(),f.minValue(1),f.maxValue(64)),sha256:f.pipe(f.string(),f.regex(/^[a-f0-9]{64}$/))});function As(e){return e.status===44}function js(e,t){return`${e}:chunk:${t}`}function Ms(e){let t=JSON.parse(e),n=fs(t);if(n!==null)return{kind:`direct`,payload:n};let r=f.safeParse(ks,t);if(r.success)return{kind:`legacy`,manifest:r.output};throw Error(`macOS Keychain credential has an unsupported format`)}function Ns(e,t){if(t.status===0)return;let n=Ps(t);throw Error(`macOS Keychain credential ${e} failed (security exited ${t.status??`without status`})${n===null?``:`: ${n}`}`)}function Ps(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 Fs(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 Is(e,t){return[`add-generic-password`,`-s`,Fs(bs),`-a`,Fs(e),`-w`,Fs(t),`-U`].join(` `)+`
137
+ `}var Ls=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??Os}async save(e,t){let n=ds(t),r=xs(e),i=await this.resolveLegacyChunkCount(r,64);if(await this.savePassword(r,gs(n)),!_s(await this.resolveDirectPassword(r),n))throw Error(`macOS Keychain credential save verification failed`);await this.deleteChunks(r,i)}async resolve(e){let t=xs(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=xs(e),n=await this.resolveLegacyChunkCount(t,64);await this.deleteChunks(t,n),await this.deletePassword(t)}async savePassword(e,t){Ns(`save`,await this.runSecurity([`-i`],Is(e,t)))}async resolvePassword(e){let t=await this.runSecurity([`find-generic-password`,`-a`,e,`-s`,bs,`-w`]);return As(t)?null:(Ns(`resolve`,t),t.stdout.replace(/\r?\n$/,``))}async resolveKeychainItem(e){let t=await this.resolvePassword(e);return t===null?null:Ms(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(js(e,r));if(t===null)throw Error(`macOS Keychain credential chunk is missing`);n.push(t)}let r=n.join(``);if(h(`sha256`).update(r).digest(`hex`)!==t.sha256)throw Error(`macOS Keychain credential checksum mismatch`);return ds(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=Ms(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(js(e,n))}async deletePassword(e){let t=await this.runSecurity([`delete-generic-password`,`-a`,e,`-s`,bs]);As(t)||Ns(`delete`,t)}};function Rs(e={}){let t=e.platform??process.platform;if(t===`darwin`)return new Ls({platform:t});if(t===`linux`)return new Ds({platform:t});throw Error(`Catena credential storage is only supported on macOS and Linux`)}const zs=/^127(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}$/;function Bs(e){let t=e.replace(/^\[|\]$/g,``);return t===`localhost`||t===`::1`||zs.test(t)}function Vs(e){let t;try{t=new URL(e)}catch{return!1}return t.protocol===`https:`||t.protocol===`http:`&&Bs(t.hostname)}function Hs(e,t){if(!Vs(e))throw Error(`${t} must be an https:// URL (http:// is allowed only for a loopback host): "${e}"`)}const Us=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/,Ws=f.object({status:f.optional(f.literal(`linked`),`linked`),bank_url:f.pipe(f.string(),f.minLength(1)),agent_id:f.pipe(f.string(),f.minLength(1)),client_instance_id:f.pipe(f.string(),f.regex(Ko))}),Gs=f.object({status:f.literal(`pending_connection`),bank_url:f.pipe(f.string(),f.minLength(1)),client_instance_id:f.pipe(f.string(),f.regex(Ko)),created_at:f.pipe(f.string(),f.isoTimestamp())}),Ks=f.variant(`status`,[Ws,Gs]);f.object({version:f.literal(1),default_profile:f.optional(f.string()),profiles:f.record(f.string(),Ks),directories:f.optional(f.record(f.string(),f.string()))});const qs=f.object({version:f.literal(1),default_profile:f.optional(f.string()),profiles:f.record(f.string(),f.unknown()),directories:f.optional(f.record(f.string(),f.unknown()))});function Js(){return ne(process.env.HOME??j(),`.catena`)}function Ys(){return ne(Js(),`profiles.json`)}function Xs(e){return Us.test(e)}function Zs(e){if(!Xs(e))throw Error(`invalid profile name "${e}" (expected [a-zA-Z0-9][a-zA-Z0-9._-]{0,63})`)}function Qs(e){return typeof e!=`object`||!e||!(`code`in e)?!1:typeof e.code==`string`}function $s(e,t){let n;try{n=JSON.parse(e)}catch(e){throw Error(`profiles.json is not valid JSON: ${Co(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=f.parse(qs,n),i={};for(let[e,n]of Object.entries(r.profiles)){if(!Xs(e)){t?.(`profiles: dropping invalid profile name "${e}"`);continue}let r=f.safeParse(Ks,n);if(!r.success){t?.(`profiles: dropping malformed profile "${e}"`);continue}i[e]=r.output}if(r.default_profile!==void 0&&(Zs(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(!te(e)){t?.(`profiles: dropping directory binding with relative path "${e}"`);continue}if(typeof n!=`string`||!Xs(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 ec(e){try{return $s(ee(Ys(),`utf-8`),e)}catch(e){if(e instanceof Error&&Qs(e)&&e.code===`ENOENT`)return{version:1,profiles:{}};throw e}}function tc(){T(Js(),{recursive:!0,mode:448}),S(Js(),448)}function nc(e){tc();let t=Ys(),n=`${t}.${_(6).toString(`hex`)}.tmp`;A(n,JSON.stringify(e,null,2)+`
138
+ `,{encoding:`utf-8`,mode:384}),D(n,t)}function rc(e,t){Zs(e);let n=f.parse(Ks,t);Hs(n.bank_url,`profile "${e}" bank_url`);let r=ec();nc({...r,profiles:{...r.profiles,[e]:n}})}function ic(e){return e.status===`linked`}function ac(e,t){return e.replace(/\/+$/,``)===t.replace(/\/+$/,``)}function oc(e,t){let n=Object.entries(ec().profiles).toSorted(([e],[t])=>e.localeCompare(t)).find(([,n])=>ic(n)&&n.agent_id===e&&ac(n.bank_url,t));return n===void 0?null:n[0]}function sc(e,t){let n=Object.fromEntries(Object.entries(e??{}).filter(([,e])=>t(e)));return Object.keys(n).length===0?{}:{directories:n}}function cc(e){Zs(e);let t=ec(),{[e]:n,...r}=t.profiles;nc({version:1,...t.default_profile===e||t.default_profile===void 0?{}:{default_profile:t.default_profile},profiles:r,...sc(t.directories,t=>t!==e)})}function lc(e){try{return E(re(e))}catch{return re(e)}}function uc(e){return ec().directories?.[lc(e)]??null}function dc(e,t){Zs(t);let n=ec();if(!Object.hasOwn(n.profiles,t))throw Error(`Profile "${t}" is not linked. Run catena link --profile ${t} <agent-id>.`);let r=lc(e);return nc({...n,directories:{...n.directories,[r]:t}}),r}function fc(e){let t=ec(),n=lc(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 nc({...o,...Object.keys(i).length===0?{}:{directories:i}}),{directory:n,removed:!0}}function pc(e){return Zs(e),ec().profiles[e]??null}function mc(){return`client_${_(16).toString(`hex`)}`}function hc(e,t){let n=pc(e);return t.agent_id===void 0?gc(e,t.bank_url,n):_c(e,t.bank_url,t.agent_id,n)}function gc(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`&&ac(n.bank_url,t)?n.client_instance_id:null)??mc();return rc(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 _c(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(!ac(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`&&ac(r.bank_url,t)?r.client_instance_id:null)??mc();return rc(e,{status:`linked`,bank_url:t,agent_id:n,client_instance_id:i}),i}function vc(e){Zs(e);let t=ec();if(!Object.hasOwn(t.profiles,e))throw Error(`Profile "${e}" is not linked. Run catena link --profile ${e} <agent-id>.`);nc({...t,default_profile:e})}function yc(e){let t=e.toLowerCase().replace(/[^a-z0-9._-]+/g,`-`).replace(/^[^a-z0-9]+/,``).slice(0,64);return Xs(t)?t:`agent`}function bc(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 xc(e){Zs(e.reservationName),Zs(e.profileName);let t=f.parse(Ks,e.profile);Hs(t.bank_url,`profile "${e.profileName}" bank_url`);let n=ec(),{[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]));nc({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 Sc(e){return e??Rs()}async function Cc(e,t){let n;try{n=pc(e.profileName)}catch(t){return{ok:!1,profileName:e.profileName,bankUrl:e.fallbackBankUrl,message:Co(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{Hs(n.bank_url,`profile "${e.profileName}" bank_url`)}catch(t){return{ok:!1,profileName:e.profileName,bankUrl:e.fallbackBankUrl,message:Co(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 Sc(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}: ${Co(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 wc={name:`catena-cli`,version:se},Tc=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function Ec(e,t){if(!Tc.test(e))throw Error(`${t} must be a valid HTTP token`)}function Dc(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 Oc(e){Ec(e.name,`appInfo.name`),e.version!==void 0&&Ec(e.version,`appInfo.version`),e.url!==void 0&&Dc(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})`}}const kc=`https://api.catena.com`,Ac=`CATENA_PROFILE`;function jc(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 Mc(e,t,n){if(e.flag!==void 0&&e.flag.length>0)return Zs(e.flag),{name:e.flag,source:`flag`};if(e.env!==void 0&&e.env.length>0){if(!Xs(e.env))throw Error(`${Ac} is set to an invalid profile name "${e.env}"`);return{name:e.env,source:`env`}}if(e.cwd!==void 0){let r=jc(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 Nc(e){return Mc(e,ec(e.log),`ignore`)}function Pc(e){let t=ec(e.log),n=Mc(e,t,`error`);if(n!==null)return n;let r=Object.keys(t.profiles),i=Object.entries(t.profiles).filter(([,e])=>ic(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 ${Ac}, run 'catena profiles use <name>', or run 'catena link' from an agent directory to bind it.`)}function Fc(e){return So({baseUrl:e.bankUrl,privateKeyHex:e.signer.privateKeyHex,appInfo:wc})}function Ic(){return Rs()}async function Lc(e){let t;try{t=Pc({flag:e,env:process.env[Ac],cwd:process.cwd(),log:e=>console.error(e)}).name}catch(e){return Z(e)}let n=await Cc({profileName:t,fallbackBankUrl:kc},void 0);return n.ok||Z(n.message),Fc(n)}const Rc=new Set([`unknown_key`,`key_revoked`,`client_unlinked`]),zc=new Set([`signature_auth_disabled`,`missing_auth`]);function Bc(e,t){if(!(e instanceof mo)||e.code===void 0)return e;let n=t===void 0?`catena link`:`catena link --profile ${t}`;return Rc.has(e.code)?Error(`This machine's signing key was rejected by the bank (${e.code}). Run '${n}' to re-authenticate.`):e.code===`client_upgrade_required`?Error(`This CLI version (${wc.version}) is no longer supported by the bank. Run 'npm i -g @catena/cli' and retry.`):zc.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 Vc(e,t){console.log(t?.compact?JSON.stringify(e):JSON.stringify(e,null,2))}function Hc(e){return e.profile===void 0||e.profile.length===0?void 0:e.profile}async function Uc(e,t){try{return await t(await Lc(e))}catch(t){return Z(Bc(t,e))}}function Wc(e,t){return async(n,r)=>{let i=await Uc(e,n);return Vc(i,t),await new Promise(e=>{process.stdout.write(``,()=>e())}),process.exit(r?.exitCode?r.exitCode(i):0)}}function Gc(e){return Wc(Hc(e),{compact:e.json===!0})}const Kc=f.pipe(f.string(),f.regex(/^\d+$/,`must be a non-negative integer`),f.transform(Number),f.maxValue(2**53-1,`must be at most ${2**53-1}`)),qc=f.pipe(Kc,f.maxValue(200,`must be at most 200`)),Jc={profile:Wo,json:Go},Yc=$(Jc),Xc=$({account:jo({description:`Account id`,required:!0,schema:qo}),...Jc}),Zc=$({account:jo({description:`Account id`,required:!0,schema:qo}),start:Q({description:`Only include transactions at or after this ISO 8601 time`}),end:Q({description:`Only include transactions at or before this ISO 8601 time`}),limit:Q({description:`Maximum transactions to return (default 50, max 200)`,schema:qc}),offset:Q({description:`Number of transactions to skip for pagination`,schema:Kc}),...Jc}),Qc=$({account:jo({description:`Account id`,required:!0,schema:qo}),network:Qo({description:`Deposit network; defaults to ${Xo}. Availability depends on the connected environment.`,default:Xo}),asset:Po({description:`Deposit asset (${Yo.join(`|`)})`,choices:Yo,default:`usdc`}),...Jc}),$c=l({meta:{name:`list`,description:`List accounts accessible under the agent's policy`},args:Yc.args,async run({args:e}){await Gc(Yc.parse(e))(e=>e.listAccounts())}}),el=l({meta:{name:`balance`,description:`Request an account balance through the policy engine`},args:Xc.args,async run({args:e}){let t=Xc.parse(e);await Gc(t)(e=>e.getAccountBalance(t.account))}}),tl=l({meta:{name:`transactions`,description:`Read an account's transaction history through the policy engine`},args:Zc.args,async run({args:e}){let t=Zc.parse(e);await Gc(t)(e=>e.listAccountTransactions(t.account,{start:t.start,end:t.end,limit:t.limit,offset:t.offset}))}}),nl=l({meta:{name:`deposit-address`,description:`Read an account deposit address through the policy engine`},args:Qc.args,async run({args:e}){let t=Qc.parse(e);await Gc(t)(e=>e.getAccountDepositAddress(t.account,{network:t.network,asset:t.asset}))}}),rl=l({meta:{name:`accounts`,description:`Inspect bank accounts`},subCommands:{list:$c,balance:el,transactions:tl,"deposit-address":nl}}),il=f.pipe(f.string(`Idempotency key must be a string`),f.minLength(1,`Idempotency key must not be empty`),f.maxLength(255,`Idempotency key is too long (max 255 characters)`)),al=f.pipe(f.string(),f.minLength(1,`must not be empty`)),ol=f.pipe(f.string(),f.trim(),f.email(`must be a valid email address`)),sl={profile:Wo,json:Go},cl=$({address:Q({description:`Only counterparties with a wallet rail matching this address (0x…)`,schema:Zo}),network:Qo({description:`Only counterparties with a wallet rail on this network (e.g. base)`}),...sl}),ll=Q({description:`Counterparty name`,required:!0,schema:al}),ul=Q({description:`Optional contact email`,schema:ol}),dl=$({name:ll,email:Q({description:`Contact email; creating the counterparty sends no email`,required:!0,schema:ol}),...sl}),fl=$({name:Q({description:`Counterparty name; required without a subcommand`,schema:al}),email:Q({description:`Contact email; required without a subcommand; creating the counterparty sends no email`,schema:ol}),...sl}),pl=$({name:ll,"bank-name":Q({description:`Receiving bank name`,required:!0,schema:al}),"routing-number":Q({description:`9-digit ABA routing number`,required:!0,schema:al}),"account-number":Q({description:`Receiving bank account number`,required:!0,schema:al}),"account-type":Po({description:`checking | savings (default checking)`,choices:[`checking`,`savings`]}),"address-street":Q({description:`Street address of the receiving bank account holder`,required:!0,schema:al}),"address-city":Q({description:`City`,required:!0,schema:al}),"address-state":Q({description:`State (e.g. NY)`,required:!0,schema:al}),"address-postal-code":Q({description:`Postal code`,required:!0,schema:al}),"address-country":Q({description:`Default USA`}),email:ul,...sl}),ml=$({name:ll,address:Q({description:`Wallet address (0x… or ENS name on EVM networks)`,required:!0,schema:al}),network:Qo({description:`Wallet network; defaults to ${Xo}. Availability depends on the connected environment.`,default:Xo}),email:ul,...sl}),hl=$({counterparty:jo({description:`Counterparty id`,required:!0,schema:qo}),bank:No({description:`Request bank account details`,default:!1}),wallet:No({description:`Request wallet details`,default:!1}),"idempotency-key":Q({description:`Optional key to replay this exact submission`,schema:il}),...sl}),gl=l({meta:{name:`list`,description:`List counterparties available under the agent's policy`},args:cl.args,async run({args:e}){let t=cl.parse(e);await Gc(t)(e=>e.listCounterparties({address:t.address,network:t.network}))}});function _l(e){return e&&e.length>0?e:void 0}function vl(e){let t=_l(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 yl(e){let t=_l(e.email);return{type:`create_counterparty`,name:e.name,email:t,rail:{type:`wallet`,walletAddress:e.address,network:e.network}}}function bl(e){return{type:`create_counterparty`,name:e.name,email:e.email}}const xl=l({meta:{name:`email`,description:`Create a counterparty with an email and no payment details. Sends no email.`},args:dl.args,async run({args:e}){let t=dl.parse(e);await Gc(t)(e=>e.submitIntent({action:bl(t)}))}}),Sl=l({meta:{name:`bank`,description:`Request bank counterparty creation through the policy engine. Prints an intent envelope.`},args:pl.args,async run({args:e}){let t=pl.parse(e),n=vl(t);await Gc(t)(e=>e.submitIntent({action:n}))}}),Cl=l({meta:{name:`wallet`,description:`Request wallet counterparty creation through the policy engine. Prints an intent envelope.`},args:ml.args,async run({args:e}){let t=ml.parse(e);await Gc(t)(e=>e.submitIntent({action:yl(t)}))}}),wl=l({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:fl.args,default:`email`,subCommands:{email:xl,bank:Sl,wallet:Cl}}),Tl=l({meta:{name:`request-details`,description:`Ask a counterparty to provide bank details, wallet details, or both through the policy engine.`},args:hl.args,async run({args:e}){let t=hl.parse(e);!t.bank&&!t.wallet&&Z(`Select at least one of --bank or --wallet`),await Gc(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`]}:{}}))}}),El=l({meta:{name:`counterparties`,description:`Inspect, create, and request details from counterparties`},subCommands:{list:gl,create:wl,"request-details":Tl}}),Dl=4e3;async function Ol(){process.stdin.setEncoding(`utf8`);let e=``;for await(let t of process.stdin)e+=t;return e}async function kl(e){return e===void 0?(process.stdin.isTTY&&Z(`<message>: pass a quoted message or pipe it on stdin; a message starting with "-" needs -- before it (catena feedback -- "<message>") or stdin`),Ol()):e}const Al=$({message:jo({description:`Plain-text feedback (1-4000 chars); omit to pipe on stdin`}),profile:Wo,json:Go}),jl=l({meta:{name:`feedback`,description:`Send free-form feedback about Catena to the Catena team`},args:Al.args,async run({args:e}){(Array.isArray(e._)?e._:[]).length>1&&Z(`<message>: pass the message as a single quoted argument`);let t=Al.parse(e),n=(await kl(t.message)).trim();n.length===0&&Z(`<message>: must not be empty`),n.length>Dl&&Z(`<message>: must be at most ${Dl} characters (got: ${n.length})`),await Gc(t)(async e=>(await e.submitFeedback(n),{ok:!0}))}});function Ml(e){return`# Catena CLI Agent Guide
139
139
 
140
140
  CLI version: ${e}
141
141
 
@@ -514,13 +514,13 @@ you need, tell the Catena team:
514
514
 
515
515
  The message must be 1-4000 characters and is write-only. Longer messages can be
516
516
  piped on stdin instead of passed as an argument.
517
- `}const El=l({meta:{name:`guide`,description:`Print the Catena CLI agent operating guide`},run(){console.log(Tl(se))}}),Dl=$({id:wo({description:`Intent id (e.g. int_…)`,required:!0,schema:Bo}),profile:Lo,json:Ro}),Ol=l({meta:{name:`get`,description:`Look up the current state of an intent created by this agent`},args:Dl.args,async run({args:e}){let t=Dl.parse(e);await Rc(t)(e=>e.getIntent(t.id))}}),kl=l({meta:{name:`intents`,description:`Inspect intent receipts returned by governed operations`},subCommands:{get:Ol}});function Al(e=process.env,t=process.platform){return!!(e.SSH_CONNECTION||e.SSH_TTY||t===`linux`&&!e.DISPLAY&&!e.WAYLAND_DISPLAY)}function jl(e){let t;try{t=E(re(e))}catch{return!1}if(t===`/`)return!0;try{let e=E(process.env.HOME??j());return t===e||e.startsWith(`${t}/`)}catch{return!0}}function Ml(e){e&&process.stderr.write(`Failed to open browser: ${e.message}\n`)}function Nl(e){process.platform===`darwin`?y(`open`,[e],Ml):process.platform===`win32`?y(`cmd`,[`/c`,`start`,``,e],Ml):y(`xdg-open`,[e],Ml)}function Pl(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 Fl(e){return typeof e!=`object`||!e||!(`access_token`in e)?!1:typeof e.access_token==`string`}function Il(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 Ll(e){if(typeof e!=`object`||!e)return!1;let t=e;return Ko.some(e=>e===t.status)&&(t.publicKeyHex===void 0||typeof t.publicKeyHex==`string`)&&(t.reason===void 0||typeof t.reason==`string`)}async function Rl(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=na}=e,p=xc(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:Pl(await m.json().catch(()=>({message:`Token exchange failed`})))??m.statusText};let h=await m.json();if(!Fl(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:Pl(await _.json().catch(()=>({message:`Claim failed`})))??_.statusText};let v=await _.json();return Il(v)?zl({bankUrl:t,claim:v,clientInstanceId:o,signerKeypair:g,identityHeaders:p,log:l}):{ok:!1,message:`Claim response missing required fields`}}async function zl(e){let{bankUrl:t,claim:n,clientInstanceId:r,signerKeypair:i,identityHeaders:a}=e;(e.log??(()=>{}))(`Registering signer...`);let o=await Vl({bankUrl:t,sessionToken:n.sessionToken,keypair:i,identityHeaders:a});return o.status===`registration_failed`?(n.activated!==!1&&await Hl({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 Bl(e){return typeof e!=`object`||!e||!(`signer`in e)?!1:Ll(e.signer)}async function Vl(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 Bl(n)?n.signer:{status:`registration_failed`,reason:`registration_response_malformed`}}async function Hl(e){try{await fetch(`${e.bankUrl}/v1/agent-api/unlink`,{method:`POST`,headers:{...e.identityHeaders,Authorization:`Bearer ${e.sessionToken}`}})}catch{}}function Ul(e){return`${e}-signer`}async function Wl(e,t){let n=await e.resolve(t);if(n!==null&&`signer`in n)return n.signer;let r=await e.resolve(Ul(t));if(r!==null&&`signer`in r)return r.signer}async function Gl(e,t,n=na){let r=await Wl(e,t);if(r!==void 0)return r;let i=os(n());return await e.save(Ul(t),i),i.signer}const Kl=[53682,53683,53684,53685,53686,53687];function ql(e){return new Promise((t,n)=>{let r=0,i=()=>{if(r>=Kl.length){n(Error(`No registered loopback callback ports are available`));return}let a=Kl[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 Jl(e){let{bankUrl:t,agentId:n,clientInstanceId:r,clientId:i,clientLabel:a,timeoutMs:o=3e5,log:s=()=>{},appInfo:c,existingSigner:l}=e;Fs(t,`bankUrl`);let u=_(32).toString(`base64url`),d=h(`sha256`).update(u).digest(`base64url`),f=_(16).toString(`hex`),p=e=>{let n=new URL(`${t}/link-complete`);return n.searchParams.set(`linked`,e),n.toString()},m=e=>{let n=new URL(`${t}/link-complete`);return n.searchParams.set(`error`,e),n.toString()};return new Promise((e,h)=>{let g=0,_=!1,v=null,y=t=>{_||(_=!0,v&&clearTimeout(v),S.close(),e(t))},b=e=>{_||(_=!0,v&&clearTimeout(v),S.close(),h(e))},x=e=>{s(`Link failed: ${e}`),y(null)},S=N((e,t)=>{C(e,t).catch(e=>{let n=Pl(e)??`Unexpected error`;t.headersSent||(t.writeHead(302,{Location:m(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 h=d.searchParams.get(`error`);if(h){let e=d.searchParams.get(`error_description`)??h;o.writeHead(302,{Location:m(e)}),o.end(),x(`OAuth error: ${e}`);return}if(d.searchParams.get(`state`)!==f){o.writeHead(302,{Location:m(`State mismatch during OAuth callback`)}),o.end(),x(`State mismatch during OAuth callback`);return}let _=d.searchParams.get(`code`);if(!_){o.writeHead(302,{Location:m(`Missing authorization code`)}),o.end(),x(`Missing authorization code`);return}let v=`http://127.0.0.1:${g}/callback`,b=await Rl({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:m(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)}ql(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...`),Nl(r),s(`If browser didn't open, visit: ${r}`)}).catch(b),v=setTimeout(()=>{x(`Timed out waiting for authentication`)},o),v.unref()})}function Yl(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 Xl(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 Zl(e){return new Promise(t=>{setTimeout(t,e)})}function Ql(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 $l(e){let{bankUrl:t,clientInstanceId:n,onUserCode:r,log:i=()=>{},appInfo:a,existingSigner:o,generateSignerKeypair:s=na,sleep:c=Zl}=e;Fs(t,`bankUrl`);let l=xc(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(Ql(e))})}catch{return u(`Could not reach the bank to start the device flow`)}if(!d.ok)return u(Xl(await d.json().catch(()=>null)).message??d.statusText);let f=await d.json();if(!Yl(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 eu({bankUrl:t,grant:f,identityHeaders:l,sleep:c});if(!p.ok)return u(p.message);let m=p.body;if(!Il(m))return u(`Device token response missing required fields`);i(`Approved. Claiming agent...`);let h=await zl({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 eu(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=Xl(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 tu(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 nu(e){let{bankUrl:t,clientInstanceId:n,onUserCode:r,log:i=()=>{},appInfo:a,sleep:o=Zl}=e;Fs(t,`bankUrl`);let s=xc(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=Xl(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(!Yl(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 eu({bankUrl:t,grant:f,identityHeaders:s,sleep:o});return p.ok?Il(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`):tu(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 ru=$({"agent-id":wo({description:`Optional agent ID shown in the Catena console; omit to create and link a new agent`,schema:Bo}),"bank-url":Q({description:`Bank API URL (defaults to $CATENA_API_URL or prod)`,default:process.env.CATENA_API_URL??`https://api.catena.com`}),browser:Eo({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:Q({description:`Suggested name for an agent created from this link; only used when agent-id is omitted`}),service:Eo({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":Q({description:`With --service: register this existing compressed P-256 public key (the deployment already holds the private key) instead of generating a keypair`}),profile:Lo}),iu=/^0[23][0-9a-f]{64}$/;function au(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 ou(e){console.log(`
518
- Keep this generated keypair if the approval completed before the CLI failed:`),console.log(`\n CATENA_AGENT_PUBLIC_KEY=${e.publicKeyHex}`),console.log(` CATENA_AGENT_PRIVATE_KEY=${e.privateKeyHex}`)}function su(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 cu({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 lu(e){let t=h(`sha256`).update(E(process.cwd())).digest(`hex`).slice(0,16);return`${fc(e??`agent`).slice(0,47)}-${t}`}function uu(e){try{let t=process.cwd();if(jl(t))return null;let n=rc(t);return{directory:ic(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 du=l({meta:{name:`link`,description:`Link an existing agent, or create and link a new agent when agent-id is omitted`},args:ru.args,async run({args:e}){let t=ru.parse(e),n=t[`bank-url`],r=t[`agent-id`],i=t.name;if(t.service){await fu({bankUrl:n,agentId:r,suggestedAgentName:i,publicKeyHex:t[`public-key`]});return}let a,o,s;try{if(Fs(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=Ec({flag:Fc(t),cwd:process.cwd(),log:e=>console.error(e)});a=(e!==null&&e.source!=="default"?e.name:null)??(r===void 0?null:$s(r,n)),o=a??(r===void 0?lu(i):fc(r)),s=cc(o,{bank_url:n,agent_id:r})}catch(e){Z(e)}console.log(`
519
- Catena — Agent Setup`),console.log(`─`.repeat(25));let c=js(),l=await Gl(c,s),u={bankUrl:n,clientInstanceId:s,log:e=>console.log(` ${e}`),appInfo:_c,existingSigner:l},d=cu({agentId:r,suggestedAgentName:i,browserRequested:t.browser,isHeadless:Al});d.kind===`device-link`&&d.notice!==void 0&&console.log(` ${d.notice}`);let f=d.kind===`pkce-link`?await Jl({...u,agentId:d.agentId,clientId:`catena-cli`,timeoutMs:3e5}):await $l({...u,...d.deviceTarget,onUserCode:au});f||Z(`
520
- Failed to link agent. Run the command again to try again.`),await c.save(s,cs(f.signer));let p=a??pc(fc(f.agentName),e=>e!==o&&oc(e)!==null);try{p===o?Xs(p,{bank_url:n,agent_id:f.agentId,client_instance_id:s}):mc({reservationName:o,profileName:p,profile:{bank_url:n,agent_id:f.agentId,client_instance_id:s}})}catch(e){Z(e)}console.log(`\n Wrote profile "${p}"`);let m=uu(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 ${Cc}=${p}`),console.log(`\nDone. Agent "${f.agentName}" linked.`),process.exit(0)}});async function fu(e){try{if(Fs(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&&!iu.test(e.publicKeyHex.toLowerCase()))throw Error(`--public-key must be compressed P-256 public key hex (66 chars)`)}catch(e){Z(e)}console.log(`
521
- Catena — Deployed Service Setup`),console.log(`─`.repeat(31));let t=e.publicKeyHex===void 0?na():null,n=t?.publicKeyHex??e.publicKeyHex?.toLowerCase()??``,r;try{r=oa(n)}catch(e){e instanceof ta||Z(e),Z(`Signing key public key is not a valid P-256 point`)}console.log(` Signing key (RFC 7638 thumbprint): ${r}`);let i=`service-${h(`sha256`).update(n).digest(`hex`).slice(0,32)}`,a=!1,o=()=>{t&&a&&ou({publicKeyHex:n,privateKeyHex:t.privateKeyHex})},s;try{s=await nu({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,au(e)},log:e=>console.log(` ${e}`),appInfo:_c})}catch(e){o(),Z(e)}s||(o(),Z(`
522
- Failed to link the service. Run the command again to try again.`)),s.keyThumbprint!==r&&(o(),Z(`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(su(s.signerReason)):console.log(` Wallet-send signer: not registered (${s.signerReason??s.signerStatus}); retry after checking the link status`),console.log(`
517
+ `}const Nl=l({meta:{name:`guide`,description:`Print the Catena CLI agent operating guide`},run(){console.log(Ml(se))}}),Pl=$({id:jo({description:`Intent id (e.g. int_…)`,required:!0,schema:qo}),profile:Wo,json:Go}),Fl=l({meta:{name:`get`,description:`Look up the current state of an intent created by this agent`},args:Pl.args,async run({args:e}){let t=Pl.parse(e);await Gc(t)(e=>e.getIntent(t.id))}}),Il=l({meta:{name:`intents`,description:`Inspect intent receipts returned by governed operations`},subCommands:{get:Fl}});function Ll(e=process.env,t=process.platform){return!!(e.SSH_CONNECTION||e.SSH_TTY||t===`linux`&&!e.DISPLAY&&!e.WAYLAND_DISPLAY)}function Rl(e){let t;try{t=E(re(e))}catch{return!1}if(t===`/`)return!0;try{let e=E(process.env.HOME??j());return t===e||e.startsWith(`${t}/`)}catch{return!0}}function zl(e){e&&process.stderr.write(`Failed to open browser: ${e.message}\n`)}function Bl(e){process.platform===`darwin`?y(`open`,[e],zl):process.platform===`win32`?y(`cmd`,[`/c`,`start`,``,e],zl):y(`xdg-open`,[e],zl)}function Vl(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 Hl(e){return typeof e!=`object`||!e||!(`access_token`in e)?!1:typeof e.access_token==`string`}function Ul(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 Wl(e){if(typeof e!=`object`||!e)return!1;let t=e;return $o.some(e=>e===t.status)&&(t.publicKeyHex===void 0||typeof t.publicKeyHex==`string`)&&(t.reason===void 0||typeof t.reason==`string`)}async function Gl(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=na}=e,p=Oc(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:Vl(await m.json().catch(()=>({message:`Token exchange failed`})))??m.statusText};let h=await m.json();if(!Hl(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:Vl(await _.json().catch(()=>({message:`Claim failed`})))??_.statusText};let v=await _.json();return Ul(v)?Kl({bankUrl:t,claim:v,clientInstanceId:o,signerKeypair:g,identityHeaders:p,log:l}):{ok:!1,message:`Claim response missing required fields`}}async function Kl(e){let{bankUrl:t,claim:n,clientInstanceId:r,signerKeypair:i,identityHeaders:a}=e;(e.log??(()=>{}))(`Registering signer...`);let o=await Jl({bankUrl:t,sessionToken:n.sessionToken,keypair:i,identityHeaders:a});return o.status===`registration_failed`?(n.activated!==!1&&await Yl({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 ql(e){return typeof e!=`object`||!e||!(`signer`in e)?!1:Wl(e.signer)}async function Jl(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 ql(n)?n.signer:{status:`registration_failed`,reason:`registration_response_malformed`}}async function Yl(e){try{await fetch(`${e.bankUrl}/v1/agent-api/unlink`,{method:`POST`,headers:{...e.identityHeaders,Authorization:`Bearer ${e.sessionToken}`}})}catch{}}function Xl(e){return`${e}-signer`}async function Zl(e,t){let n=await e.resolve(t);if(n!==null&&`signer`in n)return n.signer;let r=await e.resolve(Xl(t));if(r!==null&&`signer`in r)return r.signer}async function Ql(e,t,n=na){let r=await Zl(e,t);if(r!==void 0)return r;let i=ps(n());return await e.save(Xl(t),i),i.signer}const $l=[53682,53683,53684,53685,53686,53687];function eu(e){return new Promise((t,n)=>{let r=0,i=()=>{if(r>=$l.length){n(Error(`No registered loopback callback ports are available`));return}let a=$l[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 tu(e){let{bankUrl:t,agentId:n,clientInstanceId:r,clientId:i,clientLabel:a,timeoutMs:o=3e5,log:s=()=>{},appInfo:c,existingSigner:l}=e;Hs(t,`bankUrl`);let u=_(32).toString(`base64url`),d=h(`sha256`).update(u).digest(`base64url`),f=_(16).toString(`hex`),p=e=>{let n=new URL(`${t}/link-complete`);return n.searchParams.set(`linked`,e),n.toString()},m=e=>{let n=new URL(`${t}/link-complete`);return n.searchParams.set(`error`,e),n.toString()};return new Promise((e,h)=>{let g=0,_=!1,v=null,y=t=>{_||(_=!0,v&&clearTimeout(v),S.close(),e(t))},b=e=>{_||(_=!0,v&&clearTimeout(v),S.close(),h(e))},x=e=>{s(`Link failed: ${e}`),y(null)},S=N((e,t)=>{C(e,t).catch(e=>{let n=Vl(e)??`Unexpected error`;t.headersSent||(t.writeHead(302,{Location:m(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 h=d.searchParams.get(`error`);if(h){let e=d.searchParams.get(`error_description`)??h;o.writeHead(302,{Location:m(e)}),o.end(),x(`OAuth error: ${e}`);return}if(d.searchParams.get(`state`)!==f){o.writeHead(302,{Location:m(`State mismatch during OAuth callback`)}),o.end(),x(`State mismatch during OAuth callback`);return}let _=d.searchParams.get(`code`);if(!_){o.writeHead(302,{Location:m(`Missing authorization code`)}),o.end(),x(`Missing authorization code`);return}let v=`http://127.0.0.1:${g}/callback`,b=await Gl({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:m(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)}eu(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...`),Bl(r),s(`If browser didn't open, visit: ${r}`)}).catch(b),v=setTimeout(()=>{x(`Timed out waiting for authentication`)},o),v.unref()})}function nu(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 ru(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 iu(e){return new Promise(t=>{setTimeout(t,e)})}function au(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 ou(e){let{bankUrl:t,clientInstanceId:n,onUserCode:r,log:i=()=>{},appInfo:a,existingSigner:o,generateSignerKeypair:s=na,sleep:c=iu}=e;Hs(t,`bankUrl`);let l=Oc(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(au(e))})}catch{return u(`Could not reach the bank to start the device flow`)}if(!d.ok)return u(ru(await d.json().catch(()=>null)).message??d.statusText);let f=await d.json();if(!nu(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 su({bankUrl:t,grant:f,identityHeaders:l,sleep:c});if(!p.ok)return u(p.message);let m=p.body;if(!Ul(m))return u(`Device token response missing required fields`);i(`Approved. Claiming agent...`);let h=await Kl({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 su(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=ru(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 cu(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 lu(e){let{bankUrl:t,clientInstanceId:n,onUserCode:r,log:i=()=>{},appInfo:a,sleep:o=iu}=e;Hs(t,`bankUrl`);let s=Oc(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=ru(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(!nu(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 su({bankUrl:t,grant:f,identityHeaders:s,sleep:o});return p.ok?Ul(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`):cu(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 uu=$({"agent-id":jo({description:`Optional agent ID shown in the Catena console; omit to create and link a new agent`,schema:qo}),"bank-url":Q({description:`Bank API URL (defaults to $CATENA_API_URL or prod)`,default:process.env.CATENA_API_URL??`https://api.catena.com`}),browser:No({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:Q({description:`Suggested name for an agent created from this link; only used when agent-id is omitted`}),service:No({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":Q({description:`With --service: register this existing compressed P-256 public key (the deployment already holds the private key) instead of generating a keypair`}),profile:Wo}),du=/^0[23][0-9a-f]{64}$/;function fu(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 pu(e){console.log(`
518
+ Keep this generated keypair if the approval completed before the CLI failed:`),console.log(`\n CATENA_AGENT_PUBLIC_KEY=${e.publicKeyHex}`),console.log(` CATENA_AGENT_PRIVATE_KEY=${e.privateKeyHex}`)}function mu(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 hu({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 gu(e){let t=h(`sha256`).update(E(process.cwd())).digest(`hex`).slice(0,16);return`${yc(e??`agent`).slice(0,47)}-${t}`}function _u(e){try{let t=process.cwd();if(Rl(t))return null;let n=uc(t);return{directory:dc(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 vu=l({meta:{name:`link`,description:`Link an existing agent, or create and link a new agent when agent-id is omitted`},args:uu.args,async run({args:e}){let t=uu.parse(e),n=t[`bank-url`],r=t[`agent-id`],i=t.name;if(t.service){await yu({bankUrl:n,agentId:r,suggestedAgentName:i,publicKeyHex:t[`public-key`]});return}let a,o,s;try{if(Hs(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=Nc({flag:Hc(t),cwd:process.cwd(),log:e=>console.error(e)});a=(e!==null&&e.source!=="default"?e.name:null)??(r===void 0?null:oc(r,n)),o=a??(r===void 0?gu(i):yc(r)),s=hc(o,{bank_url:n,agent_id:r})}catch(e){Z(e)}console.log(`
519
+ Catena — Agent Setup`),console.log(`─`.repeat(25));let c=Rs(),l=await Ql(c,s),u={bankUrl:n,clientInstanceId:s,log:e=>console.log(` ${e}`),appInfo:wc,existingSigner:l},d=hu({agentId:r,suggestedAgentName:i,browserRequested:t.browser,isHeadless:Ll});d.kind===`device-link`&&d.notice!==void 0&&console.log(` ${d.notice}`);let f=d.kind===`pkce-link`?await tu({...u,agentId:d.agentId,clientId:`catena-cli`,timeoutMs:3e5}):await ou({...u,...d.deviceTarget,onUserCode:fu});f||Z(`
520
+ Failed to link agent. Run the command again to try again.`),await c.save(s,hs(f.signer));let p=a??bc(yc(f.agentName),e=>e!==o&&pc(e)!==null);try{p===o?rc(p,{bank_url:n,agent_id:f.agentId,client_instance_id:s}):xc({reservationName:o,profileName:p,profile:{bank_url:n,agent_id:f.agentId,client_instance_id:s}})}catch(e){Z(e)}console.log(`\n Wrote profile "${p}"`);let m=_u(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 ${Ac}=${p}`),console.log(`\nDone. Agent "${f.agentName}" linked.`),process.exit(0)}});async function yu(e){try{if(Hs(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&&!du.test(e.publicKeyHex.toLowerCase()))throw Error(`--public-key must be compressed P-256 public key hex (66 chars)`)}catch(e){Z(e)}console.log(`
521
+ Catena — Deployed Service Setup`),console.log(`─`.repeat(31));let t=e.publicKeyHex===void 0?na():null,n=t?.publicKeyHex??e.publicKeyHex?.toLowerCase()??``,r;try{r=oa(n)}catch(e){e instanceof ta||Z(e),Z(`Signing key public key is not a valid P-256 point`)}console.log(` Signing key (RFC 7638 thumbprint): ${r}`);let i=`service-${h(`sha256`).update(n).digest(`hex`).slice(0,32)}`,a=!1,o=()=>{t&&a&&pu({publicKeyHex:n,privateKeyHex:t.privateKeyHex})},s;try{s=await lu({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,fu(e)},log:e=>console.log(` ${e}`),appInfo:wc})}catch(e){o(),Z(e)}s||(o(),Z(`
522
+ Failed to link the service. Run the command again to try again.`)),s.keyThumbprint!==r&&(o(),Z(`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(mu(s.signerReason)):console.log(` Wallet-send signer: not registered (${s.signerReason??s.signerStatus}); retry after checking the link status`),console.log(`
523
523
  Set these in the deployment environment:`),console.log(`\n CATENA_API_URL=${e.bankUrl}`),console.log(` CATENA_AGENT_PUBLIC_KEY=${n}`),t&&console.log(` CATENA_AGENT_PRIVATE_KEY=${t.privateKeyHex}`),console.log(` CATENA_AGENT_IDENTITY_URL=<the deployment's public https origin>`),t&&console.log(`
524
- The private key is shown once and is not stored on this machine.`),process.exit(0)}const pu=$({profile:Lo,json:Ro}),mu=l({meta:{name:`show`,description:`Show the agent's assigned policy`},args:pu.args,async run({args:e}){await Rc(pu.parse(e))(e=>e.getPolicy())}}),hu=l({meta:{name:`policy`,description:`Inspect the agent's policy`},subCommands:{show:mu}}),gu=$({profile:wo({description:`Profile name`,required:!0})});function _u(){try{return Dc({env:process.env[Cc],cwd:process.cwd(),log:e=>console.error(e)})}catch(e){return Z(e)}}const vu=l({meta:{name:`use`,description:`Set the default credential profile`},args:gu.args,async run({args:e}){let t=gu.parse(e);try{dc(t.profile),Pc({defaultProfile:t.profile})}catch(e){Z(e)}}}),yu=l({meta:{name:`current`,description:`Show the selected credential profile and how it was chosen`},async run(){let e=_u(),t;try{t=oc(e.name)}catch(e){Z(e)}t===null&&Z(`Profile "${e.name}" is not linked.\nRun 'catena link --profile ${e.name} <agent-id>' to authenticate.`),Pc({profile:e.name,source:e.source,bankUrl:t.bank_url,agentId:Zs(t)?t.agent_id:void 0})}}),bu=l({meta:{name:`list`,description:`List credential profiles and their directory bindings`},async run(){let e;try{e=qs()}catch(e){Z(e)}let t;try{t=Dc({env:process.env[Cc],cwd:process.cwd()}).name}catch{t=null}let n=Object.entries(e.directories??{});Pc({defaultProfile:e.default_profile,profiles:Object.entries(e.profiles).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,r])=>({name:e,bankUrl:r.bank_url,agentId:Zs(r)?r.agent_id:void 0,directories:n.filter(([,t])=>t===e).map(([e])=>e).toSorted(),current:e===t}))})}}),xu=$({profile:wo({description:`Profile name to bind`,required:!0}),path:wo({description:`Directory to bind (defaults to the current directory)`})}),Su=l({meta:{name:`bind`,description:`Bind a directory to a profile for automatic selection`},args:xu.args,async run({args:e}){let t=xu.parse(e);try{let e=t.path??process.cwd();if(jl(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=ic(e,t.profile);Pc({profile:t.profile,directory:n})}catch(e){Z(e)}}}),Cu=$({path:wo({description:`Directory to unbind (defaults to the current directory)`})}),wu=l({meta:{name:`unbind`,description:`Remove a directory's profile binding`},args:Cu.args,async run({args:e}){let t=Cu.parse(e);try{Pc(ac(t.path??process.cwd()))}catch(e){Z(e)}}}),Tu=l({meta:{name:`profiles`,description:`Manage credential profiles`},subCommands:{use:vu,current:yu,list:bu,bind:Su,unbind:wu}}),Eu=new Map,Du=/^[A-Z]{3}$/,Ou=/^[A-Z0-9]{2,6}$/;function ku(e,t,n){if(Eu.has(e))throw Error(`duplicate asset id ${e}`);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 Au(e,t,n,r){if(!Du.test(e))throw Error(`fiat asset ids must be 3-letter ISO-4217 codes`);ku(e,n,r);let i=e;return Eu.set(e,{id:i,symbol:e,name:t,kind:`fiat`,decimals:n,presentmentDecimals:r,denomination:e,valuation:{type:`par`}}),i}function ju(e,t,n,r,i){if(!Ou.test(e)||Du.test(e))throw Error(`stablecoin tickers must be 2-6 uppercase alphanumerics and not a 3-letter ISO-4217 shape`);let a=Eu.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})`);ku(e,n,r);let o=e;return Eu.set(e,{id:o,symbol:e,name:t,kind:`stablecoin`,decimals:n,presentmentDecimals:r,denomination:a.denomination,valuation:{type:`par`}}),o}ju(`USDC`,`USD Coin`,6,2,{denomination:Au(`USD`,`US Dollar`,6,2)})
524
+ The private key is shown once and is not stored on this machine.`),process.exit(0)}const bu=$({profile:Wo,json:Go}),xu=l({meta:{name:`show`,description:`Show the agent's assigned policy`},args:bu.args,async run({args:e}){await Gc(bu.parse(e))(e=>e.getPolicy())}}),Su=l({meta:{name:`policy`,description:`Inspect the agent's policy`},subCommands:{show:xu}}),Cu=$({profile:jo({description:`Profile name`,required:!0})});function wu(){try{return Pc({env:process.env[Ac],cwd:process.cwd(),log:e=>console.error(e)})}catch(e){return Z(e)}}const Tu=l({meta:{name:`use`,description:`Set the default credential profile`},args:Cu.args,async run({args:e}){let t=Cu.parse(e);try{vc(t.profile),Vc({defaultProfile:t.profile})}catch(e){Z(e)}}}),Eu=l({meta:{name:`current`,description:`Show the selected credential profile and how it was chosen`},async run(){let e=wu(),t;try{t=pc(e.name)}catch(e){Z(e)}t===null&&Z(`Profile "${e.name}" is not linked.\nRun 'catena link --profile ${e.name} <agent-id>' to authenticate.`),Vc({profile:e.name,source:e.source,bankUrl:t.bank_url,agentId:ic(t)?t.agent_id:void 0})}}),Du=l({meta:{name:`list`,description:`List credential profiles and their directory bindings`},async run(){let e;try{e=ec()}catch(e){Z(e)}let t;try{t=Pc({env:process.env[Ac],cwd:process.cwd()}).name}catch{t=null}let n=Object.entries(e.directories??{});Vc({defaultProfile:e.default_profile,profiles:Object.entries(e.profiles).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,r])=>({name:e,bankUrl:r.bank_url,agentId:ic(r)?r.agent_id:void 0,directories:n.filter(([,t])=>t===e).map(([e])=>e).toSorted(),current:e===t}))})}}),Ou=$({profile:jo({description:`Profile name to bind`,required:!0}),path:jo({description:`Directory to bind (defaults to the current directory)`})}),ku=l({meta:{name:`bind`,description:`Bind a directory to a profile for automatic selection`},args:Ou.args,async run({args:e}){let t=Ou.parse(e);try{let e=t.path??process.cwd();if(Rl(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=dc(e,t.profile);Vc({profile:t.profile,directory:n})}catch(e){Z(e)}}}),Au=$({path:jo({description:`Directory to unbind (defaults to the current directory)`})}),ju=l({meta:{name:`unbind`,description:`Remove a directory's profile binding`},args:Au.args,async run({args:e}){let t=Au.parse(e);try{Vc(fc(t.path??process.cwd()))}catch(e){Z(e)}}}),Mu=l({meta:{name:`profiles`,description:`Manage credential profiles`},subCommands:{use:Tu,current:Eu,list:Du,bind:ku,unbind:ju}}),Nu=new Map,Pu=/^[A-Z]{3}$/,Fu=/^[A-Z0-9]{2,6}$/;function Iu(e,t,n){if(Nu.has(e))throw Error(`duplicate asset id ${e}`);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 Lu(e,t,n,r){if(!Pu.test(e))throw Error(`fiat asset ids must be 3-letter ISO-4217 codes`);Iu(e,n,r);let i=e;return Nu.set(e,{id:i,symbol:e,name:t,kind:`fiat`,decimals:n,presentmentDecimals:r,denomination:e,valuation:{type:`par`}}),i}function Ru(e,t,n,r,i){if(!Fu.test(e)||Pu.test(e))throw Error(`stablecoin tickers must be 2-6 uppercase alphanumerics and not a 3-letter ISO-4217 shape`);let a=Nu.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})`);Iu(e,n,r);let o=e;return Nu.set(e,{id:o,symbol:e,name:t,kind:`stablecoin`,decimals:n,presentmentDecimals:r,denomination:a.denomination,valuation:{type:`par`}}),o}Ru(`USDC`,`USD Coin`,6,2,{denomination:Lu(`USD`,`US Dollar`,6,2)})
525
525
  /*! decimal.js-light v2.5.1 https://github.com/MikeMcl/decimal.js-light/LICENCE */
526
- ;const Mu=e(s(((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 E(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,E(t,o))},g.minus=g.sub=function(e){var t=this;return e=new t.constructor(e),t.s==e.s?D(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)):E(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):D(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(E(s,n+1,0),s.times(s).eq(u)){r=s;break}}else if(t!=`9999`)break;l+=4}return i=!0,E(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?E(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),E(r,e+S(r)+1,t))},g.toExponential=function(e,t){var r,i=this,a=i.constructor;return e===void 0?r=O(i,!0):(v(e,0,n),t===void 0?t=a.rounding:v(t,0,8),i=E(new a(i),e+1,t),r=O(i,!0,e+1)),r},g.toFixed=function(e,t){var r,i,a=this,o=a.constructor;return e===void 0?O(a):(v(e,0,n),t===void 0?t=o.rounding:v(t,0,8),i=E(new o(a),e+S(a)+1,t),r=O(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 E(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 E(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),k(o.d,t)),n=c(n/2),n!==0;)u=u.times(u),k(u.d,t);return i=!0,e.s<0?new f(d).div(o):E(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=O(a,r<=o.toExpNeg||r>=o.toExpPos)):(v(e,1,n),t===void 0?t=o.rounding:v(t,0,8),a=E(new o(a),e,t),r=S(a),i=O(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)),E(new i(r),e,t)},g.toString=g.valueOf=g.val=g.toJSON=function(){var e=this,t=S(e),n=e.constructor;return O(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?E(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?E(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,ee,D,O,k=r.constructor,A=r.s==i.s?1:-1,j=r.d,M=i.d;if(!r.s)return new k(r);if(!i.s)throw Error(a+`Division by zero`);for(l=r.e-i.e,D=M.length,T=j.length,g=new k(A),_=g.d=[],u=0;M[u]==(j[u]||0);)++u;if(M[u]>(j[u]||0)&&--l,x=o==null?o=k.precision:s?o+(S(r)-S(i))+1:o,x<0)return new k(0);if(x=x/p+2|0,u=0,D==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),D=M.length,T=j.length),w=D,v=j.slice(0,D),y=v.length;y<D;)v[y++]=0;O=M.slice(),O.unshift(0),ee=M[0],M[1]>=f/2&&++ee;do d=0,c=t(M,v,D,y),c<0?(b=v[0],D!=y&&(b=b*f+(v[1]||0)),d=b/ee|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,D<h?O: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,D,y),c<1&&(d++,n(v,D<y?O: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,E(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=E(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=E(o.times(o),u);return m.precision=h,t==null?(i=!0,E(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 E(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,E(g,x)):g;for(l=c=g=b(g.minus(d),g.plus(d),f),p=E(g.times(g),f),o=3;;){if(c=E(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,E(l,x)):l;l=u,o+=2}}function ee(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 E(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 D(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?E(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?E(t,g):t):new h(0)}function O(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 k(e,t){if(e.length>t)return e.length=t,!0}function A(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 ee(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))ee(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=A,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=A(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;Mu.set({rounding:Mu.ROUND_HALF_EVEN}),new Mu(1e6),new Mu(1e3);const Nu=f.pipe(f.string(`Amount must be a string`),f.nonEmpty(`Amount must not be empty`),f.check(e=>e.trim()===e,`Amount must not have leading or trailing whitespace`),f.check(e=>!e.includes(`e`)&&!e.includes(`E`),`Scientific notation is not supported (e.g. use 1000000 instead of 1e6)`),f.check(e=>!e.startsWith(`+`),`Amount must not have a '+' prefix`),f.check(e=>!e.startsWith(`-`),`Amount must be non-negative`),f.check(e=>{try{return new Mu(e).gte(0)}catch{return!1}},`Amount must be a valid decimal (e.g. 100 or 100.50)`)),Pu=$({account:Q({description:`Source account id`,required:!0,schema:Bo}),rail:Q({description:`Destination counterparty rail id (cprl_...)`,required:!0,schema:Bo}),amount:Q({description:`USD amount as a decimal string (e.g. 125.00)`,required:!0,schema:Nu,showValueInError:!0}),method:Do({description:`ach | wire | on-chain; ach and wire require a bank rail, on-chain a wallet rail`,required:!0,choices:qa}),memo:Q({description:`Memo on the underlying transfer`}),description:Q({description:`Operator-facing description`}),idempotencyKey:Q({description:`Optional. Usually omit this. Identical retries are deduplicated for about 15 minutes after the movement settles and return the original intent, even if it failed, so a bare retry never re-sends on its own. Set a unique value when you intentionally want another payment with the same details, or a stable one to keep a single payment deduplicated beyond that window.`,schema:Zc}),profile:Lo,json:Ro}),Fu=l({meta:{name:`send`,description:`Submit a USD send intent to a counterparty rail`},args:Pu.args,async run({args:e}){let t=Pu.parse(e),n=Rc(t),r={type:`send`,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}:{}}))}}),Iu=$({from:Q({description:`Source account id`,required:!0,schema:Bo}),to:Q({description:`Destination account id`,required:!0,schema:Bo}),amount:Q({description:`USD amount as a decimal string (e.g. 125.00)`,required:!0,schema:Nu,showValueInError:!0}),memo:Q({description:`Memo on the underlying transfer`}),description:Q({description:`Operator-facing description`}),idempotencyKey:Q({description:`Optional. Usually omit this. Identical retries are deduplicated for about 15 minutes after the movement settles and return the original intent, even if it failed, so a bare retry never re-sends on its own. Set a unique value when you intentionally want another transfer with the same details, or a stable one to keep a single transfer deduplicated beyond that window.`,schema:Zc}),profile:Lo,json:Ro}),Lu=l({meta:{name:`transfer`,description:`Submit a USD transfer intent between two of this agent's accounts`},args:Iu.args,async run({args:e}){let t=Iu.parse(e),n=Rc(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}:{}}))}}),Ru=$({profile:Lo,force:Eo({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:Ro}),zu=l({meta:{name:`unlink`,description:`Disconnect the selected agent profile`},args:Ru.args,async run({args:e}){let t=Ru.parse(e),n=kc(),r;try{r=Dc({flag:Fc(t),env:process.env[Cc],cwd:process.cwd(),log:e=>console.error(e)}).name}catch(e){Z(e)}if(t.force){let e;try{if(e=oc(r),e===null)throw Error(`Profile "${r}" not found`);await n.delete(e.client_instance_id),await n.delete(Ul(e.client_instance_id)),tc(r)}catch(e){Z(e)}Pc({success:!0,profile:r,...Zs(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 gc({profileName:r,fallbackBankUrl:Sc},n);a.ok||Z(`${a.message} ${i}`);let o=Oc(a);try{await o.unlinkAgent(),await n.delete(a.clientInstanceId),await n.delete(Ul(a.clientInstanceId)),tc(r)}catch(e){Z(`${go(Nc(e,r))} ${i}`)}Pc({success:!0,profile:r,agentId:a.agentId},{compact:t.json})}}),Bu=$({profile:Lo,json:Ro}),Vu=l({meta:{name:`whoami`,description:`Show which agent you are currently acting as`},args:Bu.args,async run({args:e}){await Rc(Bu.parse(e))(e=>e.whoami())}});function Hu(e){throw Error(`Unhandled case: ${String(e)}`)}const Uu=[`PAYMENT-REQUIRED`,`X-Payment-Required`],Wu=/^0x[0-9a-fA-F]{64}$/,Gu=/^0x[0-9a-fA-F]{40}$/,Ku=f.looseObject({success:f.boolean(),transaction:f.string()}),qu=f.looseObject({x402Version:f.literal(2),accepts:f.array(eo),resource:f.optional(to)}),Ju=`x402_network_mismatch`,Yu=`x402_counterparty_rail_not_found`,Xu=new Set([`x402_requirement_not_payable`,Ju,Yu]),Zu={"eip155:8453":`Base`,"eip155:84532":`Base Sepolia`};function Qu(e){let t=Object.hasOwn(Zu,e)?Zu[e]:void 0;return t?`${t} (${e})`:e}function $u(e){let t=e.replaceAll(`-`,`+`).replaceAll(`_`,`/`),n=Uint8Array.from(atob(t),e=>e.charCodeAt(0));return JSON.parse(new TextDecoder().decode(n))}function ed(e){let t=Uu.map(t=>e.headers.get(t)).find(e=>e!==null);if(t)try{let e=f.safeParse(qu,$u(t));return e.success?e.output:void 0}catch{return}}async function td(e,t,n){try{let r=n.headers.get(`PAYMENT-RESPONSE`);if(!r)return;let i=f.safeParse(Ku,$u(r));if(!i.success||!i.output.success||!Wu.test(i.output.transaction))return;await e.reportSettlement({intentId:t,txHash:i.output.transaction})}catch{}}var nd=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}},rd=class extends nd{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(Qu).join(` or `)}`,n,{appendReasonsToMessage:!1}),this.name=`X402NetworkMismatchError`,this.accountId=e,this.requiredNetworks=t}},id=class extends nd{payTo;network;serviceName;constructor(e,t,n,r=[]){super(`This 402 pays ${e} on ${Qu(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}},ad=class extends nd{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}},od=class extends nd{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.x402.paymentSignature) instead of paying again`),this.name=`X402RetryFailedError`,this.receipt=e,this.cause=t}};async function sd(e,t){try{return await t()}catch(t){throw new od(e,t)}}var cd=class extends nd{intentId;requirements;constructor(e,t,n){super(`The payment could not be confirmed (intent ${e}); check getIntent("${e}") — completed: reuse its data.x402.paymentSignature 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 ld(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 nd(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 dd(e,{accountId:t.accountId,requirements:n,resource:i}).catch(e=>{if(e instanceof oo&&e.code!==void 0&&Xu.has(e.code)){a.push({error:e,requirement:n});return}throw e});if(r)return r}let o=a.filter(e=>e.error.code===Yu),s=a.filter(e=>e.error.code===Ju),c=a.filter(e=>e.error.code!==Yu&&e.error.code!==Ju),l=[...new Set([...o,...s,...c].map(e=>e.error.message))],u=o.find(e=>e.error.status===404&&Gu.test(e.requirement.payTo));throw u?new id(u.requirement.payTo,u.requirement.network,i?.serviceName,l):s.length>0&&o.length===0?new rd(t.accountId,[...new Set(s.map(e=>e.requirement.network))],l):new nd(`No requirement in the 402 challenge is payable from this account`,l)}const ud=f.object({x402:f.object({paymentSignature:f.string()})});async function dd(e,t){let n=await e.submitIntent({action:{type:`x402`,accountId:t.accountId,paymentRequirements:t.requirements,...t.resource!==void 0&&{resource:t.resource}},idempotencyKey:crypto.randomUUID()}).catch(e=>{throw e instanceof fo&&e.outcome===`unknown`?new cd(e.intentId,t.requirements,e):e});if(n.status===`completed`){let e=f.safeParse(ud,n.data);if(e.success)return{intentId:n.id,paymentSignature:e.output.x402.paymentSignature,requirements:t.requirements};throw new nd(`The completed payment did not carry an x402 payment signature`)}switch(n.status){case`pending`:throw new ad(n.id,n.reasons,n.expiresAt);case`processing`:throw new nd(`The payment is still processing (intent ${n.id}); this client cannot resume an in-flight x402 settlement`);case`blocked`:case`failed`:throw new nd(`Catena declined the payment`,n.reasons)}return Hu(n.status)}function fd(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 pd(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=ed(a);if(!o)return a;if(!fd(r,i))throw new nd(`The request body cannot be replayed after payment; buffer the body (string, Blob, or ArrayBuffer) before using the x402 fetch wrapper`);let s=await ld(e,{accountId:t.accountId,paymentRequired:o,...t.maxAtomicAmount!==void 0&&{maxAtomicAmount:t.maxAtomicAmount}});await sd(s,()=>t.onPayment?.(s));let c=new Headers(typeof Request<`u`&&r instanceof Request?r.headers:void 0);new Headers(i?.headers).forEach((e,t)=>{c.set(t,e)}),c.set(`PAYMENT-SIGNATURE`,s.paymentSignature);let l=await sd(s,()=>n(r,{...i,headers:c}));return td(e,s.intentId,l),l}}function md(e,t){try{T(e,{recursive:!0,mode:448}),S(e,448);let n=ne(e,t);return T(n,{recursive:!0,mode:448}),S(n,448),n}catch{return}}const hd=4e3;function gd(e){try{return k(e)}catch{return}}function _d(e,t,n){try{x(e,t)}catch{Z(n)}}function vd(e){let t=re(e),n=M(t),r=gd(n);(r===void 0||!r.isDirectory())&&Z(`--output ${e}: directory ${n} does not exist`);let i=gd(t);return i===void 0?(_d(n,C.W_OK|C.X_OK,`--output ${e}: directory ${n} is not writable`),t):(i.isDirectory()&&Z(`--output ${e}: destination is a directory`),i.isFile()||Z(`--output ${e}: destination is not a regular file`),_d(t,C.W_OK,`--output ${e}: destination is not writable`),t)}const yd=/^(?:con|prn|aux|nul|com\d|lpt\d)$/i;function bd(e){if(e!==void 0&&zo.test(e)&&!yd.test(e))return`${e}.body`;let t=`${Date.now()}-${_(4).toString(`hex`)}.body`;return e===void 0?`unpaid-${t}`:`paid-${t}`}function xd(e,t){let n=md(Vs(),`responses`);if(n===void 0)return;let r=ne(n,bd(t));try{return A(r,e,{mode:384}),r}catch{return}}function Sd(e){let t=e.subarray(0,hd*4),n=t.toString(`utf8`);return{decoded:n,complete:t.length===e.length&&n.length<=hd&&ae(e)}}function Cd({decoded:e,complete:t}){let n=e.slice(0,hd),r=n.charCodeAt(n.length-1);return{body:r>=55296&&r<=56319?n.slice(0,-1):n,...!t&&{bodyTruncated:!0}}}function wd(e,t){if(t.complete)return{body:t.decoded};if(e.length>268435456)return{...Cd(t),error:`no writable location for the ${e.length}-byte body and it is too large to inline; only the .body preview survived`};if(ae(e)){let t=e.toString(`utf8`);if(6*t.length+2<=ie.MAX_STRING_LENGTH)return{body:t};try{return JSON.stringify(t),{body:t}}catch{}}return{body:e.toString(`base64`),bodyEncoding:`base64`}}function Td(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 Ed(e,t,n){let r=xd(e,t);return r===void 0?wd(e,n):{...Cd(n),bodyPath:r}}function Dd(e,t,n){let r=Sd(e);if(n===void 0)return r.complete?{body:r.decoded}:Ed(e,t,r);try{A(n,e,{mode:384})}catch(i){let a=Ed(e,t,r),o=`--output ${n}: ${go(i)}`;return`bodyPath`in a?{...a,error:`${o}; the full body was saved to ${a.bodyPath}`}:{...a,error:`${o}; ${Td(a)}`}}return{...Cd(r),bodyPath:n}}function Od(e){if(e===`@-`)return kd(0,`stdin`);if(e.startsWith(`@`)){let t=e.slice(1);return t===``?Z(`--data @<path>: no file path given`):kd(t,`@${t}`)}return e}function kd(e,t){try{return ee(e,`utf8`)}catch(e){return Z(`--data ${t}: ${go(e)}`)}}function Ad(e){let[t,n=``]=e.split(`.`);return BigInt(`${t}${n.padEnd(6,`0`)}`)}function jd(e){return{intentId:e.intentId,amountAtomicUsdc:e.requirements.amount,payTo:e.requirements.payTo,network:e.requirements.network}}const Md={"eip155:8453":`base`,"eip155:84532":`base-sepolia`};function Nd(e){return Object.hasOwn(Md,e)?Md[e]:void 0}function Pd(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function Fd(e){return e===void 0?``:` --profile ${Pd(e)}`}function Id(e){let t=e?.replaceAll(/[\p{C}\s]/gu,` `).replaceAll(/ {2,}/g,` `).trim();return t!==void 0&&t.length>0?t:void 0}function Ld(e,t,n,r){let i=Nd(t)??Pd(t);return`catena counterparties create wallet --name ${Pd(n??`<name>`)} --address ${Pd(e)} --network ${i}${Fd(r)}`}const Rd=f.pipe(f.string(),f.check(e=>vc.test(e.slice(0,Math.max(e.indexOf(`:`),0))),`must be "Name: Value" with a valid HTTP header name`),f.transform(e=>{let t=e.indexOf(`:`);return{name:e.slice(0,t),value:e.slice(t+1).trimStart()}}),f.check(e=>/^[\t\x20-\x7e\x80-\xff]*$/.test(e.value),`header value contains characters not allowed in an HTTP header`));function zd(e,t){return e.some(e=>e.name.toLowerCase()===t)}function Bd(e,t){zd(e,`payment-signature`)&&Z(`--header cannot set PAYMENT-SIGNATURE; the payment loop attaches it after paying`),zd(e,`content-type`)&&t!==void 0&&Z(`--header "Content-Type: ..." conflicts with --content-type`)}function Vd(e,t,n){let r=[...n!==void 0&&!zd(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 Hd=$({url:Q({description:`The paywalled URL to fetch (an x402 v2 endpoint)`,required:!0,schema:f.pipe(f.string(),f.url())}),account:Q({description:`Source wallet account id the payment draws from`,required:!0,schema:Bo}),maxAmount:Q({description:`Refuse challenges above this USD amount (decimal string, e.g. 0.25). Policy limits still apply server-side.`,schema:f.pipe(f.string(),f.regex(/^\d+(\.\d{1,6})?$/))}),method:Do({description:`HTTP method for the request`,choices:[`GET`,`POST`]}),data:Q({description:`Request body. Use @path to read a file or @- for stdin. Implies POST and a JSON content type unless overridden.`}),contentType:Q({description:`Content-Type header for the request body (default application/json when --data is set)`}),output:Q({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:To({description:`Request header as "Name: Value" (repeatable, like curl -H); sent on the initial request and the paid retry`,schema:Rd}),profile:Lo,json:Ro}),Ud=l({meta:{name:`x402`,description:`Fetch a URL, paying its x402 (HTTP 402) challenge via USDC`},args:Hd.args,async run({args:e,rawArgs:t}){let n=Hd.parse(e,t),r=n.method??(n.data===void 0?`GET`:`POST`);n.data!==void 0&&r!==`POST`&&Z(`--data cannot be sent with --method ${r}; a body requires POST`),n.contentType!==void 0&&n.data===void 0&&Z(`--content-type has no effect without --data`),Bd(n.header,n.contentType);let i=n.output===void 0?void 0:vd(n.output),a=n.data===void 0?void 0:Od(n.data),o=Vd(n.header,n.contentType,a);await Rc(n)(async e=>{let t,s=pd(e,{accountId:n.account,...n.maxAmount!==void 0&&{maxAtomicAmount:Ad(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 od)return{status:null,paid:!0,retryFailed:!0,payment:jd(e.receipt),error:e.message};if(e instanceof rd){let t=e.requiredNetworks.map(e=>Nd(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${Fd(n.profile)}\`).`}}if(e instanceof id){let t=Id(e.serviceName),r=t!==void 0&&t.length<=40?t:void 0,i=Ld(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:Nd(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 ad)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:jd(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}${Fd(n.profile)}\` to retry manually`;return{...l,error:`failed to read the response body: ${go(e)}${r}`}}return{...l,...Dd(u,t?.intentId,i)}},{exitCode:e=>+(`error`in e)})}}),Wd=f.object({version:f.literal(1),result:f.literal(`latest-version`),latestVersion:f.string(),checkedAt:f.pipe(f.string(),f.isoTimestamp())}),Gd=f.object({version:f.literal(1),result:f.literal(`fetch-failure`),checkedAt:f.pipe(f.string(),f.isoTimestamp())}),Kd=f.variant(`result`,[Wd,Gd]),qd=f.object({"dist-tags":f.object({latest:f.string()})}),Jd=`cache`;function Yd(){return ne(Vs(),Jd,`cli-version.json`)}function Xd(e){return new URL(encodeURIComponent(e),`https://registry.npmjs.org/`).href}function Zd(e){try{let t=JSON.parse(ee(e,`utf8`)),n=f.safeParse(Kd,t);return n.success?n.output:void 0}catch{return}}function Qd(e){let t=Zd(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 $d(e){try{return!w(e)||k(e).isFile()}catch{return!1}}function ef(e){let t=md(Vs(),Jd);if(t===void 0||!$d(e))return!1;let n=ne(t,`.cli-version-check-${_(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 tf(e,t){if(md(Vs(),Jd)===void 0)return!1;try{let n=`${e}.${_(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 nf(e){let t=new AbortController,n=setTimeout(()=>t.abort(),750);n.unref();try{let n=await fetch(Xd(e.packageName),{headers:{accept:`application/json`},signal:t.signal});if(!n.ok)return;let r=await n.json(),i=f.safeParse(qd,r);return i.success?i.output[`dist-tags`].latest:void 0}catch{return}finally{clearTimeout(n)}}function rf(e){let t=P.valid(e.currentVersion),n=P.valid(e.latestVersion);t!==null&&n!==null&&P.gt(n,t)&&console.error(`A newer ${e.packageName} version is available: ${n} (current ${t}).`)}async function af({packageName:e,currentVersion:t}){let n=Yd(),r=Qd(n);if(r?.result===`latest-version`){rf({packageName:e,currentVersion:t,latestVersion:r.latestVersion});return}if(r?.result===`fetch-failure`||!ef(n))return;let i=await nf({packageName:e});if(i===void 0){tf(n,{result:`fetch-failure`});return}tf(n,{result:`latest-version`,latestVersion:i}),rf({packageName:e,currentVersion:t,latestVersion:i})}async function of(e){return typeof e==`function`?await e():await e}async function sf(e){return typeof e==`function`?await e():await e}async function cf(e){return typeof e==`function`?await e():await e}async function lf(e,t,n=[]){if(e===t)return n;let r=await cf(e.subCommands??{});return(await Promise.all(Object.entries(r).map(async([e,r])=>lf(await of(r),t,[...n,e])))).find(e=>e!==void 0)}async function uf(e,t){if(!e||!t||t.length<2)return e;let n=await sf(e.meta??{});return{...e,meta:{...n,name:t.slice(0,-1).join(` `)}}}function df(e){return async(t,n)=>{let r=await u(t,await uf(n,await lf(e,t)));console.log(`${r}\n`)}}function ff({shouldCheckCliVersionFreshness:e}){return l({meta:{name:`catena`,version:se,description:`Catena CLI`},async setup({rawArgs:t}){!e||t.length===0||await af({packageName:oe,currentVersion:se})},subCommands:{link:du,unlink:zu,profiles:Tu,whoami:Vu,policy:hu,accounts:Xc,intents:kl,send:Fu,transfer:Lu,x402:Ud,counterparties:yl,feedback:wl,guide:El}})}const pf=ff({shouldCheckCliVersionFreshness:!0});ff({shouldCheckCliVersionFreshness:!1});function mf(){d(pf,{showUsage:df(pf)})}mf();export{};
526
+ ;const zu=e(s(((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 E(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,E(t,o))},g.minus=g.sub=function(e){var t=this;return e=new t.constructor(e),t.s==e.s?D(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)):E(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):D(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(E(s,n+1,0),s.times(s).eq(u)){r=s;break}}else if(t!=`9999`)break;l+=4}return i=!0,E(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?E(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),E(r,e+S(r)+1,t))},g.toExponential=function(e,t){var r,i=this,a=i.constructor;return e===void 0?r=O(i,!0):(v(e,0,n),t===void 0?t=a.rounding:v(t,0,8),i=E(new a(i),e+1,t),r=O(i,!0,e+1)),r},g.toFixed=function(e,t){var r,i,a=this,o=a.constructor;return e===void 0?O(a):(v(e,0,n),t===void 0?t=o.rounding:v(t,0,8),i=E(new o(a),e+S(a)+1,t),r=O(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 E(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 E(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),k(o.d,t)),n=c(n/2),n!==0;)u=u.times(u),k(u.d,t);return i=!0,e.s<0?new f(d).div(o):E(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=O(a,r<=o.toExpNeg||r>=o.toExpPos)):(v(e,1,n),t===void 0?t=o.rounding:v(t,0,8),a=E(new o(a),e,t),r=S(a),i=O(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)),E(new i(r),e,t)},g.toString=g.valueOf=g.val=g.toJSON=function(){var e=this,t=S(e),n=e.constructor;return O(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?E(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?E(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,ee,D,O,k=r.constructor,A=r.s==i.s?1:-1,j=r.d,M=i.d;if(!r.s)return new k(r);if(!i.s)throw Error(a+`Division by zero`);for(l=r.e-i.e,D=M.length,T=j.length,g=new k(A),_=g.d=[],u=0;M[u]==(j[u]||0);)++u;if(M[u]>(j[u]||0)&&--l,x=o==null?o=k.precision:s?o+(S(r)-S(i))+1:o,x<0)return new k(0);if(x=x/p+2|0,u=0,D==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),D=M.length,T=j.length),w=D,v=j.slice(0,D),y=v.length;y<D;)v[y++]=0;O=M.slice(),O.unshift(0),ee=M[0],M[1]>=f/2&&++ee;do d=0,c=t(M,v,D,y),c<0?(b=v[0],D!=y&&(b=b*f+(v[1]||0)),d=b/ee|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,D<h?O: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,D,y),c<1&&(d++,n(v,D<y?O: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,E(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=E(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=E(o.times(o),u);return m.precision=h,t==null?(i=!0,E(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 E(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,E(g,x)):g;for(l=c=g=b(g.minus(d),g.plus(d),f),p=E(g.times(g),f),o=3;;){if(c=E(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,E(l,x)):l;l=u,o+=2}}function ee(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 E(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 D(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?E(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?E(t,g):t):new h(0)}function O(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 k(e,t){if(e.length>t)return e.length=t,!0}function A(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 ee(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))ee(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=A,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=A(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;zu.set({rounding:zu.ROUND_HALF_EVEN}),new zu(1e6),new zu(1e3);const Bu=f.pipe(f.string(`Amount must be a string`),f.nonEmpty(`Amount must not be empty`),f.check(e=>e.trim()===e,`Amount must not have leading or trailing whitespace`),f.check(e=>!e.includes(`e`)&&!e.includes(`E`),`Scientific notation is not supported (e.g. use 1000000 instead of 1e6)`),f.check(e=>!e.startsWith(`+`),`Amount must not have a '+' prefix`),f.check(e=>!e.startsWith(`-`),`Amount must be non-negative`),f.check(e=>{try{return new zu(e).gte(0)}catch{return!1}},`Amount must be a valid decimal (e.g. 100 or 100.50)`)),Vu=$({account:Q({description:`Source account id`,required:!0,schema:qo}),rail:Q({description:`Destination counterparty rail id (cprl_...)`,required:!0,schema:qo}),amount:Q({description:`USD amount as a decimal string (e.g. 125.00)`,required:!0,schema:Bu,showValueInError:!0}),method:Po({description:`ach | wire | on-chain; ach and wire require a bank rail, on-chain a wallet rail`,required:!0,choices:Ga}),memo:Q({description:`Memo on the underlying transfer`}),description:Q({description:`Operator-facing description`}),idempotencyKey:Q({description:`Optional. Usually omit this. Identical retries are deduplicated for about 15 minutes after the movement settles and return the original intent, even if it failed, so a bare retry never re-sends on its own. Set a unique value when you intentionally want another payment with the same details, or a stable one to keep a single payment deduplicated beyond that window.`,schema:il}),profile:Wo,json:Go}),Hu=l({meta:{name:`send`,description:`Submit a USD send intent to a counterparty rail`},args:Vu.args,async run({args:e}){let t=Vu.parse(e),n=Gc(t),r={type:`send`,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}:{}}))}}),Uu=$({from:Q({description:`Source account id`,required:!0,schema:qo}),to:Q({description:`Destination account id`,required:!0,schema:qo}),amount:Q({description:`USD amount as a decimal string (e.g. 125.00)`,required:!0,schema:Bu,showValueInError:!0}),memo:Q({description:`Memo on the underlying transfer`}),description:Q({description:`Operator-facing description`}),idempotencyKey:Q({description:`Optional. Usually omit this. Identical retries are deduplicated for about 15 minutes after the movement settles and return the original intent, even if it failed, so a bare retry never re-sends on its own. Set a unique value when you intentionally want another transfer with the same details, or a stable one to keep a single transfer deduplicated beyond that window.`,schema:il}),profile:Wo,json:Go}),Wu=l({meta:{name:`transfer`,description:`Submit a USD transfer intent between two of this agent's accounts`},args:Uu.args,async run({args:e}){let t=Uu.parse(e),n=Gc(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}:{}}))}}),Gu=$({profile:Wo,force:No({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:Go}),Ku=l({meta:{name:`unlink`,description:`Disconnect the selected agent profile`},args:Gu.args,async run({args:e}){let t=Gu.parse(e),n=Ic(),r;try{r=Pc({flag:Hc(t),env:process.env[Ac],cwd:process.cwd(),log:e=>console.error(e)}).name}catch(e){Z(e)}if(t.force){let e;try{if(e=pc(r),e===null)throw Error(`Profile "${r}" not found`);await n.delete(e.client_instance_id),await n.delete(Xl(e.client_instance_id)),cc(r)}catch(e){Z(e)}Vc({success:!0,profile:r,...ic(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 Cc({profileName:r,fallbackBankUrl:kc},n);a.ok||Z(`${a.message} ${i}`);let o=Fc(a);try{await o.unlinkAgent(),await n.delete(a.clientInstanceId),await n.delete(Xl(a.clientInstanceId)),cc(r)}catch(e){Z(`${Co(Bc(e,r))} ${i}`)}Vc({success:!0,profile:r,agentId:a.agentId},{compact:t.json})}}),qu=$({profile:Wo,json:Go}),Ju=l({meta:{name:`whoami`,description:`Show which agent you are currently acting as`},args:qu.args,async run({args:e}){await Gc(qu.parse(e))(e=>e.whoami())}});function Yu(e){throw Error(`Unhandled case: ${String(e)}`)}const Xu=[`PAYMENT-REQUIRED`,`X-Payment-Required`],Zu=/^0x[0-9a-fA-F]{64}$/,Qu=/^0x[0-9a-fA-F]{40}$/,$u=f.looseObject({success:f.boolean(),transaction:f.string()}),ed=f.looseObject({x402Version:f.literal(2),accepts:f.array(so),resource:f.optional(co)}),td=`x402_network_mismatch`,nd=`x402_counterparty_rail_not_found`,rd=new Set([`x402_requirement_not_payable`,td,nd]),id={"eip155:8453":`Base`,"eip155:84532":`Base Sepolia`};function ad(e){let t=Object.hasOwn(id,e)?id[e]:void 0;return t?`${t} (${e})`:e}function od(e){let t=e.replaceAll(`-`,`+`).replaceAll(`_`,`/`),n=Uint8Array.from(atob(t),e=>e.charCodeAt(0));return JSON.parse(new TextDecoder().decode(n))}function sd(e){let t=Xu.map(t=>e.headers.get(t)).find(e=>e!==null);if(t)try{let e=f.safeParse(ed,od(t));return e.success?e.output:void 0}catch{return}}async function cd(e,t,n){try{let r=n.headers.get(`PAYMENT-RESPONSE`);if(!r)return;let i=f.safeParse($u,od(r));if(!i.success||!i.output.success||!Zu.test(i.output.transaction))return;await e.reportSettlement({intentId:t,txHash:i.output.transaction})}catch{}}var ld=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}},ud=class extends ld{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(ad).join(` or `)}`,n,{appendReasonsToMessage:!1}),this.name=`X402NetworkMismatchError`,this.accountId=e,this.requiredNetworks=t}},dd=class extends ld{payTo;network;serviceName;constructor(e,t,n,r=[]){super(`This 402 pays ${e} on ${ad(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}},fd=class extends ld{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}},pd=class extends ld{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.x402.paymentSignature) instead of paying again`),this.name=`X402RetryFailedError`,this.receipt=e,this.cause=t}};async function md(e,t){try{return await t()}catch(t){throw new pd(e,t)}}var hd=class extends ld{intentId;requirements;constructor(e,t,n){super(`The payment could not be confirmed (intent ${e}); check getIntent("${e}") — completed: reuse its data.x402.paymentSignature 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 gd(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 ld(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 vd(e,{accountId:t.accountId,requirements:n,resource:i}).catch(e=>{if(e instanceof mo&&e.code!==void 0&&rd.has(e.code)){a.push({error:e,requirement:n});return}throw e});if(r)return r}let o=a.filter(e=>e.error.code===nd),s=a.filter(e=>e.error.code===td),c=a.filter(e=>e.error.code!==nd&&e.error.code!==td),l=[...new Set([...o,...s,...c].map(e=>e.error.message))],u=o.find(e=>e.error.status===404&&Qu.test(e.requirement.payTo));throw u?new dd(u.requirement.payTo,u.requirement.network,i?.serviceName,l):s.length>0&&o.length===0?new ud(t.accountId,[...new Set(s.map(e=>e.requirement.network))],l):new ld(`No requirement in the 402 challenge is payable from this account`,l)}const _d=f.object({x402:f.object({paymentSignature:f.string()})});async function vd(e,t){let n=await e.submitIntent({action:{type:`x402`,accountId:t.accountId,paymentRequirements:t.requirements,...t.resource!==void 0&&{resource:t.resource}},idempotencyKey:crypto.randomUUID()}).catch(e=>{throw e instanceof yo&&e.outcome===`unknown`?new hd(e.intentId,t.requirements,e):e});if(n.status===`completed`){let e=f.safeParse(_d,n.data);if(e.success)return{intentId:n.id,paymentSignature:e.output.x402.paymentSignature,requirements:t.requirements};throw new ld(`The completed payment did not carry an x402 payment signature`)}switch(n.status){case`pending`:throw new fd(n.id,n.reasons,n.expiresAt);case`processing`:throw new ld(`The payment is still processing (intent ${n.id}); this client cannot resume an in-flight x402 settlement`);case`blocked`:case`failed`:throw new ld(`Catena declined the payment`,n.reasons)}return Yu(n.status)}function yd(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 bd(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=sd(a);if(!o)return a;if(!yd(r,i))throw new ld(`The request body cannot be replayed after payment; buffer the body (string, Blob, or ArrayBuffer) before using the x402 fetch wrapper`);let s=await gd(e,{accountId:t.accountId,paymentRequired:o,...t.maxAtomicAmount!==void 0&&{maxAtomicAmount:t.maxAtomicAmount}});await md(s,()=>t.onPayment?.(s));let c=new Headers(typeof Request<`u`&&r instanceof Request?r.headers:void 0);new Headers(i?.headers).forEach((e,t)=>{c.set(t,e)}),c.set(`PAYMENT-SIGNATURE`,s.paymentSignature);let l=await md(s,()=>n(r,{...i,headers:c}));return cd(e,s.intentId,l),l}}function xd(e,t){try{T(e,{recursive:!0,mode:448}),S(e,448);let n=ne(e,t);return T(n,{recursive:!0,mode:448}),S(n,448),n}catch{return}}const Sd=4e3;function Cd(e){try{return k(e)}catch{return}}function wd(e,t,n){try{x(e,t)}catch{Z(n)}}function Td(e){let t=re(e),n=M(t),r=Cd(n);(r===void 0||!r.isDirectory())&&Z(`--output ${e}: directory ${n} does not exist`);let i=Cd(t);return i===void 0?(wd(n,C.W_OK|C.X_OK,`--output ${e}: directory ${n} is not writable`),t):(i.isDirectory()&&Z(`--output ${e}: destination is a directory`),i.isFile()||Z(`--output ${e}: destination is not a regular file`),wd(t,C.W_OK,`--output ${e}: destination is not writable`),t)}const Ed=/^(?:con|prn|aux|nul|com\d|lpt\d)$/i;function Dd(e){if(e!==void 0&&Ko.test(e)&&!Ed.test(e))return`${e}.body`;let t=`${Date.now()}-${_(4).toString(`hex`)}.body`;return e===void 0?`unpaid-${t}`:`paid-${t}`}function Od(e,t){let n=xd(Js(),`responses`);if(n===void 0)return;let r=ne(n,Dd(t));try{return A(r,e,{mode:384}),r}catch{return}}function kd(e){let t=e.subarray(0,Sd*4),n=t.toString(`utf8`);return{decoded:n,complete:t.length===e.length&&n.length<=Sd&&ae(e)}}function Ad({decoded:e,complete:t}){let n=e.slice(0,Sd),r=n.charCodeAt(n.length-1);return{body:r>=55296&&r<=56319?n.slice(0,-1):n,...!t&&{bodyTruncated:!0}}}function jd(e,t){if(t.complete)return{body:t.decoded};if(e.length>268435456)return{...Ad(t),error:`no writable location for the ${e.length}-byte body and it is too large to inline; only the .body preview survived`};if(ae(e)){let t=e.toString(`utf8`);if(6*t.length+2<=ie.MAX_STRING_LENGTH)return{body:t};try{return JSON.stringify(t),{body:t}}catch{}}return{body:e.toString(`base64`),bodyEncoding:`base64`}}function Md(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 Nd(e,t,n){let r=Od(e,t);return r===void 0?jd(e,n):{...Ad(n),bodyPath:r}}function Pd(e,t,n){let r=kd(e);if(n===void 0)return r.complete?{body:r.decoded}:Nd(e,t,r);try{A(n,e,{mode:384})}catch(i){let a=Nd(e,t,r),o=`--output ${n}: ${Co(i)}`;return`bodyPath`in a?{...a,error:`${o}; the full body was saved to ${a.bodyPath}`}:{...a,error:`${o}; ${Md(a)}`}}return{...Ad(r),bodyPath:n}}function Fd(e){if(e===`@-`)return Id(0,`stdin`);if(e.startsWith(`@`)){let t=e.slice(1);return t===``?Z(`--data @<path>: no file path given`):Id(t,`@${t}`)}return e}function Id(e,t){try{return ee(e,`utf8`)}catch(e){return Z(`--data ${t}: ${Co(e)}`)}}function Ld(e){let[t,n=``]=e.split(`.`);return BigInt(`${t}${n.padEnd(6,`0`)}`)}function Rd(e){return{intentId:e.intentId,amountAtomicUsdc:e.requirements.amount,payTo:e.requirements.payTo,network:e.requirements.network}}const zd={"eip155:8453":`base`,"eip155:84532":`base-sepolia`};function Bd(e){return Object.hasOwn(zd,e)?zd[e]:void 0}function Vd(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function Hd(e){return e===void 0?``:` --profile ${Vd(e)}`}function Ud(e){let t=e?.replaceAll(/[\p{C}\s]/gu,` `).replaceAll(/ {2,}/g,` `).trim();return t!==void 0&&t.length>0?t:void 0}function Wd(e,t,n,r){let i=Bd(t)??Vd(t);return`catena counterparties create wallet --name ${Vd(n??`<name>`)} --address ${Vd(e)} --network ${i}${Hd(r)}`}const Gd=f.pipe(f.string(),f.check(e=>Tc.test(e.slice(0,Math.max(e.indexOf(`:`),0))),`must be "Name: Value" with a valid HTTP header name`),f.transform(e=>{let t=e.indexOf(`:`);return{name:e.slice(0,t),value:e.slice(t+1).trimStart()}}),f.check(e=>/^[\t\x20-\x7e\x80-\xff]*$/.test(e.value),`header value contains characters not allowed in an HTTP header`));function Kd(e,t){return e.some(e=>e.name.toLowerCase()===t)}function qd(e,t){Kd(e,`payment-signature`)&&Z(`--header cannot set PAYMENT-SIGNATURE; the payment loop attaches it after paying`),Kd(e,`content-type`)&&t!==void 0&&Z(`--header "Content-Type: ..." conflicts with --content-type`)}function Jd(e,t,n){let r=[...n!==void 0&&!Kd(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 Yd=$({url:Q({description:`The paywalled URL to fetch (an x402 v2 endpoint)`,required:!0,schema:f.pipe(f.string(),f.url())}),account:Q({description:`Source wallet account id the payment draws from`,required:!0,schema:qo}),maxAmount:Q({description:`Refuse challenges above this USD amount (decimal string, e.g. 0.25). Policy limits still apply server-side.`,schema:f.pipe(f.string(),f.regex(/^\d+(\.\d{1,6})?$/))}),method:Po({description:`HTTP method for the request`,choices:[`GET`,`POST`]}),data:Q({description:`Request body. Use @path to read a file or @- for stdin. Implies POST and a JSON content type unless overridden.`}),contentType:Q({description:`Content-Type header for the request body (default application/json when --data is set)`}),output:Q({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:Mo({description:`Request header as "Name: Value" (repeatable, like curl -H); sent on the initial request and the paid retry`,schema:Gd}),profile:Wo,json:Go}),Xd=l({meta:{name:`x402`,description:`Fetch a URL, paying its x402 (HTTP 402) challenge via USDC`},args:Yd.args,async run({args:e,rawArgs:t}){let n=Yd.parse(e,t),r=n.method??(n.data===void 0?`GET`:`POST`);n.data!==void 0&&r!==`POST`&&Z(`--data cannot be sent with --method ${r}; a body requires POST`),n.contentType!==void 0&&n.data===void 0&&Z(`--content-type has no effect without --data`),qd(n.header,n.contentType);let i=n.output===void 0?void 0:Td(n.output),a=n.data===void 0?void 0:Fd(n.data),o=Jd(n.header,n.contentType,a);await Gc(n)(async e=>{let t,s=bd(e,{accountId:n.account,...n.maxAmount!==void 0&&{maxAtomicAmount:Ld(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 pd)return{status:null,paid:!0,retryFailed:!0,payment:Rd(e.receipt),error:e.message};if(e instanceof ud){let t=e.requiredNetworks.map(e=>Bd(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${Hd(n.profile)}\`).`}}if(e instanceof dd){let t=Ud(e.serviceName),r=t!==void 0&&t.length<=40?t:void 0,i=Wd(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:Bd(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 fd)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:Rd(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}${Hd(n.profile)}\` to retry manually`;return{...l,error:`failed to read the response body: ${Co(e)}${r}`}}return{...l,...Pd(u,t?.intentId,i)}},{exitCode:e=>+(`error`in e)})}}),Zd=f.object({version:f.literal(1),result:f.literal(`latest-version`),latestVersion:f.string(),checkedAt:f.pipe(f.string(),f.isoTimestamp())}),Qd=f.object({version:f.literal(1),result:f.literal(`fetch-failure`),checkedAt:f.pipe(f.string(),f.isoTimestamp())}),$d=f.variant(`result`,[Zd,Qd]),ef=f.object({"dist-tags":f.object({latest:f.string()})}),tf=`cache`;function nf(){return ne(Js(),tf,`cli-version.json`)}function rf(e){return new URL(encodeURIComponent(e),`https://registry.npmjs.org/`).href}function af(e){try{let t=JSON.parse(ee(e,`utf8`)),n=f.safeParse($d,t);return n.success?n.output:void 0}catch{return}}function of(e){let t=af(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 sf(e){try{return!w(e)||k(e).isFile()}catch{return!1}}function cf(e){let t=xd(Js(),tf);if(t===void 0||!sf(e))return!1;let n=ne(t,`.cli-version-check-${_(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 lf(e,t){if(xd(Js(),tf)===void 0)return!1;try{let n=`${e}.${_(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 uf(e){let t=new AbortController,n=setTimeout(()=>t.abort(),750);n.unref();try{let n=await fetch(rf(e.packageName),{headers:{accept:`application/json`},signal:t.signal});if(!n.ok)return;let r=await n.json(),i=f.safeParse(ef,r);return i.success?i.output[`dist-tags`].latest:void 0}catch{return}finally{clearTimeout(n)}}function df(e){let t=P.valid(e.currentVersion),n=P.valid(e.latestVersion);t!==null&&n!==null&&P.gt(n,t)&&console.error(`A newer ${e.packageName} version is available: ${n} (current ${t}).`)}async function ff({packageName:e,currentVersion:t}){let n=nf(),r=of(n);if(r?.result===`latest-version`){df({packageName:e,currentVersion:t,latestVersion:r.latestVersion});return}if(r?.result===`fetch-failure`||!cf(n))return;let i=await uf({packageName:e});if(i===void 0){lf(n,{result:`fetch-failure`});return}lf(n,{result:`latest-version`,latestVersion:i}),df({packageName:e,currentVersion:t,latestVersion:i})}async function pf(e){return typeof e==`function`?await e():await e}async function mf(e){return typeof e==`function`?await e():await e}async function hf(e){return typeof e==`function`?await e():await e}async function gf(e,t,n=[]){if(e===t)return n;let r=await hf(e.subCommands??{});return(await Promise.all(Object.entries(r).map(async([e,r])=>gf(await pf(r),t,[...n,e])))).find(e=>e!==void 0)}async function _f(e,t){if(!e||!t||t.length<2)return e;let n=await mf(e.meta??{});return{...e,meta:{...n,name:t.slice(0,-1).join(` `)}}}function vf(e){return async(t,n)=>{let r=await u(t,await _f(n,await gf(e,t)));console.log(`${r}\n`)}}function yf({shouldCheckCliVersionFreshness:e}){return l({meta:{name:`catena`,version:se,description:`Catena CLI`},async setup({rawArgs:t}){!e||t.length===0||await ff({packageName:oe,currentVersion:se})},subCommands:{link:vu,unlink:Ku,profiles:Mu,whoami:Ju,policy:Su,accounts:rl,intents:Il,send:Hu,transfer:Wu,x402:Xd,counterparties:El,feedback:jl,guide:Nl}})}const bf=yf({shouldCheckCliVersionFreshness:!0});yf({shouldCheckCliVersionFreshness:!1});function xf(){d(bf,{showUsage:vf(bf)})}xf();export{};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@catena/cli",
3
- "version": "0.5.1",
3
+ "version": "0.5.2",
4
4
  "description": "Catena CLI for agent runtimes",
5
5
  "homepage": "https://catena.com/",
6
6
  "license": "Apache-2.0",