@catena/cli 0.6.1 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +35 -13
- package/dist/index.mjs +68 -56
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -121,6 +121,32 @@ The policy includes `policyCapabilities` rows. Each row grants one `read`,
|
|
|
121
121
|
`rules`. It also includes `counterpartyRules` for send recipient scope and
|
|
122
122
|
counterparty creation.
|
|
123
123
|
|
|
124
|
+
### `policy request-override`
|
|
125
|
+
|
|
126
|
+
Ask a person to approve a temporary increase to one policy limit.
|
|
127
|
+
|
|
128
|
+
```bash
|
|
129
|
+
pnpm dlx @catena/cli policy request-override \
|
|
130
|
+
--account acct_... \
|
|
131
|
+
--amount 500 \
|
|
132
|
+
--duration 4h \
|
|
133
|
+
--reason "Vendor invoice INV-4471 is $420"
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
Use `--capability transfer` for a transfer limit and `--rule` to select another
|
|
137
|
+
limit type. `--idempotency-key` is optional.
|
|
138
|
+
|
|
139
|
+
### Intent idempotency
|
|
140
|
+
|
|
141
|
+
The `send`, `transfer`, `counterparties create`,
|
|
142
|
+
`counterparties request-details`, and `policy request-override` commands accept
|
|
143
|
+
an optional `--idempotency-key`. When omitted, the CLI generates a fresh key for
|
|
144
|
+
that invocation, so matching command inputs alone are not deduplicated. The
|
|
145
|
+
`x402` command manages a fresh key internally for each payment challenge. If a
|
|
146
|
+
manual retry may be needed after an ambiguous timeout, choose and persist a key
|
|
147
|
+
on the first attempt, then reuse that exact key with unchanged inputs. Reusing a
|
|
148
|
+
key with different inputs fails.
|
|
149
|
+
|
|
124
150
|
### `accounts list`
|
|
125
151
|
|
|
126
152
|
List the accounts available under the agent's policy.
|
|
@@ -152,6 +178,8 @@ pnpm dlx @catena/cli counterparties create \
|
|
|
152
178
|
|
|
153
179
|
Required flags: `--name`, `--email`.
|
|
154
180
|
|
|
181
|
+
Optional flags: `--idempotency-key`.
|
|
182
|
+
|
|
155
183
|
`counterparties create email` is an equivalent explicit form. Use the `bank` or
|
|
156
184
|
`wallet` subcommand when payment details are available.
|
|
157
185
|
|
|
@@ -177,7 +205,7 @@ Required flags: `--name`, `--bank-name`, `--routing-number`, `--account-number`,
|
|
|
177
205
|
`--address-postal-code`.
|
|
178
206
|
|
|
179
207
|
Optional flags: `--account-type` (`checking` or `savings`), `--address-country`,
|
|
180
|
-
`--email`.
|
|
208
|
+
`--email`, `--idempotency-key`.
|
|
181
209
|
|
|
182
210
|
### `counterparties create wallet`
|
|
183
211
|
|
|
@@ -193,7 +221,7 @@ pnpm dlx @catena/cli counterparties create wallet \
|
|
|
193
221
|
Required flags: `--name`, `--address`.
|
|
194
222
|
|
|
195
223
|
Optional flags: `--network` (defaults to `base`; Base is the only supported
|
|
196
|
-
wallet network), `--email`.
|
|
224
|
+
wallet network), `--email`, `--idempotency-key`.
|
|
197
225
|
|
|
198
226
|
### `counterparties request-details`
|
|
199
227
|
|
|
@@ -205,10 +233,7 @@ pnpm dlx @catena/cli counterparties request-details cp_... --bank
|
|
|
205
233
|
```
|
|
206
234
|
|
|
207
235
|
Pass at least one of `--bank` or `--wallet`. `--idempotency-key` is optional.
|
|
208
|
-
|
|
209
|
-
rejected while the current invitation is outstanding, but creates a new intent
|
|
210
|
-
after that invitation expires. To recover an exact submission after a lost
|
|
211
|
-
response, retry with the same explicit `--idempotency-key`.
|
|
236
|
+
The outstanding-invitation conflict remains independent of idempotency.
|
|
212
237
|
|
|
213
238
|
### `send`
|
|
214
239
|
|
|
@@ -229,10 +254,8 @@ Optional flags: `--memo`, `--description`, `--idempotency-key`.
|
|
|
229
254
|
`--method` must be one of `ach`, `wire`, or `on-chain`.
|
|
230
255
|
|
|
231
256
|
To check whether a send completed, run `intents get <id>` with the returned
|
|
232
|
-
intent id.
|
|
233
|
-
|
|
234
|
-
intent instead of sending again. Use `--idempotency-key` only when you
|
|
235
|
-
intentionally want another payment with the same details.
|
|
257
|
+
intent id. A separate invocation without an explicit key is a new send, even
|
|
258
|
+
when its inputs match an earlier command.
|
|
236
259
|
|
|
237
260
|
### `transfer`
|
|
238
261
|
|
|
@@ -250,9 +273,8 @@ Required flags: `--from`, `--to`, `--amount`.
|
|
|
250
273
|
Optional flags: `--memo`, `--description`, `--idempotency-key`.
|
|
251
274
|
|
|
252
275
|
To check whether a transfer completed, run `intents get <id>` with the returned
|
|
253
|
-
intent id.
|
|
254
|
-
|
|
255
|
-
another transfer with the same details.
|
|
276
|
+
intent id. A separate invocation without an explicit key is a new transfer, even
|
|
277
|
+
when its inputs match an earlier command.
|
|
256
278
|
|
|
257
279
|
### `accounts balance`
|
|
258
280
|
|
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.1`,ce=[`u8`,`u16`,`u32`,`u64`,`u128`,`i8`,`i16`,`i32`,`i64`,`i128`,`f32`,`f64`],le=function(){function e(){this.offset=0,this.buffer_size=256,this.buffer=new ArrayBuffer(this.buffer_size),this.view=new DataView(this.buffer)}return e.prototype.resize_if_necessary=function(e){if(this.buffer_size-this.offset<e){this.buffer_size=Math.max(this.buffer_size*2,this.buffer_size+e);var t=new ArrayBuffer(this.buffer_size);new Uint8Array(t).set(new Uint8Array(this.buffer)),this.buffer=t,this.view=new DataView(t)}},e.prototype.get_used_buffer=function(){return new Uint8Array(this.buffer).slice(0,this.offset)},e.prototype.store_value=function(e,t){var n=t.substring(1),r=parseInt(n)/8;this.resize_if_necessary(r);var i=t[0]===`f`?`setFloat${n}`:t[0]===`i`?`setInt${n}`:`setUint${n}`;this.view[i](this.offset,e,!0),this.offset+=r},e.prototype.store_bytes=function(e){this.resize_if_necessary(e.length),new Uint8Array(this.buffer).set(new Uint8Array(e),this.offset),this.offset+=e.length},e}(),ue=function(){function e(e){this.offset=0,this.buffer_size=e.length,this.buffer=new ArrayBuffer(e.length),new Uint8Array(this.buffer).set(e),this.view=new DataView(this.buffer)}return e.prototype.assert_enough_buffer=function(e){if(this.offset+e>this.buffer.byteLength)throw Error(`Error in schema, the buffer is smaller than expected`)},e.prototype.consume_value=function(e){var t=e.substring(1),n=parseInt(t)/8;this.assert_enough_buffer(n);var r=e[0]===`f`?`getFloat${t}`:e[0]===`i`?`getInt${t}`:`getUint${t}`,i=this.view[r](this.offset,!0);return this.offset+=n,i},e.prototype.consume_bytes=function(e){this.assert_enough_buffer(e);var t=this.buffer.slice(this.offset,this.offset+e);return this.offset+=e,t},e}(),de=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},e(t,n)};return function(t,n){if(typeof n!=`function`&&n!==null)throw TypeError(`Class extends value `+String(n)+` is not a constructor or null`);e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})();function fe(e){return Array.isArray(e)||!!e&&typeof e==`object`&&`length`in e&&typeof e.length==`number`&&(e.length===0||e.length>0&&e.length-1 in e)}function pe(e,t,n){if(typeof e!==t)throw Error(`Expected ${t} not ${typeof e}(${e}) at ${n.join(`.`)}`)}function me(e,t){var n=[`number`,`string`,`bigint`,`boolean`].includes(typeof e),r=typeof e==`object`&&!!e&&`toString`in e;if(!n&&!r)throw Error(`Expected bigint, number, boolean or string not ${typeof e}(${e}) at ${t.join(`.`)}`)}function he(e,t,n){if(e!==t)throw Error(`Array length ${e} does not match schema length ${t} at ${n.join(`.`)}`)}function F(e,t){if(typeof e!=`object`||!e)throw Error(`Expected object not ${typeof e}(${e}) at ${t.join(`.`)}`)}ce.concat([`bool`,`string`]),function(e){de(t,e);function t(t,n){var r=`Invalid schema: ${JSON.stringify(t)} expected ${n}`;return e.call(this,r)||this}return t}(Error),function(){function e(e){this.encoded=new le,this.fieldPath=[`value`],this.checkTypes=e}return e.prototype.encode=function(e,t){return this.encode_value(e,t),this.encoded.get_used_buffer()},e.prototype.encode_value=function(e,t){if(typeof t==`string`){if(ce.includes(t))return this.encode_integer(e,t);if(t===`string`)return this.encode_string(e);if(t===`bool`)return this.encode_boolean(e)}if(typeof t==`object`){if(`option`in t)return this.encode_option(e,t);if(`enum`in t)return this.encode_enum(e,t);if(`array`in t)return this.encode_array(e,t);if(`set`in t)return this.encode_set(e,t);if(`map`in t)return this.encode_map(e,t);if(`struct`in t)return this.encode_struct(e,t)}},e.prototype.encode_integer=function(e,t){var n=parseInt(t.substring(1));n<=32||t==`f64`?(this.checkTypes&&pe(e,`number`,this.fieldPath),this.encoded.store_value(e,t)):(this.checkTypes&&me(e,this.fieldPath),this.encode_bigint(BigInt(e),n))},e.prototype.encode_bigint=function(e,t){for(var n=t/8,r=new Uint8Array(n),i=0;i<n;i++)r[i]=Number(e&BigInt(255)),e>>=BigInt(8);this.encoded.store_bytes(new Uint8Array(r))},e.prototype.encode_string=function(e){this.checkTypes&&pe(e,`string`,this.fieldPath);for(var t=e,n=[],r=0;r<t.length;r++){var i=t.charCodeAt(r);i<128?n.push(i):i<2048?n.push(192|i>>6,128|i&63):i<55296||i>=57344?n.push(224|i>>12,128|i>>6&63,128|i&63):(r++,i=65536+((i&1023)<<10|t.charCodeAt(r)&1023),n.push(240|i>>18,128|i>>12&63,128|i>>6&63,128|i&63))}this.encoded.store_value(n.length,`u32`),this.encoded.store_bytes(new Uint8Array(n))},e.prototype.encode_boolean=function(e){this.checkTypes&&pe(e,`boolean`,this.fieldPath),this.encoded.store_value(+!!e,`u8`)},e.prototype.encode_option=function(e,t){e==null?this.encoded.store_value(0,`u8`):(this.encoded.store_value(1,`u8`),this.encode_value(e,t.option))},e.prototype.encode_enum=function(e,t){this.checkTypes&&F(e,this.fieldPath);for(var n=Object.keys(e)[0],r=0;r<t.enum.length;r++){var i=t.enum[r];if(n===Object.keys(i.struct)[0])return this.encoded.store_value(r,`u8`),this.encode_struct(e,i)}throw Error(`Enum key (${n}) not found in enum schema: ${JSON.stringify(t)} at ${this.fieldPath.join(`.`)}`)},e.prototype.encode_array=function(e,t){if(fe(e))return this.encode_arraylike(e,t);if(e instanceof ArrayBuffer)return this.encode_buffer(e,t);throw Error(`Expected Array-like not ${typeof e}(${e}) at ${this.fieldPath.join(`.`)}`)},e.prototype.encode_arraylike=function(e,t){t.array.len?he(e.length,t.array.len,this.fieldPath):this.encoded.store_value(e.length,`u32`);for(var n=0;n<e.length;n++)this.encode_value(e[n],t.array.type)},e.prototype.encode_buffer=function(e,t){t.array.len?he(e.byteLength,t.array.len,this.fieldPath):this.encoded.store_value(e.byteLength,`u32`),this.encoded.store_bytes(new Uint8Array(e))},e.prototype.encode_set=function(e,t){this.checkTypes&&pe(e,`object`,this.fieldPath);var n=e instanceof Set?Array.from(e.values()):Object.values(e);this.encoded.store_value(n.length,`u32`);for(var r=0,i=n;r<i.length;r++){var a=i[r];this.encode_value(a,t.set)}},e.prototype.encode_map=function(e,t){this.checkTypes&&pe(e,`object`,this.fieldPath);var n=e instanceof Map,r=n?Array.from(e.keys()):Object.keys(e);this.encoded.store_value(r.length,`u32`);for(var i=0,a=r;i<a.length;i++){var o=a[i];this.encode_value(o,t.map.key),this.encode_value(n?e.get(o):e[o],t.map.value)}},e.prototype.encode_struct=function(e,t){this.checkTypes&&pe(e,`object`,this.fieldPath);for(var n=0,r=Object.keys(t.struct);n<r.length;n++){var i=r[n];this.fieldPath.push(i),this.encode_value(e[i],t.struct[i]),this.fieldPath.pop()}},e}(),function(){function e(e){this.buffer=new ue(e)}return e.prototype.decode=function(e){return this.decode_value(e)},e.prototype.decode_value=function(e){if(typeof e==`string`){if(ce.includes(e))return this.decode_integer(e);if(e===`string`)return this.decode_string();if(e===`bool`)return this.decode_boolean()}if(typeof e==`object`){if(`option`in e)return this.decode_option(e);if(`enum`in e)return this.decode_enum(e);if(`array`in e)return this.decode_array(e);if(`set`in e)return this.decode_set(e);if(`map`in e)return this.decode_map(e);if(`struct`in e)return this.decode_struct(e)}throw Error(`Unsupported type: ${e}`)},e.prototype.decode_integer=function(e){var t=parseInt(e.substring(1));return t<=32||e==`f64`?this.buffer.consume_value(e):this.decode_bigint(t,e.startsWith(`i`))},e.prototype.decode_bigint=function(e,t){t===void 0&&(t=!1);var n=e/8,r=new Uint8Array(this.buffer.consume_bytes(n)),i=r.reduceRight(function(e,t){return e+t.toString(16).padStart(2,`0`)},``);return t&&r[n-1]?BigInt.asIntN(e,BigInt(`0x${i}`)):BigInt(`0x${i}`)},e.prototype.decode_string=function(){for(var e=this.decode_integer(`u32`),t=new Uint8Array(this.buffer.consume_bytes(e)),n=[],r=0;r<e;++r){var i=t[r];if(i<128)n.push(i);else if(i<224)n.push((i&31)<<6|t[++r]&63);else if(i<240)n.push((i&15)<<12|(t[++r]&63)<<6|t[++r]&63);else{var a=(i&7)<<18|(t[++r]&63)<<12|(t[++r]&63)<<6|t[++r]&63;n.push(a)}}return String.fromCodePoint.apply(String,n)},e.prototype.decode_boolean=function(){return this.buffer.consume_value(`u8`)>0},e.prototype.decode_option=function(e){var t=this.buffer.consume_value(`u8`);if(t===1)return this.decode_value(e.option);if(t!==0)throw Error(`Invalid option ${t}`);return null},e.prototype.decode_enum=function(e){var t,n=this.buffer.consume_value(`u8`);if(n>e.enum.length)throw Error(`Enum option ${n} is not available`);var r=e.enum[n].struct,i=Object.keys(r)[0];return t={},t[i]=this.decode_value(r[i]),t},e.prototype.decode_array=function(e){for(var t=[],n=e.array.len?e.array.len:this.decode_integer(`u32`),r=0;r<n;++r)t.push(this.decode_value(e.array.type));return t},e.prototype.decode_set=function(e){for(var t=this.decode_integer(`u32`),n=new Set,r=0;r<t;++r)n.add(this.decode_value(e.set));return n},e.prototype.decode_map=function(e){for(var t=this.decode_integer(`u32`),n=new Map,r=0;r<t;++r){var i=this.decode_value(e.map.key),a=this.decode_value(e.map.value);n.set(i,a)}return n},e.prototype.decode_struct=function(e){var t={};for(var n in e.struct)t[n]=this.decode_value(e.struct[n]);return t},e}(),new Uint8Array([75,69,77,0,16]),new Uint8Array([72,80,75,69,0,16,0,1,0,2]),new Uint8Array([72,80,75,69,45,118,49]),new Uint8Array([115,101,99,114,101,116]),new Uint8Array([101,97,101,95,112,114,107]),new Uint8Array([115,104,97,114,101,100,95,115,101,99,114,101,116]),new Uint8Array([0,32,72,80,75,69,45,118,49,72,80,75,69,0,16,0,1,0,2,107,101,121,0,143,195,174,184,50,73,10,75,90,179,228,32,35,40,125,178,154,31,75,199,194,34,192,223,34,135,39,183,10,64,33,18,47,63,4,233,32,108,209,36,19,80,53,41,180,122,198,166,48,185,46,196,207,125,35,69,8,208,175,151,113,201,158,80]),new Uint8Array([0,12,72,80,75,69,45,118,49,72,80,75,69,0,16,0,1,0,2,98,97,115,101,95,110,111,110,99,101,0,143,195,174,184,50,73,10,75,90,179,228,32,35,40,125,178,154,31,75,199,194,34,192,223,34,135,39,183,10,64,33,18,47,63,4,233,32,108,209,36,19,80,53,41,180,122,198,166,48,185,46,196,207,125,35,69,8,208,175,151,113,201,158,80]),new Uint8Array([113,111,115,95,101,110,99,114,121,112,116,105,111,110,95,104,109,97,99,95,109,101,115,115,97,103,101]);const ge=e=>{let t=n(e);if(t.length<2)throw Error(`failed to convert DER-encoded signature: insufficient length`);if(t[0]!==48)throw Error(`failed to convert DER-encoded signature: invalid format (missing SEQUENCE tag)`);let r=1,a=t[r];if(a<=127){if(t.length<2+a)throw Error(`failed to convert DER-encoded signature: inconsistent message length header`);r+=1}else throw Error(`failed to convert DER-encoded signature: unexpectedly large or invalid signature length`);if(t[r]!==2)throw Error(`failed to convert DER-encoded signature: invalid tag for r`);r++;let o=t[r];if(o>33)throw Error(`failed to convert DER-encoded signature: unexpected length for r`);r++;let s=t.slice(r,r+o);if(r+=o,t[r]!==2)throw Error(`failed to convert DER-encoded signature: invalid tag for s`);r++;let c=t[r];if(c>33)throw Error(`failed to convert DER-encoded signature: unexpected length for s`);r++;let l=t.slice(r,r+c),u=i(s,32),d=i(l,32);return new Uint8Array([...u,...d])};var _e;(function(e){e.NOTARIZER=`notarizer`,e.SIGNER=`signer`,e.EVM_PARSER=`evm-parser`,e.TLS_FETCHER=`tls-fetcher`,e.UMP=`ump`})(_e||={});var I=s(((e,t)=>{(function(e,n){var r=2**-24,i=2**32,a=2**53;function o(e){var t=new ArrayBuffer(256),r=new DataView(t),o,s=0;function c(e){for(var n=t.byteLength,i=s+e;n<i;)n*=2;if(n!==t.byteLength){var a=r;t=new ArrayBuffer(n),r=new DataView(t);for(var c=s+3>>2,l=0;l<c;++l)r.setUint32(l*4,a.getUint32(l*4))}return o=e,r}function l(){s+=o}function u(e){l(c(8).setFloat64(s,e))}function d(e){l(c(1).setUint8(s,e))}function f(e){for(var t=c(e.length),n=0;n<e.length;++n)t.setUint8(s+n,e[n]);l()}function p(e){l(c(2).setUint16(s,e))}function m(e){l(c(4).setUint32(s,e))}function h(e){var t=e%i,n=(e-t)/i,r=c(8);r.setUint32(s,n),r.setUint32(s+4,t),l()}function g(e,t){t<24?d(e<<5|t):t<256?(d(e<<5|24),d(t)):t<65536?(d(e<<5|25),p(t)):t<4294967296?(d(e<<5|26),m(t)):(d(e<<5|27),h(t))}function _(e){var t;if(e===!1)return d(244);if(e===!0)return d(245);if(e===null)return d(246);if(e===n)return d(247);switch(typeof e){case`number`:if(Math.floor(e)===e){if(0<=e&&e<=a)return g(0,e);if(-a<=e&&e<0)return g(1,-(e+1))}return d(251),u(e);case`string`:var r=[];for(t=0;t<e.length;++t){var i=e.charCodeAt(t);i<128?r.push(i):i<2048?(r.push(192|i>>6),r.push(128|i&63)):i<55296?(r.push(224|i>>12),r.push(128|i>>6&63),r.push(128|i&63)):(i=(i&1023)<<10,i|=e.charCodeAt(++t)&1023,i+=65536,r.push(240|i>>18),r.push(128|i>>12&63),r.push(128|i>>6&63),r.push(128|i&63))}return g(3,r.length),f(r);default:var o;if(Array.isArray(e))for(o=e.length,g(4,o),t=0;t<o;++t)_(e[t]);else if(e instanceof Uint8Array)g(2,e.length),f(e);else{var s=Object.keys(e);for(o=s.length,g(5,o),t=0;t<o;++t){var c=s[t];_(c),_(e[c])}}}}if(_(e),`slice`in t)return t.slice(0,s);for(var v=new ArrayBuffer(s),y=new DataView(v),b=0;b<s;++b)y.setUint8(b,r.getUint8(b));return v}function s(e,t,a){var o=new DataView(e),s=0;typeof t!=`function`&&(t=function(e){return e}),typeof a!=`function`&&(a=function(){return n});function c(e,t){return s+=t,e}function l(t){return c(new Uint8Array(e,s,t),t)}function u(){var e=new DataView(new ArrayBuffer(4)),t=m(),n=t&32768,i=t&31744,a=t&1023;if(i===31744)i=261120;else if(i!==0)i+=114688;else if(a!==0)return a*r;return e.setUint32(0,n<<16|i<<13|a<<13),e.getFloat32(0)}function d(){return c(o.getFloat32(s),4)}function f(){return c(o.getFloat64(s),8)}function p(){return c(o.getUint8(s),1)}function m(){return c(o.getUint16(s),2)}function h(){return c(o.getUint32(s),4)}function g(){return h()*i+h()}function _(){return o.getUint8(s)===255&&(s+=1,!0)}function v(e){if(e<24)return e;if(e===24)return p();if(e===25)return m();if(e===26)return h();if(e===27)return g();if(e===31)return-1;throw`Invalid length encoding`}function y(e){var t=p();if(t===255)return-1;var n=v(t&31);if(n<0||t>>5!==e)throw`Invalid indefinite length element`;return n}function b(e,t){for(var n=0;n<t;++n){var r=p();r&128&&(r<224?(r=(r&31)<<6|p()&63,--t):r<240?(r=(r&15)<<12|(p()&63)<<6|p()&63,t-=2):(r=(r&15)<<18|(p()&63)<<12|(p()&63)<<6|p()&63,t-=3)),r<65536?e.push(r):(r-=65536,e.push(55296|r>>10),e.push(56320|r&1023))}}function x(){var e=p(),r=e>>5,i=e&31,o,s;if(r===7)switch(i){case 25:return u();case 26:return d();case 27:return f()}if(s=v(i),s<0&&(r<2||6<r))throw`Invalid length`;switch(r){case 0:return s;case 1:return-1-s;case 2:if(s<0){for(var c=[],m=0;(s=y(r))>=0;)m+=s,c.push(l(s));var h=new Uint8Array(m),g=0;for(o=0;o<c.length;++o)h.set(c[o],g),g+=c[o].length;return h}return l(s);case 3:var S=[];if(s<0)for(;(s=y(r))>=0;)b(S,s);else b(S,s);return String.fromCharCode.apply(null,S);case 4:var C;if(s<0)for(C=[];!_();)C.push(x());else for(C=Array(s),o=0;o<s;++o)C[o]=x();return C;case 5:var w={};for(o=0;o<s||s<0&&!_();++o){var T=x();w[T]=x()}return w;case 6:return t(x(),s);case 7:switch(s){case 20:return!1;case 21:return!0;case 22:return null;case 23:return n;default:return a(s)}}}var S=x();if(s!==e.byteLength)throw`Remaining bytes`;return S}var c={encode:o,decode:s};typeof define==`function`&&define.amd?define(`cbor/cbor`,c):t!==void 0&&t.exports?t.exports=c:e.CBOR||=c})(e)})),ve=s((()=>{
|
|
2
|
+
import{C as e,S as t,_ as n,b as r,g as i,v as a,x as o,y as s}from"./dist-B0qgGwAq.mjs";import{n as c}from"./base64-WTSXTrii.mjs";import{defineCommand as l,renderUsage as u,runMain as d}from"citty";import*as f from"valibot";import{ECDH as p,createECDH as m,createHash as h,createPrivateKey as g,randomBytes as _,sign as v}from"node:crypto";import{execFile as y,spawn as b}from"node:child_process";import{accessSync as x,chmodSync as S,constants as C,existsSync as w,mkdirSync as T,readFileSync as ee,realpathSync as E,renameSync as D,rmSync as O,statSync as k,writeFileSync as A}from"node:fs";import{homedir as j}from"node:os";import{dirname as M,isAbsolute as te,join as ne,resolve as re}from"node:path";import{createServer as N}from"node:http";import{constants as ie,isUtf8 as ae}from"node:buffer";import P from"semver";var oe=`@catena/cli`,se=`0.7.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((()=>{
|
|
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=[`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
|
|
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
|
|
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=`offer-receipt`,Da=8192,Oa=f.pipe(f.string(),f.maxLength(Da),f.regex(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,`Expected a JWS compact serialization`)),ka=f.optional(f.pipe(f.number(),f.integer(),f.minValue(0))),Aa=f.pipe(f.string(),f.regex(/^0x[0-9a-fA-F]{130}$/,`Expected a 65-byte hex signature`)),ja=f.variant(`format`,[f.looseObject({format:f.literal(`eip712`),acceptIndex:ka,payload:f.record(f.string(),f.unknown()),signature:Aa}),f.looseObject({format:f.literal(`jws`),acceptIndex:ka,signature:Oa})]),Ma=f.variant(`format`,[f.looseObject({format:f.literal(`eip712`),payload:f.record(f.string(),f.unknown()),signature:Aa}),f.looseObject({format:f.literal(`jws`),signature:Oa})]),Na=f.object({[Ea]:f.object({info:f.object({offers:f.array(f.unknown())})})}),Pa=f.object({[Ea]:f.object({info:f.object({receipt:f.unknown()})})}),Fa=f.looseObject({version:f.literal(1),resourceUrl:f.pipe(f.string(),f.maxLength(2048)),scheme:f.pipe(f.string(),f.maxLength(64)),network:f.pipe(f.string(),f.maxLength(64)),asset:f.pipe(f.string(),f.maxLength(128)),payTo:f.pipe(f.string(),f.maxLength(128)),amount:f.pipe(f.string(),f.regex(/^\d+$/),f.maxLength(78)),validUntil:f.optional(f.pipe(f.number(),f.integer(),f.minValue(0)))});function Ia(e){let t=e.replaceAll(`-`,`+`).replaceAll(`_`,`/`),n=Uint8Array.from(atob(t),e=>e.charCodeAt(0));return JSON.parse(new TextDecoder().decode(n))}function La(e){if(e.format===`eip712`){let t=f.safeParse(Fa,e.payload);return t.success?t.output:void 0}let t=e.signature.split(`.`)[1];try{let e=f.safeParse(Fa,Ia(t));return e.success?e.output:void 0}catch{return}}function Ra(e,t){return e.toLowerCase()===t.toLowerCase()}function za(e,t){return e.scheme===t.scheme&&e.network===t.network&&Ra(e.asset,t.asset)&&Ra(e.payTo,t.payTo)&&e.amount===t.amount}function Ba(e){return new TextEncoder().encode(JSON.stringify(e)).length<=Da}function Va(e,t){let n=f.safeParse(Na,e);if(n.success)for(let e of n.output[Ea].info.offers){let n=f.safeParse(ja,e);if(!n.success)continue;let r=La(n.output);if(r!==void 0&&za(r,t)&&Ba(n.output))return n.output}}function Ha(e){let t=f.safeParse(Pa,e);if(!t.success)return;let n=f.safeParse(Ma,t.output[Ea].info.receipt);if(!(!n.success||!Ba(n.output)))return n.output}const Ua=f.pipe(f.string(),f.regex(/\S/,`Response enum values must not be blank`));function Wa(e){return Ua}const Ga=f.object({amount:f.string(),asset_id:f.string()}),Ka=f.pipe(f.string(),f.isoTimestamp()),qa=f.object({success:f.literal(!0)}),Ja=f.object({id:f.string(),name:f.string(),status:f.string(),organizationId:f.string()}),Ya=f.object({agent:Ja}),Xa=[`per_transaction_amount`,`daily_amount`,`weekly_amount`,`monthly_amount`,`hourly_count`,`daily_count`],Za=f.object({id:f.string(),ruleType:Wa(Xa),thresholdAmount:f.optional(Ga),thresholdCount:f.optional(f.number()),action:Wa([`block`,`require_approval`]),requiredApprovals:f.number(),accountAggregationScope:Wa([`per_account`,`across_accounts`]),actorAggregationScope:Wa([`per_agent`,`per_policy`]),displayOrder:f.number()}),Qa=f.object({id:f.string(),organizationId:f.string(),policyId:f.string(),capability:Wa([`query_balance`,`read`,`send`,`transfer`]),accountId:f.string(),rules:f.array(Za),createdAt:Ka,updatedAt:Ka}),$a=[`allow`,`block`,`require_approval`],eo=[`open`,`restricted`],to=Wa($a),no=f.object({mode:Wa(eo),allowedCounterparties:f.optional(f.array(f.string())),createAction:f.optional(to),requestPaymentDetailsAction:f.optional(to),allowCreate:f.optional(f.boolean())}),ro=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(no),policyCapabilities:f.array(Qa),kind:f.optional(f.picklist([`base`,`override`])),expiresAt:f.optional(f.string())}),io=f.object({policy:ro}),ao=f.object({accounts:f.array(f.object({id:f.string(),name:f.string(),type:f.string(),currency:f.string()}))}),oo=f.object({accountId:f.string(),balance:Ga,balances:f.optional(f.object({total:Ga,available:Ga}))}),so=[`operator-send`,`operator-transfer`,`operator-deposit`,`operator-refund`,`microdeposit`],co=[`pending`,`processing`,`completed`,`failed`,`reversed`],lo=[`initiated`,`provider_pending`,`processing`,`completed`,`failed`,`reversed`,`manual_review`],uo=[`ach`,`wire`,`on-chain`],fo=f.object({id:f.string(),type:Wa(so),action:f.optional(f.string()),status:Wa(co),movementStatus:Wa(lo),direction:f.picklist([`incoming`,`outgoing`]),amount:Ga,fee:Ga,currency:f.string(),counterpartyName:f.optional(f.string()),method:f.optional(Wa([`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)}),po=f.object({accountId:f.string(),transactions:f.array(fo),total:f.number()}),mo=f.object({accountId:f.string(),address:f.string(),liquidationAddressId:f.optional(f.string()),source:Wa([`wallet`,`liquidation`])}),ho=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())}))}),go=f.object({counterparties:f.array(ho)}),_o=f.picklist([`pending`,`processing`,`completed`,`blocked`,`failed`]),vo=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()})}),yo=f.object({id:f.string(),type:Wa([`send`,`transfer`,`create_counterparty`,`request_counterparty_details`,`x402`,`policy_override`]),status:_o,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(vo)});function bo(e){let{nextAction:t,...n}=e;return n}const xo=f.object({paymentCredential:f.object({protocol:f.literal(`x402`),value:f.string()})}),So=f.object({x402:f.object({paymentSignature:f.string()})});function Co(e){let t=f.safeParse(xo,e);if(t.success)return t.output.paymentCredential.value;let n=f.safeParse(So,e);return n.success?n.output.x402.paymentSignature:void 0}const wo=f.picklist(uo),To=f.object({type:f.literal(`send`),accountId:f.string(),counterpartyRailId:f.string(),amount:f.string(),method:wo,memo:f.optional(f.string()),description:f.optional(f.string())}),Eo=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())}),Do={type:f.literal(`create_counterparty`),name:f.string()},Oo=f.union([f.object({...Do,email:f.optional(f.string()),rail:f.nonOptional(f.unknown())}),f.object({...Do,email:f.string()})]),ko=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`))}),Ao=f.looseObject({scheme:f.string(),network:f.string(),asset:f.string(),amount:f.string(),payTo:f.string(),maxTimeoutSeconds:f.number()}),jo=f.looseObject({url:f.string(),serviceName:f.fallback(f.optional(f.pipe(f.string(),f.maxLength(255))),void 0)}),Mo=f.pipe(f.string(),f.regex(/^0x[0-9a-fA-F]{40}$/,`Expected a 20-byte hex address`)),No=f.pipe(f.string(),f.maxLength(78),f.regex(/^(0|[1-9]\d*)$/,`Expected a canonical decimal integer string`)),Po=f.object({from:Mo,to:Mo,value:No,validAfter:No,validBefore:No,nonce:f.pipe(f.string(),f.regex(/^0x[0-9a-fA-F]{64}$/,`Expected a 32-byte hex nonce`))}),Fo=f.object({type:f.literal(`x402`),accountId:f.string(),paymentRequirements:Ao,resource:f.optional(jo),authorization:f.optional(Po),signedOffer:f.optional(ja)}),Io=[`send`,`transfer`],Lo=f.strictObject({type:f.literal(`increase_limit`),accountId:f.pipe(f.string(),f.minLength(1)),capability:f.picklist(Io),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`)})}),Ro=f.strictObject({type:f.literal(`increase_limit`),accountId:f.pipe(f.string(),f.minLength(1)),capability:f.picklist(Io),limitType:f.picklist([`hourly_count`,`daily_count`]),newLimit:f.strictObject({count:f.pipe(f.number(),f.integer(),f.minValue(1))})}),zo=f.pipe(f.array(f.union([Lo,Ro])),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`)),Bo=f.object({type:f.literal(`policy_override`),operations:zo,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([To,Eo,Oo,ko,Fo,Bo]);function Ho(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 Uo=f.object({intent:yo});var Wo=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}},Go=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 Ko=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 qo(e){let t=f.safeParse(Ko,await e.json().catch(()=>void 0)),n=t.success?t.output:{};return n.error!=null&&n.message!=null?new Wo(e.status,n.message,n.code??n.error,n.details??void 0):new Wo(e.status,n.error??n.message??e.statusText,n.code??void 0,n.details??void 0)}async function Jo(e,t){if(!e.ok)throw await qo(e);return f.parse(t,await e.json())}var Yo=class extends Error{intentId;outcome;constructor(e){let t=e.cause instanceof Error?e.cause.message:String(e.cause);super(e.outcome===`not-submitted`?`Intent ${e.intentId} was created but never submitted; no money moved: ${t}`:`Intent ${e.intentId} submission could not be confirmed: ${t}; poll getIntent("${e.intentId}") to a terminal status and resubmit only after blocked or failed`,{cause:e.cause}),this.name=`IntentSubmitError`,this.intentId=e.intentId,this.outcome=e.outcome}};const Xo=2147483647;var Zo=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>Xo)throw TypeError(`timeout must be a positive integer no greater than ${Xo}`);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 Go(this.#o);t(e),n.abort(e)},this.#o)}),a=this.#a(r).then(e=>Jo(e,t));return await Promise.race([a,e])}finally{i!==void 0&&clearTimeout(i)}}async whoami(){return(await this.#l({method:`GET`,path:`/me`},Ya)).agent}async submitFeedback(e){await this.#l({method:`POST`,path:`/feedback`,body:{body:e}},qa)}async getPolicy(){return(await this.#l({method:`GET`,path:`/policy`},io)).policy}async listAccounts(){return this.#l({method:`GET`,path:`/accounts`},ao)}async getAccountBalance(e){return this.#l({method:`GET`,path:`/accounts/${encodeURIComponent(e)}/balance`},oo)}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()}},po)}async getAccountDepositAddress(e,t){return this.#l({method:`GET`,path:`/accounts/${encodeURIComponent(e)}/deposit-address`,query:{network:t.network,asset:t.asset}},mo)}async listCounterparties(e={}){return this.#l({method:`GET`,path:`/counterparties`,query:{address:e.address,network:e.network}},go)}async submitIntent(e){let t=await this.#d({...e,idempotencyKey:e.idempotencyKey??crypto.randomUUID()}),n=t.nextAction;if(!n)return bo(t);let r;try{let e=await this.#f(n);r=await this.#c({method:`POST`,path:`/intents/${encodeURIComponent(t.id)}/submit-stamp`,body:{preparedBody:n.preparedBody,stamp:e}})}catch(e){throw new Yo({intentId:t.id,outcome:`not-submitted`,cause:e})}try{return await this.#p(r,t.replayed)}catch(e){throw new Yo({intentId:t.id,outcome:`unknown`,cause:e})}}async#d(e){return this.#l({method:`POST`,path:`/intents`,body:{action:Ho(e.action)},headers:{"Idempotency-Key":e.idempotencyKey}},yo)}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=bo((await this.#u(e,Uo)).intent);return t?{...n,replayed:!0}:n}async getIntent(e){return bo(await this.#l({method:`GET`,path:`/intents/${encodeURIComponent(e)}`},yo))}async unlinkAgent(){await this.#l({method:`POST`,path:`/unlink`},qa)}async reportSettlement(e){await this.#l({method:`POST`,path:`/intents/${encodeURIComponent(e.intentId)}/settlement-report`,body:{txHash:e.txHash,...e.receipt!==void 0&&{receipt:e.receipt}}},qa)}};function Qo(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 Zo({...e,privateKeyHex:t})}function $o(e){let t=e instanceof Error?e.message:String(e);return e instanceof Wo&&e.details!==void 0?`${t}\nDetails:\n${JSON.stringify(e.details,null,2)}`:t}function X(e){console.error($o(e)),process.exit(1)}const es=f.string(),ts=f.boolean();function ns(e){return e===void 0}function rs(e){return e.issues?.[0]?.message??`Invalid value`}function is(e,t,n,r){return X(`${e}: ${t}${r?` (got: ${String(n)})`:``}`)}function as(e,t,n,r){let i=f.safeParse(e,t);return i.success?i.output:is(n,rs(i),t,r)}function os(e,t){let n=t.schema??es;return{type:e,description:t.description,negativeDescription:t.negativeDescription,required:t.required,default:t.default,parseValue(e,r){let i=ns(e)?t.default:e;if(ns(i)){t.required===!0&&X(`${r} is required`);return}return as(n,i,r,t.showValueInError===!0)}}}function Z(e){return os(`string`,e)}function ss(e){return os(`positional`,e)}function cs(e){let t=e.schema??es;return{type:`string`,description:e.description,repeatable:!0,parseValue(n,r){return(Array.isArray(n)?n:[]).map(n=>as(t,n,r,e.showValueInError===!0))}}}function ls(e){return{type:`boolean`,description:e.description,negativeDescription:e.negativeDescription,required:e.required,default:e.default,parseValue(t,n){let r=ns(t)?e.default:t;if(ns(r)){e.required===!0&&X(`${n} is required`);return}return as(ts,r,n,!1)}}}function us(e){return ds(`string`,e)}function ds(e,t){return os(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 fs(e,t){return t.type===`positional`?`<${e}>`:`--${e}`}function ps(e){return e.replace(/([a-z])([A-Z])/g,`$1 $2`).replace(/([A-Z0-9])([A-Z][a-z])/g,`$1 $2`).split(/[ _-]/).filter(e=>e.length>0)}function ms(e){return ps(e).join(`-`).toLowerCase()}function hs(e){return ps(e).map((e,t)=>t===0?e.charAt(0).toLowerCase()+e.slice(1):e.charAt(0).toUpperCase()+e.slice(1)).join(``)}function gs(e){return[`--${e}`,`--${ms(e)}`,`--${hs(e)}`]}function _s(e){let t=e.indexOf(`=`);return t===-1?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function vs(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(gs(t)),s=new Set(Object.entries(n).filter(([e,n])=>e!==t&&n.type===`string`).flatMap(([e])=>gs(e))),c=[];for(let e=0;e<a.length;e++){let t=a[e];if(t===`--`)break;let[n,r]=_s(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 ys(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,ys(t)])),label(t){return fs(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 vs(n,r,e)};return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.parseValue(r(e,t),fs(e,t))]))}}}const bs=Z({description:`Credential profile name`}),xs=ls({description:`Print compact single-line JSON (for piping)`,default:!1}),Ss=/^[a-zA-Z0-9_-]+$/,Cs=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(Ss,`ID may only contain letters, digits, hyphens, and underscores`)),ws=[`base`,`base-sepolia`],Ts=[`usdc`],Es=`base`,Ds=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 us({description:e.description,choices:ws,...e.default===void 0?{}:{default:e.default}})}const ks=[`registered`,`already_registered`,`not_applicable`,`registration_failed`],As=f.pipe(f.string(),f.regex(/^0[23][0-9a-f]{64}$/)),js=f.pipe(f.string(),f.regex(/^[0-9a-f]{64}$/)),Ms=f.object({status:f.picklist(ks),publicKeyHex:f.optional(As),reason:f.optional(f.string())}),Ns=f.object({algorithm:f.literal(`p256`),privateKeyHex:js,publicKeyHex:As,registration:Ms}),Ps=f.object({version:f.literal(`signer-1`),signer:Ns}),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())}),Is=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:Ns}),Ls=f.object({version:f.literal(3),signer:Ns}),Rs=f.variant(`version`,[Fs,Is,Ls]),zs=f.variant(`version`,[Ps,Fs,Is,Ls]);function Bs(e){return f.parse(Rs,e)}function Vs(e){return f.parse(zs,e)}function Hs(e){let t=f.safeParse(zs,e);return t.success?t.output:null}function Us(e){return{version:`signer-1`,signer:{algorithm:e.algorithm,privateKeyHex:e.privateKeyHex,publicKeyHex:e.publicKeyHex,registration:{status:`not_applicable`,reason:`pending_claim`}}}}function Ws(e,t){try{return Vs(JSON.parse(e))}catch(e){throw Error(`${t} credential has an unsupported format`,{cause:e})}}function Gs(e){return Bs({version:3,signer:e})}function Ks(e){return JSON.stringify(e)}function qs(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Js(e){return(t,n)=>Ys(e,t,n)}function Ys(e,t,n){return new Promise((r,i)=>{let a=b(e,[...t],{stdio:[`pipe`,`pipe`,`pipe`]}),o=[],s=[],c=!1,l=!1,u=null,d=null,f=null,p=e=>{c||(c=!0,d!==null&&clearTimeout(d),f!==null&&clearTimeout(f),r(e))},m=e=>{c||(c=!0,d!==null&&clearTimeout(d),f!==null&&clearTimeout(f),i(e))};d=setTimeout(()=>{l=!0,a.kill(`SIGTERM`),f=setTimeout(()=>{a.kill(`SIGKILL`),p({stdout:o.join(``),stderr:s.join(``),status:124})},1e3)},3e4),a.stdout.setEncoding(`utf8`),a.stderr.setEncoding(`utf8`),a.stdout.on(`data`,e=>o.push(e)),a.stderr.on(`data`,e=>s.push(e)),a.on(`error`,t=>{m(Error(`Unable to run ${e}: ${t.message}`))}),a.on(`close`,t=>{if(u!==null&&t===0){m(Error(`Unable to write to ${e} stdin: ${u.message}`));return}p({stdout:o.join(``),stderr:s.join(``),status:l?124:t})}),a.stdin.on(`error`,e=>{u=e});try{a.stdin.end(n)}catch(t){m(t instanceof Error?Error(`Unable to write to ${e} stdin: ${t.message}`):Error(`Unable to write to ${e} stdin`))}})}const Xs=`catena-agent`;function Zs(e){if(!Ss.test(e))throw Error(`Invalid credential location for credential storage: "${e}"`);return e}const Qs=Js(`/usr/bin/secret-tool`);function $s(e){return e.status===1&&e.stdout===``&&e.stderr.trim()===``}function ec(e,t){if(t.status===0)return;let n=tc(t);throw Error(`Linux Secret Service credential ${e} failed (secret-tool exited ${t.status??`without status`}): ${n}`)}function tc(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 nc(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 rc=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??Qs}async save(e,t){let n=Vs(t),r=Zs(e);if(await this.savePassword(r,Ks(n)),!qs(await this.resolveDirectPassword(r),n))throw Error(`Linux Secret Service credential save verification failed`)}async resolve(e){return this.resolveDirectPassword(Zs(e))}async delete(e){await this.deletePassword(Zs(e))}async savePassword(e,t){ec(`save`,await this.runSecretToolCommand([`store`,`--label`,`${Xs} ${e}`,`app`,Xs,`account`,e],t))}async resolvePassword(e){let t=await this.runSecretToolCommand([`lookup`,`app`,Xs,`account`,e]);return $s(t)?null:(ec(`resolve`,t),t.stdout.replace(/\r?\n$/,``))}async resolveDirectPassword(e){let t=await this.resolvePassword(e);return t===null?null:Ws(t,`Linux Secret Service`)}async deletePassword(e){let t=await this.runSecretToolCommand([`clear`,`app`,Xs,`account`,e]);$s(t)||ec(`delete`,t)}async runSecretToolCommand(e,t){try{return await this.runSecretTool(e,t)}catch(e){throw nc(e)}}};const ic=Js(`/usr/bin/security`),ac=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 oc(e){return e.status===44}function sc(e,t){return`${e}:chunk:${t}`}function cc(e){let t=JSON.parse(e),n=Hs(t);if(n!==null)return{kind:`direct`,payload:n};let r=f.safeParse(ac,t);if(r.success)return{kind:`legacy`,manifest:r.output};throw Error(`macOS Keychain credential has an unsupported format`)}function lc(e,t){if(t.status===0)return;let n=uc(t);throw Error(`macOS Keychain credential ${e} failed (security exited ${t.status??`without status`})${n===null?``:`: ${n}`}`)}function uc(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 dc(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 fc(e,t){return[`add-generic-password`,`-s`,dc(Xs),`-a`,dc(e),`-w`,dc(t),`-U`].join(` `)+`
|
|
137
|
+
`}var pc=class{runSecurity;constructor(e={}){if((e.platform??process.platform)!==`darwin`)throw Error(`macOS Keychain credential storage is only supported on macOS`);this.runSecurity=e.runSecurity??ic}async save(e,t){let n=Vs(t),r=Zs(e),i=await this.resolveLegacyChunkCount(r,64);if(await this.savePassword(r,Ks(n)),!qs(await this.resolveDirectPassword(r),n))throw Error(`macOS Keychain credential save verification failed`);await this.deleteChunks(r,i)}async resolve(e){let t=Zs(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=Zs(e),n=await this.resolveLegacyChunkCount(t,64);await this.deleteChunks(t,n),await this.deletePassword(t)}async savePassword(e,t){lc(`save`,await this.runSecurity([`-i`],fc(e,t)))}async resolvePassword(e){let t=await this.runSecurity([`find-generic-password`,`-a`,e,`-s`,Xs,`-w`]);return oc(t)?null:(lc(`resolve`,t),t.stdout.replace(/\r?\n$/,``))}async resolveKeychainItem(e){let t=await this.resolvePassword(e);return t===null?null:cc(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(sc(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 Vs(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=cc(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(sc(e,n))}async deletePassword(e){let t=await this.runSecurity([`delete-generic-password`,`-a`,e,`-s`,Xs]);oc(t)||lc(`delete`,t)}};function mc(e={}){let t=e.platform??process.platform;if(t===`darwin`)return new pc({platform:t});if(t===`linux`)return new rc({platform:t});throw Error(`Catena credential storage is only supported on macOS and Linux`)}const hc=/^127(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}$/;function gc(e){let t=e.replace(/^\[|\]$/g,``);return t===`localhost`||t===`::1`||hc.test(t)}function _c(e){let t;try{t=new URL(e)}catch{return!1}return t.protocol===`https:`||t.protocol===`http:`&&gc(t.hostname)}function vc(e,t){if(!_c(e))throw Error(`${t} must be an https:// URL (http:// is allowed only for a loopback host): "${e}"`)}const yc=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/,bc=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(Ss))}),xc=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(Ss)),created_at:f.pipe(f.string(),f.isoTimestamp())}),Sc=f.variant(`status`,[bc,xc]);f.object({version:f.literal(1),default_profile:f.optional(f.string()),profiles:f.record(f.string(),Sc),directories:f.optional(f.record(f.string(),f.string()))});const Cc=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 wc(){return ne(process.env.HOME??j(),`.catena`)}function Tc(){return ne(wc(),`profiles.json`)}function Ec(e){return yc.test(e)}function Dc(e){if(!Ec(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 kc(e,t){let n;try{n=JSON.parse(e)}catch(e){throw Error(`profiles.json is not valid JSON: ${$o(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(Cc,n),i={};for(let[e,n]of Object.entries(r.profiles)){if(!Ec(e)){t?.(`profiles: dropping invalid profile name "${e}"`);continue}let r=f.safeParse(Sc,n);if(!r.success){t?.(`profiles: dropping malformed profile "${e}"`);continue}i[e]=r.output}if(r.default_profile!==void 0&&(Dc(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`||!Ec(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 Ac(e){try{return kc(ee(Tc(),`utf-8`),e)}catch(e){if(e instanceof Error&&Oc(e)&&e.code===`ENOENT`)return{version:1,profiles:{}};throw e}}function jc(){T(wc(),{recursive:!0,mode:448}),S(wc(),448)}function Mc(e){jc();let t=Tc(),n=`${t}.${_(6).toString(`hex`)}.tmp`;A(n,JSON.stringify(e,null,2)+`
|
|
138
|
+
`,{encoding:`utf-8`,mode:384}),D(n,t)}function Nc(e,t){Dc(e);let n=f.parse(Sc,t);vc(n.bank_url,`profile "${e}" bank_url`);let r=Ac();Mc({...r,profiles:{...r.profiles,[e]:n}})}function Pc(e){return e.status===`linked`}function Fc(e,t){return e.replace(/\/+$/,``)===t.replace(/\/+$/,``)}function Ic(e,t){let n=Object.entries(Ac().profiles).toSorted(([e],[t])=>e.localeCompare(t)).find(([,n])=>Pc(n)&&n.agent_id===e&&Fc(n.bank_url,t));return n===void 0?null:n[0]}function Lc(e,t){let n=Object.fromEntries(Object.entries(e??{}).filter(([,e])=>t(e)));return Object.keys(n).length===0?{}:{directories:n}}function Rc(e){Dc(e);let t=Ac(),{[e]:n,...r}=t.profiles;Mc({version:1,...t.default_profile===e||t.default_profile===void 0?{}:{default_profile:t.default_profile},profiles:r,...Lc(t.directories,t=>t!==e)})}function zc(e){try{return E(re(e))}catch{return re(e)}}function Bc(e){return Ac().directories?.[zc(e)]??null}function Vc(e,t){Dc(t);let n=Ac();if(!Object.hasOwn(n.profiles,t))throw Error(`Profile "${t}" is not linked. Run catena link --profile ${t} <agent-id>.`);let r=zc(e);return Mc({...n,directories:{...n.directories,[r]:t}}),r}function Hc(e){let t=Ac(),n=zc(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 Mc({...o,...Object.keys(i).length===0?{}:{directories:i}}),{directory:n,removed:!0}}function Uc(e){return Dc(e),Ac().profiles[e]??null}function Wc(){return`client_${_(16).toString(`hex`)}`}function Gc(e,t){let n=Uc(e);return t.agent_id===void 0?Kc(e,t.bank_url,n):qc(e,t.bank_url,t.agent_id,n)}function Kc(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)??Wc();return Nc(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 qc(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)??Wc();return Nc(e,{status:`linked`,bank_url:t,agent_id:n,client_instance_id:i}),i}function Jc(e){Dc(e);let t=Ac();if(!Object.hasOwn(t.profiles,e))throw Error(`Profile "${e}" is not linked. Run catena link --profile ${e} <agent-id>.`);Mc({...t,default_profile:e})}function Yc(e){let t=e.toLowerCase().replace(/[^a-z0-9._-]+/g,`-`).replace(/^[^a-z0-9]+/,``).slice(0,64);return Ec(t)?t:`agent`}function Xc(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 Zc(e){Dc(e.reservationName),Dc(e.profileName);let t=f.parse(Sc,e.profile);vc(t.bank_url,`profile "${e.profileName}" bank_url`);let n=Ac(),{[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]));Mc({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 Qc(e){return e??mc()}async function $c(e,t){let n;try{n=Uc(e.profileName)}catch(t){return{ok:!1,profileName:e.profileName,bankUrl:e.fallbackBankUrl,message:$o(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{vc(n.bank_url,`profile "${e.profileName}" bank_url`)}catch(t){return{ok:!1,profileName:e.profileName,bankUrl:e.fallbackBankUrl,message:$o(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 Qc(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}: ${$o(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 el={name:`catena-cli`,version:se},tl=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function nl(e,t){if(!tl.test(e))throw Error(`${t} must be a valid HTTP token`)}function rl(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 il(e){nl(e.name,`appInfo.name`),e.version!==void 0&&nl(e.version,`appInfo.version`),e.url!==void 0&&rl(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 al=`https://api.catena.com`,ol=`CATENA_PROFILE`;function sl(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 cl(e,t,n){if(e.flag!==void 0&&e.flag.length>0)return Dc(e.flag),{name:e.flag,source:`flag`};if(e.env!==void 0&&e.env.length>0){if(!Ec(e.env))throw Error(`${ol} is set to an invalid profile name "${e.env}"`);return{name:e.env,source:`env`}}if(e.cwd!==void 0){let r=sl(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 ll(e){return cl(e,Ac(e.log),`ignore`)}function ul(e){let t=Ac(e.log),n=cl(e,t,`error`);if(n!==null)return n;let r=Object.keys(t.profiles),i=Object.entries(t.profiles).filter(([,e])=>Pc(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 ${ol}, run 'catena profiles use <name>', or run 'catena link' from an agent directory to bind it.`)}function dl(e){return Qo({baseUrl:e.bankUrl,privateKeyHex:e.signer.privateKeyHex,appInfo:el})}function fl(){return mc()}async function pl(e){let t;try{t=ul({flag:e,env:process.env[ol],cwd:process.cwd(),log:e=>console.error(e)}).name}catch(e){return X(e)}let n=await $c({profileName:t,fallbackBankUrl:al},void 0);return n.ok||X(n.message),dl(n)}const ml=new Set([`unknown_key`,`key_revoked`,`client_unlinked`]),hl=new Set([`signature_auth_disabled`,`missing_auth`]);function gl(e,t){if(!(e instanceof Wo)||e.code===void 0)return e;let n=t===void 0?`catena link`:`catena link --profile ${t}`;return ml.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 (${el.version}) is no longer supported by the bank. Run 'npm i -g @catena/cli' and retry.`):hl.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 _l(e,t){console.log(t?.compact?JSON.stringify(e):JSON.stringify(e,null,2))}function vl(e){return e.profile===void 0||e.profile.length===0?void 0:e.profile}async function yl(e,t){try{return await t(await pl(e))}catch(t){return X(gl(t,e))}}function bl(e,t){return async(n,r)=>{let i=await yl(e,n);return _l(i,t),await new Promise(e=>{process.stdout.write(``,()=>e())}),process.exit(r?.exitCode?r.exitCode(i):0)}}function $(e){return bl(vl(e),{compact:e.json===!0})}const xl=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}`)),Sl=f.pipe(xl,f.maxValue(200,`must be at most 200`)),Cl={profile:bs,json:xs},wl=Q(Cl),Tl=Q({account:ss({description:`Account id`,required:!0,schema:Cs}),...Cl}),El=Q({account:ss({description:`Account id`,required:!0,schema:Cs}),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:Sl}),offset:Z({description:`Number of transactions to skip for pagination`,schema:xl}),...Cl}),Dl=Q({account:ss({description:`Account id`,required:!0,schema:Cs}),network:Os({description:`Deposit network; defaults to ${Es}. Availability depends on the connected environment.`,default:Es}),asset:us({description:`Deposit asset (${Ts.join(`|`)})`,choices:Ts,default:`usdc`}),...Cl}),Ol=l({meta:{name:`list`,description:`List accounts accessible under the agent's policy`},args:wl.args,async run({args:e}){await $(wl.parse(e))(e=>e.listAccounts())}}),kl=l({meta:{name:`balance`,description:`Request an account balance through the policy engine`},args:Tl.args,async run({args:e}){let t=Tl.parse(e);await $(t)(e=>e.getAccountBalance(t.account))}}),Al=l({meta:{name:`transactions`,description:`Read an account's transaction history through the policy engine`},args:El.args,async run({args:e}){let t=El.parse(e);await $(t)(e=>e.listAccountTransactions(t.account,{start:t.start,end:t.end,limit:t.limit,offset:t.offset}))}}),jl=l({meta:{name:`deposit-address`,description:`Read an account deposit address through the policy engine`},args:Dl.args,async run({args:e}){let t=Dl.parse(e);await $(t)(e=>e.getAccountDepositAddress(t.account,{network:t.network,asset:t.asset}))}}),Ml=l({meta:{name:`accounts`,description:`Inspect bank accounts`},subCommands:{list:Ol,balance:kl,transactions:Al,"deposit-address":jl}}),Nl=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)`)),Pl=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`)),Il={profile:bs,json:xs},Ll=Q({address:Z({description:`Only counterparties with a wallet rail matching this address (0x…)`,schema:Ds}),network:Os({description:`Only counterparties with a wallet rail on this network (e.g. base)`}),...Il}),Rl=Z({description:`Counterparty name`,required:!0,schema:Pl}),zl=Z({description:`Optional contact email`,schema:Fl}),Bl=Z({description:`Optional operation key. Reuse the same value only when retrying the same submission; omitted generates a fresh key for this invocation.`,schema:Nl}),Vl=Q({name:Rl,email:Z({description:`Contact email; creating the counterparty sends no email`,required:!0,schema:Fl}),"idempotency-key":Bl,...Il}),Hl=Q({name:Z({description:`Counterparty name; required without a subcommand`,schema:Pl}),email:Z({description:`Contact email; required without a subcommand; creating the counterparty sends no email`,schema:Fl}),"idempotency-key":Bl,...Il}),Ul=Q({name:Rl,"bank-name":Z({description:`Receiving bank name`,required:!0,schema:Pl}),"routing-number":Z({description:`9-digit ABA routing number`,required:!0,schema:Pl}),"account-number":Z({description:`Receiving bank account number`,required:!0,schema:Pl}),"account-type":us({description:`checking | savings (default checking)`,choices:[`checking`,`savings`]}),"address-street":Z({description:`Street address of the receiving bank account holder`,required:!0,schema:Pl}),"address-city":Z({description:`City`,required:!0,schema:Pl}),"address-state":Z({description:`State (e.g. NY)`,required:!0,schema:Pl}),"address-postal-code":Z({description:`Postal code`,required:!0,schema:Pl}),"address-country":Z({description:`Default USA`}),email:zl,"idempotency-key":Bl,...Il}),Wl=Q({name:Rl,address:Z({description:`Wallet address (0x… or ENS name on EVM networks)`,required:!0,schema:Pl}),network:Os({description:`Wallet network; defaults to ${Es}. Availability depends on the connected environment.`,default:Es}),email:zl,"idempotency-key":Bl,...Il}),Gl=Q({counterparty:ss({description:`Counterparty id`,required:!0,schema:Cs}),bank:ls({description:`Request bank account details`,default:!1}),wallet:ls({description:`Request wallet details`,default:!1}),"idempotency-key":Bl,...Il}),Kl=l({meta:{name:`list`,description:`List counterparties available under the agent's policy`},args:Ll.args,async run({args:e}){let t=Ll.parse(e);await $(t)(e=>e.listCounterparties({address:t.address,network:t.network}))}});function ql(e){return e&&e.length>0?e:void 0}function Jl(e){let t=ql(e.email);return{type:`create_counterparty`,name:e.name,email:t,rail:{type:`bank`,bankName:e[`bank-name`],routingNumber:e[`routing-number`],accountNumber:e[`account-number`],addressStreet:e[`address-street`],addressCity:e[`address-city`],addressState:e[`address-state`],addressPostalCode:e[`address-postal-code`],...e[`account-type`]?{accountType:e[`account-type`]}:{},...e[`address-country`]?{addressCountry:e[`address-country`]}:{}}}}function Yl(e){let t=ql(e.email);return{type:`create_counterparty`,name:e.name,email:t,rail:{type:`wallet`,walletAddress:e.address,network:e.network}}}function Xl(e){return{type:`create_counterparty`,name:e.name,email:e.email}}const Zl=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:Xl(t),...t[`idempotency-key`]!==void 0&&{idempotencyKey:t[`idempotency-key`]}}))}}),Ql=l({meta:{name:`bank`,description:`Request bank counterparty creation through the policy engine. Prints an intent envelope.`},args:Ul.args,async run({args:e}){let t=Ul.parse(e),n=Jl(t);await $(t)(e=>e.submitIntent({action:n,...t[`idempotency-key`]!==void 0&&{idempotencyKey:t[`idempotency-key`]}}))}}),$l=l({meta:{name:`wallet`,description:`Request wallet counterparty creation through the policy engine. Prints an intent envelope.`},args:Wl.args,async run({args:e}){let t=Wl.parse(e);await $(t)(e=>e.submitIntent({action:Yl(t),...t[`idempotency-key`]!==void 0&&{idempotencyKey:t[`idempotency-key`]}}))}}),eu=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:Hl.args,default:`email`,subCommands:{email:Zl,bank:Ql,wallet:$l}}),tu=l({meta:{name:`request-details`,description:`Ask a counterparty to provide bank details, wallet details, or both through the policy engine.`},args:Gl.args,async run({args:e}){let t=Gl.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`]}:{}}))}}),nu=l({meta:{name:`counterparties`,description:`Inspect, create, and request details from counterparties`},subCommands:{list:Kl,create:eu,"request-details":tu}}),ru=4e3;async function iu(){process.stdin.setEncoding(`utf8`);let e=``;for await(let t of process.stdin)e+=t;return e}async function au(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`),iu()):e}const ou=Q({message:ss({description:`Plain-text feedback (1-4000 chars); omit to pipe on stdin`}),profile:bs,json:xs}),su=l({meta:{name:`feedback`,description:`Send free-form feedback about Catena to the Catena team`},args:ou.args,async run({args:e}){(Array.isArray(e._)?e._:[]).length>1&&X(`<message>: pass the message as a single quoted argument`);let t=ou.parse(e),n=(await au(t.message)).trim();n.length===0&&X(`<message>: must not be empty`),n.length>ru&&X(`<message>: must be at most ${ru} characters (got: ${n.length})`),await $(t)(async e=>(await e.submitFeedback(n),{ok:!0}))}});function cu(e){return`# Catena CLI Agent Guide
|
|
139
139
|
|
|
140
140
|
CLI version: ${e}
|
|
141
141
|
|
|
@@ -334,33 +334,29 @@ through response-body validation; local request signing happens before that
|
|
|
334
334
|
clock starts. A timeout means the client stopped waiting, not that the server
|
|
335
335
|
did no work.
|
|
336
336
|
|
|
337
|
-
Read-only commands are safe to run again.
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
A bare x402 timeout happens before payment receipt, so the same command is safe
|
|
361
|
-
to run again. If the result instead says \`.paid\` and \`.retryFailed\`, do not
|
|
362
|
-
pay again: use \`intents get <id>\` to recover the \`PAYMENT-SIGNATURE\` as
|
|
363
|
-
described below.
|
|
337
|
+
Read-only commands are safe to run again. Intent commands generate a fresh UUID
|
|
338
|
+
when \`--idempotency-key\` is omitted: identical inputs do not identify a retry.
|
|
339
|
+
For recovery across invocations, choose and save a key before the first attempt,
|
|
340
|
+
then reuse it with unchanged inputs for the same agent. Changed inputs with the
|
|
341
|
+
same key return 409; use a new key for a new operation. Without a saved key,
|
|
342
|
+
reconcile an ambiguous submission before repeating it.
|
|
343
|
+
|
|
344
|
+
Payment errors override the general same-key retry advice:
|
|
345
|
+
|
|
346
|
+
- "Already prepared" (409 \`wallet_send_intent_not_executing\`): the original
|
|
347
|
+
wallet signing body cannot be recovered. Check \`intents get <id>\` if you
|
|
348
|
+
have the id; otherwise ask an operator to reconcile it. Do not bypass this
|
|
349
|
+
error with a new key.
|
|
350
|
+
- "Created but never submitted; no money moved": fix the reported problem,
|
|
351
|
+
then use a new key (omit the flag or supply a different value). The original
|
|
352
|
+
key cannot restart signing.
|
|
353
|
+
- "Could not be confirmed": poll \`intents get <id>\` even if you saved the
|
|
354
|
+
key. Submit again only after \`blocked\` or \`failed\`; see Intents below.
|
|
355
|
+
|
|
356
|
+
A bare x402 timeout is before payment authorization and is safe to retry. An
|
|
357
|
+
unconfirmed payment follows the polling rule above. If \`.paid\` and
|
|
358
|
+
\`.retryFailed\` are set, recover the \`PAYMENT-SIGNATURE\` as described below
|
|
359
|
+
instead of paying again.
|
|
364
360
|
|
|
365
361
|
## Money Movement
|
|
366
362
|
|
|
@@ -373,8 +369,6 @@ Before either:
|
|
|
373
369
|
- Use ids from \`accounts list\` and \`counterparties list\`.
|
|
374
370
|
- USD only. Pass \`--amount\` as a plain decimal string such as \`100.50\`. Do
|
|
375
371
|
not use scientific notation or signed values.
|
|
376
|
-
- Do not retry an ambiguous movement unless \`intents get\` shows it is
|
|
377
|
-
\`blocked\` or \`failed\`.
|
|
378
372
|
|
|
379
373
|
Examples:
|
|
380
374
|
|
|
@@ -402,6 +396,9 @@ the request with the payment attached:
|
|
|
402
396
|
catena x402 --url https://api.example.com/paid \\
|
|
403
397
|
--account acct_... --max-amount 0.25
|
|
404
398
|
|
|
399
|
+
\`x402\` manages its own keys, generating a fresh one per payment challenge
|
|
400
|
+
attempt. Re-running after success can pay again, even for the same URL and price.
|
|
401
|
+
|
|
405
402
|
To POST a request body (e.g. an OpenAI-compatible chat-completions call), pass
|
|
406
403
|
\`--data\`; it implies \`POST\` and a JSON content type unless overridden with
|
|
407
404
|
\`--method\` / \`--content-type\`. Use \`@path\` to read the body from a file or
|
|
@@ -445,18 +442,26 @@ refused before any payment. Payments follow the same policy as sends
|
|
|
445
442
|
policy's approval threshold parks for a human approval instead of paying:
|
|
446
443
|
the result carries \`.approvalPending\` (intent id, expiry, reasons) and the
|
|
447
444
|
command exits non-zero. Ask an operator to approve it in the console, then
|
|
448
|
-
re-run the SAME command
|
|
449
|
-
|
|
450
|
-
|
|
445
|
+
re-run the SAME command — the retry consumes the matching approval and pays
|
|
446
|
+
without re-approving; if the approval expires unused, the re-run parks a fresh
|
|
447
|
+
one. Approval matching is independent of keys and requires the same agent,
|
|
448
|
+
source account, payment requirements, and resource — not just URL and price.
|
|
449
|
+
The JSON result carries \`.paid\`, \`.payment\` (intent id, atomic
|
|
451
450
|
USDC amount, recipient), and the response \`.body\`. When \`.bodyTruncated\` is
|
|
452
451
|
true, read the complete body from the file at \`.bodyPath\` (if \`.bodyPath\`
|
|
453
452
|
is absent, \`.error\` says what survived); never re-fetch to see more of a
|
|
454
|
-
body — a re-run pays again.
|
|
455
|
-
|
|
456
|
-
|
|
453
|
+
body — a re-run pays again. To recover a completed payment after an interrupted
|
|
454
|
+
submission or failed paid request, read \`intents get <id>\`:
|
|
455
|
+
\`.data.paymentCredential.value\` is the
|
|
457
456
|
\`PAYMENT-SIGNATURE\` header value to retry with manually while the
|
|
458
457
|
authorization is still valid.
|
|
459
458
|
|
|
459
|
+
When a seller implements the x402 offer-receipt extension, the payment loop
|
|
460
|
+
relays the seller's signed offer and signed receipt to Catena automatically;
|
|
461
|
+
Catena verifies them and stores them on the intent as evidence for audit and
|
|
462
|
+
disputes. This changes nothing about the payment itself, and sellers without
|
|
463
|
+
the extension behave exactly as before.
|
|
464
|
+
|
|
460
465
|
## Temporary Policy Overrides
|
|
461
466
|
|
|
462
467
|
When policy blocks a task the user asked for, the agent may ask a human to
|
|
@@ -481,10 +486,10 @@ out of. The MCP equivalent is
|
|
|
481
486
|
\`request_policy_override\`; over REST, an intent with a \`policy_override\`
|
|
482
487
|
action.
|
|
483
488
|
|
|
484
|
-
One request may be pending per agent
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
rather than re-asking.
|
|
489
|
+
One request may be pending per agent, independently of idempotency keys.
|
|
490
|
+
Repeating it returns the pending one. Different limits with the same key return
|
|
491
|
+
409; with a fresh key they are not recorded — the reply says so, and the person
|
|
492
|
+
still sees the original. Wait for a decision rather than re-asking.
|
|
488
493
|
|
|
489
494
|
Status follows the usual intent vocabulary, with two collapses worth knowing:
|
|
490
495
|
a person declining shows as \`blocked\`, not a state of its own, and should not
|
|
@@ -499,24 +504,31 @@ them until the override expires.
|
|
|
499
504
|
|
|
500
505
|
## Intents
|
|
501
506
|
|
|
502
|
-
Money movement
|
|
503
|
-
|
|
504
|
-
raw backend status
|
|
507
|
+
Money movement, counterparty creation, counterparty detail requests, and policy
|
|
508
|
+
override requests return intents. Balance, transaction, and deposit-address
|
|
509
|
+
reads do not. Match the simplified \`.status\` value, not raw backend status
|
|
510
|
+
strings.
|
|
505
511
|
|
|
506
512
|
Treat \`completed\`, \`blocked\`, and \`failed\` as final. Re-check \`pending\` or
|
|
507
513
|
\`processing\` with \`intents get\`; \`pending\` can still advance without agent
|
|
508
514
|
action. \`reasons\` explains policy decisions or approval routing, and should be
|
|
509
515
|
summarized when present.
|
|
510
516
|
|
|
517
|
+
After a policy block is resolved, retrying unchanged inputs with the same key
|
|
518
|
+
creates a new intent evaluated under current policy; the old intent stays
|
|
519
|
+
\`blocked\`. Respect human denials rather than retrying them. A \`failed\`
|
|
520
|
+
intent's key still identifies that failed attempt: use a new key if another
|
|
521
|
+
attempt is appropriate. Never repay a \`completed\` intent as recovery.
|
|
522
|
+
|
|
511
523
|
Re-read current state with:
|
|
512
524
|
|
|
513
525
|
catena intents get int_...
|
|
514
526
|
|
|
515
527
|
\`.data\` carries the result once one exists: the linked transaction for send or
|
|
516
528
|
transfer, or the created counterparty for creation. It is \`null\` when there is
|
|
517
|
-
none yet. A \`send\` or \`transfer\`
|
|
518
|
-
|
|
519
|
-
|
|
529
|
+
none yet. A successful \`send\` or \`transfer\` replay returns the original
|
|
530
|
+
intent's current result, not a second movement. \`.replayed\` identifies a
|
|
531
|
+
returned existing intent; it does not mean the operation executed again.
|
|
520
532
|
|
|
521
533
|
## Output, Exit Codes, and Scripting
|
|
522
534
|
|
|
@@ -554,13 +566,13 @@ you need, tell the Catena team:
|
|
|
554
566
|
|
|
555
567
|
The message must be 1-4000 characters and is write-only. Longer messages can be
|
|
556
568
|
piped on stdin instead of passed as an argument.
|
|
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
|
|
559
|
-
Catena — Agent Setup`),console.log(`─`.repeat(25));let c=
|
|
560
|
-
Failed to link agent. Run the command again to try again.`),await c.save(s,
|
|
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&&
|
|
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(
|
|
569
|
+
`}const lu=l({meta:{name:`guide`,description:`Print the Catena CLI agent operating guide`},run(){console.log(cu(se))}}),uu=Q({id:ss({description:`Intent id (e.g. int_…)`,required:!0,schema:Cs}),profile:bs,json:xs}),du=l({meta:{name:`get`,description:`Look up the current state of an intent created by this agent`},args:uu.args,async run({args:e}){let t=uu.parse(e);await $(t)(e=>e.getIntent(t.id))}}),fu=l({meta:{name:`intents`,description:`Inspect intent receipts returned by governed operations`},subCommands:{get:du}});function pu(e=process.env,t=process.platform){return!!(e.SSH_CONNECTION||e.SSH_TTY||t===`linux`&&!e.DISPLAY&&!e.WAYLAND_DISPLAY)}function mu(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 hu(e){e&&process.stderr.write(`Failed to open browser: ${e.message}\n`)}function gu(e){process.platform===`darwin`?y(`open`,[e],hu):process.platform===`win32`?y(`cmd`,[`/c`,`start`,``,e],hu):y(`xdg-open`,[e],hu)}function _u(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 vu(e){return typeof e!=`object`||!e||!(`access_token`in e)?!1:typeof e.access_token==`string`}function yu(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 bu(e){if(typeof e!=`object`||!e)return!1;let t=e;return ks.some(e=>e===t.status)&&(t.publicKeyHex===void 0||typeof t.publicKeyHex==`string`)&&(t.reason===void 0||typeof t.reason==`string`)}async function xu(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=il(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:_u(await m.json().catch(()=>({message:`Token exchange failed`})))??m.statusText};let h=await m.json();if(!vu(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:_u(await _.json().catch(()=>({message:`Claim failed`})))??_.statusText};let v=await _.json();return yu(v)?Su({bankUrl:t,claim:v,clientInstanceId:o,signerKeypair:g,identityHeaders:p,log:l}):{ok:!1,message:`Claim response missing required fields`}}async function Su(e){let{bankUrl:t,claim:n,clientInstanceId:r,signerKeypair:i,identityHeaders:a}=e;(e.log??(()=>{}))(`Registering signer...`);let o=await wu({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 Cu(e){return typeof e!=`object`||!e||!(`signer`in e)?!1:bu(e.signer)}async function wu(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 Cu(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 Eu(e){return`${e}-signer`}async function Du(e,t){let n=await e.resolve(t);if(n!==null&&`signer`in n)return n.signer;let r=await e.resolve(Eu(t));if(r!==null&&`signer`in r)return r.signer}async function Ou(e,t,n=ra){let r=await Du(e,t);if(r!==void 0)return r;let i=Us(n());return await e.save(Eu(t),i),i.signer}const ku=[53682,53683,53684,53685,53686,53687];function Au(e){return new Promise((t,n)=>{let r=0,i=()=>{if(r>=ku.length){n(Error(`No registered loopback callback ports are available`));return}let a=ku[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 ju(e){let{bankUrl:t,agentId:n,clientInstanceId:r,clientId:i,clientLabel:a,timeoutMs:o=3e5,log:s=()=>{},appInfo:c,existingSigner:l}=e;vc(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=_u(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 xu({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)}Au(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...`),gu(r),s(`If browser didn't open, visit: ${r}`)}).catch(b),v=setTimeout(()=>{x(`Timed out waiting for authentication`)},o),v.unref()})}function Mu(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 Nu(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 Pu(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 Iu(e){let{bankUrl:t,clientInstanceId:n,onUserCode:r,log:i=()=>{},appInfo:a,existingSigner:o,generateSignerKeypair:s=ra,sleep:c=Pu}=e;vc(t,`bankUrl`);let l=il(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(Nu(await d.json().catch(()=>null)).message??d.statusText);let f=await d.json();if(!Mu(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 Lu({bankUrl:t,grant:f,identityHeaders:l,sleep:c});if(!p.ok)return u(p.message);let m=p.body;if(!yu(m))return u(`Device token response missing required fields`);i(`Approved. Claiming agent...`);let h=await Su({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 Lu(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=Nu(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 Ru(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 zu(e){let{bankUrl:t,clientInstanceId:n,onUserCode:r,log:i=()=>{},appInfo:a,sleep:o=Pu}=e;vc(t,`bankUrl`);let s=il(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=Nu(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(!Mu(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 Lu({bankUrl:t,grant:f,identityHeaders:s,sleep:o});return p.ok?yu(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`):Ru(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 Bu=Q({"agent-id":ss({description:`Optional agent ID shown in the Catena console; omit to create and link a new agent`,schema:Cs}),"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:ls({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:ls({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:bs}),Vu=/^0[23][0-9a-f]{64}$/;function Hu(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 Uu(e){console.log(`
|
|
570
|
+
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 Wu(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 Gu({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 Ku(e){let t=h(`sha256`).update(E(process.cwd())).digest(`hex`).slice(0,16);return`${Yc(e??`agent`).slice(0,47)}-${t}`}function qu(e){try{let t=process.cwd();if(mu(t))return null;let n=Bc(t);return{directory:Vc(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 Ju=l({meta:{name:`link`,description:`Link an existing agent, or create and link a new agent when agent-id is omitted`},args:Bu.args,async run({args:e}){let t=Bu.parse(e),n=t[`bank-url`],r=t[`agent-id`],i=t.name;if(t.service){await Yu({bankUrl:n,agentId:r,suggestedAgentName:i,publicKeyHex:t[`public-key`]});return}let a,o,s;try{if(vc(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=ll({flag:vl(t),cwd:process.cwd(),log:e=>console.error(e)});a=(e!==null&&e.source!=="default"?e.name:null)??(r===void 0?null:Ic(r,n)),o=a??(r===void 0?Ku(i):Yc(r)),s=Gc(o,{bank_url:n,agent_id:r})}catch(e){X(e)}console.log(`
|
|
571
|
+
Catena — Agent Setup`),console.log(`─`.repeat(25));let c=mc(),l=await Ou(c,s),u={bankUrl:n,clientInstanceId:s,log:e=>console.log(` ${e}`),appInfo:el,existingSigner:l},d=Gu({agentId:r,suggestedAgentName:i,browserRequested:t.browser,isHeadless:pu});d.kind===`device-link`&&d.notice!==void 0&&console.log(` ${d.notice}`);let f=d.kind===`pkce-link`?await ju({...u,agentId:d.agentId,clientId:`catena-cli`,timeoutMs:3e5}):await Iu({...u,...d.deviceTarget,onUserCode:Hu});f||X(`
|
|
572
|
+
Failed to link agent. Run the command again to try again.`),await c.save(s,Gs(f.signer));let p=a??Xc(Yc(f.agentName),e=>e!==o&&Uc(e)!==null);try{p===o?Nc(p,{bank_url:n,agent_id:f.agentId,client_instance_id:s}):Zc({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=qu(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 ${ol}=${p}`),console.log(`\nDone. Agent "${f.agentName}" linked.`),process.exit(0)}});async function Yu(e){try{if(vc(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(`
|
|
573
|
+
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&&Uu({publicKeyHex:n,privateKeyHex:t.privateKeyHex})},s;try{s=await zu({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,Hu(e)},log:e=>console.log(` ${e}`),appInfo:el})}catch(e){o(),X(e)}s||(o(),X(`
|
|
574
|
+
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(Wu(s.signerReason)):console.log(` Wallet-send signer: not registered (${s.signerReason??s.signerStatus}); retry after checking the link status`),console.log(`
|
|
563
575
|
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(`
|
|
564
576
|
The private key is shown once and is not stored on this machine.`),process.exit(0)}
|
|
565
577
|
/*! decimal.js-light v2.5.1 https://github.com/MikeMcl/decimal.js-light/LICENCE */
|
|
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{};
|
|
578
|
+
const Xu=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;Xu.set({rounding:Xu.ROUND_HALF_EVEN});const Zu=new Map,Qu=/^[A-Z]{3}$/,$u=/^[A-Z0-9]{2,6}$/;function ed(e,t,n,r){if(Zu.has(e))throw Error(`duplicate asset id ${e}`);let i=new Xu(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 td(e,t,n,r,i){if(!Qu.test(e))throw Error(`fiat asset ids must be 3-letter ISO-4217 codes`);ed(e,n,r,i.dustThreshold);let a=e;return Zu.set(e,{id:a,symbol:e,name:t,kind:`fiat`,decimals:n,presentmentDecimals:r,denomination:e,valuation:{type:`par`},dustThreshold:i.dustThreshold}),a}function nd(e,t,n,r,i){if(!$u.test(e)||Qu.test(e))throw Error(`stablecoin tickers must be 2-6 uppercase alphanumerics and not a 3-letter ISO-4217 shape`);let a=Zu.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})`);ed(e,n,r,i.dustThreshold);let o=e;return Zu.set(e,{id:o,symbol:e,name:t,kind:`stablecoin`,decimals:n,presentmentDecimals:r,denomination:a.denomination,valuation:{type:`par`},dustThreshold:i.dustThreshold}),o}nd(`USDC`,`USD Coin`,6,2,{denomination:td(`USD`,`US Dollar`,6,2,{dustThreshold:`0.01`}),dustThreshold:`0.01`}),new Xu(1e6),new Xu(1e3);const rd=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 Xu(e).gte(0)}catch{return!1}},`Amount must be a valid decimal (e.g. 100 or 100.50)`)),id=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`)),ad={s:1,m:60,h:3600,d:86400},od=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 ad?Number(e.slice(0,-1))*ad[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`)),sd=Q({profile:bs,json:xs}),cd=l({meta:{name:`show`,description:`Show the agent's assigned policy`},args:sd.args,async run({args:e}){await $(sd.parse(e))(e=>e.getPolicy())}}),ld=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:us({description:`Which capability's limit to increase: send (payments to counterparties) or transfer (between the user's own accounts)`,choices:Io,default:`send`}),rule:us({description:`Which limit to adjust`,choices:Xa,default:`per_transaction_amount`}),amount:Z({description:`New threshold for an amount limit, as a decimal USD string (e.g. 500.00)`,schema:rd,showValueInError:!0}),count:Z({description:`New threshold for a transaction-count limit (e.g. 20)`,schema:id,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:od,showValueInError:!0}),reason:Z({description:`Why the task needs this, for the person who reviews the request`,required:!0}),idempotencyKey:Z({description:`Optional operation key. Reuse the same value only when retrying the same submission; omitted generates a fresh key for this invocation.`,schema:Nl}),profile:bs,json:xs}),ud=l({meta:{name:`request-override`,description:`Ask a person to approve a temporary change to this agent's limits`},args:ld.args,async run({args:e}){let t=ld.parse(e),n=$(t),r={type:`policy_override`,operations:[dd(t)],durationSeconds:t.duration,reason:t.reason};await n(e=>e.submitIntent({action:r,...t.idempotencyKey!==void 0&&{idempotencyKey:t.idempotencyKey}}))}});function dd(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 fd=l({meta:{name:`policy`,description:`Inspect the agent's policy`},subCommands:{show:cd,"request-override":ud}}),pd=Q({profile:ss({description:`Profile name`,required:!0})});function md(){try{return ul({env:process.env[ol],cwd:process.cwd(),log:e=>console.error(e)})}catch(e){return X(e)}}const hd=l({meta:{name:`use`,description:`Set the default credential profile`},args:pd.args,async run({args:e}){let t=pd.parse(e);try{Jc(t.profile),_l({defaultProfile:t.profile})}catch(e){X(e)}}}),gd=l({meta:{name:`current`,description:`Show the selected credential profile and how it was chosen`},async run(){let e=md(),t;try{t=Uc(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.`),_l({profile:e.name,source:e.source,bankUrl:t.bank_url,agentId:Pc(t)?t.agent_id:void 0})}}),_d=l({meta:{name:`list`,description:`List credential profiles and their directory bindings`},async run(){let e;try{e=Ac()}catch(e){X(e)}let t;try{t=ul({env:process.env[ol],cwd:process.cwd()}).name}catch{t=null}let n=Object.entries(e.directories??{});_l({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:Pc(r)?r.agent_id:void 0,directories:n.filter(([,t])=>t===e).map(([e])=>e).toSorted(),current:e===t}))})}}),vd=Q({profile:ss({description:`Profile name to bind`,required:!0}),path:ss({description:`Directory to bind (defaults to the current directory)`})}),yd=l({meta:{name:`bind`,description:`Bind a directory to a profile for automatic selection`},args:vd.args,async run({args:e}){let t=vd.parse(e);try{let e=t.path??process.cwd();if(mu(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);_l({profile:t.profile,directory:n})}catch(e){X(e)}}}),bd=Q({path:ss({description:`Directory to unbind (defaults to the current directory)`})}),xd=l({meta:{name:`unbind`,description:`Remove a directory's profile binding`},args:bd.args,async run({args:e}){let t=bd.parse(e);try{_l(Hc(t.path??process.cwd()))}catch(e){X(e)}}}),Sd=l({meta:{name:`profiles`,description:`Manage credential profiles`},subCommands:{use:hd,current:gd,list:_d,bind:yd,unbind:xd}}),Cd=Q({account:Z({description:`Source account id`,required:!0,schema:Cs}),rail:Z({description:`Destination counterparty rail id (cprl_...)`,required:!0,schema:Cs}),amount:Z({description:`USD amount as a decimal string (e.g. 125.00)`,required:!0,schema:rd,showValueInError:!0}),method:us({description:`ach | wire | on-chain; ach and wire require a bank rail, on-chain a wallet rail`,required:!0,choices:uo}),memo:Z({description:`Memo on the underlying transfer`}),description:Z({description:`Operator-facing description`}),idempotencyKey:Z({description:`Optional operation key. Reuse the same value only when retrying the same submission; omitted generates a fresh key for this invocation.`,schema:Nl}),profile:bs,json:xs}),wd=l({meta:{name:`send`,description:`Submit a USD send intent to a counterparty rail`},args:Cd.args,async run({args:e}){let t=Cd.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:Cs}),to:Z({description:`Destination account id`,required:!0,schema:Cs}),amount:Z({description:`USD amount as a decimal string (e.g. 125.00)`,required:!0,schema:rd,showValueInError:!0}),memo:Z({description:`Memo on the underlying transfer`}),description:Z({description:`Operator-facing description`}),idempotencyKey:Z({description:`Optional operation key. Reuse the same value only when retrying the same submission; omitted generates a fresh key for this invocation.`,schema:Nl}),profile:bs,json:xs}),Ed=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}:{}}))}}),Dd=Q({profile:bs,force:ls({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:xs}),Od=l({meta:{name:`unlink`,description:`Disconnect the selected agent profile`},args:Dd.args,async run({args:e}){let t=Dd.parse(e),n=fl(),r;try{r=ul({flag:vl(t),env:process.env[ol],cwd:process.cwd(),log:e=>console.error(e)}).name}catch(e){X(e)}if(t.force){let e;try{if(e=Uc(r),e===null)throw Error(`Profile "${r}" not found`);await n.delete(e.client_instance_id),await n.delete(Eu(e.client_instance_id)),Rc(r)}catch(e){X(e)}_l({success:!0,profile:r,...Pc(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 $c({profileName:r,fallbackBankUrl:al},n);a.ok||X(`${a.message} ${i}`);let o=dl(a);try{await o.unlinkAgent(),await n.delete(a.clientInstanceId),await n.delete(Eu(a.clientInstanceId)),Rc(r)}catch(e){X(`${$o(gl(e,r))} ${i}`)}_l({success:!0,profile:r,agentId:a.agentId},{compact:t.json})}}),kd=Q({profile:bs,json:xs}),Ad=l({meta:{name:`whoami`,description:`Show which agent you are currently acting as`},args:kd.args,async run({args:e}){await $(kd.parse(e))(e=>e.whoami())}});function jd(e){throw Error(`Unhandled case: ${String(e)}`)}const Md=[`PAYMENT-REQUIRED`,`X-Payment-Required`],Nd=/^0x[0-9a-fA-F]{64}$/,Pd=/^0x[0-9a-fA-F]{40}$/,Fd=f.looseObject({success:f.boolean(),transaction:f.string(),extensions:f.optional(f.unknown())}),Id=f.looseObject({x402Version:f.literal(2),accepts:f.array(Ao),resource:f.optional(jo),extensions:f.optional(f.unknown())}),Ld=`x402_network_mismatch`,Rd=`x402_counterparty_rail_not_found`,zd=new Set([`x402_requirement_not_payable`,Ld,Rd]),Bd={"eip155:8453":`Base`,"eip155:84532":`Base Sepolia`};function Vd(e){let t=Object.hasOwn(Bd,e)?Bd[e]:void 0;return t?`${t} (${e})`:e}function Hd(e){let t=e.replaceAll(`-`,`+`).replaceAll(`_`,`/`),n=Uint8Array.from(atob(t),e=>e.charCodeAt(0));return JSON.parse(new TextDecoder().decode(n))}function Ud(e){let t=Md.map(t=>e.headers.get(t)).find(e=>e!==null);if(t)try{let e=f.safeParse(Id,Hd(t));return e.success?e.output:void 0}catch{return}}async function Wd(e,t,n){try{let r=n.headers.get(`PAYMENT-RESPONSE`);if(!r)return;let i=f.safeParse(Fd,Hd(r));if(!i.success||!i.output.success||!Nd.test(i.output.transaction))return;let a=Ha(i.output.extensions);await e.reportSettlement({intentId:t,txHash:i.output.transaction,...a!==void 0&&{receipt:a}})}catch{}}var Gd=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}},Kd=class extends Gd{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}},qd=class extends Gd{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}},Jd=class extends Gd{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}},Yd=class extends Gd{receipt;constructor(e,t){super(`The payment settled (intent ${e.intentId}) but the post-payment continuation failed; retry the request with the PAYMENT-SIGNATURE header from the receipt (or getIntent("${e.intentId}") data.paymentCredential.value) instead of paying again`),this.name=`X402RetryFailedError`,this.receipt=e,this.cause=t}};async function Xd(e,t){try{return await t()}catch(t){throw new Yd(e,t)}}var Zd=class extends Gd{intentId;requirements;constructor(e,t,n){super(`The payment could not be confirmed (intent ${e}); check getIntent("${e}") — completed: reuse its data.paymentCredential.value as the PAYMENT-SIGNATURE header; processing: poll until terminal; pay again only after blocked or failed`),this.name=`X402SubmitInterruptedError`,this.intentId=e,this.requirements=t,this.cause=n}};async function Qd(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 Gd(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 $d(e,{accountId:t.accountId,requirements:n,resource:i,signedOffer:Va(t.paymentRequired.extensions,n)}).catch(e=>{if(e instanceof Wo&&e.code!==void 0&&zd.has(e.code)){a.push({error:e,requirement:n});return}throw e});if(r)return r}let o=a.filter(e=>e.error.code===Rd),s=a.filter(e=>e.error.code===Ld),c=a.filter(e=>e.error.code!==Rd&&e.error.code!==Ld),l=[...new Set([...o,...s,...c].map(e=>e.error.message))],u=o.find(e=>e.error.status===404&&Pd.test(e.requirement.payTo));throw u?new qd(u.requirement.payTo,u.requirement.network,i?.serviceName,l):s.length>0&&o.length===0?new Kd(t.accountId,[...new Set(s.map(e=>e.requirement.network))],l):new Gd(`No requirement in the 402 challenge is payable from this account`,l)}async function $d(e,t){let n=await e.submitIntent({action:{type:`x402`,accountId:t.accountId,paymentRequirements:t.requirements,...t.resource!==void 0&&{resource:t.resource},...t.signedOffer!==void 0&&{signedOffer:t.signedOffer}},idempotencyKey:crypto.randomUUID()}).catch(e=>{throw e instanceof Yo&&e.outcome===`unknown`?new Zd(e.intentId,t.requirements,e):e});if(n.status===`completed`){let e=Co(n.data);if(e!==void 0)return{intentId:n.id,paymentSignature:e,requirements:t.requirements};throw new Gd(`The completed payment did not carry an x402 payment signature`)}switch(n.status){case`pending`:throw new Jd(n.id,n.reasons,n.expiresAt);case`processing`:throw new Gd(`The payment is still processing (intent ${n.id}); this client cannot resume an in-flight x402 settlement`);case`blocked`:case`failed`:throw new Gd(`Catena declined the payment`,n.reasons)}return jd(n.status)}function ef(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 tf(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=Ud(a);if(!o)return a;if(!ef(r,i))throw new Gd(`The request body cannot be replayed after payment; buffer the body (string, Blob, or ArrayBuffer) before using the x402 fetch wrapper`);let s=await Qd(e,{accountId:t.accountId,paymentRequired:o,...t.maxAtomicAmount!==void 0&&{maxAtomicAmount:t.maxAtomicAmount}});await Xd(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 Xd(s,()=>n(r,{...i,headers:c}));return Wd(e,s.intentId,l),l}}function nf(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 rf=4e3;function af(e){try{return k(e)}catch{return}}function of(e,t,n){try{x(e,t)}catch{X(n)}}function sf(e){let t=re(e),n=M(t),r=af(n);(r===void 0||!r.isDirectory())&&X(`--output ${e}: directory ${n} does not exist`);let i=af(t);return i===void 0?(of(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`),of(t,C.W_OK,`--output ${e}: destination is not writable`),t)}const cf=/^(?:con|prn|aux|nul|com\d|lpt\d)$/i;function lf(e){if(e!==void 0&&Ss.test(e)&&!cf.test(e))return`${e}.body`;let t=`${Date.now()}-${_(4).toString(`hex`)}.body`;return e===void 0?`unpaid-${t}`:`paid-${t}`}function uf(e,t){let n=nf(wc(),`responses`);if(n===void 0)return;let r=ne(n,lf(t));try{return A(r,e,{mode:384}),r}catch{return}}function df(e){let t=e.subarray(0,rf*4),n=t.toString(`utf8`);return{decoded:n,complete:t.length===e.length&&n.length<=rf&&ae(e)}}function ff({decoded:e,complete:t}){let n=e.slice(0,rf),r=n.charCodeAt(n.length-1);return{body:r>=55296&&r<=56319?n.slice(0,-1):n,...!t&&{bodyTruncated:!0}}}function pf(e,t){if(t.complete)return{body:t.decoded};if(e.length>268435456)return{...ff(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 mf(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 hf(e,t,n){let r=uf(e,t);return r===void 0?pf(e,n):{...ff(n),bodyPath:r}}function gf(e,t,n){let r=df(e);if(n===void 0)return r.complete?{body:r.decoded}:hf(e,t,r);try{A(n,e,{mode:384})}catch(i){let a=hf(e,t,r),o=`--output ${n}: ${$o(i)}`;return`bodyPath`in a?{...a,error:`${o}; the full body was saved to ${a.bodyPath}`}:{...a,error:`${o}; ${mf(a)}`}}return{...ff(r),bodyPath:n}}function _f(e){if(e===`@-`)return vf(0,`stdin`);if(e.startsWith(`@`)){let t=e.slice(1);return t===``?X(`--data @<path>: no file path given`):vf(t,`@${t}`)}return e}function vf(e,t){try{return ee(e,`utf8`)}catch(e){return X(`--data ${t}: ${$o(e)}`)}}function yf(e){let[t,n=``]=e.split(`.`);return BigInt(`${t}${n.padEnd(6,`0`)}`)}function bf(e){return{intentId:e.intentId,amountAtomicUsdc:e.requirements.amount,payTo:e.requirements.payTo,network:e.requirements.network}}const xf={"eip155:8453":`base`,"eip155:84532":`base-sepolia`};function Sf(e){return Object.hasOwn(xf,e)?xf[e]:void 0}function Cf(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function wf(e){return e===void 0?``:` --profile ${Cf(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 Ef(e,t,n,r){let i=Sf(t)??Cf(t);return`catena counterparties create wallet --name ${Cf(n??`<name>`)} --address ${Cf(e)} --network ${i}${wf(r)}`}const Df=f.pipe(f.string(),f.check(e=>tl.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 kf(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 Af(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 jf=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:Cs}),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:us({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:cs({description:`Request header as "Name: Value" (repeatable, like curl -H); sent on the initial request and the paid retry`,schema:Df}),profile:bs,json:xs}),Mf=l({meta:{name:`x402`,description:`Fetch a URL, paying its x402 (HTTP 402) challenge via USDC`},args:jf.args,async run({args:e,rawArgs:t}){let n=jf.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`),kf(n.header,n.contentType);let i=n.output===void 0?void 0:sf(n.output),a=n.data===void 0?void 0:_f(n.data),o=Af(n.header,n.contentType,a);await $(n)(async e=>{let t,s=tf(e,{accountId:n.account,...n.maxAmount!==void 0&&{maxAtomicAmount:yf(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 Yd)return{status:null,paid:!0,retryFailed:!0,payment:bf(e.receipt),error:e.message};if(e instanceof Kd){let t=e.requiredNetworks.map(e=>Sf(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${wf(n.profile)}\`).`}}if(e instanceof qd){let t=Tf(e.serviceName),r=t!==void 0&&t.length<=40?t:void 0,i=Ef(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:Sf(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 Jd)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:bf(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}${wf(n.profile)}\` to retry manually`;return{...l,error:`failed to read the response body: ${$o(e)}${r}`}}return{...l,...gf(u,t?.intentId,i)}},{exitCode:e=>+(`error`in e)})}}),Nf=f.object({version:f.literal(1),result:f.literal(`latest-version`),latestVersion:f.string(),checkedAt:f.pipe(f.string(),f.isoTimestamp())}),Pf=f.object({version:f.literal(1),result:f.literal(`fetch-failure`),checkedAt:f.pipe(f.string(),f.isoTimestamp())}),Ff=f.variant(`result`,[Nf,Pf]),If=f.object({"dist-tags":f.object({latest:f.string()})}),Lf=`cache`;function Rf(){return ne(wc(),Lf,`cli-version.json`)}function zf(e){return new URL(encodeURIComponent(e),`https://registry.npmjs.org/`).href}function Bf(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=Bf(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 Hf(e){try{return!w(e)||k(e).isFile()}catch{return!1}}function Uf(e){let t=nf(wc(),Lf);if(t===void 0||!Hf(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 Wf(e,t){if(nf(wc(),Lf)===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 Gf(e){let t=new AbortController,n=setTimeout(()=>t.abort(),750);n.unref();try{let n=await fetch(zf(e.packageName),{headers:{accept:`application/json`},signal:t.signal});if(!n.ok)return;let r=await n.json(),i=f.safeParse(If,r);return i.success?i.output[`dist-tags`].latest:void 0}catch{return}finally{clearTimeout(n)}}function Kf(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 qf({packageName:e,currentVersion:t}){let n=Rf(),r=Vf(n);if(r?.result===`latest-version`){Kf({packageName:e,currentVersion:t,latestVersion:r.latestVersion});return}if(r?.result===`fetch-failure`||!Uf(n))return;let i=await Gf({packageName:e});if(i===void 0){Wf(n,{result:`fetch-failure`});return}Wf(n,{result:`latest-version`,latestVersion:i}),Kf({packageName:e,currentVersion:t,latestVersion:i})}async function Jf(e){return typeof e==`function`?await e():await e}async function Yf(e){return typeof e==`function`?await e():await e}async function Xf(e){return typeof e==`function`?await e():await e}async function Zf(e,t,n=[]){if(e===t)return n;let r=await Xf(e.subCommands??{});return(await Promise.all(Object.entries(r).map(async([e,r])=>Zf(await Jf(r),t,[...n,e])))).find(e=>e!==void 0)}async function Qf(e,t){if(!e||!t||t.length<2)return e;let n=await Yf(e.meta??{});return{...e,meta:{...n,name:t.slice(0,-1).join(` `)}}}function $f(e){return async(t,n)=>{let r=await u(t,await Qf(n,await Zf(e,t)));console.log(`${r}\n`)}}function ep({shouldCheckCliVersionFreshness:e}){return l({meta:{name:`catena`,version:se,description:`Catena CLI`},async setup({rawArgs:t}){!e||t.length===0||await qf({packageName:oe,currentVersion:se})},subCommands:{link:Ju,unlink:Od,profiles:Sd,whoami:Ad,policy:fd,accounts:Ml,intents:fu,send:wd,transfer:Ed,x402:Mf,counterparties:nu,feedback:su,guide:lu}})}const tp=ep({shouldCheckCliVersionFreshness:!0});ep({shouldCheckCliVersionFreshness:!1});function np(){d(tp,{showUsage:$f(tp)})}np();export{};
|