@catena/cli 0.6.0 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +16 -14
- package/package.json +3 -3
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.6.0`,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.6.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((()=>{
|
|
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=q(),r=Y(),i=Ye(),a=ir(),o=dr(),s=xr(),c=(G(),t(L)),l=Ei(),u=Wi(),d=Ji
|
|
|
133
133
|
`)}if(!t)throw Error(`Required argument 'tag' is missed`);return this.encodeStruct({type:t,rawData:i.BufferSourceConverter.toArrayBuffer(e)})}static encodeStruct(e){let t=e.type.toLocaleUpperCase(),n=[];if(n.push(`-----BEGIN ${t}-----`),e.headers?.length){for(let t of e.headers)n.push(`${t.key}: ${t.value}`);n.push(``)}let r=i.Convert.ToBase64(e.rawData),a,o=0,s=[];for(;o<r.length&&(r.length-o<64?a=r.substring(o):(a=r.substring(o,o+64),o+=64),a.length!==0)&&(s.push(a),!(a.length<64)););return n.push(...s),n.push(`-----END ${t}-----`),n.join(`
|
|
134
134
|
`)}};U.CertificateTag=`CERTIFICATE`,U.CrlTag=`CRL`,U.CertificateRequestTag=`CERTIFICATE REQUEST`,U.PublicKeyTag=`PUBLIC KEY`,U.PrivateKeyTag=`PRIVATE KEY`;var W=class e extends Se{static isAsnEncoded(e){return i.BufferSourceConverter.isBufferSource(e)||typeof e==`string`}static toArrayBuffer(e){if(typeof e==`string`){if(U.isPem(e))return U.decode(e)[0];if(i.Convert.isHex(e))return i.Convert.FromHex(e);if(i.Convert.isBase64(e))return i.Convert.FromBase64(e);if(i.Convert.isBase64Url(e))return i.Convert.FromBase64Url(e);throw TypeError(`Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url`)}{let t=i.Convert.ToBinary(e);return U.isPem(t)?U.decode(t)[0]:i.Convert.isHex(t)?i.Convert.FromHex(t):i.Convert.isBase64(t)?i.Convert.FromBase64(t):i.Convert.isBase64Url(t)?i.Convert.FromBase64Url(t):i.BufferSourceConverter.toArrayBuffer(e)}}constructor(...t){e.isAsnEncoded(t[0])?super(e.toArrayBuffer(t[0]),t[1]):super(t[0])}toString(e=`pem`){switch(e){case`pem`:return U.encode(this.rawData,this.tag);default:return super.toString(e)}}},Ve=class e extends W{static async create(t,n=z.get()){if(t instanceof e)return t;if(we.isCryptoKey(t)){if(t.type!==`public`)throw TypeError(`Public key is required`);let r=await n.subtle.exportKey(`spki`,t);return new e(r)}if(t.publicKey)return t.publicKey;if(i.BufferSourceConverter.isBufferSource(t))return new e(t);throw TypeError(`Unsupported PublicKeyType`)}constructor(e){W.isAsnEncoded(e)?super(e,r.SubjectPublicKeyInfo):super(e),this.tag=U.PublicKeyTag}async export(...e){let t,i=[`verify`],a={hash:`SHA-256`,...this.algorithm};e.length>1?(a=e[0]||a,i=e[1]||i,t=e[2]||z.get()):t=e[0]||z.get();let o=this.rawData,c=n.AsnConvert.parse(this.rawData,r.SubjectPublicKeyInfo);return c.algorithm.algorithm===s.id_RSASSA_PSS&&(o=He(c,o)),t.subtle.importKey(`spki`,o,a,!0,i)}onInit(e){let t=l.container.resolve(b),r=this.algorithm=t.toWebAlgorithm(e.algorithm);switch(e.algorithm.algorithm){case s.id_rsaEncryption:{let t=n.AsnConvert.parse(e.subjectPublicKey,s.RSAPublicKey),a=i.BufferSourceConverter.toUint8Array(t.modulus);r.publicExponent=i.BufferSourceConverter.toUint8Array(t.publicExponent),r.modulusLength=(a[0]?a:a.slice(1)).byteLength<<3;break}}}async getThumbprint(...e){let t,n=`SHA-1`;return e.length>=1&&!e[0]?.subtle?(n=e[0]||n,t=e[1]||z.get()):t=e[0]||z.get(),await t.subtle.digest(n,this.rawData)}async getKeyIdentifier(...e){let t,i=`SHA-1`;e.length===1?typeof e[0]==`string`?(i=e[0],t=z.get()):t=e[0]:e.length===2?(i=e[0],t=e[1]):t=z.get();let a=n.AsnConvert.parse(this.rawData,r.SubjectPublicKeyInfo);return await t.subtle.digest(i,a.subjectPublicKey)}toTextObject(){let e=this.toTextObjectEmpty(),t=n.AsnConvert.parse(this.rawData,r.SubjectPublicKeyInfo);switch(e.Algorithm=xe.serializeAlgorithm(t.algorithm),t.algorithm.algorithm){case o.id_ecPublicKey:e[`EC Point`]=t.subjectPublicKey;break;case s.id_rsaEncryption:default:e[`Raw Data`]=t.subjectPublicKey}return e}};function He(e,t){return e.algorithm=new r.AlgorithmIdentifier({algorithm:s.id_rsaEncryption,parameters:null}),t=n.AsnConvert.serialize(e),t}var Ue=class e extends R{static async create(t,n=!1,r=z.get()){if(`name`in t&&`serialNumber`in t)return new e(t,n);let a=await(await Ve.create(t,r)).getKeyIdentifier(r);return new e(i.Convert.ToHex(a),n)}constructor(...e){if(i.BufferSourceConverter.isBufferSource(e[0]))super(e[0]);else if(typeof e[0]==`string`){let t=new p.AuthorityKeyIdentifier({keyIdentifier:new p.KeyIdentifier(i.Convert.FromHex(e[0]))});super(p.id_ce_authorityKeyIdentifier,e[1],n.AsnConvert.serialize(t))}else{let t=e[0],r=t.name instanceof ze?n.AsnConvert.parse(t.name.rawData,p.GeneralNames):t.name,a=new p.AuthorityKeyIdentifier({authorityCertIssuer:r,authorityCertSerialNumber:i.Convert.FromHex(t.serialNumber)});super(p.id_ce_authorityKeyIdentifier,e[1],n.AsnConvert.serialize(a))}}onInit(e){super.onInit(e);let t=n.AsnConvert.parse(e.extnValue,p.AuthorityKeyIdentifier);t.keyIdentifier&&(this.keyId=i.Convert.ToHex(t.keyIdentifier)),(t.authorityCertIssuer||t.authorityCertSerialNumber)&&(this.certId={name:t.authorityCertIssuer||[],serialNumber:t.authorityCertSerialNumber?i.Convert.ToHex(t.authorityCertSerialNumber):``})}toTextObject(){let e=this.toTextObjectWithoutValue(),t=n.AsnConvert.parse(this.value,p.AuthorityKeyIdentifier);return t.authorityCertIssuer&&(e[`Authority Issuer`]=new ze(t.authorityCertIssuer).toTextObject()),t.authorityCertSerialNumber&&(e[`Authority Serial Number`]=t.authorityCertSerialNumber),t.keyIdentifier&&(e[``]=t.keyIdentifier),e}};Ue.NAME=`Authority Key Identifier`;var We=class extends R{constructor(...e){if(i.BufferSourceConverter.isBufferSource(e[0])){super(e[0]);let t=n.AsnConvert.parse(this.value,r.BasicConstraints);this.ca=t.cA,this.pathLength=t.pathLenConstraint}else{let t=new r.BasicConstraints({cA:e[0],pathLenConstraint:e[1]});super(r.id_ce_basicConstraints,e[2],n.AsnConvert.serialize(t)),this.ca=e[0],this.pathLength=e[1]}}toTextObject(){let e=this.toTextObjectWithoutValue();return this.ca&&(e.CA=this.ca),this.pathLength!==void 0&&(e[`Path Length`]=this.pathLength),e}};We.NAME=`Basic Constraints`,e.ExtendedKeyUsage=void 0,(function(e){e.serverAuth=`1.3.6.1.5.5.7.3.1`,e.clientAuth=`1.3.6.1.5.5.7.3.2`,e.codeSigning=`1.3.6.1.5.5.7.3.3`,e.emailProtection=`1.3.6.1.5.5.7.3.4`,e.timeStamping=`1.3.6.1.5.5.7.3.8`,e.ocspSigning=`1.3.6.1.5.5.7.3.9`})(e.ExtendedKeyUsage||={});var Ge=class extends R{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=>be.toString(e)).join(`, `),e}};Ge.NAME=`Extended Key Usages`,e.KeyUsageFlags=void 0,(function(e){e[e.digitalSignature=1]=`digitalSignature`,e[e.nonRepudiation=2]=`nonRepudiation`,e[e.keyEncipherment=4]=`keyEncipherment`,e[e.dataEncipherment=8]=`dataEncipherment`,e[e.keyAgreement=16]=`keyAgreement`,e[e.keyCertSign=32]=`keyCertSign`,e[e.cRLSign=64]=`cRLSign`,e[e.encipherOnly=128]=`encipherOnly`,e[e.decipherOnly=256]=`decipherOnly`})(e.KeyUsageFlags||={});var Ke=class extends R{constructor(...e){if(i.BufferSourceConverter.isBufferSource(e[0])){super(e[0]);let t=n.AsnConvert.parse(this.value,r.KeyUsage);this.usages=t.toNumber()}else{let t=new r.KeyUsage(e[0]);super(r.id_ce_keyUsage,e[1],n.AsnConvert.serialize(t)),this.usages=e[0]}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[``]=n.AsnConvert.parse(this.value,r.KeyUsage).toJSON().join(`, `),e}};Ke.NAME=`Key Usages`;var qe=class e extends R{static async create(t,n=!1,r=z.get()){let a=await(await Ve.create(t,r)).getKeyIdentifier(r);return new e(i.Convert.ToHex(a),n)}constructor(...e){if(i.BufferSourceConverter.isBufferSource(e[0])){super(e[0]);let t=n.AsnConvert.parse(this.value,p.SubjectKeyIdentifier);this.keyId=i.Convert.ToHex(t)}else{let t=typeof e[0]==`string`?i.Convert.FromHex(e[0]):e[0],r=new p.SubjectKeyIdentifier(t);super(p.id_ce_subjectKeyIdentifier,e[1],n.AsnConvert.serialize(r)),this.keyId=i.Convert.ToHex(t)}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[``]=n.AsnConvert.parse(this.value,p.SubjectKeyIdentifier),e}};qe.NAME=`Subject Key Identifier`;var Je=class extends R{constructor(...e){i.BufferSourceConverter.isBufferSource(e[0])?super(e[0]):super(p.id_ce_subjectAltName,e[1],new ze(e[0]||[]).rawData)}onInit(e){super.onInit(e);let t=n.AsnConvert.parse(e.extnValue,p.SubjectAlternativeName);this.names=new ze(t)}toTextObject(){let e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(let n in t)e[n]=t[n];return e}};Je.NAME=`Subject Alternative Name`;var Xe=class{static register(e,t){this.items.set(e,t)}static create(e){let t=new R(e),n=this.items.get(t.type);return n?new n(e):t}};Xe.items=new Map;var Ze=class extends R{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(``,{},be.toString(e))),e}};Ze.NAME=`Certificate Policies`,Xe.register(p.id_ce_certificatePolicies,Ze);var Qe=class extends R{constructor(...e){if(i.BufferSourceConverter.isBufferSource(e[0]))super(e[0]);else if(Array.isArray(e[0])&&typeof e[0][0]==`string`){let t=e[0].map(e=>new p.DistributionPoint({distributionPoint:new p.DistributionPointName({fullName:[new p.GeneralName({uniformResourceIdentifier:e})]})})),r=new p.CRLDistributionPoints(t);super(p.id_ce_cRLDistributionPoints,e[1],n.AsnConvert.serialize(r))}else{let t=new p.CRLDistributionPoints(e[0]);super(p.id_ce_cRLDistributionPoints,e[1],n.AsnConvert.serialize(t))}this.distributionPoints??=[]}onInit(e){super.onInit(e);let t=n.AsnConvert.parse(e.extnValue,p.CRLDistributionPoints);this.distributionPoints=t}toTextObject(){let e=this.toTextObjectWithoutValue();return e[`Distribution Point`]=this.distributionPoints.map(e=>{let t={};return e.distributionPoint&&(t[``]=e.distributionPoint.fullName?.map(e=>new Re(e).toString()).join(`, `)),e.reasons&&(t.Reasons=e.reasons.toString()),e.cRLIssuer&&(t[`CRL Issuer`]=e.cRLIssuer.map(e=>e.toString()).join(`, `)),t}),e}};Qe.NAME=`CRL Distribution Points`;var $e=class extends R{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;tt(r,t,p.id_ad_ocsp,`ocsp`),tt(r,t,p.id_ad_caIssuers,`caIssuers`),tt(r,t,p.id_ad_timeStamping,`timeStamping`),tt(r,t,p.id_ad_caRepository,`caRepository`),super(p.id_pe_authorityInfoAccess,e[1],n.AsnConvert.serialize(r))}this.ocsp??=[],this.caIssuers??=[],this.timeStamping??=[],this.caRepository??=[]}onInit(e){super.onInit(e),this.ocsp=[],this.caIssuers=[],this.timeStamping=[],this.caRepository=[],n.AsnConvert.parse(e.extnValue,p.AuthorityInfoAccessSyntax).forEach(e=>{switch(e.accessMethod){case p.id_ad_ocsp:this.ocsp.push(new Re(e.accessLocation));break;case p.id_ad_caIssuers:this.caIssuers.push(new Re(e.accessLocation));break;case p.id_ad_timeStamping:this.timeStamping.push(new Re(e.accessLocation));break;case p.id_ad_caRepository:this.caRepository.push(new Re(e.accessLocation))}})}toTextObject(){let e=this.toTextObjectWithoutValue();return this.ocsp.length&&et(e,`OCSP`,this.ocsp),this.caIssuers.length&&et(e,`CA Issuers`,this.caIssuers),this.timeStamping.length&&et(e,`Time Stamping`,this.timeStamping),this.caRepository.length&&et(e,`CA Repository`,this.caRepository),e}};$e.NAME=`Authority Info Access`;function et(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 tt(e,t,r,i){let a=t[i];a&&(Array.isArray(a)?a:[a]).forEach(t=>{typeof t==`string`&&(t=new Re(`url`,t)),e.push(new p.AccessDescription({accessMethod:r,accessLocation:n.AsnConvert.parse(t.rawData,p.GeneralName)}))})}var K=class e extends Se{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]=be.toString(this.type)),t}};K.NAME=`Attribute`;var nt=class extends K{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}};nt.NAME=`Challenge Password`;var rt=class extends K{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=>Xe.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}};rt.NAME=`Extensions`;var it=class{static register(e,t){this.items.set(e,t)}static create(e){let t=new K(e),n=this.items.get(t.type);return n?new n(e):t}};it.items=new Map;let at=`crypto.signatureFormatter`;var ot=class{toAsnSignature(e,t){return i.BufferSourceConverter.toArrayBuffer(t)}toWebSignature(e,t){return i.BufferSourceConverter.toArrayBuffer(t)}},st;e.RsaAlgorithm=st=class{static createPssParams(e,t){let i=st.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=st.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=st=c.__decorate([l.injectable()],e.RsaAlgorithm),l.container.registerSingleton(v,e.RsaAlgorithm),e.ShaAlgorithm=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case`sha-1`:return new r.AlgorithmIdentifier({algorithm:s.id_sha1});case`sha-256`:return new r.AlgorithmIdentifier({algorithm:s.id_sha256});case`sha-384`:return new r.AlgorithmIdentifier({algorithm:s.id_sha384});case`sha-512`:return new r.AlgorithmIdentifier({algorithm:s.id_sha512})}return null}toWebAlgorithm(e){switch(e.algorithm){case s.id_sha1:return{name:`SHA-1`};case s.id_sha256:return{name:`SHA-256`};case s.id_sha384:return{name:`SHA-384`};case s.id_sha512:return{name:`SHA-512`}}return null}},e.ShaAlgorithm=c.__decorate([l.injectable()],e.ShaAlgorithm),l.container.registerSingleton(v,e.ShaAlgorithm);var ct=class e{addPadding(e,t){let n=i.BufferSourceConverter.toUint8Array(t),r=new Uint8Array(e);return r.set(n,e-n.length),r}removePadding(e,t=!1){let n=i.BufferSourceConverter.toUint8Array(e);for(let e=0;e<n.length;e++)if(n[e]){n=n.slice(e);break}if(t&&n[0]>127){let e=new Uint8Array(n.length+1);return e.set(n,1),e.buffer}return n.buffer}toAsnSignature(t,r){if(t.name===`ECDSA`){let a=t.namedCurve,s=e.namedCurveSize.get(a)||e.defaultNamedCurveSize,c=new o.ECDSASigValue,l=i.BufferSourceConverter.toUint8Array(r);return c.r=this.removePadding(l.slice(0,s),!0),c.s=this.removePadding(l.slice(s,s+s),!0),n.AsnConvert.serialize(c)}return null}toWebSignature(t,r){if(t.name===`ECDSA`){let a=n.AsnConvert.parse(r,o.ECDSASigValue),s=t.namedCurve,c=e.namedCurveSize.get(s)||e.defaultNamedCurveSize,l=this.addPadding(c,this.removePadding(a.r)),u=this.addPadding(c,this.removePadding(a.s));return i.combine(l,u)}return null}};ct.namedCurveSize=new Map,ct.defaultNamedCurveSize=32;let lt=`1.3.101.110`,ut=`1.3.101.111`,dt=`1.3.101.112`,ft=`1.3.101.113`;e.EdAlgorithm=class{toAsnAlgorithm(e){let t=null;switch(e.name.toLowerCase()){case`ed25519`:t=dt;break;case`x25519`:t=lt;break;case`eddsa`:switch(e.namedCurve.toLowerCase()){case`ed25519`:t=dt;break;case`ed448`:t=ft}break;case`ecdh-es`:switch(e.namedCurve.toLowerCase()){case`x25519`:t=lt;break;case`x448`:t=ut}}return t?new r.AlgorithmIdentifier({algorithm:t}):null}toWebAlgorithm(e){switch(e.algorithm){case dt:return{name:`Ed25519`};case ft:return{name:`EdDSA`,namedCurve:`Ed448`};case lt:return{name:`X25519`};case ut:return{name:`ECDH-ES`,namedCurve:`X448`}}return null}},e.EdAlgorithm=c.__decorate([l.injectable()],e.EdAlgorithm),l.container.registerSingleton(v,e.EdAlgorithm);var pt=class extends W{constructor(e){W.isAsnEncoded(e)?super(e,d.CertificationRequest):super(e),this.tag=U.CertificateRequestTag}onInit(e){this.tbs=n.AsnConvert.serialize(e.certificationRequestInfo),this.publicKey=new Ve(e.certificationRequestInfo.subjectPKInfo);let t=l.container.resolve(b);this.signatureAlgorithm=t.toWebAlgorithm(e.signatureAlgorithm),this.signature=e.signature,this.attributes=e.certificationRequestInfo.attributes.map(e=>it.create(n.AsnConvert.serialize(e)));let r=this.getAttribute(u.id_pkcs9_at_extensionRequest);this.extensions=[],r instanceof rt&&(this.extensions=r.items),this.subjectName=new V(e.certificationRequestInfo.subject),this.subject=this.subjectName.toString()}getAttribute(e){for(let t of this.attributes)if(t.type===e)return t;return null}getAttributes(e){return this.attributes.filter(t=>t.type===e)}getExtension(e){for(let t of this.extensions)if(t.type===e)return t;return null}getExtensions(e){return this.extensions.filter(t=>t.type===e)}async verify(e=z.get()){let t={...this.publicKey.algorithm,...this.signatureAlgorithm},n=await this.publicKey.export(t,[`verify`],e),r=l.container.resolveAll(at).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:xe.serializeAlgorithm(t.signatureAlgorithm),"":t.signature}),e}};pt.NAME=`PKCS#10 Certificate Request`;var mt=class{static async create(e,t=z.get()){if(!e.keys.privateKey)throw Error(`Bad field 'keys' in 'params' argument. 'privateKey' is empty`);if(!e.keys.publicKey)throw Error(`Bad field 'keys' in 'params' argument. 'publicKey' is empty`);let i=await t.subtle.exportKey(`spki`,e.keys.publicKey),a=new d.CertificationRequest({certificationRequestInfo:new d.CertificationRequestInfo({subjectPKInfo:n.AsnConvert.parse(i,r.SubjectPublicKeyInfo)})});if(e.name){let t=e.name instanceof V?e.name:new V(e.name);a.certificationRequestInfo.subject=n.AsnConvert.parse(t.toArrayBuffer(),r.Name)}if(e.attributes)for(let t of e.attributes)a.certificationRequestInfo.attributes.push(n.AsnConvert.parse(t.rawData,r.Attribute));if(e.extensions&&e.extensions.length){let t=new r.Attribute({type:u.id_pkcs9_at_extensionRequest}),i=new r.Extensions;for(let t of e.extensions)i.push(n.AsnConvert.parse(t.rawData,r.Extension));t.values.push(n.AsnConvert.serialize(i)),a.certificationRequestInfo.attributes.push(t)}let o={...e.signingAlgorithm,...e.keys.privateKey.algorithm};a.signatureAlgorithm=l.container.resolve(b).toAsnAlgorithm(o);let s=n.AsnConvert.serialize(a.certificationRequestInfo),c=await t.subtle.sign(o,e.keys.privateKey,s),f=l.container.resolveAll(at).reverse(),p=null;for(let e of f)if(p=e.toAsnSignature(o,c),p)break;if(!p)throw Error(`Cannot convert WebCrypto signature value to ASN.1 format`);return a.signature=p,new pt(n.AsnConvert.serialize(a))}},ht=class extends W{constructor(e){W.isAsnEncoded(e)?super(e,r.Certificate):super(e),this.tag=U.CertificateTag}onInit(e){let t=e.tbsCertificate;this.tbs=n.AsnConvert.serialize(t),this.serialNumber=i.Convert.ToHex(t.serialNumber),this.subjectName=new V(t.subject),this.subject=new V(t.subject).toString(),this.issuerName=new V(t.issuer),this.issuer=this.issuerName.toString();let r=l.container.resolve(b);this.signatureAlgorithm=r.toWebAlgorithm(e.signatureAlgorithm),this.signature=e.signatureValue;let a=t.validity.notBefore.utcTime||t.validity.notBefore.generalTime;if(!a)throw Error(`Cannot get 'notBefore' value`);this.notBefore=a;let o=t.validity.notAfter.utcTime||t.validity.notAfter.generalTime;if(!o)throw Error(`Cannot get 'notAfter' value`);this.notAfter=o,this.extensions=[],t.extensions&&(this.extensions=t.extensions.map(e=>Xe.create(n.AsnConvert.serialize(e)))),this.publicKey=new Ve(t.subjectPublicKeyInfo)}getExtension(e){for(let t of this.extensions)if(typeof e==`string`){if(t.type===e)return t}else if(t instanceof e)return t;return null}getExtensions(e){return this.extensions.filter(t=>typeof e==`string`?t.type===e:t instanceof e)}async verify(e={},t=z.get()){let n,r,a=e.publicKey;try{if(!a)n={...this.publicKey.algorithm,...this.signatureAlgorithm},r=await this.publicKey.export(n,[`verify`],t);else if(`publicKey`in a)n={...a.publicKey.algorithm,...this.signatureAlgorithm},r=await a.publicKey.export(n,[`verify`],t);else if(a instanceof Ve)n={...a.algorithm,...this.signatureAlgorithm},r=await a.export(n,[`verify`],t);else if(i.BufferSourceConverter.isBufferSource(a)){let e=new Ve(a);n={...e.algorithm,...this.signatureAlgorithm},r=await e.export(n,[`verify`],t)}else n={...a.algorithm,...this.signatureAlgorithm},r=a}catch{return!1}let o=l.container.resolveAll(at).reverse(),s=null;for(let e of o)if(s=e.toWebSignature(n,this.signature),s)break;if(!s)throw Error(`Cannot convert ASN.1 signature value to WebCrypto format`);let c=await t.subtle.verify(this.signatureAlgorithm,r,s,this.tbs);if(e.signatureOnly)return c;{let t=(e.date||new Date).getTime();return c&&this.notBefore.getTime()<t&&t<this.notAfter.getTime()}}async getThumbprint(...e){let t,n=`SHA-1`;return e[0]&&(e[0].subtle?t=e[0]:(n=e[0]||n,t=e[1])),t??=z.get(),await t.subtle.digest(n,this.rawData)}async isSelfSigned(e=z.get()){return this.subject===this.issuer&&await this.verify({signatureOnly:!0},e)}toTextObject(){let e=this.toTextObjectEmpty(),t=n.AsnConvert.parse(this.rawData,r.Certificate),i=t.tbsCertificate,a=new I(``,{Version:`${r.Version[i.version]} (${i.version})`,"Serial Number":i.serialNumber,"Signature Algorithm":xe.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:xe.serializeAlgorithm(t.signatureAlgorithm),"":t.signatureValue}),e}};ht.NAME=`Certificate`;var gt=class extends Array{constructor(e){if(super(),W.isAsnEncoded(e))this.import(e);else if(e instanceof ht)this.push(e);else if(Array.isArray(e))for(let t of e)this.push(t)}export(e){let t=new m.SignedData;t.version=1,t.encapContentInfo.eContentType=m.id_data,t.encapContentInfo.eContent=new m.EncapsulatedContent({single:new n.OctetString}),t.certificates=new m.CertificateSet(this.map(e=>new m.CertificateChoices({certificate:n.AsnConvert.parse(e.rawData,r.Certificate)})));let i=new m.ContentInfo({contentType:m.id_signedData,content:n.AsnConvert.serialize(t)}),a=n.AsnConvert.serialize(i);return e===`raw`?a:this.toString(e)}import(e){let t=W.toArrayBuffer(e),r=n.AsnConvert.parse(t,m.ContentInfo);if(r.contentType!==m.id_signedData)throw TypeError(`Cannot parse CMS package. Incoming data is not a SignedData object.`);let i=n.AsnConvert.parse(r.content,m.SignedData);this.clear();for(let e of i.certificates||[])e.certificate&&this.push(new ht(e.certificate))}clear(){for(;this.pop(););}toString(e=`pem`){let t=this.export(`raw`);switch(e){case`pem`:return U.encode(t,`CMS`);case`pem-chain`:return this.map(e=>e.toString(`pem`)).join(`
|
|
135
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 xe.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":be.toString(e.contentType),Content:new I(``,{Version:`${m.CMSVersion[t.version]} (${t.version})`,Certificates:new I(``,{Certificate:this.map(e=>e.toTextObject())})})})}},_t=class{constructor(e={}){this.certificates=[],e.certificates&&(this.certificates=e.certificates)}async build(e,t=z.get()){let n=new gt(e),r=e;for(;r=await this.findIssuer(r,t);){let e=await r.getThumbprint(t);for(let r of n){let n=await r.getThumbprint(t);if(i.isEqual(e,n))throw Error(`Cannot build a certificate chain. Circular dependency.`)}n.push(r)}return n}async findIssuer(e,t=z.get()){if(!await e.isSelfSigned(t)){let r=e.getExtension(p.id_ce_authorityKeyIdentifier);for(let a of this.certificates)if(a.subject===e.issuer){if(r){if(r.keyId){let e=a.getExtension(p.id_ce_subjectKeyIdentifier);if(e&&e.keyId!==r.keyId)continue}else if(r.certId){let e=a.getExtension(p.id_ce_subjectAltName);if(e&&!(r.certId.serialNumber===a.serialNumber&&i.isEqual(n.AsnConvert.serialize(r.certId.name),n.AsnConvert.serialize(e))))continue}}try{let n={...a.publicKey.algorithm,...e.signatureAlgorithm},r=await a.publicKey.export(n,[`verify`],t);if(!await e.verify({publicKey:r,signatureOnly:!0},t))continue}catch{continue}return a}}return null}},vt=class{static async createSelfSigned(e,t=z.get()){if(!e.keys.privateKey)throw Error(`Bad field 'keys' in 'params' argument. 'privateKey' is empty`);if(!e.keys.publicKey)throw Error(`Bad field 'keys' in 'params' argument. 'publicKey' is empty`);return this.create({serialNumber:e.serialNumber,subject:e.name,issuer:e.name,notBefore:e.notBefore,notAfter:e.notAfter,publicKey:e.keys.publicKey,signingKey:e.keys.privateKey,signingAlgorithm:e.signingAlgorithm,extensions:e.extensions},t)}static async create(e,t=z.get()){let r;r=e.publicKey instanceof Ve?e.publicKey.rawData:`publicKey`in e.publicKey?e.publicKey.publicKey.rawData:i.BufferSourceConverter.isBufferSource(e.publicKey)?e.publicKey:await t.subtle.exportKey(`spki`,e.publicKey);let a=e.serialNumber?i.BufferSourceConverter.toUint8Array(i.Convert.FromHex(e.serialNumber)):t.getRandomValues(new Uint8Array(16));a[0]>127&&(a[0]&=127),a.length>1&&a[0]===0&&(a[1]|=128);let o=e.notBefore||new Date,s=e.notAfter||new Date(o.getTime()+31536e6),c=new p.Certificate({tbsCertificate:new p.TBSCertificate({version:p.Version.v3,serialNumber:a,validity:new p.Validity({notBefore:o,notAfter:s}),extensions:new p.Extensions(e.extensions?.map(e=>n.AsnConvert.parse(e.rawData,p.Extension))||[]),subjectPublicKeyInfo:n.AsnConvert.parse(r,p.SubjectPublicKeyInfo)})});if(e.subject){let t=e.subject instanceof V?e.subject:new V(e.subject);c.tbsCertificate.subject=n.AsnConvert.parse(t.toArrayBuffer(),p.Name)}if(e.issuer){let t=e.issuer instanceof V?e.issuer:new V(e.issuer);c.tbsCertificate.issuer=n.AsnConvert.parse(t.toArrayBuffer(),p.Name)}let u={hash:`SHA-256`},d=`signingKey`in e?{...u,...e.signingAlgorithm,...e.signingKey.algorithm}:{...u,...e.signingAlgorithm},f=l.container.resolve(b);c.tbsCertificate.signature=c.signatureAlgorithm=f.toAsnAlgorithm(d);let m=n.AsnConvert.serialize(c.tbsCertificate),h=`signingKey`in e?await t.subtle.sign(d,e.signingKey,m):e.signature,g=l.container.resolveAll(at).reverse(),_=null;for(let e of g)if(_=e.toAsnSignature(d,h),_)break;if(!_)throw Error(`Cannot convert ASN.1 signature value to WebCrypto format`);return c.signatureValue=_,new ht(n.AsnConvert.serialize(c))}};e.X509CrlReason=void 0,(function(e){e[e.unspecified=0]=`unspecified`,e[e.keyCompromise=1]=`keyCompromise`,e[e.cACompromise=2]=`cACompromise`,e[e.affiliationChanged=3]=`affiliationChanged`,e[e.superseded=4]=`superseded`,e[e.cessationOfOperation=5]=`cessationOfOperation`,e[e.certificateHold=6]=`certificateHold`,e[e.removeFromCRL=8]=`removeFromCRL`,e[e.privilegeWithdrawn=9]=`privilegeWithdrawn`,e[e.aACompromise=10]=`aACompromise`})(e.X509CrlReason||={});var yt=class extends Se{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=Xe.create(n.AsnConvert.serialize(e));switch(t.type){case r.id_ce_cRLReasons:this.reason=n.AsnConvert.parse(t.value,r.CRLReason).reason;break;case r.id_ce_invalidityDate:this.invalidity=n.AsnConvert.parse(t.value,r.InvalidityDate).value}return t}))}},bt=class extends W{constructor(e){W.isAsnEncoded(e)?super(e,r.CertificateList):super(e),this.tag=U.CrlTag}onInit(e){let t=e.tbsCertList;this.tbs=n.AsnConvert.serialize(t),this.version=t.version;let r=l.container.resolve(b);this.signatureAlgorithm=r.toWebAlgorithm(e.signatureAlgorithm),this.tbsCertListSignatureAlgorithm=t.signature,this.certListSignatureAlgorithm=e.signatureAlgorithm,this.signature=e.signature,this.issuerName=new V(t.issuer),this.issuer=this.issuerName.toString();let i=t.thisUpdate.getTime();if(!i)throw Error(`Cannot get 'thisUpdate' value`);this.thisUpdate=i;let a=t.nextUpdate?.getTime();this.nextUpdate=a,this.entries=t.revokedCertificates?.map(e=>new yt(n.AsnConvert.serialize(e)))||[],this.extensions=[],t.crlExtensions&&(this.extensions=t.crlExtensions.map(e=>Xe.create(n.AsnConvert.serialize(e))))}getExtension(e){for(let t of this.extensions)if(typeof e==`string`){if(t.type===e)return t}else if(t instanceof e)return t;return null}getExtensions(e){return this.extensions.filter(t=>typeof e==`string`?t.type===e:t instanceof e)}async verify(e,t=z.get()){if(!this.certListSignatureAlgorithm.isEqual(this.tbsCertListSignatureAlgorithm))throw Error(`algorithm identifier in the sequence tbsCertList and CertificateList mismatch`);let n,r,i=e.publicKey;try{i instanceof ht?(n={...i.publicKey.algorithm,...i.signatureAlgorithm},r=await i.publicKey.export(n,[`verify`])):i instanceof Ve?(n={...i.algorithm,...this.signature},r=await i.export(n,[`verify`])):(n={...i.algorithm,...this.signature},r=i)}catch{return!1}let a=l.container.resolveAll(at).reverse(),o=null;for(let e of a)if(o=e.toWebSignature(n,this.signature),o)break;if(!o)throw Error(`Cannot convert ASN.1 signature value to WebCrypto format`);return await t.subtle.verify(this.signatureAlgorithm,r,o,this.tbs)}async getThumbprint(...e){let t,n=`SHA-1`;return e[0]&&(e[0].subtle?t=e[0]:(n=e[0]||n,t=e[1])),t??=z.get(),await t.subtle.digest(n,this.rawData)}findRevoked(e){let t=typeof e==`string`?e:e.serialNumber;for(let e of this.entries)if(e.serialNumber===t)return e;return null}},xt=class{static async create(e,t=z.get()){let a=e.issuer instanceof V?e.issuer:new V(e.issuer),o=new p.CertificateList({tbsCertList:new p.TBSCertList({version:p.Version.v2,issuer:n.AsnConvert.parse(a.toArrayBuffer(),p.Name),thisUpdate:new r.Time(e.thisUpdate||new Date)})});if(e.nextUpdate&&(o.tbsCertList.nextUpdate=new r.Time(e.nextUpdate)),e.extensions&&e.extensions.length&&(o.tbsCertList.crlExtensions=new p.Extensions(e.extensions.map(e=>n.AsnConvert.parse(e.rawData,p.Extension))||[])),e.entries&&e.entries.length){o.tbsCertList.revokedCertificates=[];for(let t of e.entries){let a=W.toArrayBuffer(t.serialNumber);if(o.tbsCertList.revokedCertificates.findIndex(e=>i.isEqual(e.userCertificate,a))>-1)throw Error(`Certificate serial number ${t.serialNumber} already exists in tbsCertList`);let s=new r.RevokedCertificate({userCertificate:a,revocationDate:new r.Time(t.revocationDate||new Date)});if(s.crlEntryExtensions=`extensions`in t&&t.extensions?.length?t.extensions.map(e=>n.AsnConvert.parse(e.rawData,p.Extension)):[],!(t instanceof yt)&&(t.reason&&s.crlEntryExtensions.push(new p.Extension({extnID:p.id_ce_cRLReasons,critical:!1,extnValue:new n.OctetString(n.AsnConvert.serialize(new p.CRLReason(t.reason)))})),t.invalidity&&s.crlEntryExtensions.push(new p.Extension({extnID:p.id_ce_invalidityDate,critical:!1,extnValue:new n.OctetString(n.AsnConvert.serialize(new p.InvalidityDate(t.invalidity)))})),t.issuer)){let t=e.issuer instanceof V?e.issuer:new V(e.issuer);s.crlEntryExtensions.push(new p.Extension({extnID:p.id_ce_certificateIssuer,critical:!1,extnValue:new n.OctetString(n.AsnConvert.serialize(n.AsnConvert.parse(t.toArrayBuffer(),p.Name)))}))}o.tbsCertList.revokedCertificates.push(s)}}let s={...e.signingAlgorithm,...e.signingKey.algorithm},c=l.container.resolve(b);o.tbsCertList.signature=o.signatureAlgorithm=c.toAsnAlgorithm(s);let u=n.AsnConvert.serialize(o.tbsCertList),d=await t.subtle.sign(s,e.signingKey,u),f=l.container.resolveAll(at).reverse(),m=null;for(let e of f)if(m=e.toAsnSignature(s,d),m)break;if(!m)throw Error(`Cannot convert ASN.1 signature value to WebCrypto format`);return o.signature=m,new bt(n.AsnConvert.serialize(o))}};Xe.register(p.id_ce_basicConstraints,We),Xe.register(p.id_ce_extKeyUsage,Ge),Xe.register(p.id_ce_keyUsage,Ke),Xe.register(p.id_ce_subjectKeyIdentifier,qe),Xe.register(p.id_ce_authorityKeyIdentifier,Ue),Xe.register(p.id_ce_subjectAltName,Je),Xe.register(p.id_ce_cRLDistributionPoints,Qe),Xe.register(p.id_pe_authorityInfoAccess,$e),it.register(_.id_pkcs9_at_challengePassword,nt),it.register(_.id_pkcs9_at_extensionRequest,rt),l.container.registerSingleton(at,ot),l.container.registerSingleton(at,ct),ct.namedCurveSize.set(`P-256`,32),ct.namedCurveSize.set(`K-256`,32),ct.namedCurveSize.set(`P-384`,48),ct.namedCurveSize.set(`P-521`,66),e.AlgorithmProvider=y,e.AsnData=Se,e.AsnDefaultSignatureFormatter=ot,e.AsnEcSignatureFormatter=ct,e.Attribute=K,e.AttributeFactory=it,e.AuthorityInfoAccessExtension=$e,e.AuthorityKeyIdentifierExtension=Ue,e.BasicConstraintsExtension=We,e.CRLDistributionPointsExtension=Qe,e.CertificatePolicyExtension=Ze,e.ChallengePasswordAttribute=nt,e.CryptoProvider=we,e.DefaultAlgorithmSerializer=ye,e.ExtendedKeyUsageExtension=Ge,e.Extension=R,e.ExtensionFactory=Xe,e.ExtensionsAttribute=rt,e.GeneralName=Re,e.GeneralNames=ze,e.KeyUsagesExtension=Ke,e.Name=V,e.NameIdentifier=De,e.OidSerializer=be,e.PemConverter=U,e.Pkcs10CertificateRequest=pt,e.Pkcs10CertificateRequestGenerator=mt,e.PublicKey=Ve,e.SubjectAlternativeNameExtension=Je,e.SubjectKeyIdentifierExtension=qe,e.TextConverter=xe,e.TextObject=I,e.X509Certificate=ht,e.X509CertificateGenerator=vt,e.X509Certificates=gt,e.X509ChainBuilder=_t,e.X509Crl=bt,e.X509CrlEntry=yt,e.X509CrlGenerator=xt,e.cryptoProvider=z,e.diAlgorithm=v,e.diAlgorithmProvider=b,e.diAsnSignatureFormatter=at,e.idEd25519=dt,e.idEd448=ft,e.idX25519=lt,e.idX448=ut}));I(),Yi();var Xi;(function(e){e.Der=`der`,e.Raw=`raw`})(Xi||={});const Zi=typeof window<`u`&&window.document!==void 0&&typeof crypto<`u`&&crypto.subtle!==void 0,Qi=typeof process<`u`&&process.versions!=null&&process.versions.node!=null,$i=()=>Zi?`browser`:Qi?`node`:`purejs`,ea=async(e,t)=>{let n=t??$i();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 ta=class{constructor(e){this.apiPublicKey=e.apiPublicKey,this.apiPrivateKey=e.apiPrivateKey,this.runtimeOverride=e.runtimeOverride}async stamp(e){let t=await ea({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 Xi.Raw:{let t=await ea({publicKey:this.apiPublicKey,privateKey:this.apiPrivateKey,content:e},this.runtimeOverride),n=ge(t);return a(n)}case Xi.Der:return ea({publicKey:this.apiPublicKey,privateKey:this.apiPrivateKey,content:e},this.runtimeOverride);default:throw Error(`Unsupported signature format: ${t}`)}}},na=class extends Error{constructor(e){super(e),this.name=`InvalidKeyError`}};function ra(){let e=m(`prime256v1`);return e.generateKeys(),aa(e.getPrivateKey().toString(`hex`).padStart(64,`0`))}const ia=/^[0-9a-f]{64}$/i;function aa(e){if(!ia.test(e))throw new na(`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 na(`value is not a valid P-256 private key (scalar out of range)`)}return{algorithm:`p256`,privateKeyHex:t,publicKeyHex:n.getPublicKey(`hex`,`compressed`)}}function oa(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 sa(e){let t=oa(e);if(t===null)throw new na(`value is not a valid P-256 public key`);return ca(t)}function ca(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 la=/^https?:\/\/[\x21\x23-\x7e]{1,255}$/,ua=/^[\x21\x23-\x3a\x3c-\x7e]{1,128}$/;function da(e,t){return`${e.replace(/\/+$/,``)}/agent-keys/${t}`}function fa(e){let t=pa(e.keypair),n={...t,identityUrl:ma(e.identityUrl??da(e.baseUrl,t.keyId))};return{sign:async e=>{let t=new Uint8Array(await e.clone().arrayBuffer()),r=ha(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 pa(e){let t=oa(e.publicKeyHex);if(t===null)throw Error(`signer keypair has an invalid P-256 public key`);return{signingKey:ya(t,e.privateKeyHex),keyId:ca(t)}}function ma(e){if(!la.test(e))throw Error(`identity URL is outside the signature profile: "${e}"`);return e}function ha(e,t,n){if(!ua.test(n.nonce))throw Error(`nonce is outside the signature profile`);let r=ga(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": ${_a(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 ga(e){return`sha-256=:${h(`sha256`).update(e??``).digest(`base64`)}:`}function _a(e){return`${e.protocol}//${va(e)}${e.pathname}${e.search}`}function va(e){let t=e.host.toLowerCase();return e.protocol===`https:`&&e.port===`443`||e.protocol===`http:`&&e.port===`80`?e.hostname.toLowerCase():t}function ya(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 ba=`0.1.0`;const xa=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Sa=ba;function Ca(e,t){if(!xa.test(e))throw Error(`${t} must be a valid HTTP token`)}function wa(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 Ta(e){let t=`catena-agent-client/${Sa}`;if(!e)return t;Ca(e.name,`appInfo.name`),e.version!==void 0&&Ca(e.version,`appInfo.version`),e.url!==void 0&&wa(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 Ea=f.pipe(f.string(),f.regex(/\S/,`Response enum values must not be blank`));function Da(e){return Ea}const Oa=f.object({amount:f.string(),asset_id:f.string()}),ka=f.pipe(f.string(),f.isoTimestamp()),Aa=f.object({success:f.literal(!0)}),ja=f.object({id:f.string(),name:f.string(),status:f.string(),organizationId:f.string()}),Ma=f.object({agent:ja}),Na=[`per_transaction_amount`,`daily_amount`,`weekly_amount`,`monthly_amount`,`hourly_count`,`daily_count`],Pa=f.object({id:f.string(),ruleType:Da(Na),thresholdAmount:f.optional(Oa),thresholdCount:f.optional(f.number()),action:Da([`block`,`require_approval`]),requiredApprovals:f.number(),accountAggregationScope:Da([`per_account`,`across_accounts`]),actorAggregationScope:Da([`per_agent`,`per_policy`]),displayOrder:f.number()}),Fa=f.object({id:f.string(),organizationId:f.string(),policyId:f.string(),capability:Da([`query_balance`,`read`,`send`,`transfer`]),accountId:f.string(),rules:f.array(Pa),createdAt:ka,updatedAt:ka}),Ia=[`allow`,`block`,`require_approval`],La=[`open`,`restricted`],Ra=Da(Ia),za=f.object({mode:Da(La),allowedCounterparties:f.optional(f.array(f.string())),createAction:f.optional(Ra),requestPaymentDetailsAction:f.optional(Ra),allowCreate:f.optional(f.boolean())}),Ba=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(za),policyCapabilities:f.array(Fa),kind:f.optional(f.picklist([`base`,`override`])),expiresAt:f.optional(f.string())}),Va=f.object({policy:Ba}),Ha=f.object({accounts:f.array(f.object({id:f.string(),name:f.string(),type:f.string(),currency:f.string()}))}),Ua=f.object({accountId:f.string(),balance:Oa,balances:f.optional(f.object({total:Oa,available:Oa}))}),Wa=[`operator-send`,`operator-transfer`,`operator-deposit`,`operator-refund`,`microdeposit`],Ga=[`pending`,`processing`,`completed`,`failed`,`reversed`],Ka=[`initiated`,`provider_pending`,`processing`,`completed`,`failed`,`reversed`,`manual_review`],qa=[`ach`,`wire`,`on-chain`],Ja=f.object({id:f.string(),type:Da(Wa),action:f.optional(f.string()),status:Da(Ga),movementStatus:Da(Ka),direction:f.picklist([`incoming`,`outgoing`]),amount:Oa,fee:Oa,currency:f.string(),counterpartyName:f.optional(f.string()),method:f.optional(Da([`ach`,`wire`,`on-chain`])),memo:f.optional(f.string()),description:f.optional(f.string()),txHash:f.optional(f.string()),createdAt:ka,completedAt:f.optional(ka)}),Ya=f.object({accountId:f.string(),transactions:f.array(Ja),total:f.number()}),Xa=f.object({accountId:f.string(),address:f.string(),liquidationAddressId:f.optional(f.string()),source:Da([`wallet`,`liquidation`])}),Za=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())}))}),Qa=f.object({counterparties:f.array(Za)}),$a=f.picklist([`pending`,`processing`,`completed`,`blocked`,`failed`]),eo=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:ka,prepareToken:f.string()})}),to=f.object({id:f.string(),type:Da([`send`,`transfer`,`create_counterparty`,`request_counterparty_details`,`x402`,`policy_override`]),status:$a,reasons:f.array(f.string()),expiresAt:f.optional(f.nullable(ka),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(eo)});function no(e){let{nextAction:t,...n}=e;return n}const ro=f.picklist(qa),io=f.object({type:f.literal(`send`),accountId:f.string(),counterpartyRailId:f.string(),amount:f.string(),method:ro,memo:f.optional(f.string()),description:f.optional(f.string())}),ao=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())}),oo={type:f.literal(`create_counterparty`),name:f.string()},so=f.union([f.object({...oo,email:f.optional(f.string()),rail:f.nonOptional(f.unknown())}),f.object({...oo,email:f.string()})]),co=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`))}),lo=f.looseObject({scheme:f.string(),network:f.string(),asset:f.string(),amount:f.string(),payTo:f.string(),maxTimeoutSeconds:f.number()}),uo=f.looseObject({url:f.string(),serviceName:f.fallback(f.optional(f.pipe(f.string(),f.maxLength(255))),void 0)}),fo=f.object({from:f.string(),to:f.string(),value:f.string(),validAfter:f.string(),validBefore:f.string(),nonce:f.string()}),po=f.object({type:f.literal(`x402`),accountId:f.string(),paymentRequirements:lo,resource:f.optional(uo),authorization:f.optional(fo)}),mo=f.strictObject({type:f.literal(`increase_limit`),accountId:f.pipe(f.string(),f.minLength(1)),capability:f.literal(`send`),limitType:f.picklist([`per_transaction_amount`,`daily_amount`,`weekly_amount`,`monthly_amount`]),newLimit:f.strictObject({amount:f.pipe(f.string(),f.regex(/^\d+(\.\d{1,6})?$/),f.check(e=>Number(e)>0,`The amount must be greater than zero`)),assetId:f.literal(`USD`)})}),ho=f.strictObject({type:f.literal(`increase_limit`),accountId:f.pipe(f.string(),f.minLength(1)),capability:f.literal(`send`),limitType:f.picklist([`hourly_count`,`daily_count`]),newLimit:f.strictObject({count:f.pipe(f.number(),f.integer(),f.minValue(1))})}),go=f.pipe(f.array(f.union([mo,ho])),f.minLength(1),f.maxLength(10),f.check(e=>new Set(e.map(e=>`${e.accountId}|${e.capability}|${e.limitType}`)).size===e.length,`Each account, capability, and limit type may appear only once`)),_o=f.object({type:f.literal(`policy_override`),operations:go,durationSeconds:f.pipe(f.number(),f.integer(),f.minValue(60),f.maxValue(604800)),reason:f.pipe(f.string(),f.trim(),f.minLength(1),f.maxLength(280))}),vo=f.union([io,ao,so,co,po,_o]);function yo(e){let t=f.parse(vo,e);return t.type===`send`||t.type===`transfer`?{...t,amount:{amount:t.amount,asset_id:`USD`}}:t.type===`policy_override`?{...t,schemaVersion:1}:t}const bo=f.object({intent:to});var xo=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 wo(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 xo(e.status,n.message,n.code??n.error,n.details??void 0):new xo(e.status,n.error??n.message??e.statusText,n.code??void 0,n.details??void 0)}async function To(e,t){if(!e.ok)throw await wo(e);return f.parse(t,await e.json())}var Eo=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 Do=2147483647;var Oo=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>Do)throw TypeError(`timeout must be a positive integer no greater than ${Do}`);this.#e=e.baseUrl??`https://api.catena.com`,this.#t=Ta(e.appInfo),this.#n=e.defaultHeaders??{},this.#r=aa(e.privateKeyHex),this.#a=(e.fetch??globalThis.fetch).bind(globalThis),this.#o=t,this.#i=fa({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=>To(e,t));return await Promise.race([a,e])}finally{i!==void 0&&clearTimeout(i)}}async whoami(){return(await this.#l({method:`GET`,path:`/me`},Ma)).agent}async submitFeedback(e){await this.#l({method:`POST`,path:`/feedback`,body:{body:e}},Aa)}async getPolicy(){return(await this.#l({method:`GET`,path:`/policy`},Va)).policy}async listAccounts(){return this.#l({method:`GET`,path:`/accounts`},Ha)}async getAccountBalance(e){return this.#l({method:`GET`,path:`/accounts/${encodeURIComponent(e)}/balance`},Ua)}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()}},Ya)}async getAccountDepositAddress(e,t){return this.#l({method:`GET`,path:`/accounts/${encodeURIComponent(e)}/deposit-address`,query:{network:t.network,asset:t.asset}},Xa)}async listCounterparties(e={}){return this.#l({method:`GET`,path:`/counterparties`,query:{address:e.address,network:e.network}},Qa)}async submitIntent(e){let t=await this.#d(e),n=t.nextAction;if(!n)return no(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 Eo({intentId:t.id,outcome:`not-submitted`,cause:e})}try{return await this.#p(r,t.replayed)}catch(e){throw new Eo({intentId:t.id,outcome:`unknown`,cause:e})}}async#d(e){return this.#l({method:`POST`,path:`/intents`,body:{action:yo(e.action)},...e.idempotencyKey!==void 0&&{headers:{"Idempotency-Key":e.idempotencyKey}}},to)}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 ta({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=no((await this.#u(e,bo)).intent);return t?{...n,replayed:!0}:n}async getIntent(e){return no(await this.#l({method:`GET`,path:`/intents/${encodeURIComponent(e)}`},to))}async unlinkAgent(){await this.#l({method:`POST`,path:`/unlink`},Aa)}async reportSettlement(e){await this.#l({method:`POST`,path:`/intents/${encodeURIComponent(e.intentId)}/settlement-report`,body:{txHash:e.txHash}},Aa)}};function ko(e={}){let t=e.privateKeyHex===void 0?process.env.CATENA_SECRET_KEY:e.privateKeyHex;if(t===void 0)throw new na(`privateKeyHex is required; pass it explicitly or set CATENA_SECRET_KEY`);return new Oo({...e,privateKeyHex:t})}function Ao(e){let t=e instanceof Error?e.message:String(e);return e instanceof xo&&e.details!==void 0?`${t}\nDetails:\n${JSON.stringify(e.details,null,2)}`:t}function X(e){console.error(Ao(e)),process.exit(1)}const jo=f.string(),Mo=f.boolean();function No(e){return e===void 0}function Po(e){return e.issues?.[0]?.message??`Invalid value`}function Fo(e,t,n,r){return X(`${e}: ${t}${r?` (got: ${String(n)})`:``}`)}function Io(e,t,n,r){let i=f.safeParse(e,t);return i.success?i.output:Fo(n,Po(i),t,r)}function Lo(e,t){let n=t.schema??jo;return{type:e,description:t.description,negativeDescription:t.negativeDescription,required:t.required,default:t.default,parseValue(e,r){let i=No(e)?t.default:e;if(No(i)){t.required===!0&&X(`${r} is required`);return}return Io(n,i,r,t.showValueInError===!0)}}}function Z(e){return Lo(`string`,e)}function Ro(e){return Lo(`positional`,e)}function zo(e){let t=e.schema??jo;return{type:`string`,description:e.description,repeatable:!0,parseValue(n,r){return(Array.isArray(n)?n:[]).map(n=>Io(t,n,r,e.showValueInError===!0))}}}function Bo(e){return{type:`boolean`,description:e.description,negativeDescription:e.negativeDescription,required:e.required,default:e.default,parseValue(t,n){let r=No(t)?e.default:t;if(No(r)){e.required===!0&&X(`${n} is required`);return}return Io(Mo,r,n,!1)}}}function Vo(e){return Ho(`string`,e)}function Ho(e,t){return Lo(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 Uo(e,t){return t.type===`positional`?`<${e}>`:`--${e}`}function Wo(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 Go(e){return Wo(e).join(`-`).toLowerCase()}function Ko(e){return Wo(e).map((e,t)=>t===0?e.charAt(0).toLowerCase()+e.slice(1):e.charAt(0).toUpperCase()+e.slice(1)).join(``)}function qo(e){return[`--${e}`,`--${Go(e)}`,`--${Ko(e)}`]}function Jo(e){let t=e.indexOf(`=`);return t===-1?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function Yo(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(qo(t)),s=new Set(Object.entries(n).filter(([e,n])=>e!==t&&n.type===`string`).flatMap(([e])=>qo(e))),c=[];for(let e=0;e<a.length;e++){let t=a[e];if(t===`--`)break;let[n,r]=Jo(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 Xo(e){let t=e.required??(e.type!==`positional`&&void 0);return e.type===`boolean`?{type:e.type,description:e.description,negativeDescription:e.negativeDescription,required:t,default:typeof e.default==`boolean`?e.default:void 0}:{type:e.type,description:e.description,required:t,default:typeof e.default==`string`?e.default:void 0}}function Q(e){return{args:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Xo(t)])),label(t){return Uo(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 Yo(n,r,e)};return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.parseValue(r(e,t),Uo(e,t))]))}}}const Zo=Z({description:`Credential profile name`}),Qo=Bo({description:`Print compact single-line JSON (for piping)`,default:!1}),$o=/^[a-zA-Z0-9_-]+$/,es=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($o,`ID may only contain letters, digits, hyphens, and underscores`)),ts=[`base`,`base-sepolia`],ns=[`usdc`],rs=`base`,is=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 as(e){return Vo({description:e.description,choices:ts,...e.default===void 0?{}:{default:e.default}})}const os=[`registered`,`already_registered`,`not_applicable`,`registration_failed`],ss=f.pipe(f.string(),f.regex(/^0[23][0-9a-f]{64}$/)),cs=f.pipe(f.string(),f.regex(/^[0-9a-f]{64}$/)),ls=f.object({status:f.picklist(os),publicKeyHex:f.optional(ss),reason:f.optional(f.string())}),us=f.object({algorithm:f.literal(`p256`),privateKeyHex:cs,publicKeyHex:ss,registration:ls}),ds=f.object({version:f.literal(`signer-1`),signer:us}),fs=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())}),ps=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:us}),ms=f.object({version:f.literal(3),signer:us}),hs=f.variant(`version`,[fs,ps,ms]),gs=f.variant(`version`,[ds,fs,ps,ms]);function _s(e){return f.parse(hs,e)}function vs(e){return f.parse(gs,e)}function ys(e){let t=f.safeParse(gs,e);return t.success?t.output:null}function bs(e){return{version:`signer-1`,signer:{algorithm:e.algorithm,privateKeyHex:e.privateKeyHex,publicKeyHex:e.publicKeyHex,registration:{status:`not_applicable`,reason:`pending_claim`}}}}function xs(e,t){try{return vs(JSON.parse(e))}catch(e){throw Error(`${t} credential has an unsupported format`,{cause:e})}}function Ss(e){return _s({version:3,signer:e})}function Cs(e){return JSON.stringify(e)}function ws(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Ts(e){return(t,n)=>Es(e,t,n)}function Es(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 Ds=`catena-agent`;function Os(e){if(!$o.test(e))throw Error(`Invalid credential location for credential storage: "${e}"`);return e}const ks=Ts(`/usr/bin/secret-tool`);function As(e){return e.status===1&&e.stdout===``&&e.stderr.trim()===``}function js(e,t){if(t.status===0)return;let n=Ms(t);throw Error(`Linux Secret Service credential ${e} failed (secret-tool exited ${t.status??`without status`}): ${n}`)}function Ms(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 Ns(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 Ps=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??ks}async save(e,t){let n=vs(t),r=Os(e);if(await this.savePassword(r,Cs(n)),!ws(await this.resolveDirectPassword(r),n))throw Error(`Linux Secret Service credential save verification failed`)}async resolve(e){return this.resolveDirectPassword(Os(e))}async delete(e){await this.deletePassword(Os(e))}async savePassword(e,t){js(`save`,await this.runSecretToolCommand([`store`,`--label`,`${Ds} ${e}`,`app`,Ds,`account`,e],t))}async resolvePassword(e){let t=await this.runSecretToolCommand([`lookup`,`app`,Ds,`account`,e]);return As(t)?null:(js(`resolve`,t),t.stdout.replace(/\r?\n$/,``))}async resolveDirectPassword(e){let t=await this.resolvePassword(e);return t===null?null:xs(t,`Linux Secret Service`)}async deletePassword(e){let t=await this.runSecretToolCommand([`clear`,`app`,Ds,`account`,e]);As(t)||js(`delete`,t)}async runSecretToolCommand(e,t){try{return await this.runSecretTool(e,t)}catch(e){throw Ns(e)}}};const Fs=Ts(`/usr/bin/security`),Is=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 Ls(e){return e.status===44}function Rs(e,t){return`${e}:chunk:${t}`}function zs(e){let t=JSON.parse(e),n=ys(t);if(n!==null)return{kind:`direct`,payload:n};let r=f.safeParse(Is,t);if(r.success)return{kind:`legacy`,manifest:r.output};throw Error(`macOS Keychain credential has an unsupported format`)}function Bs(e,t){if(t.status===0)return;let n=Vs(t);throw Error(`macOS Keychain credential ${e} failed (security exited ${t.status??`without status`})${n===null?``:`: ${n}`}`)}function Vs(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 Hs(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 Us(e,t){return[`add-generic-password`,`-s`,Hs(Ds),`-a`,Hs(e),`-w`,Hs(t),`-U`].join(` `)+`
|
|
137
|
-
`}var
|
|
138
|
-
`,{encoding:`utf-8`,mode:384}),D(n,t)}function uc(e,t){ic(e);let n=f.parse($s,t);Ys(n.bank_url,`profile "${e}" bank_url`);let r=sc();lc({...r,profiles:{...r.profiles,[e]:n}})}function dc(e){return e.status===`linked`}function fc(e,t){return e.replace(/\/+$/,``)===t.replace(/\/+$/,``)}function pc(e,t){let n=Object.entries(sc().profiles).toSorted(([e],[t])=>e.localeCompare(t)).find(([,n])=>dc(n)&&n.agent_id===e&&fc(n.bank_url,t));return n===void 0?null:n[0]}function mc(e,t){let n=Object.fromEntries(Object.entries(e??{}).filter(([,e])=>t(e)));return Object.keys(n).length===0?{}:{directories:n}}function hc(e){ic(e);let t=sc(),{[e]:n,...r}=t.profiles;lc({version:1,...t.default_profile===e||t.default_profile===void 0?{}:{default_profile:t.default_profile},profiles:r,...mc(t.directories,t=>t!==e)})}function gc(e){try{return E(re(e))}catch{return re(e)}}function _c(e){return sc().directories?.[gc(e)]??null}function vc(e,t){ic(t);let n=sc();if(!Object.hasOwn(n.profiles,t))throw Error(`Profile "${t}" is not linked. Run catena link --profile ${t} <agent-id>.`);let r=gc(e);return lc({...n,directories:{...n.directories,[r]:t}}),r}function yc(e){let t=sc(),n=gc(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 lc({...o,...Object.keys(i).length===0?{}:{directories:i}}),{directory:n,removed:!0}}function bc(e){return ic(e),sc().profiles[e]??null}function xc(){return`client_${_(16).toString(`hex`)}`}function Sc(e,t){let n=bc(e);return t.agent_id===void 0?Cc(e,t.bank_url,n):wc(e,t.bank_url,t.agent_id,n)}function Cc(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`&&fc(n.bank_url,t)?n.client_instance_id:null)??xc();return uc(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 wc(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(!fc(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`&&fc(r.bank_url,t)?r.client_instance_id:null)??xc();return uc(e,{status:`linked`,bank_url:t,agent_id:n,client_instance_id:i}),i}function Tc(e){ic(e);let t=sc();if(!Object.hasOwn(t.profiles,e))throw Error(`Profile "${e}" is not linked. Run catena link --profile ${e} <agent-id>.`);lc({...t,default_profile:e})}function Ec(e){let t=e.toLowerCase().replace(/[^a-z0-9._-]+/g,`-`).replace(/^[^a-z0-9]+/,``).slice(0,64);return rc(t)?t:`agent`}function Dc(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 Oc(e){ic(e.reservationName),ic(e.profileName);let t=f.parse($s,e.profile);Ys(t.bank_url,`profile "${e.profileName}" bank_url`);let n=sc(),{[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]));lc({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 kc(e){return e??Gs()}async function Ac(e,t){let n;try{n=bc(e.profileName)}catch(t){return{ok:!1,profileName:e.profileName,bankUrl:e.fallbackBankUrl,message:Ao(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{Ys(n.bank_url,`profile "${e.profileName}" bank_url`)}catch(t){return{ok:!1,profileName:e.profileName,bankUrl:e.fallbackBankUrl,message:Ao(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 kc(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}: ${Ao(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 jc={name:`catena-cli`,version:se},Mc=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function Nc(e,t){if(!Mc.test(e))throw Error(`${t} must be a valid HTTP token`)}function Pc(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 Fc(e){Nc(e.name,`appInfo.name`),e.version!==void 0&&Nc(e.version,`appInfo.version`),e.url!==void 0&&Pc(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 Ic=`https://api.catena.com`,Lc=`CATENA_PROFILE`;function Rc(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 zc(e,t,n){if(e.flag!==void 0&&e.flag.length>0)return ic(e.flag),{name:e.flag,source:`flag`};if(e.env!==void 0&&e.env.length>0){if(!rc(e.env))throw Error(`${Lc} is set to an invalid profile name "${e.env}"`);return{name:e.env,source:`env`}}if(e.cwd!==void 0){let r=Rc(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 Bc(e){return zc(e,sc(e.log),`ignore`)}function Vc(e){let t=sc(e.log),n=zc(e,t,`error`);if(n!==null)return n;let r=Object.keys(t.profiles),i=Object.entries(t.profiles).filter(([,e])=>dc(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 ${Lc}, run 'catena profiles use <name>', or run 'catena link' from an agent directory to bind it.`)}function Hc(e){return ko({baseUrl:e.bankUrl,privateKeyHex:e.signer.privateKeyHex,appInfo:jc})}function Uc(){return Gs()}async function Wc(e){let t;try{t=Vc({flag:e,env:process.env[Lc],cwd:process.cwd(),log:e=>console.error(e)}).name}catch(e){return X(e)}let n=await Ac({profileName:t,fallbackBankUrl:Ic},void 0);return n.ok||X(n.message),Hc(n)}const Gc=new Set([`unknown_key`,`key_revoked`,`client_unlinked`]),Kc=new Set([`signature_auth_disabled`,`missing_auth`]);function qc(e,t){if(!(e instanceof xo)||e.code===void 0)return e;let n=t===void 0?`catena link`:`catena link --profile ${t}`;return Gc.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 (${jc.version}) is no longer supported by the bank. Run 'npm i -g @catena/cli' and retry.`):Kc.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 Jc(e,t){console.log(t?.compact?JSON.stringify(e):JSON.stringify(e,null,2))}function Yc(e){return e.profile===void 0||e.profile.length===0?void 0:e.profile}async function Xc(e,t){try{return await t(await Wc(e))}catch(t){return X(qc(t,e))}}function Zc(e,t){return async(n,r)=>{let i=await Xc(e,n);return Jc(i,t),await new Promise(e=>{process.stdout.write(``,()=>e())}),process.exit(r?.exitCode?r.exitCode(i):0)}}function $(e){return Zc(Yc(e),{compact:e.json===!0})}const Qc=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}`)),$c=f.pipe(Qc,f.maxValue(200,`must be at most 200`)),el={profile:Zo,json:Qo},tl=Q(el),nl=Q({account:Ro({description:`Account id`,required:!0,schema:es}),...el}),rl=Q({account:Ro({description:`Account id`,required:!0,schema:es}),start:Z({description:`Only include transactions at or after this ISO 8601 time`}),end:Z({description:`Only include transactions at or before this ISO 8601 time`}),limit:Z({description:`Maximum transactions to return (default 50, max 200)`,schema:$c}),offset:Z({description:`Number of transactions to skip for pagination`,schema:Qc}),...el}),il=Q({account:Ro({description:`Account id`,required:!0,schema:es}),network:as({description:`Deposit network; defaults to ${rs}. Availability depends on the connected environment.`,default:rs}),asset:Vo({description:`Deposit asset (${ns.join(`|`)})`,choices:ns,default:`usdc`}),...el}),al=l({meta:{name:`list`,description:`List accounts accessible under the agent's policy`},args:tl.args,async run({args:e}){await $(tl.parse(e))(e=>e.listAccounts())}}),ol=l({meta:{name:`balance`,description:`Request an account balance through the policy engine`},args:nl.args,async run({args:e}){let t=nl.parse(e);await $(t)(e=>e.getAccountBalance(t.account))}}),sl=l({meta:{name:`transactions`,description:`Read an account's transaction history through the policy engine`},args:rl.args,async run({args:e}){let t=rl.parse(e);await $(t)(e=>e.listAccountTransactions(t.account,{start:t.start,end:t.end,limit:t.limit,offset:t.offset}))}}),cl=l({meta:{name:`deposit-address`,description:`Read an account deposit address through the policy engine`},args:il.args,async run({args:e}){let t=il.parse(e);await $(t)(e=>e.getAccountDepositAddress(t.account,{network:t.network,asset:t.asset}))}}),ll=l({meta:{name:`accounts`,description:`Inspect bank accounts`},subCommands:{list:al,balance:ol,transactions:sl,"deposit-address":cl}}),ul=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)`)),dl=f.pipe(f.string(),f.minLength(1,`must not be empty`)),fl=f.pipe(f.string(),f.trim(),f.email(`must be a valid email address`)),pl={profile:Zo,json:Qo},ml=Q({address:Z({description:`Only counterparties with a wallet rail matching this address (0x…)`,schema:is}),network:as({description:`Only counterparties with a wallet rail on this network (e.g. base)`}),...pl}),hl=Z({description:`Counterparty name`,required:!0,schema:dl}),gl=Z({description:`Optional contact email`,schema:fl}),_l=Q({name:hl,email:Z({description:`Contact email; creating the counterparty sends no email`,required:!0,schema:fl}),...pl}),vl=Q({name:Z({description:`Counterparty name; required without a subcommand`,schema:dl}),email:Z({description:`Contact email; required without a subcommand; creating the counterparty sends no email`,schema:fl}),...pl}),yl=Q({name:hl,"bank-name":Z({description:`Receiving bank name`,required:!0,schema:dl}),"routing-number":Z({description:`9-digit ABA routing number`,required:!0,schema:dl}),"account-number":Z({description:`Receiving bank account number`,required:!0,schema:dl}),"account-type":Vo({description:`checking | savings (default checking)`,choices:[`checking`,`savings`]}),"address-street":Z({description:`Street address of the receiving bank account holder`,required:!0,schema:dl}),"address-city":Z({description:`City`,required:!0,schema:dl}),"address-state":Z({description:`State (e.g. NY)`,required:!0,schema:dl}),"address-postal-code":Z({description:`Postal code`,required:!0,schema:dl}),"address-country":Z({description:`Default USA`}),email:gl,...pl}),bl=Q({name:hl,address:Z({description:`Wallet address (0x… or ENS name on EVM networks)`,required:!0,schema:dl}),network:as({description:`Wallet network; defaults to ${rs}. Availability depends on the connected environment.`,default:rs}),email:gl,...pl}),xl=Q({counterparty:Ro({description:`Counterparty id`,required:!0,schema:es}),bank:Bo({description:`Request bank account details`,default:!1}),wallet:Bo({description:`Request wallet details`,default:!1}),"idempotency-key":Z({description:`Optional key to replay this exact submission`,schema:ul}),...pl}),Sl=l({meta:{name:`list`,description:`List counterparties available under the agent's policy`},args:ml.args,async run({args:e}){let t=ml.parse(e);await $(t)(e=>e.listCounterparties({address:t.address,network:t.network}))}});function Cl(e){return e&&e.length>0?e:void 0}function wl(e){let t=Cl(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 Tl(e){let t=Cl(e.email);return{type:`create_counterparty`,name:e.name,email:t,rail:{type:`wallet`,walletAddress:e.address,network:e.network}}}function El(e){return{type:`create_counterparty`,name:e.name,email:e.email}}const Dl=l({meta:{name:`email`,description:`Create a counterparty with an email and no payment details. Sends no email.`},args:_l.args,async run({args:e}){let t=_l.parse(e);await $(t)(e=>e.submitIntent({action:El(t)}))}}),Ol=l({meta:{name:`bank`,description:`Request bank counterparty creation through the policy engine. Prints an intent envelope.`},args:yl.args,async run({args:e}){let t=yl.parse(e),n=wl(t);await $(t)(e=>e.submitIntent({action:n}))}}),kl=l({meta:{name:`wallet`,description:`Request wallet counterparty creation through the policy engine. Prints an intent envelope.`},args:bl.args,async run({args:e}){let t=bl.parse(e);await $(t)(e=>e.submitIntent({action:Tl(t)}))}}),Al=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:vl.args,default:`email`,subCommands:{email:Dl,bank:Ol,wallet:kl}}),jl=l({meta:{name:`request-details`,description:`Ask a counterparty to provide bank details, wallet details, or both through the policy engine.`},args:xl.args,async run({args:e}){let t=xl.parse(e);!t.bank&&!t.wallet&&X(`Select at least one of --bank or --wallet`),await $(t)(e=>e.submitIntent({action:{type:`request_counterparty_details`,counterpartyId:t.counterparty,methods:{bank:t.bank,wallet:t.wallet}},...t[`idempotency-key`]?{idempotencyKey:t[`idempotency-key`]}:{}}))}}),Ml=l({meta:{name:`counterparties`,description:`Inspect, create, and request details from counterparties`},subCommands:{list:Sl,create:Al,"request-details":jl}}),Nl=4e3;async function Pl(){process.stdin.setEncoding(`utf8`);let e=``;for await(let t of process.stdin)e+=t;return e}async function Fl(e){return e===void 0?(process.stdin.isTTY&&X(`<message>: pass a quoted message or pipe it on stdin; a message starting with "-" needs -- before it (catena feedback -- "<message>") or stdin`),Pl()):e}const Il=Q({message:Ro({description:`Plain-text feedback (1-4000 chars); omit to pipe on stdin`}),profile:Zo,json:Qo}),Ll=l({meta:{name:`feedback`,description:`Send free-form feedback about Catena to the Catena team`},args:Il.args,async run({args:e}){(Array.isArray(e._)?e._:[]).length>1&&X(`<message>: pass the message as a single quoted argument`);let t=Il.parse(e),n=(await Fl(t.message)).trim();n.length===0&&X(`<message>: must not be empty`),n.length>Nl&&X(`<message>: must be at most ${Nl} characters (got: ${n.length})`),await $(t)(async e=>(await e.submitFeedback(n),{ok:!0}))}});function Rl(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 ga(e){return`sha-256=:${h(`sha256`).update(e??``).digest(`base64`)}:`}function _a(e){return`${e.protocol}//${va(e)}${e.pathname}${e.search}`}function va(e){let t=e.host.toLowerCase();return e.protocol===`https:`&&e.port===`443`||e.protocol===`http:`&&e.port===`80`?e.hostname.toLowerCase():t}function ya(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 ba=`0.1.0`;const xa=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Sa=ba;function Ca(e,t){if(!xa.test(e))throw Error(`${t} must be a valid HTTP token`)}function wa(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 Ta(e){let t=`catena-agent-client/${Sa}`;if(!e)return t;Ca(e.name,`appInfo.name`),e.version!==void 0&&Ca(e.version,`appInfo.version`),e.url!==void 0&&wa(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 Ea=f.pipe(f.string(),f.regex(/\S/,`Response enum values must not be blank`));function Da(e){return Ea}const Oa=f.object({amount:f.string(),asset_id:f.string()}),ka=f.pipe(f.string(),f.isoTimestamp()),Aa=f.object({success:f.literal(!0)}),ja=f.object({id:f.string(),name:f.string(),status:f.string(),organizationId:f.string()}),Ma=f.object({agent:ja}),Na=[`per_transaction_amount`,`daily_amount`,`weekly_amount`,`monthly_amount`,`hourly_count`,`daily_count`],Pa=f.object({id:f.string(),ruleType:Da(Na),thresholdAmount:f.optional(Oa),thresholdCount:f.optional(f.number()),action:Da([`block`,`require_approval`]),requiredApprovals:f.number(),accountAggregationScope:Da([`per_account`,`across_accounts`]),actorAggregationScope:Da([`per_agent`,`per_policy`]),displayOrder:f.number()}),Fa=f.object({id:f.string(),organizationId:f.string(),policyId:f.string(),capability:Da([`query_balance`,`read`,`send`,`transfer`]),accountId:f.string(),rules:f.array(Pa),createdAt:ka,updatedAt:ka}),Ia=[`allow`,`block`,`require_approval`],La=[`open`,`restricted`],Ra=Da(Ia),za=f.object({mode:Da(La),allowedCounterparties:f.optional(f.array(f.string())),createAction:f.optional(Ra),requestPaymentDetailsAction:f.optional(Ra),allowCreate:f.optional(f.boolean())}),Ba=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(za),policyCapabilities:f.array(Fa),kind:f.optional(f.picklist([`base`,`override`])),expiresAt:f.optional(f.string())}),Va=f.object({policy:Ba}),Ha=f.object({accounts:f.array(f.object({id:f.string(),name:f.string(),type:f.string(),currency:f.string()}))}),Ua=f.object({accountId:f.string(),balance:Oa,balances:f.optional(f.object({total:Oa,available:Oa}))}),Wa=[`operator-send`,`operator-transfer`,`operator-deposit`,`operator-refund`,`microdeposit`],Ga=[`pending`,`processing`,`completed`,`failed`,`reversed`],Ka=[`initiated`,`provider_pending`,`processing`,`completed`,`failed`,`reversed`,`manual_review`],qa=[`ach`,`wire`,`on-chain`],Ja=f.object({id:f.string(),type:Da(Wa),action:f.optional(f.string()),status:Da(Ga),movementStatus:Da(Ka),direction:f.picklist([`incoming`,`outgoing`]),amount:Oa,fee:Oa,currency:f.string(),counterpartyName:f.optional(f.string()),method:f.optional(Da([`ach`,`wire`,`on-chain`])),memo:f.optional(f.string()),description:f.optional(f.string()),txHash:f.optional(f.string()),createdAt:ka,completedAt:f.optional(ka)}),Ya=f.object({accountId:f.string(),transactions:f.array(Ja),total:f.number()}),Xa=f.object({accountId:f.string(),address:f.string(),liquidationAddressId:f.optional(f.string()),source:Da([`wallet`,`liquidation`])}),Za=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())}))}),Qa=f.object({counterparties:f.array(Za)}),$a=f.picklist([`pending`,`processing`,`completed`,`blocked`,`failed`]),eo=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:ka,prepareToken:f.string()})}),to=f.object({id:f.string(),type:Da([`send`,`transfer`,`create_counterparty`,`request_counterparty_details`,`x402`,`policy_override`]),status:$a,reasons:f.array(f.string()),expiresAt:f.optional(f.nullable(ka),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(eo)});function no(e){let{nextAction:t,...n}=e;return n}const ro=f.picklist(qa),io=f.object({type:f.literal(`send`),accountId:f.string(),counterpartyRailId:f.string(),amount:f.string(),method:ro,memo:f.optional(f.string()),description:f.optional(f.string())}),ao=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())}),oo={type:f.literal(`create_counterparty`),name:f.string()},so=f.union([f.object({...oo,email:f.optional(f.string()),rail:f.nonOptional(f.unknown())}),f.object({...oo,email:f.string()})]),co=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`))}),lo=f.looseObject({scheme:f.string(),network:f.string(),asset:f.string(),amount:f.string(),payTo:f.string(),maxTimeoutSeconds:f.number()}),uo=f.looseObject({url:f.string(),serviceName:f.fallback(f.optional(f.pipe(f.string(),f.maxLength(255))),void 0)}),fo=f.object({from:f.string(),to:f.string(),value:f.string(),validAfter:f.string(),validBefore:f.string(),nonce:f.string()}),po=f.object({type:f.literal(`x402`),accountId:f.string(),paymentRequirements:lo,resource:f.optional(uo),authorization:f.optional(fo)}),mo=[`send`,`transfer`],ho=f.strictObject({type:f.literal(`increase_limit`),accountId:f.pipe(f.string(),f.minLength(1)),capability:f.picklist(mo),limitType:f.picklist([`per_transaction_amount`,`daily_amount`,`weekly_amount`,`monthly_amount`]),newLimit:f.strictObject({amount:f.pipe(f.string(),f.regex(/^\d+(\.\d{1,6})?$/),f.check(e=>Number(e)>0,`The amount must be greater than zero`)),assetId:f.literal(`USD`)})}),go=f.strictObject({type:f.literal(`increase_limit`),accountId:f.pipe(f.string(),f.minLength(1)),capability:f.picklist(mo),limitType:f.picklist([`hourly_count`,`daily_count`]),newLimit:f.strictObject({count:f.pipe(f.number(),f.integer(),f.minValue(1))})}),_o=f.pipe(f.array(f.union([ho,go])),f.minLength(1),f.maxLength(10),f.check(e=>new Set(e.map(e=>`${e.accountId}|${e.capability}|${e.limitType}`)).size===e.length,`Each account, capability, and limit type may appear only once`)),vo=f.object({type:f.literal(`policy_override`),operations:_o,durationSeconds:f.pipe(f.number(),f.integer(),f.minValue(60),f.maxValue(604800)),reason:f.pipe(f.string(),f.trim(),f.minLength(1),f.maxLength(280))}),yo=f.union([io,ao,so,co,po,vo]);function bo(e){let t=f.parse(yo,e);return t.type===`send`||t.type===`transfer`?{...t,amount:{amount:t.amount,asset_id:`USD`}}:t.type===`policy_override`?{...t,schemaVersion:1}:t}const xo=f.object({intent:to});var So=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}},Co=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 wo=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 To(e){let t=f.safeParse(wo,await e.json().catch(()=>void 0)),n=t.success?t.output:{};return n.error!=null&&n.message!=null?new So(e.status,n.message,n.code??n.error,n.details??void 0):new So(e.status,n.error??n.message??e.statusText,n.code??void 0,n.details??void 0)}async function Eo(e,t){if(!e.ok)throw await To(e);return f.parse(t,await e.json())}var Do=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 Oo=2147483647;var ko=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>Oo)throw TypeError(`timeout must be a positive integer no greater than ${Oo}`);this.#e=e.baseUrl??`https://api.catena.com`,this.#t=Ta(e.appInfo),this.#n=e.defaultHeaders??{},this.#r=aa(e.privateKeyHex),this.#a=(e.fetch??globalThis.fetch).bind(globalThis),this.#o=t,this.#i=fa({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 Co(this.#o);t(e),n.abort(e)},this.#o)}),a=this.#a(r).then(e=>Eo(e,t));return await Promise.race([a,e])}finally{i!==void 0&&clearTimeout(i)}}async whoami(){return(await this.#l({method:`GET`,path:`/me`},Ma)).agent}async submitFeedback(e){await this.#l({method:`POST`,path:`/feedback`,body:{body:e}},Aa)}async getPolicy(){return(await this.#l({method:`GET`,path:`/policy`},Va)).policy}async listAccounts(){return this.#l({method:`GET`,path:`/accounts`},Ha)}async getAccountBalance(e){return this.#l({method:`GET`,path:`/accounts/${encodeURIComponent(e)}/balance`},Ua)}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()}},Ya)}async getAccountDepositAddress(e,t){return this.#l({method:`GET`,path:`/accounts/${encodeURIComponent(e)}/deposit-address`,query:{network:t.network,asset:t.asset}},Xa)}async listCounterparties(e={}){return this.#l({method:`GET`,path:`/counterparties`,query:{address:e.address,network:e.network}},Qa)}async submitIntent(e){let t=await this.#d(e),n=t.nextAction;if(!n)return no(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 Do({intentId:t.id,outcome:`not-submitted`,cause:e})}try{return await this.#p(r,t.replayed)}catch(e){throw new Do({intentId:t.id,outcome:`unknown`,cause:e})}}async#d(e){return this.#l({method:`POST`,path:`/intents`,body:{action:bo(e.action)},...e.idempotencyKey!==void 0&&{headers:{"Idempotency-Key":e.idempotencyKey}}},to)}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 ta({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=no((await this.#u(e,xo)).intent);return t?{...n,replayed:!0}:n}async getIntent(e){return no(await this.#l({method:`GET`,path:`/intents/${encodeURIComponent(e)}`},to))}async unlinkAgent(){await this.#l({method:`POST`,path:`/unlink`},Aa)}async reportSettlement(e){await this.#l({method:`POST`,path:`/intents/${encodeURIComponent(e.intentId)}/settlement-report`,body:{txHash:e.txHash}},Aa)}};function Ao(e={}){let t=e.privateKeyHex===void 0?process.env.CATENA_SECRET_KEY:e.privateKeyHex;if(t===void 0)throw new na(`privateKeyHex is required; pass it explicitly or set CATENA_SECRET_KEY`);return new ko({...e,privateKeyHex:t})}function jo(e){let t=e instanceof Error?e.message:String(e);return e instanceof So&&e.details!==void 0?`${t}\nDetails:\n${JSON.stringify(e.details,null,2)}`:t}function X(e){console.error(jo(e)),process.exit(1)}const Mo=f.string(),No=f.boolean();function Po(e){return e===void 0}function Fo(e){return e.issues?.[0]?.message??`Invalid value`}function Io(e,t,n,r){return X(`${e}: ${t}${r?` (got: ${String(n)})`:``}`)}function Lo(e,t,n,r){let i=f.safeParse(e,t);return i.success?i.output:Io(n,Fo(i),t,r)}function Ro(e,t){let n=t.schema??Mo;return{type:e,description:t.description,negativeDescription:t.negativeDescription,required:t.required,default:t.default,parseValue(e,r){let i=Po(e)?t.default:e;if(Po(i)){t.required===!0&&X(`${r} is required`);return}return Lo(n,i,r,t.showValueInError===!0)}}}function Z(e){return Ro(`string`,e)}function zo(e){return Ro(`positional`,e)}function Bo(e){let t=e.schema??Mo;return{type:`string`,description:e.description,repeatable:!0,parseValue(n,r){return(Array.isArray(n)?n:[]).map(n=>Lo(t,n,r,e.showValueInError===!0))}}}function Vo(e){return{type:`boolean`,description:e.description,negativeDescription:e.negativeDescription,required:e.required,default:e.default,parseValue(t,n){let r=Po(t)?e.default:t;if(Po(r)){e.required===!0&&X(`${n} is required`);return}return Lo(No,r,n,!1)}}}function Ho(e){return Uo(`string`,e)}function Uo(e,t){return Ro(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 Wo(e,t){return t.type===`positional`?`<${e}>`:`--${e}`}function Go(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 Ko(e){return Go(e).join(`-`).toLowerCase()}function qo(e){return Go(e).map((e,t)=>t===0?e.charAt(0).toLowerCase()+e.slice(1):e.charAt(0).toUpperCase()+e.slice(1)).join(``)}function Jo(e){return[`--${e}`,`--${Ko(e)}`,`--${qo(e)}`]}function Yo(e){let t=e.indexOf(`=`);return t===-1?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function Xo(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(Jo(t)),s=new Set(Object.entries(n).filter(([e,n])=>e!==t&&n.type===`string`).flatMap(([e])=>Jo(e))),c=[];for(let e=0;e<a.length;e++){let t=a[e];if(t===`--`)break;let[n,r]=Yo(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 Zo(e){let t=e.required??(e.type!==`positional`&&void 0);return e.type===`boolean`?{type:e.type,description:e.description,negativeDescription:e.negativeDescription,required:t,default:typeof e.default==`boolean`?e.default:void 0}:{type:e.type,description:e.description,required:t,default:typeof e.default==`string`?e.default:void 0}}function Q(e){return{args:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Zo(t)])),label(t){return Wo(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 Xo(n,r,e)};return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.parseValue(r(e,t),Wo(e,t))]))}}}const Qo=Z({description:`Credential profile name`}),$o=Vo({description:`Print compact single-line JSON (for piping)`,default:!1}),es=/^[a-zA-Z0-9_-]+$/,ts=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(es,`ID may only contain letters, digits, hyphens, and underscores`)),ns=[`base`,`base-sepolia`],rs=[`usdc`],is=`base`,as=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 os(e){return Ho({description:e.description,choices:ns,...e.default===void 0?{}:{default:e.default}})}const ss=[`registered`,`already_registered`,`not_applicable`,`registration_failed`],cs=f.pipe(f.string(),f.regex(/^0[23][0-9a-f]{64}$/)),ls=f.pipe(f.string(),f.regex(/^[0-9a-f]{64}$/)),us=f.object({status:f.picklist(ss),publicKeyHex:f.optional(cs),reason:f.optional(f.string())}),ds=f.object({algorithm:f.literal(`p256`),privateKeyHex:ls,publicKeyHex:cs,registration:us}),fs=f.object({version:f.literal(`signer-1`),signer:ds}),ps=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())}),ms=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:ds}),hs=f.object({version:f.literal(3),signer:ds}),gs=f.variant(`version`,[ps,ms,hs]),_s=f.variant(`version`,[fs,ps,ms,hs]);function vs(e){return f.parse(gs,e)}function ys(e){return f.parse(_s,e)}function bs(e){let t=f.safeParse(_s,e);return t.success?t.output:null}function xs(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 ys(JSON.parse(e))}catch(e){throw Error(`${t} credential has an unsupported format`,{cause:e})}}function Cs(e){return vs({version:3,signer:e})}function ws(e){return JSON.stringify(e)}function Ts(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Es(e){return(t,n)=>Ds(e,t,n)}function Ds(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 Os=`catena-agent`;function ks(e){if(!es.test(e))throw Error(`Invalid credential location for credential storage: "${e}"`);return e}const As=Es(`/usr/bin/secret-tool`);function js(e){return e.status===1&&e.stdout===``&&e.stderr.trim()===``}function Ms(e,t){if(t.status===0)return;let n=Ns(t);throw Error(`Linux Secret Service credential ${e} failed (secret-tool exited ${t.status??`without status`}): ${n}`)}function Ns(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 Ps(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 Fs=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??As}async save(e,t){let n=ys(t),r=ks(e);if(await this.savePassword(r,ws(n)),!Ts(await this.resolveDirectPassword(r),n))throw Error(`Linux Secret Service credential save verification failed`)}async resolve(e){return this.resolveDirectPassword(ks(e))}async delete(e){await this.deletePassword(ks(e))}async savePassword(e,t){Ms(`save`,await this.runSecretToolCommand([`store`,`--label`,`${Os} ${e}`,`app`,Os,`account`,e],t))}async resolvePassword(e){let t=await this.runSecretToolCommand([`lookup`,`app`,Os,`account`,e]);return js(t)?null:(Ms(`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`,Os,`account`,e]);js(t)||Ms(`delete`,t)}async runSecretToolCommand(e,t){try{return await this.runSecretTool(e,t)}catch(e){throw Ps(e)}}};const Is=Es(`/usr/bin/security`),Ls=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 Rs(e){return e.status===44}function zs(e,t){return`${e}:chunk:${t}`}function Bs(e){let t=JSON.parse(e),n=bs(t);if(n!==null)return{kind:`direct`,payload:n};let r=f.safeParse(Ls,t);if(r.success)return{kind:`legacy`,manifest:r.output};throw Error(`macOS Keychain credential has an unsupported format`)}function Vs(e,t){if(t.status===0)return;let n=Hs(t);throw Error(`macOS Keychain credential ${e} failed (security exited ${t.status??`without status`})${n===null?``:`: ${n}`}`)}function Hs(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 Us(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 Ws(e,t){return[`add-generic-password`,`-s`,Us(Os),`-a`,Us(e),`-w`,Us(t),`-U`].join(` `)+`
|
|
137
|
+
`}var Gs=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??Is}async save(e,t){let n=ys(t),r=ks(e),i=await this.resolveLegacyChunkCount(r,64);if(await this.savePassword(r,ws(n)),!Ts(await this.resolveDirectPassword(r),n))throw Error(`macOS Keychain credential save verification failed`);await this.deleteChunks(r,i)}async resolve(e){let t=ks(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=ks(e),n=await this.resolveLegacyChunkCount(t,64);await this.deleteChunks(t,n),await this.deletePassword(t)}async savePassword(e,t){Vs(`save`,await this.runSecurity([`-i`],Ws(e,t)))}async resolvePassword(e){let t=await this.runSecurity([`find-generic-password`,`-a`,e,`-s`,Os,`-w`]);return Rs(t)?null:(Vs(`resolve`,t),t.stdout.replace(/\r?\n$/,``))}async resolveKeychainItem(e){let t=await this.resolvePassword(e);return t===null?null:Bs(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(zs(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 ys(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=Bs(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(zs(e,n))}async deletePassword(e){let t=await this.runSecurity([`delete-generic-password`,`-a`,e,`-s`,Os]);Rs(t)||Vs(`delete`,t)}};function Ks(e={}){let t=e.platform??process.platform;if(t===`darwin`)return new Gs({platform:t});if(t===`linux`)return new Fs({platform:t});throw Error(`Catena credential storage is only supported on macOS and Linux`)}const qs=/^127(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}$/;function Js(e){let t=e.replace(/^\[|\]$/g,``);return t===`localhost`||t===`::1`||qs.test(t)}function Ys(e){let t;try{t=new URL(e)}catch{return!1}return t.protocol===`https:`||t.protocol===`http:`&&Js(t.hostname)}function Xs(e,t){if(!Ys(e))throw Error(`${t} must be an https:// URL (http:// is allowed only for a loopback host): "${e}"`)}const Zs=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/,Qs=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(es))}),$s=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(es)),created_at:f.pipe(f.string(),f.isoTimestamp())}),ec=f.variant(`status`,[Qs,$s]);f.object({version:f.literal(1),default_profile:f.optional(f.string()),profiles:f.record(f.string(),ec),directories:f.optional(f.record(f.string(),f.string()))});const tc=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 nc(){return ne(process.env.HOME??j(),`.catena`)}function rc(){return ne(nc(),`profiles.json`)}function ic(e){return Zs.test(e)}function ac(e){if(!ic(e))throw Error(`invalid profile name "${e}" (expected [a-zA-Z0-9][a-zA-Z0-9._-]{0,63})`)}function oc(e){return typeof e!=`object`||!e||!(`code`in e)?!1:typeof e.code==`string`}function sc(e,t){let n;try{n=JSON.parse(e)}catch(e){throw Error(`profiles.json is not valid JSON: ${jo(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(tc,n),i={};for(let[e,n]of Object.entries(r.profiles)){if(!ic(e)){t?.(`profiles: dropping invalid profile name "${e}"`);continue}let r=f.safeParse(ec,n);if(!r.success){t?.(`profiles: dropping malformed profile "${e}"`);continue}i[e]=r.output}if(r.default_profile!==void 0&&(ac(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`||!ic(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 cc(e){try{return sc(ee(rc(),`utf-8`),e)}catch(e){if(e instanceof Error&&oc(e)&&e.code===`ENOENT`)return{version:1,profiles:{}};throw e}}function lc(){T(nc(),{recursive:!0,mode:448}),S(nc(),448)}function uc(e){lc();let t=rc(),n=`${t}.${_(6).toString(`hex`)}.tmp`;A(n,JSON.stringify(e,null,2)+`
|
|
138
|
+
`,{encoding:`utf-8`,mode:384}),D(n,t)}function dc(e,t){ac(e);let n=f.parse(ec,t);Xs(n.bank_url,`profile "${e}" bank_url`);let r=cc();uc({...r,profiles:{...r.profiles,[e]:n}})}function fc(e){return e.status===`linked`}function pc(e,t){return e.replace(/\/+$/,``)===t.replace(/\/+$/,``)}function mc(e,t){let n=Object.entries(cc().profiles).toSorted(([e],[t])=>e.localeCompare(t)).find(([,n])=>fc(n)&&n.agent_id===e&&pc(n.bank_url,t));return n===void 0?null:n[0]}function hc(e,t){let n=Object.fromEntries(Object.entries(e??{}).filter(([,e])=>t(e)));return Object.keys(n).length===0?{}:{directories:n}}function gc(e){ac(e);let t=cc(),{[e]:n,...r}=t.profiles;uc({version:1,...t.default_profile===e||t.default_profile===void 0?{}:{default_profile:t.default_profile},profiles:r,...hc(t.directories,t=>t!==e)})}function _c(e){try{return E(re(e))}catch{return re(e)}}function vc(e){return cc().directories?.[_c(e)]??null}function yc(e,t){ac(t);let n=cc();if(!Object.hasOwn(n.profiles,t))throw Error(`Profile "${t}" is not linked. Run catena link --profile ${t} <agent-id>.`);let r=_c(e);return uc({...n,directories:{...n.directories,[r]:t}}),r}function bc(e){let t=cc(),n=_c(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 uc({...o,...Object.keys(i).length===0?{}:{directories:i}}),{directory:n,removed:!0}}function xc(e){return ac(e),cc().profiles[e]??null}function Sc(){return`client_${_(16).toString(`hex`)}`}function Cc(e,t){let n=xc(e);return t.agent_id===void 0?wc(e,t.bank_url,n):Tc(e,t.bank_url,t.agent_id,n)}function wc(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`&&pc(n.bank_url,t)?n.client_instance_id:null)??Sc();return dc(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 Tc(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(!pc(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`&&pc(r.bank_url,t)?r.client_instance_id:null)??Sc();return dc(e,{status:`linked`,bank_url:t,agent_id:n,client_instance_id:i}),i}function Ec(e){ac(e);let t=cc();if(!Object.hasOwn(t.profiles,e))throw Error(`Profile "${e}" is not linked. Run catena link --profile ${e} <agent-id>.`);uc({...t,default_profile:e})}function Dc(e){let t=e.toLowerCase().replace(/[^a-z0-9._-]+/g,`-`).replace(/^[^a-z0-9]+/,``).slice(0,64);return ic(t)?t:`agent`}function Oc(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 kc(e){ac(e.reservationName),ac(e.profileName);let t=f.parse(ec,e.profile);Xs(t.bank_url,`profile "${e.profileName}" bank_url`);let n=cc(),{[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]));uc({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 Ac(e){return e??Ks()}async function jc(e,t){let n;try{n=xc(e.profileName)}catch(t){return{ok:!1,profileName:e.profileName,bankUrl:e.fallbackBankUrl,message:jo(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{Xs(n.bank_url,`profile "${e.profileName}" bank_url`)}catch(t){return{ok:!1,profileName:e.profileName,bankUrl:e.fallbackBankUrl,message:jo(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 Ac(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}: ${jo(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 Mc={name:`catena-cli`,version:se},Nc=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function Pc(e,t){if(!Nc.test(e))throw Error(`${t} must be a valid HTTP token`)}function Fc(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 Ic(e){Pc(e.name,`appInfo.name`),e.version!==void 0&&Pc(e.version,`appInfo.version`),e.url!==void 0&&Fc(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 Lc=`https://api.catena.com`,Rc=`CATENA_PROFILE`;function zc(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 Bc(e,t,n){if(e.flag!==void 0&&e.flag.length>0)return ac(e.flag),{name:e.flag,source:`flag`};if(e.env!==void 0&&e.env.length>0){if(!ic(e.env))throw Error(`${Rc} is set to an invalid profile name "${e.env}"`);return{name:e.env,source:`env`}}if(e.cwd!==void 0){let r=zc(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 Vc(e){return Bc(e,cc(e.log),`ignore`)}function Hc(e){let t=cc(e.log),n=Bc(e,t,`error`);if(n!==null)return n;let r=Object.keys(t.profiles),i=Object.entries(t.profiles).filter(([,e])=>fc(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 ${Rc}, run 'catena profiles use <name>', or run 'catena link' from an agent directory to bind it.`)}function Uc(e){return Ao({baseUrl:e.bankUrl,privateKeyHex:e.signer.privateKeyHex,appInfo:Mc})}function Wc(){return Ks()}async function Gc(e){let t;try{t=Hc({flag:e,env:process.env[Rc],cwd:process.cwd(),log:e=>console.error(e)}).name}catch(e){return X(e)}let n=await jc({profileName:t,fallbackBankUrl:Lc},void 0);return n.ok||X(n.message),Uc(n)}const Kc=new Set([`unknown_key`,`key_revoked`,`client_unlinked`]),qc=new Set([`signature_auth_disabled`,`missing_auth`]);function Jc(e,t){if(!(e instanceof So)||e.code===void 0)return e;let n=t===void 0?`catena link`:`catena link --profile ${t}`;return Kc.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 (${Mc.version}) is no longer supported by the bank. Run 'npm i -g @catena/cli' and retry.`):qc.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 Yc(e,t){console.log(t?.compact?JSON.stringify(e):JSON.stringify(e,null,2))}function Xc(e){return e.profile===void 0||e.profile.length===0?void 0:e.profile}async function Zc(e,t){try{return await t(await Gc(e))}catch(t){return X(Jc(t,e))}}function Qc(e,t){return async(n,r)=>{let i=await Zc(e,n);return Yc(i,t),await new Promise(e=>{process.stdout.write(``,()=>e())}),process.exit(r?.exitCode?r.exitCode(i):0)}}function $(e){return Qc(Xc(e),{compact:e.json===!0})}const $c=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}`)),el=f.pipe($c,f.maxValue(200,`must be at most 200`)),tl={profile:Qo,json:$o},nl=Q(tl),rl=Q({account:zo({description:`Account id`,required:!0,schema:ts}),...tl}),il=Q({account:zo({description:`Account id`,required:!0,schema:ts}),start:Z({description:`Only include transactions at or after this ISO 8601 time`}),end:Z({description:`Only include transactions at or before this ISO 8601 time`}),limit:Z({description:`Maximum transactions to return (default 50, max 200)`,schema:el}),offset:Z({description:`Number of transactions to skip for pagination`,schema:$c}),...tl}),al=Q({account:zo({description:`Account id`,required:!0,schema:ts}),network:os({description:`Deposit network; defaults to ${is}. Availability depends on the connected environment.`,default:is}),asset:Ho({description:`Deposit asset (${rs.join(`|`)})`,choices:rs,default:`usdc`}),...tl}),ol=l({meta:{name:`list`,description:`List accounts accessible under the agent's policy`},args:nl.args,async run({args:e}){await $(nl.parse(e))(e=>e.listAccounts())}}),sl=l({meta:{name:`balance`,description:`Request an account balance through the policy engine`},args:rl.args,async run({args:e}){let t=rl.parse(e);await $(t)(e=>e.getAccountBalance(t.account))}}),cl=l({meta:{name:`transactions`,description:`Read an account's transaction history through the policy engine`},args:il.args,async run({args:e}){let t=il.parse(e);await $(t)(e=>e.listAccountTransactions(t.account,{start:t.start,end:t.end,limit:t.limit,offset:t.offset}))}}),ll=l({meta:{name:`deposit-address`,description:`Read an account deposit address through the policy engine`},args:al.args,async run({args:e}){let t=al.parse(e);await $(t)(e=>e.getAccountDepositAddress(t.account,{network:t.network,asset:t.asset}))}}),ul=l({meta:{name:`accounts`,description:`Inspect bank accounts`},subCommands:{list:ol,balance:sl,transactions:cl,"deposit-address":ll}}),dl=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)`)),fl=f.pipe(f.string(),f.minLength(1,`must not be empty`)),pl=f.pipe(f.string(),f.trim(),f.email(`must be a valid email address`)),ml={profile:Qo,json:$o},hl=Q({address:Z({description:`Only counterparties with a wallet rail matching this address (0x…)`,schema:as}),network:os({description:`Only counterparties with a wallet rail on this network (e.g. base)`}),...ml}),gl=Z({description:`Counterparty name`,required:!0,schema:fl}),_l=Z({description:`Optional contact email`,schema:pl}),vl=Q({name:gl,email:Z({description:`Contact email; creating the counterparty sends no email`,required:!0,schema:pl}),...ml}),yl=Q({name:Z({description:`Counterparty name; required without a subcommand`,schema:fl}),email:Z({description:`Contact email; required without a subcommand; creating the counterparty sends no email`,schema:pl}),...ml}),bl=Q({name:gl,"bank-name":Z({description:`Receiving bank name`,required:!0,schema:fl}),"routing-number":Z({description:`9-digit ABA routing number`,required:!0,schema:fl}),"account-number":Z({description:`Receiving bank account number`,required:!0,schema:fl}),"account-type":Ho({description:`checking | savings (default checking)`,choices:[`checking`,`savings`]}),"address-street":Z({description:`Street address of the receiving bank account holder`,required:!0,schema:fl}),"address-city":Z({description:`City`,required:!0,schema:fl}),"address-state":Z({description:`State (e.g. NY)`,required:!0,schema:fl}),"address-postal-code":Z({description:`Postal code`,required:!0,schema:fl}),"address-country":Z({description:`Default USA`}),email:_l,...ml}),xl=Q({name:gl,address:Z({description:`Wallet address (0x… or ENS name on EVM networks)`,required:!0,schema:fl}),network:os({description:`Wallet network; defaults to ${is}. Availability depends on the connected environment.`,default:is}),email:_l,...ml}),Sl=Q({counterparty:zo({description:`Counterparty id`,required:!0,schema:ts}),bank:Vo({description:`Request bank account details`,default:!1}),wallet:Vo({description:`Request wallet details`,default:!1}),"idempotency-key":Z({description:`Optional key to replay this exact submission`,schema:dl}),...ml}),Cl=l({meta:{name:`list`,description:`List counterparties available under the agent's policy`},args:hl.args,async run({args:e}){let t=hl.parse(e);await $(t)(e=>e.listCounterparties({address:t.address,network:t.network}))}});function wl(e){return e&&e.length>0?e:void 0}function Tl(e){let t=wl(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 El(e){let t=wl(e.email);return{type:`create_counterparty`,name:e.name,email:t,rail:{type:`wallet`,walletAddress:e.address,network:e.network}}}function Dl(e){return{type:`create_counterparty`,name:e.name,email:e.email}}const Ol=l({meta:{name:`email`,description:`Create a counterparty with an email and no payment details. Sends no email.`},args:vl.args,async run({args:e}){let t=vl.parse(e);await $(t)(e=>e.submitIntent({action:Dl(t)}))}}),kl=l({meta:{name:`bank`,description:`Request bank counterparty creation through the policy engine. Prints an intent envelope.`},args:bl.args,async run({args:e}){let t=bl.parse(e),n=Tl(t);await $(t)(e=>e.submitIntent({action:n}))}}),Al=l({meta:{name:`wallet`,description:`Request wallet counterparty creation through the policy engine. Prints an intent envelope.`},args:xl.args,async run({args:e}){let t=xl.parse(e);await $(t)(e=>e.submitIntent({action:El(t)}))}}),jl=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:yl.args,default:`email`,subCommands:{email:Ol,bank:kl,wallet:Al}}),Ml=l({meta:{name:`request-details`,description:`Ask a counterparty to provide bank details, wallet details, or both through the policy engine.`},args:Sl.args,async run({args:e}){let t=Sl.parse(e);!t.bank&&!t.wallet&&X(`Select at least one of --bank or --wallet`),await $(t)(e=>e.submitIntent({action:{type:`request_counterparty_details`,counterpartyId:t.counterparty,methods:{bank:t.bank,wallet:t.wallet}},...t[`idempotency-key`]?{idempotencyKey:t[`idempotency-key`]}:{}}))}}),Nl=l({meta:{name:`counterparties`,description:`Inspect, create, and request details from counterparties`},subCommands:{list:Cl,create:jl,"request-details":Ml}}),Pl=4e3;async function Fl(){process.stdin.setEncoding(`utf8`);let e=``;for await(let t of process.stdin)e+=t;return e}async function Il(e){return e===void 0?(process.stdin.isTTY&&X(`<message>: pass a quoted message or pipe it on stdin; a message starting with "-" needs -- before it (catena feedback -- "<message>") or stdin`),Fl()):e}const Ll=Q({message:zo({description:`Plain-text feedback (1-4000 chars); omit to pipe on stdin`}),profile:Qo,json:$o}),Rl=l({meta:{name:`feedback`,description:`Send free-form feedback about Catena to the Catena team`},args:Ll.args,async run({args:e}){(Array.isArray(e._)?e._:[]).length>1&&X(`<message>: pass the message as a single quoted argument`);let t=Ll.parse(e),n=(await Il(t.message)).trim();n.length===0&&X(`<message>: must not be empty`),n.length>Pl&&X(`<message>: must be at most ${Pl} characters (got: ${n.length})`),await $(t)(async e=>(await e.submitFeedback(n),{ok:!0}))}});function zl(e){return`# Catena CLI Agent Guide
|
|
139
139
|
|
|
140
140
|
CLI version: ${e}
|
|
141
141
|
|
|
@@ -473,9 +473,11 @@ Request one with:
|
|
|
473
473
|
--amount 500 --duration 4h \\
|
|
474
474
|
--reason "Vendor invoice INV-4471 is $420"
|
|
475
475
|
|
|
476
|
-
Send limits
|
|
477
|
-
accounts' limits are untouched
|
|
478
|
-
|
|
476
|
+
Send and transfer hard limits can be raised, for the one account named by
|
|
477
|
+
--account — other accounts' limits are untouched. The default is a send
|
|
478
|
+
limit; pass \`--capability transfer\` for a transfer limit, where --account
|
|
479
|
+
is the source account, since transfer limits govern the account funds move
|
|
480
|
+
out of. The MCP equivalent is
|
|
479
481
|
\`request_policy_override\`; over REST, an intent with a \`policy_override\`
|
|
480
482
|
action.
|
|
481
483
|
|
|
@@ -552,13 +554,13 @@ you need, tell the Catena team:
|
|
|
552
554
|
|
|
553
555
|
The message must be 1-4000 characters and is write-only. Longer messages can be
|
|
554
556
|
piped on stdin instead of passed as an argument.
|
|
555
|
-
`}const zl=l({meta:{name:`guide`,description:`Print the Catena CLI agent operating guide`},run(){console.log(Rl(se))}}),Bl=Q({id:Ro({description:`Intent id (e.g. int_…)`,required:!0,schema:es}),profile:Zo,json:Qo}),Vl=l({meta:{name:`get`,description:`Look up the current state of an intent created by this agent`},args:Bl.args,async run({args:e}){let t=Bl.parse(e);await $(t)(e=>e.getIntent(t.id))}}),Hl=l({meta:{name:`intents`,description:`Inspect intent receipts returned by governed operations`},subCommands:{get:Vl}});function Ul(e=process.env,t=process.platform){return!!(e.SSH_CONNECTION||e.SSH_TTY||t===`linux`&&!e.DISPLAY&&!e.WAYLAND_DISPLAY)}function Wl(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 Gl(e){e&&process.stderr.write(`Failed to open browser: ${e.message}\n`)}function Kl(e){process.platform===`darwin`?y(`open`,[e],Gl):process.platform===`win32`?y(`cmd`,[`/c`,`start`,``,e],Gl):y(`xdg-open`,[e],Gl)}function ql(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 Jl(e){return typeof e!=`object`||!e||!(`access_token`in e)?!1:typeof e.access_token==`string`}function Yl(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 Xl(e){if(typeof e!=`object`||!e)return!1;let t=e;return os.some(e=>e===t.status)&&(t.publicKeyHex===void 0||typeof t.publicKeyHex==`string`)&&(t.reason===void 0||typeof t.reason==`string`)}async function Zl(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=ra}=e,p=Fc(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:ql(await m.json().catch(()=>({message:`Token exchange failed`})))??m.statusText};let h=await m.json();if(!Jl(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:ql(await _.json().catch(()=>({message:`Claim failed`})))??_.statusText};let v=await _.json();return Yl(v)?Ql({bankUrl:t,claim:v,clientInstanceId:o,signerKeypair:g,identityHeaders:p,log:l}):{ok:!1,message:`Claim response missing required fields`}}async function Ql(e){let{bankUrl:t,claim:n,clientInstanceId:r,signerKeypair:i,identityHeaders:a}=e;(e.log??(()=>{}))(`Registering signer...`);let o=await eu({bankUrl:t,sessionToken:n.sessionToken,keypair:i,identityHeaders:a});return o.status===`registration_failed`?(n.activated!==!1&&await tu({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 $l(e){return typeof e!=`object`||!e||!(`signer`in e)?!1:Xl(e.signer)}async function eu(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 $l(n)?n.signer:{status:`registration_failed`,reason:`registration_response_malformed`}}async function tu(e){try{await fetch(`${e.bankUrl}/v1/agent-api/unlink`,{method:`POST`,headers:{...e.identityHeaders,Authorization:`Bearer ${e.sessionToken}`}})}catch{}}function nu(e){return`${e}-signer`}async function ru(e,t){let n=await e.resolve(t);if(n!==null&&`signer`in n)return n.signer;let r=await e.resolve(nu(t));if(r!==null&&`signer`in r)return r.signer}async function iu(e,t,n=ra){let r=await ru(e,t);if(r!==void 0)return r;let i=bs(n());return await e.save(nu(t),i),i.signer}const au=[53682,53683,53684,53685,53686,53687];function ou(e){return new Promise((t,n)=>{let r=0,i=()=>{if(r>=au.length){n(Error(`No registered loopback callback ports are available`));return}let a=au[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 su(e){let{bankUrl:t,agentId:n,clientInstanceId:r,clientId:i,clientLabel:a,timeoutMs:o=3e5,log:s=()=>{},appInfo:c,existingSigner:l}=e;Ys(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=ql(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 Zl({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)}ou(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...`),Kl(r),s(`If browser didn't open, visit: ${r}`)}).catch(b),v=setTimeout(()=>{x(`Timed out waiting for authentication`)},o),v.unref()})}function cu(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 lu(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 uu(e){return new Promise(t=>{setTimeout(t,e)})}function du(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 fu(e){let{bankUrl:t,clientInstanceId:n,onUserCode:r,log:i=()=>{},appInfo:a,existingSigner:o,generateSignerKeypair:s=ra,sleep:c=uu}=e;Ys(t,`bankUrl`);let l=Fc(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(du(e))})}catch{return u(`Could not reach the bank to start the device flow`)}if(!d.ok)return u(lu(await d.json().catch(()=>null)).message??d.statusText);let f=await d.json();if(!cu(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 pu({bankUrl:t,grant:f,identityHeaders:l,sleep:c});if(!p.ok)return u(p.message);let m=p.body;if(!Yl(m))return u(`Device token response missing required fields`);i(`Approved. Claiming agent...`);let h=await Ql({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 pu(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=lu(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 mu(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 hu(e){let{bankUrl:t,clientInstanceId:n,onUserCode:r,log:i=()=>{},appInfo:a,sleep:o=uu}=e;Ys(t,`bankUrl`);let s=Fc(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=lu(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(!cu(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 pu({bankUrl:t,grant:f,identityHeaders:s,sleep:o});return p.ok?Yl(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`):mu(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 gu=Q({"agent-id":Ro({description:`Optional agent ID shown in the Catena console; omit to create and link a new agent`,schema:es}),"bank-url":Z({description:`Bank API URL (defaults to $CATENA_API_URL or prod)`,default:process.env.CATENA_API_URL??`https://api.catena.com`}),browser:Bo({description:`Open the browser PKCE flow (default)`,negativeDescription:`Skip the browser and link with a device code you approve from another machine`,default:!0}),name:Z({description:`Suggested name for an agent created from this link; only used when agent-id is omitted`}),service:Bo({description:`Provision a deployed-service signing credential instead of linking this machine: approval registers a P-256 key, no session tokens are minted, and nothing is stored locally. Interactive agent hosts must NOT use this`,default:!1}),"public-key":Z({description:`With --service: register this existing compressed P-256 public key (the deployment already holds the private key) instead of generating a keypair`}),profile:Zo}),_u=/^0[23][0-9a-f]{64}$/;function vu(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 yu(e){console.log(`
|
|
556
|
-
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
|
|
557
|
-
Catena — Agent Setup`),console.log(`─`.repeat(25));let c=
|
|
558
|
-
Failed to link agent. Run the command again to try again.`),await c.save(s,
|
|
559
|
-
Catena — Deployed Service Setup`),console.log(`─`.repeat(31));let t=e.publicKeyHex===void 0?ra():null,n=t?.publicKeyHex??e.publicKeyHex?.toLowerCase()??``,r;try{r=sa(n)}catch(e){e instanceof na||X(e),X(`Signing key public key is not a valid P-256 point`)}console.log(` Signing key (RFC 7638 thumbprint): ${r}`);let i=`service-${h(`sha256`).update(n).digest(`hex`).slice(0,32)}`,a=!1,o=()=>{t&&a&&
|
|
560
|
-
Failed to link the service. Run the command again to try again.`)),s.keyThumbprint!==r&&(o(),X(`The bank registered signing key thumbprint ${s.keyThumbprint}, which does not match the local key (${r}). Do not deploy this credential. Unlink the agent in the console and run link again`)),console.log(`\nDone. Agent "${s.agentName}" linked as a deployed service.`),console.log(` Agent ID: ${s.agentId}`),console.log(` Signing key (RFC 7638 thumbprint): ${s.keyThumbprint}`),s.signerStatus===`registered`||s.signerStatus===`already_registered`?console.log(` Wallet-send signer: registered`):s.signerStatus===`not_applicable`?console.log(` Wallet-send signer: deferred (${s.signerReason??`topology not ready`}); the org must be signing-ready before live sends`):s.signerStatus===`registration_failed`?console.log(
|
|
557
|
+
`}const Bl=l({meta:{name:`guide`,description:`Print the Catena CLI agent operating guide`},run(){console.log(zl(se))}}),Vl=Q({id:zo({description:`Intent id (e.g. int_…)`,required:!0,schema:ts}),profile:Qo,json:$o}),Hl=l({meta:{name:`get`,description:`Look up the current state of an intent created by this agent`},args:Vl.args,async run({args:e}){let t=Vl.parse(e);await $(t)(e=>e.getIntent(t.id))}}),Ul=l({meta:{name:`intents`,description:`Inspect intent receipts returned by governed operations`},subCommands:{get:Hl}});function Wl(e=process.env,t=process.platform){return!!(e.SSH_CONNECTION||e.SSH_TTY||t===`linux`&&!e.DISPLAY&&!e.WAYLAND_DISPLAY)}function Gl(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 Kl(e){e&&process.stderr.write(`Failed to open browser: ${e.message}\n`)}function ql(e){process.platform===`darwin`?y(`open`,[e],Kl):process.platform===`win32`?y(`cmd`,[`/c`,`start`,``,e],Kl):y(`xdg-open`,[e],Kl)}function Jl(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 Yl(e){return typeof e!=`object`||!e||!(`access_token`in e)?!1:typeof e.access_token==`string`}function Xl(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 Zl(e){if(typeof e!=`object`||!e)return!1;let t=e;return ss.some(e=>e===t.status)&&(t.publicKeyHex===void 0||typeof t.publicKeyHex==`string`)&&(t.reason===void 0||typeof t.reason==`string`)}async function Ql(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=ra}=e,p=Ic(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:Jl(await m.json().catch(()=>({message:`Token exchange failed`})))??m.statusText};let h=await m.json();if(!Yl(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:Jl(await _.json().catch(()=>({message:`Claim failed`})))??_.statusText};let v=await _.json();return Xl(v)?$l({bankUrl:t,claim:v,clientInstanceId:o,signerKeypair:g,identityHeaders:p,log:l}):{ok:!1,message:`Claim response missing required fields`}}async function $l(e){let{bankUrl:t,claim:n,clientInstanceId:r,signerKeypair:i,identityHeaders:a}=e;(e.log??(()=>{}))(`Registering signer...`);let o=await tu({bankUrl:t,sessionToken:n.sessionToken,keypair:i,identityHeaders:a});return o.status===`registration_failed`?(n.activated!==!1&&await nu({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 eu(e){return typeof e!=`object`||!e||!(`signer`in e)?!1:Zl(e.signer)}async function tu(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 eu(n)?n.signer:{status:`registration_failed`,reason:`registration_response_malformed`}}async function nu(e){try{await fetch(`${e.bankUrl}/v1/agent-api/unlink`,{method:`POST`,headers:{...e.identityHeaders,Authorization:`Bearer ${e.sessionToken}`}})}catch{}}function ru(e){return`${e}-signer`}async function iu(e,t){let n=await e.resolve(t);if(n!==null&&`signer`in n)return n.signer;let r=await e.resolve(ru(t));if(r!==null&&`signer`in r)return r.signer}async function au(e,t,n=ra){let r=await iu(e,t);if(r!==void 0)return r;let i=xs(n());return await e.save(ru(t),i),i.signer}const ou=[53682,53683,53684,53685,53686,53687];function su(e){return new Promise((t,n)=>{let r=0,i=()=>{if(r>=ou.length){n(Error(`No registered loopback callback ports are available`));return}let a=ou[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 cu(e){let{bankUrl:t,agentId:n,clientInstanceId:r,clientId:i,clientLabel:a,timeoutMs:o=3e5,log:s=()=>{},appInfo:c,existingSigner:l}=e;Xs(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=Jl(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 Ql({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)}su(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...`),ql(r),s(`If browser didn't open, visit: ${r}`)}).catch(b),v=setTimeout(()=>{x(`Timed out waiting for authentication`)},o),v.unref()})}function lu(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 uu(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 du(e){return new Promise(t=>{setTimeout(t,e)})}function fu(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 pu(e){let{bankUrl:t,clientInstanceId:n,onUserCode:r,log:i=()=>{},appInfo:a,existingSigner:o,generateSignerKeypair:s=ra,sleep:c=du}=e;Xs(t,`bankUrl`);let l=Ic(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(fu(e))})}catch{return u(`Could not reach the bank to start the device flow`)}if(!d.ok)return u(uu(await d.json().catch(()=>null)).message??d.statusText);let f=await d.json();if(!lu(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 mu({bankUrl:t,grant:f,identityHeaders:l,sleep:c});if(!p.ok)return u(p.message);let m=p.body;if(!Xl(m))return u(`Device token response missing required fields`);i(`Approved. Claiming agent...`);let h=await $l({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 mu(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=uu(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 hu(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 gu(e){let{bankUrl:t,clientInstanceId:n,onUserCode:r,log:i=()=>{},appInfo:a,sleep:o=du}=e;Xs(t,`bankUrl`);let s=Ic(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=uu(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(!lu(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 mu({bankUrl:t,grant:f,identityHeaders:s,sleep:o});return p.ok?Xl(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`):hu(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 _u=Q({"agent-id":zo({description:`Optional agent ID shown in the Catena console; omit to create and link a new agent`,schema:ts}),"bank-url":Z({description:`Bank API URL (defaults to $CATENA_API_URL or prod)`,default:process.env.CATENA_API_URL??`https://api.catena.com`}),browser:Vo({description:`Open the browser PKCE flow (default)`,negativeDescription:`Skip the browser and link with a device code you approve from another machine`,default:!0}),name:Z({description:`Suggested name for an agent created from this link; only used when agent-id is omitted`}),service:Vo({description:`Provision a deployed-service signing credential instead of linking this machine: approval registers a P-256 key, no session tokens are minted, and nothing is stored locally. Interactive agent hosts must NOT use this`,default:!1}),"public-key":Z({description:`With --service: register this existing compressed P-256 public key (the deployment already holds the private key) instead of generating a keypair`}),profile:Qo}),vu=/^0[23][0-9a-f]{64}$/;function yu(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 bu(e){console.log(`
|
|
558
|
+
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 xu(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 Su({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 Cu(e){let t=h(`sha256`).update(E(process.cwd())).digest(`hex`).slice(0,16);return`${Dc(e??`agent`).slice(0,47)}-${t}`}function wu(e){try{let t=process.cwd();if(Gl(t))return null;let n=vc(t);return{directory:yc(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 Tu=l({meta:{name:`link`,description:`Link an existing agent, or create and link a new agent when agent-id is omitted`},args:_u.args,async run({args:e}){let t=_u.parse(e),n=t[`bank-url`],r=t[`agent-id`],i=t.name;if(t.service){await Eu({bankUrl:n,agentId:r,suggestedAgentName:i,publicKeyHex:t[`public-key`]});return}let a,o,s;try{if(Xs(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=Vc({flag:Xc(t),cwd:process.cwd(),log:e=>console.error(e)});a=(e!==null&&e.source!=="default"?e.name:null)??(r===void 0?null:mc(r,n)),o=a??(r===void 0?Cu(i):Dc(r)),s=Cc(o,{bank_url:n,agent_id:r})}catch(e){X(e)}console.log(`
|
|
559
|
+
Catena — Agent Setup`),console.log(`─`.repeat(25));let c=Ks(),l=await au(c,s),u={bankUrl:n,clientInstanceId:s,log:e=>console.log(` ${e}`),appInfo:Mc,existingSigner:l},d=Su({agentId:r,suggestedAgentName:i,browserRequested:t.browser,isHeadless:Wl});d.kind===`device-link`&&d.notice!==void 0&&console.log(` ${d.notice}`);let f=d.kind===`pkce-link`?await cu({...u,agentId:d.agentId,clientId:`catena-cli`,timeoutMs:3e5}):await pu({...u,...d.deviceTarget,onUserCode:yu});f||X(`
|
|
560
|
+
Failed to link agent. Run the command again to try again.`),await c.save(s,Cs(f.signer));let p=a??Oc(Dc(f.agentName),e=>e!==o&&xc(e)!==null);try{p===o?dc(p,{bank_url:n,agent_id:f.agentId,client_instance_id:s}):kc({reservationName:o,profileName:p,profile:{bank_url:n,agent_id:f.agentId,client_instance_id:s}})}catch(e){X(e)}console.log(`\n Wrote profile "${p}"`);let m=wu(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 ${Rc}=${p}`),console.log(`\nDone. Agent "${f.agentName}" linked.`),process.exit(0)}});async function Eu(e){try{if(Xs(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&&!vu.test(e.publicKeyHex.toLowerCase()))throw Error(`--public-key must be compressed P-256 public key hex (66 chars)`)}catch(e){X(e)}console.log(`
|
|
561
|
+
Catena — Deployed Service Setup`),console.log(`─`.repeat(31));let t=e.publicKeyHex===void 0?ra():null,n=t?.publicKeyHex??e.publicKeyHex?.toLowerCase()??``,r;try{r=sa(n)}catch(e){e instanceof na||X(e),X(`Signing key public key is not a valid P-256 point`)}console.log(` Signing key (RFC 7638 thumbprint): ${r}`);let i=`service-${h(`sha256`).update(n).digest(`hex`).slice(0,32)}`,a=!1,o=()=>{t&&a&&bu({publicKeyHex:n,privateKeyHex:t.privateKeyHex})},s;try{s=await gu({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,yu(e)},log:e=>console.log(` ${e}`),appInfo:Mc})}catch(e){o(),X(e)}s||(o(),X(`
|
|
562
|
+
Failed to link the service. Run the command again to try again.`)),s.keyThumbprint!==r&&(o(),X(`The bank registered signing key thumbprint ${s.keyThumbprint}, which does not match the local key (${r}). Do not deploy this credential. Unlink the agent in the console and run link again`)),console.log(`\nDone. Agent "${s.agentName}" linked as a deployed service.`),console.log(` Agent ID: ${s.agentId}`),console.log(` Signing key (RFC 7638 thumbprint): ${s.keyThumbprint}`),s.signerStatus===`registered`||s.signerStatus===`already_registered`?console.log(` Wallet-send signer: registered`):s.signerStatus===`not_applicable`?console.log(` Wallet-send signer: deferred (${s.signerReason??`topology not ready`}); the org must be signing-ready before live sends`):s.signerStatus===`registration_failed`?console.log(xu(s.signerReason)):console.log(` Wallet-send signer: not registered (${s.signerReason??s.signerStatus}); retry after checking the link status`),console.log(`
|
|
561
563
|
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(`
|
|
562
564
|
The private key is shown once and is not stored on this machine.`),process.exit(0)}
|
|
563
565
|
/*! decimal.js-light v2.5.1 https://github.com/MikeMcl/decimal.js-light/LICENCE */
|
|
564
|
-
const Eu=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;Eu.set({rounding:Eu.ROUND_HALF_EVEN});const Du=new Map,Ou=/^[A-Z]{3}$/,ku=/^[A-Z0-9]{2,6}$/;function Au(e,t,n,r){if(Du.has(e))throw Error(`duplicate asset id ${e}`);let i=new Eu(r);if(i.isNegative())throw Error(`dustThreshold must be a non-negative decimal`);if(i.decimalPlaces()>t)throw Error(`dustThreshold (${r}) must not be finer than the asset's ${t} decimals`);if(!Number.isInteger(t)||!Number.isInteger(n)||t<0||n<0)throw Error(`decimals and presentmentDecimals must be non-negative integers`);if(n>t)throw Error(`presentment decimals should be less than or equal to decimals`)}function ju(e,t,n,r,i){if(!Ou.test(e))throw Error(`fiat asset ids must be 3-letter ISO-4217 codes`);Au(e,n,r,i.dustThreshold);let a=e;return Du.set(e,{id:a,symbol:e,name:t,kind:`fiat`,decimals:n,presentmentDecimals:r,denomination:e,valuation:{type:`par`},dustThreshold:i.dustThreshold}),a}function Mu(e,t,n,r,i){if(!ku.test(e)||Ou.test(e))throw Error(`stablecoin tickers must be 2-6 uppercase alphanumerics and not a 3-letter ISO-4217 shape`);let a=Du.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})`);Au(e,n,r,i.dustThreshold);let o=e;return Du.set(e,{id:o,symbol:e,name:t,kind:`stablecoin`,decimals:n,presentmentDecimals:r,denomination:a.denomination,valuation:{type:`par`},dustThreshold:i.dustThreshold}),o}Mu(`USDC`,`USD Coin`,6,2,{denomination:ju(`USD`,`US Dollar`,6,2,{dustThreshold:`0.01`}),dustThreshold:`0.01`}),new Eu(1e6),new Eu(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 Eu(e).gte(0)}catch{return!1}},`Amount must be a valid decimal (e.g. 100 or 100.50)`)),Pu=f.pipe(f.string(`Count must be a string`),f.transform(e=>e.trim()),f.check(e=>/^\d+$/.test(e),`Count must be a whole number of transactions (e.g. 20)`),f.transform(Number),f.check(e=>Number.isSafeInteger(e),`Count is too large`),f.check(e=>e>=1,`Count must be at least 1`)),Fu={s:1,m:60,h:3600,d:86400},Iu=f.pipe(f.string(`Duration must be a string`),f.transform(e=>e.trim()),f.check(e=>/^\d+[smhd]?$/.test(e),`Duration must be a number of seconds or a value with a unit (e.g. 90s, 30m, 4h, 2d)`),f.transform(e=>{let t=e.at(-1)??``;return t in Fu?Number(e.slice(0,-1))*Fu[t]:Number(e)}),f.check(e=>e>=60,`Duration must be at least 1 minute`),f.check(e=>e<=604800,`Duration must be at most 7 days`)),Lu=Q({profile:Zo,json:Qo}),Ru=l({meta:{name:`show`,description:`Show the agent's assigned policy`},args:Lu.args,async run({args:e}){await $(Lu.parse(e))(e=>e.getPolicy())}}),zu=Q({account:Z({description:`Account whose existing send hard limit should increase`,required:!0}),rule:Vo({description:`Which limit to adjust`,choices:Na,default:`per_transaction_amount`}),amount:Z({description:`New threshold for an amount limit, as a decimal USD string (e.g. 500.00)`,schema:Nu,showValueInError:!0}),count:Z({description:`New threshold for a transaction-count limit (e.g. 20)`,schema:Pu,showValueInError:!0}),duration:Z({description:`How long the override should last once approved (e.g. 90s, 30m, 4h, 2d). One minute to seven days.`,required:!0,schema:Iu,showValueInError:!0}),reason:Z({description:`Why the task needs this, for the person who reviews the request`,required:!0}),profile:Zo,json:Qo}),Bu=l({meta:{name:`request-override`,description:`Ask a person to approve a temporary change to this agent's limits`},args:zu.args,async run({args:e}){let t=zu.parse(e),n=$(t),r={type:`policy_override`,operations:[Vu(t)],durationSeconds:t.duration,reason:t.reason};await n(e=>e.submitIntent({action:r}))}});function Vu(e){return e.rule===`hourly_count`||e.rule===`daily_count`?(e.amount!==void 0&&X(`--amount does not apply to ${e.rule}; use --count`),e.count===void 0&&X(`--count is required for ${e.rule}`),{type:`increase_limit`,accountId:e.account,capability:`send`,limitType:e.rule,newLimit:{count:e.count}}):(e.count!==void 0&&X(`--count does not apply to ${e.rule}; use --amount`),e.amount===void 0&&X(`--amount is required for ${e.rule}`),{type:`increase_limit`,accountId:e.account,capability:`send`,limitType:e.rule,newLimit:{amount:e.amount,assetId:`USD`}})}const Hu=l({meta:{name:`policy`,description:`Inspect the agent's policy`},subCommands:{show:Ru,"request-override":Bu}}),Uu=Q({profile:Ro({description:`Profile name`,required:!0})});function Wu(){try{return Vc({env:process.env[Lc],cwd:process.cwd(),log:e=>console.error(e)})}catch(e){return X(e)}}const Gu=l({meta:{name:`use`,description:`Set the default credential profile`},args:Uu.args,async run({args:e}){let t=Uu.parse(e);try{Tc(t.profile),Jc({defaultProfile:t.profile})}catch(e){X(e)}}}),Ku=l({meta:{name:`current`,description:`Show the selected credential profile and how it was chosen`},async run(){let e=Wu(),t;try{t=bc(e.name)}catch(e){X(e)}t===null&&X(`Profile "${e.name}" is not linked.\nRun 'catena link --profile ${e.name} <agent-id>' to authenticate.`),Jc({profile:e.name,source:e.source,bankUrl:t.bank_url,agentId:dc(t)?t.agent_id:void 0})}}),qu=l({meta:{name:`list`,description:`List credential profiles and their directory bindings`},async run(){let e;try{e=sc()}catch(e){X(e)}let t;try{t=Vc({env:process.env[Lc],cwd:process.cwd()}).name}catch{t=null}let n=Object.entries(e.directories??{});Jc({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:dc(r)?r.agent_id:void 0,directories:n.filter(([,t])=>t===e).map(([e])=>e).toSorted(),current:e===t}))})}}),Ju=Q({profile:Ro({description:`Profile name to bind`,required:!0}),path:Ro({description:`Directory to bind (defaults to the current directory)`})}),Yu=l({meta:{name:`bind`,description:`Bind a directory to a profile for automatic selection`},args:Ju.args,async run({args:e}){let t=Ju.parse(e);try{let e=t.path??process.cwd();if(Wl(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=vc(e,t.profile);Jc({profile:t.profile,directory:n})}catch(e){X(e)}}}),Xu=Q({path:Ro({description:`Directory to unbind (defaults to the current directory)`})}),Zu=l({meta:{name:`unbind`,description:`Remove a directory's profile binding`},args:Xu.args,async run({args:e}){let t=Xu.parse(e);try{Jc(yc(t.path??process.cwd()))}catch(e){X(e)}}}),Qu=l({meta:{name:`profiles`,description:`Manage credential profiles`},subCommands:{use:Gu,current:Ku,list:qu,bind:Yu,unbind:Zu}}),$u=Q({account:Z({description:`Source account id`,required:!0,schema:es}),rail:Z({description:`Destination counterparty rail id (cprl_...)`,required:!0,schema:es}),amount:Z({description:`USD amount as a decimal string (e.g. 125.00)`,required:!0,schema:Nu,showValueInError:!0}),method:Vo({description:`ach | wire | on-chain; ach and wire require a bank rail, on-chain a wallet rail`,required:!0,choices:qa}),memo:Z({description:`Memo on the underlying transfer`}),description:Z({description:`Operator-facing description`}),idempotencyKey:Z({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:ul}),profile:Zo,json:Qo}),ed=l({meta:{name:`send`,description:`Submit a USD send intent to a counterparty rail`},args:$u.args,async run({args:e}){let t=$u.parse(e),n=$(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}:{}}))}}),td=Q({from:Z({description:`Source account id`,required:!0,schema:es}),to:Z({description:`Destination account id`,required:!0,schema:es}),amount:Z({description:`USD amount as a decimal string (e.g. 125.00)`,required:!0,schema:Nu,showValueInError:!0}),memo:Z({description:`Memo on the underlying transfer`}),description:Z({description:`Operator-facing description`}),idempotencyKey:Z({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:ul}),profile:Zo,json:Qo}),nd=l({meta:{name:`transfer`,description:`Submit a USD transfer intent between two of this agent's accounts`},args:td.args,async run({args:e}){let t=td.parse(e),n=$(t),r={type:`transfer`,accountId:t.from,toAccountId:t.to,amount:t.amount,...t.memo?{memo:t.memo}:{},...t.description?{description:t.description}:{}};await n(e=>e.submitIntent({action:r,...t.idempotencyKey?{idempotencyKey:t.idempotencyKey}:{}}))}}),rd=Q({profile:Zo,force:Bo({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:Qo}),id=l({meta:{name:`unlink`,description:`Disconnect the selected agent profile`},args:rd.args,async run({args:e}){let t=rd.parse(e),n=Uc(),r;try{r=Vc({flag:Yc(t),env:process.env[Lc],cwd:process.cwd(),log:e=>console.error(e)}).name}catch(e){X(e)}if(t.force){let e;try{if(e=bc(r),e===null)throw Error(`Profile "${r}" not found`);await n.delete(e.client_instance_id),await n.delete(nu(e.client_instance_id)),hc(r)}catch(e){X(e)}Jc({success:!0,profile:r,...dc(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 Ac({profileName:r,fallbackBankUrl:Ic},n);a.ok||X(`${a.message} ${i}`);let o=Hc(a);try{await o.unlinkAgent(),await n.delete(a.clientInstanceId),await n.delete(nu(a.clientInstanceId)),hc(r)}catch(e){X(`${Ao(qc(e,r))} ${i}`)}Jc({success:!0,profile:r,agentId:a.agentId},{compact:t.json})}}),ad=Q({profile:Zo,json:Qo}),od=l({meta:{name:`whoami`,description:`Show which agent you are currently acting as`},args:ad.args,async run({args:e}){await $(ad.parse(e))(e=>e.whoami())}});function sd(e){throw Error(`Unhandled case: ${String(e)}`)}const cd=[`PAYMENT-REQUIRED`,`X-Payment-Required`],ld=/^0x[0-9a-fA-F]{64}$/,ud=/^0x[0-9a-fA-F]{40}$/,dd=f.looseObject({success:f.boolean(),transaction:f.string()}),fd=f.looseObject({x402Version:f.literal(2),accepts:f.array(lo),resource:f.optional(uo)}),pd=`x402_network_mismatch`,md=`x402_counterparty_rail_not_found`,hd=new Set([`x402_requirement_not_payable`,pd,md]),gd={"eip155:8453":`Base`,"eip155:84532":`Base Sepolia`};function _d(e){let t=Object.hasOwn(gd,e)?gd[e]:void 0;return t?`${t} (${e})`:e}function vd(e){let t=e.replaceAll(`-`,`+`).replaceAll(`_`,`/`),n=Uint8Array.from(atob(t),e=>e.charCodeAt(0));return JSON.parse(new TextDecoder().decode(n))}function yd(e){let t=cd.map(t=>e.headers.get(t)).find(e=>e!==null);if(t)try{let e=f.safeParse(fd,vd(t));return e.success?e.output:void 0}catch{return}}async function bd(e,t,n){try{let r=n.headers.get(`PAYMENT-RESPONSE`);if(!r)return;let i=f.safeParse(dd,vd(r));if(!i.success||!i.output.success||!ld.test(i.output.transaction))return;await e.reportSettlement({intentId:t,txHash:i.output.transaction})}catch{}}var xd=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}},Sd=class extends xd{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(_d).join(` or `)}`,n,{appendReasonsToMessage:!1}),this.name=`X402NetworkMismatchError`,this.accountId=e,this.requiredNetworks=t}},Cd=class extends xd{payTo;network;serviceName;constructor(e,t,n,r=[]){super(`This 402 pays ${e} on ${_d(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}},wd=class extends xd{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}},Td=class extends xd{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 Ed(e,t){try{return await t()}catch(t){throw new Td(e,t)}}var Dd=class extends xd{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 Od(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 xd(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 Ad(e,{accountId:t.accountId,requirements:n,resource:i}).catch(e=>{if(e instanceof xo&&e.code!==void 0&&hd.has(e.code)){a.push({error:e,requirement:n});return}throw e});if(r)return r}let o=a.filter(e=>e.error.code===md),s=a.filter(e=>e.error.code===pd),c=a.filter(e=>e.error.code!==md&&e.error.code!==pd),l=[...new Set([...o,...s,...c].map(e=>e.error.message))],u=o.find(e=>e.error.status===404&&ud.test(e.requirement.payTo));throw u?new Cd(u.requirement.payTo,u.requirement.network,i?.serviceName,l):s.length>0&&o.length===0?new Sd(t.accountId,[...new Set(s.map(e=>e.requirement.network))],l):new xd(`No requirement in the 402 challenge is payable from this account`,l)}const kd=f.object({x402:f.object({paymentSignature:f.string()})});async function Ad(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 Eo&&e.outcome===`unknown`?new Dd(e.intentId,t.requirements,e):e});if(n.status===`completed`){let e=f.safeParse(kd,n.data);if(e.success)return{intentId:n.id,paymentSignature:e.output.x402.paymentSignature,requirements:t.requirements};throw new xd(`The completed payment did not carry an x402 payment signature`)}switch(n.status){case`pending`:throw new wd(n.id,n.reasons,n.expiresAt);case`processing`:throw new xd(`The payment is still processing (intent ${n.id}); this client cannot resume an in-flight x402 settlement`);case`blocked`:case`failed`:throw new xd(`Catena declined the payment`,n.reasons)}return sd(n.status)}function jd(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 Md(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=yd(a);if(!o)return a;if(!jd(r,i))throw new xd(`The request body cannot be replayed after payment; buffer the body (string, Blob, or ArrayBuffer) before using the x402 fetch wrapper`);let s=await Od(e,{accountId:t.accountId,paymentRequired:o,...t.maxAtomicAmount!==void 0&&{maxAtomicAmount:t.maxAtomicAmount}});await Ed(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 Ed(s,()=>n(r,{...i,headers:c}));return bd(e,s.intentId,l),l}}function Nd(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 Pd=4e3;function Fd(e){try{return k(e)}catch{return}}function Id(e,t,n){try{x(e,t)}catch{X(n)}}function Ld(e){let t=re(e),n=M(t),r=Fd(n);(r===void 0||!r.isDirectory())&&X(`--output ${e}: directory ${n} does not exist`);let i=Fd(t);return i===void 0?(Id(n,C.W_OK|C.X_OK,`--output ${e}: directory ${n} is not writable`),t):(i.isDirectory()&&X(`--output ${e}: destination is a directory`),i.isFile()||X(`--output ${e}: destination is not a regular file`),Id(t,C.W_OK,`--output ${e}: destination is not writable`),t)}const Rd=/^(?:con|prn|aux|nul|com\d|lpt\d)$/i;function zd(e){if(e!==void 0&&$o.test(e)&&!Rd.test(e))return`${e}.body`;let t=`${Date.now()}-${_(4).toString(`hex`)}.body`;return e===void 0?`unpaid-${t}`:`paid-${t}`}function Bd(e,t){let n=Nd(tc(),`responses`);if(n===void 0)return;let r=ne(n,zd(t));try{return A(r,e,{mode:384}),r}catch{return}}function Vd(e){let t=e.subarray(0,Pd*4),n=t.toString(`utf8`);return{decoded:n,complete:t.length===e.length&&n.length<=Pd&&ae(e)}}function Hd({decoded:e,complete:t}){let n=e.slice(0,Pd),r=n.charCodeAt(n.length-1);return{body:r>=55296&&r<=56319?n.slice(0,-1):n,...!t&&{bodyTruncated:!0}}}function Ud(e,t){if(t.complete)return{body:t.decoded};if(e.length>268435456)return{...Hd(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 Wd(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 Gd(e,t,n){let r=Bd(e,t);return r===void 0?Ud(e,n):{...Hd(n),bodyPath:r}}function Kd(e,t,n){let r=Vd(e);if(n===void 0)return r.complete?{body:r.decoded}:Gd(e,t,r);try{A(n,e,{mode:384})}catch(i){let a=Gd(e,t,r),o=`--output ${n}: ${Ao(i)}`;return`bodyPath`in a?{...a,error:`${o}; the full body was saved to ${a.bodyPath}`}:{...a,error:`${o}; ${Wd(a)}`}}return{...Hd(r),bodyPath:n}}function qd(e){if(e===`@-`)return Jd(0,`stdin`);if(e.startsWith(`@`)){let t=e.slice(1);return t===``?X(`--data @<path>: no file path given`):Jd(t,`@${t}`)}return e}function Jd(e,t){try{return ee(e,`utf8`)}catch(e){return X(`--data ${t}: ${Ao(e)}`)}}function Yd(e){let[t,n=``]=e.split(`.`);return BigInt(`${t}${n.padEnd(6,`0`)}`)}function Xd(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 Qd(e){return Object.hasOwn(Zd,e)?Zd[e]:void 0}function $d(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function ef(e){return e===void 0?``:` --profile ${$d(e)}`}function tf(e){let t=e?.replaceAll(/[\p{C}\s]/gu,` `).replaceAll(/ {2,}/g,` `).trim();return t!==void 0&&t.length>0?t:void 0}function nf(e,t,n,r){let i=Qd(t)??$d(t);return`catena counterparties create wallet --name ${$d(n??`<name>`)} --address ${$d(e)} --network ${i}${ef(r)}`}const rf=f.pipe(f.string(),f.check(e=>Mc.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 af(e,t){return e.some(e=>e.name.toLowerCase()===t)}function of(e,t){af(e,`payment-signature`)&&X(`--header cannot set PAYMENT-SIGNATURE; the payment loop attaches it after paying`),af(e,`content-type`)&&t!==void 0&&X(`--header "Content-Type: ..." conflicts with --content-type`)}function sf(e,t,n){let r=[...n!==void 0&&!af(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 cf=Q({url:Z({description:`The paywalled URL to fetch (an x402 v2 endpoint)`,required:!0,schema:f.pipe(f.string(),f.url())}),account:Z({description:`Source wallet account id the payment draws from`,required:!0,schema:es}),maxAmount:Z({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:Vo({description:`HTTP method for the request`,choices:[`GET`,`POST`]}),data:Z({description:`Request body. Use @path to read a file or @- for stdin. Implies POST and a JSON content type unless overridden.`}),contentType:Z({description:`Content-Type header for the request body (default application/json when --data is set)`}),output:Z({description:`Write the full response body to this file (must be a regular file; written for any HTTP status — check .status). Without it .body is capped at 4000 characters; longer or non-UTF-8 bodies are saved to a file (path reported in .bodyPath)`}),header:zo({description:`Request header as "Name: Value" (repeatable, like curl -H); sent on the initial request and the paid retry`,schema:rf}),profile:Zo,json:Qo}),lf=l({meta:{name:`x402`,description:`Fetch a URL, paying its x402 (HTTP 402) challenge via USDC`},args:cf.args,async run({args:e,rawArgs:t}){let n=cf.parse(e,t),r=n.method??(n.data===void 0?`GET`:`POST`);n.data!==void 0&&r!==`POST`&&X(`--data cannot be sent with --method ${r}; a body requires POST`),n.contentType!==void 0&&n.data===void 0&&X(`--content-type has no effect without --data`),of(n.header,n.contentType);let i=n.output===void 0?void 0:Ld(n.output),a=n.data===void 0?void 0:qd(n.data),o=sf(n.header,n.contentType,a);await $(n)(async e=>{let t,s=Md(e,{accountId:n.account,...n.maxAmount!==void 0&&{maxAtomicAmount:Yd(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 Td)return{status:null,paid:!0,retryFailed:!0,payment:Xd(e.receipt),error:e.message};if(e instanceof Sd){let t=e.requiredNetworks.map(e=>Qd(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${ef(n.profile)}\`).`}}if(e instanceof Cd){let t=tf(e.serviceName),r=t!==void 0&&t.length<=40?t:void 0,i=nf(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:Qd(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 wd)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:Xd(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}${ef(n.profile)}\` to retry manually`;return{...l,error:`failed to read the response body: ${Ao(e)}${r}`}}return{...l,...Kd(u,t?.intentId,i)}},{exitCode:e=>+(`error`in e)})}}),uf=f.object({version:f.literal(1),result:f.literal(`latest-version`),latestVersion:f.string(),checkedAt:f.pipe(f.string(),f.isoTimestamp())}),df=f.object({version:f.literal(1),result:f.literal(`fetch-failure`),checkedAt:f.pipe(f.string(),f.isoTimestamp())}),ff=f.variant(`result`,[uf,df]),pf=f.object({"dist-tags":f.object({latest:f.string()})}),mf=`cache`;function hf(){return ne(tc(),mf,`cli-version.json`)}function gf(e){return new URL(encodeURIComponent(e),`https://registry.npmjs.org/`).href}function _f(e){try{let t=JSON.parse(ee(e,`utf8`)),n=f.safeParse(ff,t);return n.success?n.output:void 0}catch{return}}function vf(e){let t=_f(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 yf(e){try{return!w(e)||k(e).isFile()}catch{return!1}}function bf(e){let t=Nd(tc(),mf);if(t===void 0||!yf(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 xf(e,t){if(Nd(tc(),mf)===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 Sf(e){let t=new AbortController,n=setTimeout(()=>t.abort(),750);n.unref();try{let n=await fetch(gf(e.packageName),{headers:{accept:`application/json`},signal:t.signal});if(!n.ok)return;let r=await n.json(),i=f.safeParse(pf,r);return i.success?i.output[`dist-tags`].latest:void 0}catch{return}finally{clearTimeout(n)}}function Cf(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 wf({packageName:e,currentVersion:t}){let n=hf(),r=vf(n);if(r?.result===`latest-version`){Cf({packageName:e,currentVersion:t,latestVersion:r.latestVersion});return}if(r?.result===`fetch-failure`||!bf(n))return;let i=await Sf({packageName:e});if(i===void 0){xf(n,{result:`fetch-failure`});return}xf(n,{result:`latest-version`,latestVersion:i}),Cf({packageName:e,currentVersion:t,latestVersion:i})}async function Tf(e){return typeof e==`function`?await e():await e}async function Ef(e){return typeof e==`function`?await e():await e}async function Df(e){return typeof e==`function`?await e():await e}async function Of(e,t,n=[]){if(e===t)return n;let r=await Df(e.subCommands??{});return(await Promise.all(Object.entries(r).map(async([e,r])=>Of(await Tf(r),t,[...n,e])))).find(e=>e!==void 0)}async function kf(e,t){if(!e||!t||t.length<2)return e;let n=await Ef(e.meta??{});return{...e,meta:{...n,name:t.slice(0,-1).join(` `)}}}function Af(e){return async(t,n)=>{let r=await u(t,await kf(n,await Of(e,t)));console.log(`${r}\n`)}}function jf({shouldCheckCliVersionFreshness:e}){return l({meta:{name:`catena`,version:se,description:`Catena CLI`},async setup({rawArgs:t}){!e||t.length===0||await wf({packageName:oe,currentVersion:se})},subCommands:{link:wu,unlink:id,profiles:Qu,whoami:od,policy:Hu,accounts:ll,intents:Hl,send:ed,transfer:nd,x402:lf,counterparties:Ml,feedback:Ll,guide:zl}})}const Mf=jf({shouldCheckCliVersionFreshness:!0});jf({shouldCheckCliVersionFreshness:!1});function Nf(){d(Mf,{showUsage:Af(Mf)})}Nf();export{};
|
|
566
|
+
const Du=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;Du.set({rounding:Du.ROUND_HALF_EVEN});const Ou=new Map,ku=/^[A-Z]{3}$/,Au=/^[A-Z0-9]{2,6}$/;function ju(e,t,n,r){if(Ou.has(e))throw Error(`duplicate asset id ${e}`);let i=new Du(r);if(i.isNegative())throw Error(`dustThreshold must be a non-negative decimal`);if(i.decimalPlaces()>t)throw Error(`dustThreshold (${r}) must not be finer than the asset's ${t} decimals`);if(!Number.isInteger(t)||!Number.isInteger(n)||t<0||n<0)throw Error(`decimals and presentmentDecimals must be non-negative integers`);if(n>t)throw Error(`presentment decimals should be less than or equal to decimals`)}function Mu(e,t,n,r,i){if(!ku.test(e))throw Error(`fiat asset ids must be 3-letter ISO-4217 codes`);ju(e,n,r,i.dustThreshold);let a=e;return Ou.set(e,{id:a,symbol:e,name:t,kind:`fiat`,decimals:n,presentmentDecimals:r,denomination:e,valuation:{type:`par`},dustThreshold:i.dustThreshold}),a}function Nu(e,t,n,r,i){if(!Au.test(e)||ku.test(e))throw Error(`stablecoin tickers must be 2-6 uppercase alphanumerics and not a 3-letter ISO-4217 shape`);let a=Ou.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})`);ju(e,n,r,i.dustThreshold);let o=e;return Ou.set(e,{id:o,symbol:e,name:t,kind:`stablecoin`,decimals:n,presentmentDecimals:r,denomination:a.denomination,valuation:{type:`par`},dustThreshold:i.dustThreshold}),o}Nu(`USDC`,`USD Coin`,6,2,{denomination:Mu(`USD`,`US Dollar`,6,2,{dustThreshold:`0.01`}),dustThreshold:`0.01`}),new Du(1e6),new Du(1e3);const Pu=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 Du(e).gte(0)}catch{return!1}},`Amount must be a valid decimal (e.g. 100 or 100.50)`)),Fu=f.pipe(f.string(`Count must be a string`),f.transform(e=>e.trim()),f.check(e=>/^\d+$/.test(e),`Count must be a whole number of transactions (e.g. 20)`),f.transform(Number),f.check(e=>Number.isSafeInteger(e),`Count is too large`),f.check(e=>e>=1,`Count must be at least 1`)),Iu={s:1,m:60,h:3600,d:86400},Lu=f.pipe(f.string(`Duration must be a string`),f.transform(e=>e.trim()),f.check(e=>/^\d+[smhd]?$/.test(e),`Duration must be a number of seconds or a value with a unit (e.g. 90s, 30m, 4h, 2d)`),f.transform(e=>{let t=e.at(-1)??``;return t in Iu?Number(e.slice(0,-1))*Iu[t]:Number(e)}),f.check(e=>e>=60,`Duration must be at least 1 minute`),f.check(e=>e<=604800,`Duration must be at most 7 days`)),Ru=Q({profile:Qo,json:$o}),zu=l({meta:{name:`show`,description:`Show the agent's assigned policy`},args:Ru.args,async run({args:e}){await $(Ru.parse(e))(e=>e.getPolicy())}}),Bu=Q({account:Z({description:`Account whose existing hard limit should increase. For a transfer limit, the source account funds move out of.`,required:!0}),capability:Ho({description:`Which capability's limit to increase: send (payments to counterparties) or transfer (between the user's own accounts)`,choices:mo,default:`send`}),rule:Ho({description:`Which limit to adjust`,choices:Na,default:`per_transaction_amount`}),amount:Z({description:`New threshold for an amount limit, as a decimal USD string (e.g. 500.00)`,schema:Pu,showValueInError:!0}),count:Z({description:`New threshold for a transaction-count limit (e.g. 20)`,schema:Fu,showValueInError:!0}),duration:Z({description:`How long the override should last once approved (e.g. 90s, 30m, 4h, 2d). One minute to seven days.`,required:!0,schema:Lu,showValueInError:!0}),reason:Z({description:`Why the task needs this, for the person who reviews the request`,required:!0}),profile:Qo,json:$o}),Vu=l({meta:{name:`request-override`,description:`Ask a person to approve a temporary change to this agent's limits`},args:Bu.args,async run({args:e}){let t=Bu.parse(e),n=$(t),r={type:`policy_override`,operations:[Hu(t)],durationSeconds:t.duration,reason:t.reason};await n(e=>e.submitIntent({action:r}))}});function Hu(e){return e.rule===`hourly_count`||e.rule===`daily_count`?(e.amount!==void 0&&X(`--amount does not apply to ${e.rule}; use --count`),e.count===void 0&&X(`--count is required for ${e.rule}`),{type:`increase_limit`,accountId:e.account,capability:e.capability,limitType:e.rule,newLimit:{count:e.count}}):(e.count!==void 0&&X(`--count does not apply to ${e.rule}; use --amount`),e.amount===void 0&&X(`--amount is required for ${e.rule}`),{type:`increase_limit`,accountId:e.account,capability:e.capability,limitType:e.rule,newLimit:{amount:e.amount,assetId:`USD`}})}const Uu=l({meta:{name:`policy`,description:`Inspect the agent's policy`},subCommands:{show:zu,"request-override":Vu}}),Wu=Q({profile:zo({description:`Profile name`,required:!0})});function Gu(){try{return Hc({env:process.env[Rc],cwd:process.cwd(),log:e=>console.error(e)})}catch(e){return X(e)}}const Ku=l({meta:{name:`use`,description:`Set the default credential profile`},args:Wu.args,async run({args:e}){let t=Wu.parse(e);try{Ec(t.profile),Yc({defaultProfile:t.profile})}catch(e){X(e)}}}),qu=l({meta:{name:`current`,description:`Show the selected credential profile and how it was chosen`},async run(){let e=Gu(),t;try{t=xc(e.name)}catch(e){X(e)}t===null&&X(`Profile "${e.name}" is not linked.\nRun 'catena link --profile ${e.name} <agent-id>' to authenticate.`),Yc({profile:e.name,source:e.source,bankUrl:t.bank_url,agentId:fc(t)?t.agent_id:void 0})}}),Ju=l({meta:{name:`list`,description:`List credential profiles and their directory bindings`},async run(){let e;try{e=cc()}catch(e){X(e)}let t;try{t=Hc({env:process.env[Rc],cwd:process.cwd()}).name}catch{t=null}let n=Object.entries(e.directories??{});Yc({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:fc(r)?r.agent_id:void 0,directories:n.filter(([,t])=>t===e).map(([e])=>e).toSorted(),current:e===t}))})}}),Yu=Q({profile:zo({description:`Profile name to bind`,required:!0}),path:zo({description:`Directory to bind (defaults to the current directory)`})}),Xu=l({meta:{name:`bind`,description:`Bind a directory to a profile for automatic selection`},args:Yu.args,async run({args:e}){let t=Yu.parse(e);try{let e=t.path??process.cwd();if(Gl(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=yc(e,t.profile);Yc({profile:t.profile,directory:n})}catch(e){X(e)}}}),Zu=Q({path:zo({description:`Directory to unbind (defaults to the current directory)`})}),Qu=l({meta:{name:`unbind`,description:`Remove a directory's profile binding`},args:Zu.args,async run({args:e}){let t=Zu.parse(e);try{Yc(bc(t.path??process.cwd()))}catch(e){X(e)}}}),$u=l({meta:{name:`profiles`,description:`Manage credential profiles`},subCommands:{use:Ku,current:qu,list:Ju,bind:Xu,unbind:Qu}}),ed=Q({account:Z({description:`Source account id`,required:!0,schema:ts}),rail:Z({description:`Destination counterparty rail id (cprl_...)`,required:!0,schema:ts}),amount:Z({description:`USD amount as a decimal string (e.g. 125.00)`,required:!0,schema:Pu,showValueInError:!0}),method:Ho({description:`ach | wire | on-chain; ach and wire require a bank rail, on-chain a wallet rail`,required:!0,choices:qa}),memo:Z({description:`Memo on the underlying transfer`}),description:Z({description:`Operator-facing description`}),idempotencyKey:Z({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:dl}),profile:Qo,json:$o}),td=l({meta:{name:`send`,description:`Submit a USD send intent to a counterparty rail`},args:ed.args,async run({args:e}){let t=ed.parse(e),n=$(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}:{}}))}}),nd=Q({from:Z({description:`Source account id`,required:!0,schema:ts}),to:Z({description:`Destination account id`,required:!0,schema:ts}),amount:Z({description:`USD amount as a decimal string (e.g. 125.00)`,required:!0,schema:Pu,showValueInError:!0}),memo:Z({description:`Memo on the underlying transfer`}),description:Z({description:`Operator-facing description`}),idempotencyKey:Z({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:dl}),profile:Qo,json:$o}),rd=l({meta:{name:`transfer`,description:`Submit a USD transfer intent between two of this agent's accounts`},args:nd.args,async run({args:e}){let t=nd.parse(e),n=$(t),r={type:`transfer`,accountId:t.from,toAccountId:t.to,amount:t.amount,...t.memo?{memo:t.memo}:{},...t.description?{description:t.description}:{}};await n(e=>e.submitIntent({action:r,...t.idempotencyKey?{idempotencyKey:t.idempotencyKey}:{}}))}}),id=Q({profile:Qo,force:Vo({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:$o}),ad=l({meta:{name:`unlink`,description:`Disconnect the selected agent profile`},args:id.args,async run({args:e}){let t=id.parse(e),n=Wc(),r;try{r=Hc({flag:Xc(t),env:process.env[Rc],cwd:process.cwd(),log:e=>console.error(e)}).name}catch(e){X(e)}if(t.force){let e;try{if(e=xc(r),e===null)throw Error(`Profile "${r}" not found`);await n.delete(e.client_instance_id),await n.delete(ru(e.client_instance_id)),gc(r)}catch(e){X(e)}Yc({success:!0,profile:r,...fc(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 jc({profileName:r,fallbackBankUrl:Lc},n);a.ok||X(`${a.message} ${i}`);let o=Uc(a);try{await o.unlinkAgent(),await n.delete(a.clientInstanceId),await n.delete(ru(a.clientInstanceId)),gc(r)}catch(e){X(`${jo(Jc(e,r))} ${i}`)}Yc({success:!0,profile:r,agentId:a.agentId},{compact:t.json})}}),od=Q({profile:Qo,json:$o}),sd=l({meta:{name:`whoami`,description:`Show which agent you are currently acting as`},args:od.args,async run({args:e}){await $(od.parse(e))(e=>e.whoami())}});function cd(e){throw Error(`Unhandled case: ${String(e)}`)}const ld=[`PAYMENT-REQUIRED`,`X-Payment-Required`],ud=/^0x[0-9a-fA-F]{64}$/,dd=/^0x[0-9a-fA-F]{40}$/,fd=f.looseObject({success:f.boolean(),transaction:f.string()}),pd=f.looseObject({x402Version:f.literal(2),accepts:f.array(lo),resource:f.optional(uo)}),md=`x402_network_mismatch`,hd=`x402_counterparty_rail_not_found`,gd=new Set([`x402_requirement_not_payable`,md,hd]),_d={"eip155:8453":`Base`,"eip155:84532":`Base Sepolia`};function vd(e){let t=Object.hasOwn(_d,e)?_d[e]:void 0;return t?`${t} (${e})`:e}function yd(e){let t=e.replaceAll(`-`,`+`).replaceAll(`_`,`/`),n=Uint8Array.from(atob(t),e=>e.charCodeAt(0));return JSON.parse(new TextDecoder().decode(n))}function bd(e){let t=ld.map(t=>e.headers.get(t)).find(e=>e!==null);if(t)try{let e=f.safeParse(pd,yd(t));return e.success?e.output:void 0}catch{return}}async function xd(e,t,n){try{let r=n.headers.get(`PAYMENT-RESPONSE`);if(!r)return;let i=f.safeParse(fd,yd(r));if(!i.success||!i.output.success||!ud.test(i.output.transaction))return;await e.reportSettlement({intentId:t,txHash:i.output.transaction})}catch{}}var Sd=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}},Cd=class extends Sd{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(vd).join(` or `)}`,n,{appendReasonsToMessage:!1}),this.name=`X402NetworkMismatchError`,this.accountId=e,this.requiredNetworks=t}},wd=class extends Sd{payTo;network;serviceName;constructor(e,t,n,r=[]){super(`This 402 pays ${e} on ${vd(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}},Td=class extends Sd{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}},Ed=class extends Sd{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 Dd(e,t){try{return await t()}catch(t){throw new Ed(e,t)}}var Od=class extends Sd{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 kd(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 Sd(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 jd(e,{accountId:t.accountId,requirements:n,resource:i}).catch(e=>{if(e instanceof So&&e.code!==void 0&&gd.has(e.code)){a.push({error:e,requirement:n});return}throw e});if(r)return r}let o=a.filter(e=>e.error.code===hd),s=a.filter(e=>e.error.code===md),c=a.filter(e=>e.error.code!==hd&&e.error.code!==md),l=[...new Set([...o,...s,...c].map(e=>e.error.message))],u=o.find(e=>e.error.status===404&&dd.test(e.requirement.payTo));throw u?new wd(u.requirement.payTo,u.requirement.network,i?.serviceName,l):s.length>0&&o.length===0?new Cd(t.accountId,[...new Set(s.map(e=>e.requirement.network))],l):new Sd(`No requirement in the 402 challenge is payable from this account`,l)}const Ad=f.object({x402:f.object({paymentSignature:f.string()})});async function jd(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 Do&&e.outcome===`unknown`?new Od(e.intentId,t.requirements,e):e});if(n.status===`completed`){let e=f.safeParse(Ad,n.data);if(e.success)return{intentId:n.id,paymentSignature:e.output.x402.paymentSignature,requirements:t.requirements};throw new Sd(`The completed payment did not carry an x402 payment signature`)}switch(n.status){case`pending`:throw new Td(n.id,n.reasons,n.expiresAt);case`processing`:throw new Sd(`The payment is still processing (intent ${n.id}); this client cannot resume an in-flight x402 settlement`);case`blocked`:case`failed`:throw new Sd(`Catena declined the payment`,n.reasons)}return cd(n.status)}function Md(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 Nd(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=bd(a);if(!o)return a;if(!Md(r,i))throw new Sd(`The request body cannot be replayed after payment; buffer the body (string, Blob, or ArrayBuffer) before using the x402 fetch wrapper`);let s=await kd(e,{accountId:t.accountId,paymentRequired:o,...t.maxAtomicAmount!==void 0&&{maxAtomicAmount:t.maxAtomicAmount}});await Dd(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 Dd(s,()=>n(r,{...i,headers:c}));return xd(e,s.intentId,l),l}}function Pd(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 Fd=4e3;function Id(e){try{return k(e)}catch{return}}function Ld(e,t,n){try{x(e,t)}catch{X(n)}}function Rd(e){let t=re(e),n=M(t),r=Id(n);(r===void 0||!r.isDirectory())&&X(`--output ${e}: directory ${n} does not exist`);let i=Id(t);return i===void 0?(Ld(n,C.W_OK|C.X_OK,`--output ${e}: directory ${n} is not writable`),t):(i.isDirectory()&&X(`--output ${e}: destination is a directory`),i.isFile()||X(`--output ${e}: destination is not a regular file`),Ld(t,C.W_OK,`--output ${e}: destination is not writable`),t)}const zd=/^(?:con|prn|aux|nul|com\d|lpt\d)$/i;function Bd(e){if(e!==void 0&&es.test(e)&&!zd.test(e))return`${e}.body`;let t=`${Date.now()}-${_(4).toString(`hex`)}.body`;return e===void 0?`unpaid-${t}`:`paid-${t}`}function Vd(e,t){let n=Pd(nc(),`responses`);if(n===void 0)return;let r=ne(n,Bd(t));try{return A(r,e,{mode:384}),r}catch{return}}function Hd(e){let t=e.subarray(0,Fd*4),n=t.toString(`utf8`);return{decoded:n,complete:t.length===e.length&&n.length<=Fd&&ae(e)}}function Ud({decoded:e,complete:t}){let n=e.slice(0,Fd),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{...Ud(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 Gd(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 Kd(e,t,n){let r=Vd(e,t);return r===void 0?Wd(e,n):{...Ud(n),bodyPath:r}}function qd(e,t,n){let r=Hd(e);if(n===void 0)return r.complete?{body:r.decoded}:Kd(e,t,r);try{A(n,e,{mode:384})}catch(i){let a=Kd(e,t,r),o=`--output ${n}: ${jo(i)}`;return`bodyPath`in a?{...a,error:`${o}; the full body was saved to ${a.bodyPath}`}:{...a,error:`${o}; ${Gd(a)}`}}return{...Ud(r),bodyPath:n}}function Jd(e){if(e===`@-`)return Yd(0,`stdin`);if(e.startsWith(`@`)){let t=e.slice(1);return t===``?X(`--data @<path>: no file path given`):Yd(t,`@${t}`)}return e}function Yd(e,t){try{return ee(e,`utf8`)}catch(e){return X(`--data ${t}: ${jo(e)}`)}}function Xd(e){let[t,n=``]=e.split(`.`);return BigInt(`${t}${n.padEnd(6,`0`)}`)}function Zd(e){return{intentId:e.intentId,amountAtomicUsdc:e.requirements.amount,payTo:e.requirements.payTo,network:e.requirements.network}}const Qd={"eip155:8453":`base`,"eip155:84532":`base-sepolia`};function $d(e){return Object.hasOwn(Qd,e)?Qd[e]:void 0}function ef(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function tf(e){return e===void 0?``:` --profile ${ef(e)}`}function nf(e){let t=e?.replaceAll(/[\p{C}\s]/gu,` `).replaceAll(/ {2,}/g,` `).trim();return t!==void 0&&t.length>0?t:void 0}function rf(e,t,n,r){let i=$d(t)??ef(t);return`catena counterparties create wallet --name ${ef(n??`<name>`)} --address ${ef(e)} --network ${i}${tf(r)}`}const af=f.pipe(f.string(),f.check(e=>Nc.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 of(e,t){return e.some(e=>e.name.toLowerCase()===t)}function sf(e,t){of(e,`payment-signature`)&&X(`--header cannot set PAYMENT-SIGNATURE; the payment loop attaches it after paying`),of(e,`content-type`)&&t!==void 0&&X(`--header "Content-Type: ..." conflicts with --content-type`)}function cf(e,t,n){let r=[...n!==void 0&&!of(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 lf=Q({url:Z({description:`The paywalled URL to fetch (an x402 v2 endpoint)`,required:!0,schema:f.pipe(f.string(),f.url())}),account:Z({description:`Source wallet account id the payment draws from`,required:!0,schema:ts}),maxAmount:Z({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:Ho({description:`HTTP method for the request`,choices:[`GET`,`POST`]}),data:Z({description:`Request body. Use @path to read a file or @- for stdin. Implies POST and a JSON content type unless overridden.`}),contentType:Z({description:`Content-Type header for the request body (default application/json when --data is set)`}),output:Z({description:`Write the full response body to this file (must be a regular file; written for any HTTP status — check .status). Without it .body is capped at 4000 characters; longer or non-UTF-8 bodies are saved to a file (path reported in .bodyPath)`}),header:Bo({description:`Request header as "Name: Value" (repeatable, like curl -H); sent on the initial request and the paid retry`,schema:af}),profile:Qo,json:$o}),uf=l({meta:{name:`x402`,description:`Fetch a URL, paying its x402 (HTTP 402) challenge via USDC`},args:lf.args,async run({args:e,rawArgs:t}){let n=lf.parse(e,t),r=n.method??(n.data===void 0?`GET`:`POST`);n.data!==void 0&&r!==`POST`&&X(`--data cannot be sent with --method ${r}; a body requires POST`),n.contentType!==void 0&&n.data===void 0&&X(`--content-type has no effect without --data`),sf(n.header,n.contentType);let i=n.output===void 0?void 0:Rd(n.output),a=n.data===void 0?void 0:Jd(n.data),o=cf(n.header,n.contentType,a);await $(n)(async e=>{let t,s=Nd(e,{accountId:n.account,...n.maxAmount!==void 0&&{maxAtomicAmount:Xd(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 Ed)return{status:null,paid:!0,retryFailed:!0,payment:Zd(e.receipt),error:e.message};if(e instanceof Cd){let t=e.requiredNetworks.map(e=>$d(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${tf(n.profile)}\`).`}}if(e instanceof wd){let t=nf(e.serviceName),r=t!==void 0&&t.length<=40?t:void 0,i=rf(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:$d(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 Td)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:Zd(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}${tf(n.profile)}\` to retry manually`;return{...l,error:`failed to read the response body: ${jo(e)}${r}`}}return{...l,...qd(u,t?.intentId,i)}},{exitCode:e=>+(`error`in e)})}}),df=f.object({version:f.literal(1),result:f.literal(`latest-version`),latestVersion:f.string(),checkedAt:f.pipe(f.string(),f.isoTimestamp())}),ff=f.object({version:f.literal(1),result:f.literal(`fetch-failure`),checkedAt:f.pipe(f.string(),f.isoTimestamp())}),pf=f.variant(`result`,[df,ff]),mf=f.object({"dist-tags":f.object({latest:f.string()})}),hf=`cache`;function gf(){return ne(nc(),hf,`cli-version.json`)}function _f(e){return new URL(encodeURIComponent(e),`https://registry.npmjs.org/`).href}function vf(e){try{let t=JSON.parse(ee(e,`utf8`)),n=f.safeParse(pf,t);return n.success?n.output:void 0}catch{return}}function yf(e){let t=vf(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 bf(e){try{return!w(e)||k(e).isFile()}catch{return!1}}function xf(e){let t=Pd(nc(),hf);if(t===void 0||!bf(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 Sf(e,t){if(Pd(nc(),hf)===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 Cf(e){let t=new AbortController,n=setTimeout(()=>t.abort(),750);n.unref();try{let n=await fetch(_f(e.packageName),{headers:{accept:`application/json`},signal:t.signal});if(!n.ok)return;let r=await n.json(),i=f.safeParse(mf,r);return i.success?i.output[`dist-tags`].latest:void 0}catch{return}finally{clearTimeout(n)}}function wf(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 Tf({packageName:e,currentVersion:t}){let n=gf(),r=yf(n);if(r?.result===`latest-version`){wf({packageName:e,currentVersion:t,latestVersion:r.latestVersion});return}if(r?.result===`fetch-failure`||!xf(n))return;let i=await Cf({packageName:e});if(i===void 0){Sf(n,{result:`fetch-failure`});return}Sf(n,{result:`latest-version`,latestVersion:i}),wf({packageName:e,currentVersion:t,latestVersion:i})}async function Ef(e){return typeof e==`function`?await e():await e}async function Df(e){return typeof e==`function`?await e():await e}async function Of(e){return typeof e==`function`?await e():await e}async function kf(e,t,n=[]){if(e===t)return n;let r=await Of(e.subCommands??{});return(await Promise.all(Object.entries(r).map(async([e,r])=>kf(await Ef(r),t,[...n,e])))).find(e=>e!==void 0)}async function Af(e,t){if(!e||!t||t.length<2)return e;let n=await Df(e.meta??{});return{...e,meta:{...n,name:t.slice(0,-1).join(` `)}}}function jf(e){return async(t,n)=>{let r=await u(t,await Af(n,await kf(e,t)));console.log(`${r}\n`)}}function Mf({shouldCheckCliVersionFreshness:e}){return l({meta:{name:`catena`,version:se,description:`Catena CLI`},async setup({rawArgs:t}){!e||t.length===0||await Tf({packageName:oe,currentVersion:se})},subCommands:{link:Tu,unlink:ad,profiles:$u,whoami:sd,policy:Uu,accounts:ul,intents:Ul,send:td,transfer:rd,x402:uf,counterparties:Nl,feedback:Rl,guide:Bl}})}const Nf=Mf({shouldCheckCliVersionFreshness:!0});Mf({shouldCheckCliVersionFreshness:!1});function Pf(){d(Nf,{showUsage:jf(Nf)})}Pf();export{};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@catena/cli",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.1",
|
|
4
4
|
"description": "Catena CLI for agent runtimes",
|
|
5
5
|
"homepage": "https://catena.com/",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -26,9 +26,9 @@
|
|
|
26
26
|
"publint": "0.3.23",
|
|
27
27
|
"tsdown": "0.22.14",
|
|
28
28
|
"tsx": "4.23.12",
|
|
29
|
+
"@bank/money": "0.1.0",
|
|
29
30
|
"@bank/shared": "0.1.0",
|
|
30
|
-
"@catena/sdk": "0.1.0"
|
|
31
|
-
"@bank/money": "0.1.0"
|
|
31
|
+
"@catena/sdk": "0.1.0"
|
|
32
32
|
},
|
|
33
33
|
"engines": {
|
|
34
34
|
"node": ">=20"
|