@astralbeam/cli 0.30.0 → 0.30.4
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.
|
@@ -1,33 +1,33 @@
|
|
|
1
|
-
import{createRequire as e}from"node:module";import{cwd as t,env as n,pid as r,platform as i,stderr as a,stdin as o,stdout as s}from"node:process";import{notStrictEqual as c,strictEqual as l}from"assert";import{basename as u,dirname as d,extname as f,normalize as p,relative as m,resolve as h}from"path";import{readFileSync as g,readdirSync as
|
|
2
|
-
`).map(e=>e.split(` `)),n=0;return t.forEach(e=>{e.length>1&&
|
|
3
|
-
`)}rowToString(e,t){return this.rasterize(e).forEach((n,r)=>{let i=``;n.forEach((n,a)=>{let{width:o}=e[a],s=this.negatePadding(e[a]),c=n;if(s>
|
|
1
|
+
import{createRequire as e}from"node:module";import{cwd as t,env as n,pid as r,platform as i,stderr as a,stdin as o,stdout as s}from"node:process";import{notStrictEqual as c,strictEqual as l}from"assert";import{basename as u,dirname as d,extname as f,normalize as p,relative as m,resolve as h}from"path";import{readFileSync as g,readdirSync as _,statSync as v,writeFile as ee}from"fs";import{format as y,inspect as te}from"util";import{fileURLToPath as ne}from"url";import{mkdir as re,readFile as b,realpath as x,rename as ie,rm as S,writeFile as C}from"node:fs/promises";import{isIPv4 as w}from"node:net";import{homedir as ae}from"node:os";import{dirname as oe,join as se,resolve as ce,sep as T}from"node:path";import{readFileSync as le}from"node:fs";import{text as ue}from"node:stream/consumers";import{createInterface as E}from"node:readline/promises";var de=Object.defineProperty,D=(e,t)=>{let n={};for(var r in e)de(n,r,{get:e[r],enumerable:!0});return t||de(n,Symbol.toStringTag,{value:`Module`}),n},fe=/* @__PURE__ */ e(import.meta.url);const pe={right:_e,center:k};var me=class{constructor(e){this.width=e.width,this.wrap=e.wrap??!0,this.rows=[]}span(...e){let t=this.div(...e);t.span=!0}resetOutput(){this.rows=[]}div(...e){if(e.length===0&&this.div(``),this.wrap&&this.shouldApplyLayoutDSL(...e)&&typeof e[0]==`string`)return this.applyLayoutDSL(e[0]);let t=e.map(e=>typeof e==`string`?this.colFromString(e):e);return this.rows.push(t),t}shouldApplyLayoutDSL(...e){return e.length===1&&typeof e[0]==`string`&&/[\t\n]/.test(e[0])}applyLayoutDSL(e){let t=e.split(`
|
|
2
|
+
`).map(e=>e.split(` `)),n=0;return t.forEach(e=>{e.length>1&&A.stringWidth(e[0])>n&&(n=Math.min(Math.floor(this.width*.5),A.stringWidth(e[0])))}),t.forEach(e=>{this.div(...e.map((t,r)=>({text:t.trim(),padding:this.measurePadding(t),width:r===0&&e.length>1?n:void 0})))}),this.rows[this.rows.length-1]}colFromString(e){return{text:e,padding:this.measurePadding(e)}}measurePadding(e){let t=A.stripAnsi(e);return[0,t.match(/\s*$/)[0].length,0,t.match(/^\s*/)[0].length]}toString(){let e=[];return this.rows.forEach(t=>{this.rowToString(t,e)}),e.filter(e=>!e.hidden).map(e=>e.text).join(`
|
|
3
|
+
`)}rowToString(e,t){return this.rasterize(e).forEach((n,r)=>{let i=``;n.forEach((n,a)=>{let{width:o}=e[a],s=this.negatePadding(e[a]),c=n;if(s>A.stringWidth(n)&&(c+=` `.repeat(s-A.stringWidth(n))),e[a].align&&e[a].align!==`left`&&this.wrap){let t=pe[e[a].align];c=t(c,s),A.stringWidth(c)<s&&(c+=` `.repeat((o||0)-A.stringWidth(c)-1))}let l=e[a].padding||[0,0,0,0];l[3]&&(i+=` `.repeat(l[3])),i+=he(e[a],c,`| `),i+=c,i+=he(e[a],c,` |`),l[1]&&(i+=` `.repeat(l[1])),r===0&&t.length>0&&(i=this.renderInline(i,t[t.length-1]))}),t.push({text:i.replace(/ +$/,``),span:e.span})}),t}renderInline(e,t){let n=e.match(/^ */),r=n?n[0].length:0,i=t.text,a=A.stringWidth(i.trimRight());return t.span?this.wrap?r<a?e:(t.hidden=!0,i.trimRight()+` `.repeat(r-a)+e.trimLeft()):(t.hidden=!0,i+e):e}rasterize(e){let t=[],n=this.columnWidths(e),r;return e.forEach((e,i)=>{e.width=n[i],r=this.wrap?A.wrap(e.text,this.negatePadding(e),{hard:!0}).split(`
|
|
4
4
|
`):e.text.split(`
|
|
5
|
-
`),e.border&&(r.unshift(`.`+`-`.repeat(this.negatePadding(e)+2)+`.`),r.push(`'`+`-`.repeat(this.negatePadding(e)+2)+`'`)),e.padding&&(r.unshift(...Array(e.padding[0]||0).fill(``)),r.push(...Array(e.padding[2]||0).fill(``))),r.forEach((e,n)=>{t[n]||t.push([]);let r=t[n];for(let e=0;e<i;e++)r[e]===void 0&&r.push(``);r.push(e)})}),t}negatePadding(e){let t=e.width||0;return e.padding&&(t-=(e.padding[3]||0)+(e.padding[1]||0)),e.border&&(t-=4),t}columnWidths(e){if(!this.wrap)return e.map(e=>e.width||
|
|
6
|
-
`),i+=e.charAt(n);return n&&r&&(i=`${n}${i}${r}`),i}function
|
|
5
|
+
`),e.border&&(r.unshift(`.`+`-`.repeat(this.negatePadding(e)+2)+`.`),r.push(`'`+`-`.repeat(this.negatePadding(e)+2)+`'`)),e.padding&&(r.unshift(...Array(e.padding[0]||0).fill(``)),r.push(...Array(e.padding[2]||0).fill(``))),r.forEach((e,n)=>{t[n]||t.push([]);let r=t[n];for(let e=0;e<i;e++)r[e]===void 0&&r.push(``);r.push(e)})}),t}negatePadding(e){let t=e.width||0;return e.padding&&(t-=(e.padding[3]||0)+(e.padding[1]||0)),e.border&&(t-=4),t}columnWidths(e){if(!this.wrap)return e.map(e=>e.width||A.stringWidth(e.text));let t=e.length,n=this.width,r=e.map(e=>{if(e.width)return t--,n-=e.width,e.width}),i=t?Math.floor(n/t):0;return r.map((t,n)=>t===void 0?Math.max(i,ge(e[n])):t)}};function he(e,t,n){return e.border?/[.']-+[.']/.test(t)?``:t.trim().length===0?` `:n:``}function ge(e){let t=e.padding||[],n=1+(t[3]||0)+(t[1]||0);return e.border?n+4:n}function O(){return typeof process==`object`&&process.stdout&&process.stdout.columns?process.stdout.columns:80}function _e(e,t){e=e.trim();let n=A.stringWidth(e);return n<t?` `.repeat(t-n)+e:e}function k(e,t){e=e.trim();let n=A.stringWidth(e);return n>=t?e:` `.repeat(t-n>>1)+e}let A;function ve(e,t){return A=t,new me({width:e?.width||O(),wrap:e?.wrap})}const ye=/* @__PURE__ */ RegExp(`\x1B(?:\\[(?:\\d+[ABCDEFGJKSTm]|\\d+;\\d+[Hfm]|\\d+;\\d+;\\d+m|6n|s|u|\\?25[lh])|\\w)`,`g`);function be(e){return e.replace(ye,``)}function xe(e,t){let[n,r]=e.match(ye)||[``,``];e=be(e);let i=``;for(let n=0;n<e.length;n++)n!==0&&n%t===0&&(i+=`
|
|
6
|
+
`),i+=e.charAt(n);return n&&r&&(i=`${n}${i}${r}`),i}function Se(e){return ve(e,{stringWidth:e=>[...e].length,stripAnsi:be,wrap:xe})}function j(e,t){let n=h(`.`,e),r;for(v(n).isDirectory()||(n=d(n));;){if(r=t(n,_(n)),r)return h(n,r);if(n=d(r=n),r===n)break}}
|
|
7
7
|
/**
|
|
8
8
|
* @license
|
|
9
9
|
* Copyright (c) 2016, Contributors
|
|
10
10
|
* SPDX-License-Identifier: ISC
|
|
11
11
|
*/
|
|
12
|
-
function
|
|
12
|
+
function Ce(e){if((e===e.toLowerCase()||e===e.toUpperCase())&&(e=e.toLowerCase()),e.indexOf(`-`)===-1&&e.indexOf(`_`)===-1)return e;{let t=``,n=!1,r=e.match(/^-+/);for(let i=r?r[0].length:0;i<e.length;i++){let r=e.charAt(i);n&&(n=!1,r=r.toUpperCase()),i!==0&&(r===`-`||r===`_`)?n=!0:r!==`-`&&r!==`_`&&(t+=r)}return t}}function we(e,t){let n=e.toLowerCase();t||=`-`;let r=``;for(let i=0;i<e.length;i++){let a=n.charAt(i),o=e.charAt(i);r+=a!==o&&i>0?`${t}${n.charAt(i)}`:o}return r}function Te(e){return e==null?!1:typeof e==`number`||/^0x[0-9a-f]+$/i.test(e)?!0:!/^0[^.]/.test(e)&&/^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(e)}
|
|
13
13
|
/**
|
|
14
14
|
* @license
|
|
15
15
|
* Copyright (c) 2016, Contributors
|
|
16
16
|
* SPDX-License-Identifier: ISC
|
|
17
17
|
*/
|
|
18
|
-
function
|
|
18
|
+
function Ee(e){if(Array.isArray(e))return e.map(e=>typeof e==`string`?e:e+``);e=e.trim();let t=0,n=null,r=null,i=null,a=[];for(let o=0;o<e.length;o++)n=r,r=e.charAt(o),r===` `&&!i?n!==` `&&t++:(r===i?i=null:(r===`'`||r===`"`)&&!i&&(i=r),a[t]||(a[t]=``),a[t]+=r);return a}
|
|
19
19
|
/**
|
|
20
20
|
* @license
|
|
21
21
|
* Copyright (c) 2016, Contributors
|
|
22
22
|
* SPDX-License-Identifier: ISC
|
|
23
23
|
*/
|
|
24
|
-
var
|
|
24
|
+
var M;(function(e){e.BOOLEAN=`boolean`,e.STRING=`string`,e.NUMBER=`number`,e.ARRAY=`array`})(M||={});
|
|
25
25
|
/**
|
|
26
26
|
* @license
|
|
27
27
|
* Copyright (c) 2016, Contributors
|
|
28
28
|
* SPDX-License-Identifier: ISC
|
|
29
29
|
*/
|
|
30
|
-
let ke;var Ae=class{constructor(e){ke=e}parse(e,t){let n=Object.assign({alias:void 0,array:void 0,boolean:void 0,config:void 0,configObjects:void 0,configuration:void 0,coerce:void 0,count:void 0,default:void 0,envPrefix:void 0,narg:void 0,normalize:void 0,string:void 0,number:void 0,__:void 0,key:void 0},t),r=Oe(e),i=typeof e==`string`,a=je(Object.assign(Object.create(null),n.alias)),o=Object.assign({"boolean-negation":!0,"camel-case-expansion":!0,"combine-arrays":!1,"dot-notation":!0,"duplicate-arguments-array":!0,"flatten-duplicate-arrays":!0,"greedy-arrays":!0,"halt-at-non-option":!1,"nargs-eats-options":!1,"negation-prefix":`no-`,"parse-numbers":!0,"parse-positional-numbers":!0,"populate--":!1,"set-placeholder-key":!1,"short-option-groups":!0,"strip-aliased":!1,"strip-dashed":!1,"unknown-options-as-args":!1},n.configuration),s=Object.assign(Object.create(null),n.default),c=n.configObjects||[],l=n.envPrefix,u=o[`populate--`],d=u?`--`:`_`,f=Object.create(null),p=Object.create(null),m=n.__||ke.format,h={aliases:Object.create(null),arrays:Object.create(null),bools:Object.create(null),strings:Object.create(null),numbers:Object.create(null),counts:Object.create(null),normalize:Object.create(null),configs:Object.create(null),nargs:Object.create(null),coercions:Object.create(null),keys:[]},g=/^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/,ee=RegExp(`^--`+o[`negation-prefix`]+`(.+)`);[].concat(n.array||[]).filter(Boolean).forEach(function(e){let t=typeof e==`object`?e.key:e,n=Object.keys(e).map(function(e){return{boolean:`bools`,string:`strings`,number:`numbers`}[e]}).filter(Boolean).pop();n&&(h[n][t]=!0),h.arrays[t]=!0,h.keys.push(t)}),[].concat(n.boolean||[]).filter(Boolean).forEach(function(e){h.bools[e]=!0,h.keys.push(e)}),[].concat(n.string||[]).filter(Boolean).forEach(function(e){h.strings[e]=!0,h.keys.push(e)}),[].concat(n.number||[]).filter(Boolean).forEach(function(e){h.numbers[e]=!0,h.keys.push(e)}),[].concat(n.count||[]).filter(Boolean).forEach(function(e){h.counts[e]=!0,h.keys.push(e)}),[].concat(n.normalize||[]).filter(Boolean).forEach(function(e){h.normalize[e]=!0,h.keys.push(e)}),typeof n.narg==`object`&&Object.entries(n.narg).forEach(([e,t])=>{typeof t==`number`&&(h.nargs[e]=t,h.keys.push(e))}),typeof n.coerce==`object`&&Object.entries(n.coerce).forEach(([e,t])=>{typeof t==`function`&&(h.coercions[e]=t,h.keys.push(e))}),n.config!==void 0&&(Array.isArray(n.config)||typeof n.config==`string`?[].concat(n.config).filter(Boolean).forEach(function(e){h.configs[e]=!0}):typeof n.config==`object`&&Object.entries(n.config).forEach(([e,t])=>{(typeof t==`boolean`||typeof t==`function`)&&(h.configs[e]=t)})),pe(n.key,a,n.default,h.arrays),Object.keys(s).forEach(function(e){(h.aliases[e]||[]).forEach(function(t){s[t]=s[e]})});let _=null;be();let te=[],v=Object.assign(Object.create(null),{_:[]}),y={};for(let e=0;e<r.length;e++){let t=r[e],n=t.replace(/^-{3,}/,`---`),i,a,s,c,l,u;if(t!==`--`&&/^-/.test(t)&&ge(t))ne(t);else if(n.match(/^---+(=|$)/)){ne(t);continue}else if(t.match(/^--.+=/)||!o[`short-option-groups`]&&t.match(/^-.+=/))c=t.match(/^--?([^=]+)=([\s\S]*)$/),c!==null&&Array.isArray(c)&&c.length>=3&&(T(c[1],h.arrays)?e=b(e,c[1],r,c[2]):T(c[1],h.nargs)===!1?x(c[1],c[2],!0):e=re(e,c[1],r,c[2]));else if(t.match(ee)&&o[`boolean-negation`])c=t.match(ee),c!==null&&Array.isArray(c)&&c.length>=2&&(a=c[1],x(a,T(a,h.arrays)?[!1]:!1));else if(t.match(/^--.+/)||!o[`short-option-groups`]&&t.match(/^-[^-]+/))c=t.match(/^--?(.+)/),c!==null&&Array.isArray(c)&&c.length>=2&&(a=c[1],T(a,h.arrays)?e=b(e,a,r):T(a,h.nargs)===!1?(l=r[e+1],l!==void 0&&(!l.match(/^-/)||l.match(g))&&!T(a,h.bools)&&!T(a,h.counts)||/^(true|false)$/.test(l)?(x(a,l),e++):x(a,_e(a))):e=re(e,a,r));else if(t.match(/^-.\..+=/))c=t.match(/^-([^=]+)=([\s\S]*)$/),c!==null&&Array.isArray(c)&&c.length>=3&&x(c[1],c[2]);else if(t.match(/^-.\..+/)&&!t.match(g))l=r[e+1],c=t.match(/^-(.\..+)/),c!==null&&Array.isArray(c)&&c.length>=2&&(a=c[1],l!==void 0&&!l.match(/^-/)&&!T(a,h.bools)&&!T(a,h.counts)?(x(a,l),e++):x(a,_e(a)));else if(t.match(/^-[^-]+/)&&!t.match(g)){s=t.slice(1,-1).split(``),i=!1;for(let n=0;n<s.length;n++){if(l=t.slice(n+2),s[n+1]&&s[n+1]===`=`){u=t.slice(n+3),a=s[n],T(a,h.arrays)?e=b(e,a,r,u):T(a,h.nargs)===!1?x(a,u):e=re(e,a,r,u),i=!0;break}if(l===`-`)x(s[n],l);else{if(/[A-Za-z]/.test(s[n])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(l)&&T(l,h.bools)===!1||s[n+1]&&s[n+1].match(/\W/)){x(s[n],l),i=!0;break}x(s[n],_e(s[n]))}}a=t.slice(-1)[0],!i&&a!==`-`&&(T(a,h.arrays)?e=b(e,a,r):T(a,h.nargs)===!1?(l=r[e+1],l!==void 0&&(!/^(-|--)[^-]/.test(l)||l.match(g))&&!T(a,h.bools)&&!T(a,h.counts)||/^(true|false)$/.test(l)?(x(a,l),e++):x(a,_e(a))):e=re(e,a,r))}else if(t.match(/^-[0-9]$/)&&t.match(g)&&T(t.slice(1),h.bools))a=t.slice(1),x(a,_e(a));else if(t===`--`){te=r.slice(e+1);break}else if(o[`halt-at-non-option`]){te=r.slice(e);break}else ne(t)}se(v,!0),se(v,!1),ae(v),w(),ue(v,h.aliases,s,!0),ce(v),o[`set-placeholder-key`]&&le(v),Object.keys(h.counts).forEach(function(e){de(v,e.split(`.`))||x(e,0)}),u&&te.length&&(v[d]=[]),te.forEach(function(e){v[d].push(e)}),o[`camel-case-expansion`]&&o[`strip-dashed`]&&Object.keys(v).filter(e=>e!==`--`&&e.includes(`-`)).forEach(e=>{delete v[e]}),o[`strip-aliased`]&&[].concat(...Object.keys(a).map(e=>a[e])).forEach(e=>{o[`camel-case-expansion`]&&e.includes(`-`)&&delete v[e.split(`.`).map(e=>Te(e)).join(`.`)],delete v[e]});function ne(e){let t=C(`_`,e);(typeof t==`string`||typeof t==`number`)&&v._.push(t)}function re(e,t,n,r){let i,a=T(t,h.nargs);if(a=typeof a!=`number`||isNaN(a)?1:a,a===0)return O(r)||(_=Error(m(`Argument unexpected for: %s`,t))),x(t,_e(t)),e;let s=+!O(r);if(o[`nargs-eats-options`])n.length-(e+1)+s<a&&(_=Error(m(`Not enough arguments following: %s`,t))),s=a;else{for(i=e+1;i<n.length&&(!n[i].match(/^-[^0-9]/)||n[i].match(g)||ge(n[i]));i++)s++;s<a&&(_=Error(m(`Not enough arguments following: %s`,t)))}let c=Math.min(s,a);for(!O(r)&&c>0&&(x(t,r),c--),i=e+1;i<c+e+1;i++)x(t,n[i]);return e+c}function b(e,t,n,r){let a=[],c=r||n[e+1],l=T(t,h.nargs);if(T(t,h.bools)&&!/^(true|false)$/.test(c))a.push(!0);else if(O(c)||O(r)&&/^-/.test(c)&&!g.test(c)&&!ge(c)){if(s[t]!==void 0){let e=s[t];a=Array.isArray(e)?e:[e]}}else{O(r)||a.push(ie(t,r,!0));for(let r=e+1;r<n.length&&!(!o[`greedy-arrays`]&&a.length>0||l&&typeof l==`number`&&a.length>=l||(c=n[r],/^-/.test(c)&&!g.test(c)&&!ge(c)));r++)e=r,a.push(ie(t,c,i))}return typeof l==`number`&&(l&&a.length<l||isNaN(l)&&a.length===0)&&(_=Error(m(`Not enough arguments following: %s`,t))),x(t,a),e}function x(e,t,n=i){/-/.test(e)&&o[`camel-case-expansion`]&&S(e,e.split(`.`).map(function(e){return Te(e)}).join(`.`));let r=ie(e,t,n),a=e.split(`.`);fe(v,a,r),h.aliases[e]&&h.aliases[e].forEach(function(e){let t=e.split(`.`);fe(v,t,r)}),a.length>1&&o[`dot-notation`]&&(h.aliases[a[0]]||[]).forEach(function(t){let n=t.split(`.`),i=[].concat(a);i.shift(),n=n.concat(i),(h.aliases[e]||[]).includes(n.join(`.`))||fe(v,n,r)}),T(e,h.normalize)&&!T(e,h.arrays)&&[e].concat(h.aliases[e]||[]).forEach(function(e){Object.defineProperty(y,e,{enumerable:!0,get(){return t},set(e){t=typeof e==`string`?ke.normalize(e):e}})})}function S(e,t){h.aliases[e]&&h.aliases[e].length||(h.aliases[e]=[t],f[t]=!0),h.aliases[t]&&h.aliases[t].length||S(t,e)}function ie(e,t,n){n&&(t=Pe(t)),(T(e,h.bools)||T(e,h.counts))&&typeof t==`string`&&(t=t===`true`);let r=Array.isArray(t)?t.map(function(t){return C(e,t)}):C(e,t);return T(e,h.counts)&&(O(r)||typeof r==`boolean`)&&(r=Me()),T(e,h.normalize)&&T(e,h.arrays)&&(r=Array.isArray(t)?t.map(e=>ke.normalize(e)):ke.normalize(t)),r}function C(e,t){return!o[`parse-positional-numbers`]&&e===`_`||!T(e,h.strings)&&!T(e,h.bools)&&!Array.isArray(t)&&(De(t)&&o[`parse-numbers`]&&Number.isSafeInteger(Math.floor(parseFloat(`${t}`)))||!O(t)&&T(e,h.numbers))&&(t=Number(t)),t}function ae(e){let t=Object.create(null);ue(t,h.aliases,s),Object.keys(h.configs).forEach(function(n){let r=e[n]||t[n];if(r)try{let e=null,t=ke.resolve(ke.cwd(),r),i=h.configs[n];if(typeof i==`function`){try{e=i(t)}catch(t){e=t}if(e instanceof Error){_=e;return}}else e=ke.require(t);oe(e)}catch(t){t.name===`PermissionDenied`?_=t:e[n]&&(_=Error(m(`Invalid JSON config file: %s`,r)))}})}function oe(e,t){Object.keys(e).forEach(function(n){let r=e[n],i=t?t+`.`+n:n;typeof r==`object`&&r&&!Array.isArray(r)&&o[`dot-notation`]?oe(r,i):(!de(v,i.split(`.`))||T(i,h.arrays)&&o[`combine-arrays`])&&x(i,r)})}function w(){c!==void 0&&c.forEach(function(e){oe(e)})}function se(e,t){if(l===void 0)return;let n=typeof l==`string`?l:``,r=ke.env();Object.keys(r).forEach(function(i){if(n===``||i.lastIndexOf(n,0)===0){let a=i.split(`__`).map(function(e,t){return t===0&&(e=e.substring(n.length)),Te(e)});(t&&h.configs[a.join(`.`)]||!t)&&!de(e,a)&&x(a.join(`.`),r[i])}})}function ce(e){let t,n=/* @__PURE__ */ new Set;Object.keys(e).forEach(function(r){if(!n.has(r)&&(t=T(r,h.coercions),typeof t==`function`))try{let i=C(r,t(e[r]));[].concat(h.aliases[r]||[],r).forEach(t=>{n.add(t),e[t]=i})}catch(e){_=e}})}function le(e){return h.keys.forEach(t=>{~t.indexOf(`.`)||e[t]===void 0&&(e[t]=void 0)}),e}function ue(e,t,n,r=!1){Object.keys(n).forEach(function(i){de(e,i.split(`.`))||(fe(e,i.split(`.`),n[i]),r&&(p[i]=!0),(t[i]||[]).forEach(function(t){de(e,t.split(`.`))||fe(e,t.split(`.`),n[i])}))})}function de(e,t){let n=e;o[`dot-notation`]||(t=[t.join(`.`)]),t.slice(0,-1).forEach(function(e){n=n[e]||{}});let r=t[t.length-1];return typeof n==`object`&&r in n}function fe(e,t,n){let r=e;o[`dot-notation`]||(t=[t.join(`.`)]),t.slice(0,-1).forEach(function(e){e=Ne(e),typeof r==`object`&&r[e]===void 0&&(r[e]={}),typeof r[e]!=`object`||Array.isArray(r[e])?(Array.isArray(r[e])?r[e].push({}):r[e]=[r[e],{}],r=r[e][r[e].length-1]):r=r[e]});let i=Ne(t[t.length-1]),a=T(t.join(`.`),h.arrays),s=Array.isArray(n),c=o[`duplicate-arguments-array`];!c&&T(i,h.nargs)&&(c=!0,(!O(r[i])&&h.nargs[i]===1||Array.isArray(r[i])&&r[i].length===h.nargs[i])&&(r[i]=void 0)),n===Me()?r[i]=Me(r[i]):Array.isArray(r[i])?c&&a&&s?r[i]=o[`flatten-duplicate-arrays`]?r[i].concat(n):(Array.isArray(r[i][0])?r[i]:[r[i]]).concat([n]):!c&&!!a==!!s?r[i]=n:r[i]=r[i].concat([n]):r[i]===void 0&&a?r[i]=s?n:[n]:c&&!(r[i]===void 0||T(i,h.counts)||T(i,h.bools))?r[i]=[r[i],n]:r[i]=n}function pe(...e){e.forEach(function(e){Object.keys(e||{}).forEach(function(e){h.aliases[e]||(h.aliases[e]=[].concat(a[e]||[]),h.aliases[e].concat(e).forEach(function(t){if(/-/.test(t)&&o[`camel-case-expansion`]){let n=Te(t);n!==e&&h.aliases[e].indexOf(n)===-1&&(h.aliases[e].push(n),f[n]=!0)}}),h.aliases[e].concat(e).forEach(function(t){if(t.length>1&&/[A-Z]/.test(t)&&o[`camel-case-expansion`]){let n=Ee(t,`-`);n!==e&&h.aliases[e].indexOf(n)===-1&&(h.aliases[e].push(n),f[n]=!0)}}),h.aliases[e].forEach(function(t){h.aliases[t]=[e].concat(h.aliases[e].filter(function(e){return t!==e}))}))})})}function T(e,t){let n=[].concat(h.aliases[e]||[],e),r=Object.keys(t),i=n.find(e=>r.includes(e));return i?t[i]:!1}function me(e){let t=Object.keys(h);return[].concat(t.map(e=>h[e])).some(function(t){return Array.isArray(t)?t.includes(e):t[e]})}function he(e,...t){return[].concat(...t).some(function(t){let n=e.match(t);return n&&me(n[1])})}function E(e){if(e.match(g)||!e.match(/^-[^-]+/))return!1;let t=!0,n,r=e.slice(1).split(``);for(let i=0;i<r.length;i++){if(n=e.slice(i+2),!me(r[i])){t=!1;break}if(r[i+1]&&r[i+1]===`=`||n===`-`||/[A-Za-z]/.test(r[i])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(n)||r[i+1]&&r[i+1].match(/\W/))break}return t}function ge(e){return o[`unknown-options-as-args`]&&D(e)}function D(e){return e=e.replace(/^-{3,}/,`--`),e.match(g)||E(e)?!1:!he(e,/^-+([^=]+?)=[\s\S]*$/,ee,/^-+([^=]+?)$/,/^-+([^=]+?)-$/,/^-+([^=]+?\d+)$/,/^-+([^=]+?)\W+.*$/)}function _e(e){return!T(e,h.bools)&&!T(e,h.counts)&&`${e}`in s?s[e]:ve(ye(e))}function ve(e){return{[A.BOOLEAN]:!0,[A.STRING]:``,[A.NUMBER]:void 0,[A.ARRAY]:[]}[e]}function ye(e){let t=A.BOOLEAN;return T(e,h.strings)?t=A.STRING:T(e,h.numbers)?t=A.NUMBER:T(e,h.bools)?t=A.BOOLEAN:T(e,h.arrays)&&(t=A.ARRAY),t}function O(e){return e===void 0}function be(){Object.keys(h.counts).find(e=>T(e,h.arrays)?(_=Error(m(`Invalid configuration: %s, opts.count excludes opts.array.`,e)),!0):T(e,h.nargs)?(_=Error(m(`Invalid configuration: %s, opts.count excludes opts.narg.`,e)),!0):!1)}return{aliases:Object.assign({},h.aliases),argv:Object.assign(y,v),configuration:o,defaulted:Object.assign({},p),error:_,newAliases:Object.assign({},f)}}};function je(e){let t=[],n=Object.create(null),r=!0;for(Object.keys(e).forEach(function(n){t.push([].concat(e[n],n))});r;){r=!1;for(let e=0;e<t.length;e++)for(let n=e+1;n<t.length;n++)if(t[e].filter(function(e){return t[n].indexOf(e)!==-1}).length){t[e]=t[e].concat(t[n]),t.splice(n,1),r=!0;break}}return t.forEach(function(e){e=e.filter(function(e,t,n){return n.indexOf(e)===t});let t=e.pop();t!==void 0&&typeof t==`string`&&(n[t]=e)}),n}function Me(e){return e===void 0?1:e+1}function Ne(e){return e===`__proto__`?`___proto___`:e}function Pe(e){return typeof e==`string`&&(e[0]===`'`||e[0]===`"`)&&e[e.length-1]===e[0]?e.substring(1,e.length-1):e}
|
|
30
|
+
let De;var Oe=class{constructor(e){De=e}parse(e,t){let n=Object.assign({alias:void 0,array:void 0,boolean:void 0,config:void 0,configObjects:void 0,configuration:void 0,coerce:void 0,count:void 0,default:void 0,envPrefix:void 0,narg:void 0,normalize:void 0,string:void 0,number:void 0,__:void 0,key:void 0},t),r=Ee(e),i=typeof e==`string`,a=ke(Object.assign(Object.create(null),n.alias)),o=Object.assign({"boolean-negation":!0,"camel-case-expansion":!0,"combine-arrays":!1,"dot-notation":!0,"duplicate-arguments-array":!0,"flatten-duplicate-arrays":!0,"greedy-arrays":!0,"halt-at-non-option":!1,"nargs-eats-options":!1,"negation-prefix":`no-`,"parse-numbers":!0,"parse-positional-numbers":!0,"populate--":!1,"set-placeholder-key":!1,"short-option-groups":!0,"strip-aliased":!1,"strip-dashed":!1,"unknown-options-as-args":!1},n.configuration),s=Object.assign(Object.create(null),n.default),c=n.configObjects||[],l=n.envPrefix,u=o[`populate--`],d=u?`--`:`_`,f=Object.create(null),p=Object.create(null),m=n.__||De.format,h={aliases:Object.create(null),arrays:Object.create(null),bools:Object.create(null),strings:Object.create(null),numbers:Object.create(null),counts:Object.create(null),normalize:Object.create(null),configs:Object.create(null),nargs:Object.create(null),coercions:Object.create(null),keys:[]},g=/^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/,_=RegExp(`^--`+o[`negation-prefix`]+`(.+)`);[].concat(n.array||[]).filter(Boolean).forEach(function(e){let t=typeof e==`object`?e.key:e,n=Object.keys(e).map(function(e){return{boolean:`bools`,string:`strings`,number:`numbers`}[e]}).filter(Boolean).pop();n&&(h[n][t]=!0),h.arrays[t]=!0,h.keys.push(t)}),[].concat(n.boolean||[]).filter(Boolean).forEach(function(e){h.bools[e]=!0,h.keys.push(e)}),[].concat(n.string||[]).filter(Boolean).forEach(function(e){h.strings[e]=!0,h.keys.push(e)}),[].concat(n.number||[]).filter(Boolean).forEach(function(e){h.numbers[e]=!0,h.keys.push(e)}),[].concat(n.count||[]).filter(Boolean).forEach(function(e){h.counts[e]=!0,h.keys.push(e)}),[].concat(n.normalize||[]).filter(Boolean).forEach(function(e){h.normalize[e]=!0,h.keys.push(e)}),typeof n.narg==`object`&&Object.entries(n.narg).forEach(([e,t])=>{typeof t==`number`&&(h.nargs[e]=t,h.keys.push(e))}),typeof n.coerce==`object`&&Object.entries(n.coerce).forEach(([e,t])=>{typeof t==`function`&&(h.coercions[e]=t,h.keys.push(e))}),n.config!==void 0&&(Array.isArray(n.config)||typeof n.config==`string`?[].concat(n.config).filter(Boolean).forEach(function(e){h.configs[e]=!0}):typeof n.config==`object`&&Object.entries(n.config).forEach(([e,t])=>{(typeof t==`boolean`||typeof t==`function`)&&(h.configs[e]=t)})),de(n.key,a,n.default,h.arrays),Object.keys(s).forEach(function(e){(h.aliases[e]||[]).forEach(function(t){s[t]=s[e]})});let v=null;ve();let ee=[],y=Object.assign(Object.create(null),{_:[]}),te={};for(let e=0;e<r.length;e++){let t=r[e],n=t.replace(/^-{3,}/,`---`),i,a,s,c,l,u;if(t!==`--`&&/^-/.test(t)&&he(t))ne(t);else if(n.match(/^---+(=|$)/)){ne(t);continue}else if(t.match(/^--.+=/)||!o[`short-option-groups`]&&t.match(/^-.+=/))c=t.match(/^--?([^=]+)=([\s\S]*)$/),c!==null&&Array.isArray(c)&&c.length>=3&&(D(c[1],h.arrays)?e=b(e,c[1],r,c[2]):D(c[1],h.nargs)===!1?x(c[1],c[2],!0):e=re(e,c[1],r,c[2]));else if(t.match(_)&&o[`boolean-negation`])c=t.match(_),c!==null&&Array.isArray(c)&&c.length>=2&&(a=c[1],x(a,D(a,h.arrays)?[!1]:!1));else if(t.match(/^--.+/)||!o[`short-option-groups`]&&t.match(/^-[^-]+/))c=t.match(/^--?(.+)/),c!==null&&Array.isArray(c)&&c.length>=2&&(a=c[1],D(a,h.arrays)?e=b(e,a,r):D(a,h.nargs)===!1?(l=r[e+1],l!==void 0&&(!l.match(/^-/)||l.match(g))&&!D(a,h.bools)&&!D(a,h.counts)||/^(true|false)$/.test(l)?(x(a,l),e++):x(a,O(a))):e=re(e,a,r));else if(t.match(/^-.\..+=/))c=t.match(/^-([^=]+)=([\s\S]*)$/),c!==null&&Array.isArray(c)&&c.length>=3&&x(c[1],c[2]);else if(t.match(/^-.\..+/)&&!t.match(g))l=r[e+1],c=t.match(/^-(.\..+)/),c!==null&&Array.isArray(c)&&c.length>=2&&(a=c[1],l!==void 0&&!l.match(/^-/)&&!D(a,h.bools)&&!D(a,h.counts)?(x(a,l),e++):x(a,O(a)));else if(t.match(/^-[^-]+/)&&!t.match(g)){s=t.slice(1,-1).split(``),i=!1;for(let n=0;n<s.length;n++){if(l=t.slice(n+2),s[n+1]&&s[n+1]===`=`){u=t.slice(n+3),a=s[n],D(a,h.arrays)?e=b(e,a,r,u):D(a,h.nargs)===!1?x(a,u):e=re(e,a,r,u),i=!0;break}if(l===`-`)x(s[n],l);else{if(/[A-Za-z]/.test(s[n])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(l)&&D(l,h.bools)===!1||s[n+1]&&s[n+1].match(/\W/)){x(s[n],l),i=!0;break}x(s[n],O(s[n]))}}a=t.slice(-1)[0],!i&&a!==`-`&&(D(a,h.arrays)?e=b(e,a,r):D(a,h.nargs)===!1?(l=r[e+1],l!==void 0&&(!/^(-|--)[^-]/.test(l)||l.match(g))&&!D(a,h.bools)&&!D(a,h.counts)||/^(true|false)$/.test(l)?(x(a,l),e++):x(a,O(a))):e=re(e,a,r))}else if(t.match(/^-[0-9]$/)&&t.match(g)&&D(t.slice(1),h.bools))a=t.slice(1),x(a,O(a));else if(t===`--`){ee=r.slice(e+1);break}else if(o[`halt-at-non-option`]){ee=r.slice(e);break}else ne(t)}se(y,!0),se(y,!1),w(y),oe(),le(y,h.aliases,s,!0),ce(y),o[`set-placeholder-key`]&&T(y),Object.keys(h.counts).forEach(function(e){ue(y,e.split(`.`))||x(e,0)}),u&&ee.length&&(y[d]=[]),ee.forEach(function(e){y[d].push(e)}),o[`camel-case-expansion`]&&o[`strip-dashed`]&&Object.keys(y).filter(e=>e!==`--`&&e.includes(`-`)).forEach(e=>{delete y[e]}),o[`strip-aliased`]&&[].concat(...Object.keys(a).map(e=>a[e])).forEach(e=>{o[`camel-case-expansion`]&&e.includes(`-`)&&delete y[e.split(`.`).map(e=>Ce(e)).join(`.`)],delete y[e]});function ne(e){let t=C(`_`,e);(typeof t==`string`||typeof t==`number`)&&y._.push(t)}function re(e,t,n,r){let i,a=D(t,h.nargs);if(a=typeof a!=`number`||isNaN(a)?1:a,a===0)return A(r)||(v=Error(m(`Argument unexpected for: %s`,t))),x(t,O(t)),e;let s=+!A(r);if(o[`nargs-eats-options`])n.length-(e+1)+s<a&&(v=Error(m(`Not enough arguments following: %s`,t))),s=a;else{for(i=e+1;i<n.length&&(!n[i].match(/^-[^0-9]/)||n[i].match(g)||he(n[i]));i++)s++;s<a&&(v=Error(m(`Not enough arguments following: %s`,t)))}let c=Math.min(s,a);for(!A(r)&&c>0&&(x(t,r),c--),i=e+1;i<c+e+1;i++)x(t,n[i]);return e+c}function b(e,t,n,r){let a=[],c=r||n[e+1],l=D(t,h.nargs);if(D(t,h.bools)&&!/^(true|false)$/.test(c))a.push(!0);else if(A(c)||A(r)&&/^-/.test(c)&&!g.test(c)&&!he(c)){if(s[t]!==void 0){let e=s[t];a=Array.isArray(e)?e:[e]}}else{A(r)||a.push(S(t,r,!0));for(let r=e+1;r<n.length&&!(!o[`greedy-arrays`]&&a.length>0||l&&typeof l==`number`&&a.length>=l||(c=n[r],/^-/.test(c)&&!g.test(c)&&!he(c)));r++)e=r,a.push(S(t,c,i))}return typeof l==`number`&&(l&&a.length<l||isNaN(l)&&a.length===0)&&(v=Error(m(`Not enough arguments following: %s`,t))),x(t,a),e}function x(e,t,n=i){/-/.test(e)&&o[`camel-case-expansion`]&&ie(e,e.split(`.`).map(function(e){return Ce(e)}).join(`.`));let r=S(e,t,n),a=e.split(`.`);E(y,a,r),h.aliases[e]&&h.aliases[e].forEach(function(e){let t=e.split(`.`);E(y,t,r)}),a.length>1&&o[`dot-notation`]&&(h.aliases[a[0]]||[]).forEach(function(t){let n=t.split(`.`),i=[].concat(a);i.shift(),n=n.concat(i),(h.aliases[e]||[]).includes(n.join(`.`))||E(y,n,r)}),D(e,h.normalize)&&!D(e,h.arrays)&&[e].concat(h.aliases[e]||[]).forEach(function(e){Object.defineProperty(te,e,{enumerable:!0,get(){return t},set(e){t=typeof e==`string`?De.normalize(e):e}})})}function ie(e,t){h.aliases[e]&&h.aliases[e].length||(h.aliases[e]=[t],f[t]=!0),h.aliases[t]&&h.aliases[t].length||ie(t,e)}function S(e,t,n){n&&(t=Me(t)),(D(e,h.bools)||D(e,h.counts))&&typeof t==`string`&&(t=t===`true`);let r=Array.isArray(t)?t.map(function(t){return C(e,t)}):C(e,t);return D(e,h.counts)&&(A(r)||typeof r==`boolean`)&&(r=Ae()),D(e,h.normalize)&&D(e,h.arrays)&&(r=Array.isArray(t)?t.map(e=>De.normalize(e)):De.normalize(t)),r}function C(e,t){return!o[`parse-positional-numbers`]&&e===`_`||!D(e,h.strings)&&!D(e,h.bools)&&!Array.isArray(t)&&(Te(t)&&o[`parse-numbers`]&&Number.isSafeInteger(Math.floor(parseFloat(`${t}`)))||!A(t)&&D(e,h.numbers))&&(t=Number(t)),t}function w(e){let t=Object.create(null);le(t,h.aliases,s),Object.keys(h.configs).forEach(function(n){let r=e[n]||t[n];if(r)try{let e=null,t=De.resolve(De.cwd(),r),i=h.configs[n];if(typeof i==`function`){try{e=i(t)}catch(t){e=t}if(e instanceof Error){v=e;return}}else e=De.require(t);ae(e)}catch(t){t.name===`PermissionDenied`?v=t:e[n]&&(v=Error(m(`Invalid JSON config file: %s`,r)))}})}function ae(e,t){Object.keys(e).forEach(function(n){let r=e[n],i=t?t+`.`+n:n;typeof r==`object`&&r&&!Array.isArray(r)&&o[`dot-notation`]?ae(r,i):(!ue(y,i.split(`.`))||D(i,h.arrays)&&o[`combine-arrays`])&&x(i,r)})}function oe(){c!==void 0&&c.forEach(function(e){ae(e)})}function se(e,t){if(l===void 0)return;let n=typeof l==`string`?l:``,r=De.env();Object.keys(r).forEach(function(i){if(n===``||i.lastIndexOf(n,0)===0){let a=i.split(`__`).map(function(e,t){return t===0&&(e=e.substring(n.length)),Ce(e)});(t&&h.configs[a.join(`.`)]||!t)&&!ue(e,a)&&x(a.join(`.`),r[i])}})}function ce(e){let t,n=/* @__PURE__ */ new Set;Object.keys(e).forEach(function(r){if(!n.has(r)&&(t=D(r,h.coercions),typeof t==`function`))try{let i=C(r,t(e[r]));[].concat(h.aliases[r]||[],r).forEach(t=>{n.add(t),e[t]=i})}catch(e){v=e}})}function T(e){return h.keys.forEach(t=>{~t.indexOf(`.`)||e[t]===void 0&&(e[t]=void 0)}),e}function le(e,t,n,r=!1){Object.keys(n).forEach(function(i){ue(e,i.split(`.`))||(E(e,i.split(`.`),n[i]),r&&(p[i]=!0),(t[i]||[]).forEach(function(t){ue(e,t.split(`.`))||E(e,t.split(`.`),n[i])}))})}function ue(e,t){let n=e;o[`dot-notation`]||(t=[t.join(`.`)]),t.slice(0,-1).forEach(function(e){n=n[e]||{}});let r=t[t.length-1];return typeof n==`object`&&r in n}function E(e,t,n){let r=e;o[`dot-notation`]||(t=[t.join(`.`)]),t.slice(0,-1).forEach(function(e){e=je(e),typeof r==`object`&&r[e]===void 0&&(r[e]={}),typeof r[e]!=`object`||Array.isArray(r[e])?(Array.isArray(r[e])?r[e].push({}):r[e]=[r[e],{}],r=r[e][r[e].length-1]):r=r[e]});let i=je(t[t.length-1]),a=D(t.join(`.`),h.arrays),s=Array.isArray(n),c=o[`duplicate-arguments-array`];!c&&D(i,h.nargs)&&(c=!0,(!A(r[i])&&h.nargs[i]===1||Array.isArray(r[i])&&r[i].length===h.nargs[i])&&(r[i]=void 0)),n===Ae()?r[i]=Ae(r[i]):Array.isArray(r[i])?c&&a&&s?r[i]=o[`flatten-duplicate-arrays`]?r[i].concat(n):(Array.isArray(r[i][0])?r[i]:[r[i]]).concat([n]):!c&&!!a==!!s?r[i]=n:r[i]=r[i].concat([n]):r[i]===void 0&&a?r[i]=s?n:[n]:c&&!(r[i]===void 0||D(i,h.counts)||D(i,h.bools))?r[i]=[r[i],n]:r[i]=n}function de(...e){e.forEach(function(e){Object.keys(e||{}).forEach(function(e){h.aliases[e]||(h.aliases[e]=[].concat(a[e]||[]),h.aliases[e].concat(e).forEach(function(t){if(/-/.test(t)&&o[`camel-case-expansion`]){let n=Ce(t);n!==e&&h.aliases[e].indexOf(n)===-1&&(h.aliases[e].push(n),f[n]=!0)}}),h.aliases[e].concat(e).forEach(function(t){if(t.length>1&&/[A-Z]/.test(t)&&o[`camel-case-expansion`]){let n=we(t,`-`);n!==e&&h.aliases[e].indexOf(n)===-1&&(h.aliases[e].push(n),f[n]=!0)}}),h.aliases[e].forEach(function(t){h.aliases[t]=[e].concat(h.aliases[e].filter(function(e){return t!==e}))}))})})}function D(e,t){let n=[].concat(h.aliases[e]||[],e),r=Object.keys(t),i=n.find(e=>r.includes(e));return i?t[i]:!1}function fe(e){let t=Object.keys(h);return[].concat(t.map(e=>h[e])).some(function(t){return Array.isArray(t)?t.includes(e):t[e]})}function pe(e,...t){return[].concat(...t).some(function(t){let n=e.match(t);return n&&fe(n[1])})}function me(e){if(e.match(g)||!e.match(/^-[^-]+/))return!1;let t=!0,n,r=e.slice(1).split(``);for(let i=0;i<r.length;i++){if(n=e.slice(i+2),!fe(r[i])){t=!1;break}if(r[i+1]&&r[i+1]===`=`||n===`-`||/[A-Za-z]/.test(r[i])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(n)||r[i+1]&&r[i+1].match(/\W/))break}return t}function he(e){return o[`unknown-options-as-args`]&&ge(e)}function ge(e){return e=e.replace(/^-{3,}/,`--`),e.match(g)||me(e)?!1:!pe(e,/^-+([^=]+?)=[\s\S]*$/,_,/^-+([^=]+?)$/,/^-+([^=]+?)-$/,/^-+([^=]+?\d+)$/,/^-+([^=]+?)\W+.*$/)}function O(e){return!D(e,h.bools)&&!D(e,h.counts)&&`${e}`in s?s[e]:_e(k(e))}function _e(e){return{[M.BOOLEAN]:!0,[M.STRING]:``,[M.NUMBER]:void 0,[M.ARRAY]:[]}[e]}function k(e){let t=M.BOOLEAN;return D(e,h.strings)?t=M.STRING:D(e,h.numbers)?t=M.NUMBER:D(e,h.bools)?t=M.BOOLEAN:D(e,h.arrays)&&(t=M.ARRAY),t}function A(e){return e===void 0}function ve(){Object.keys(h.counts).find(e=>D(e,h.arrays)?(v=Error(m(`Invalid configuration: %s, opts.count excludes opts.array.`,e)),!0):D(e,h.nargs)?(v=Error(m(`Invalid configuration: %s, opts.count excludes opts.narg.`,e)),!0):!1)}return{aliases:Object.assign({},h.aliases),argv:Object.assign(te,y),configuration:o,defaulted:Object.assign({},p),error:v,newAliases:Object.assign({},f)}}};function ke(e){let t=[],n=Object.create(null),r=!0;for(Object.keys(e).forEach(function(n){t.push([].concat(e[n],n))});r;){r=!1;for(let e=0;e<t.length;e++)for(let n=e+1;n<t.length;n++)if(t[e].filter(function(e){return t[n].indexOf(e)!==-1}).length){t[e]=t[e].concat(t[n]),t.splice(n,1),r=!0;break}}return t.forEach(function(e){e=e.filter(function(e,t,n){return n.indexOf(e)===t});let t=e.pop();t!==void 0&&typeof t==`string`&&(n[t]=e)}),n}function Ae(e){return e===void 0?1:e+1}function je(e){return e===`__proto__`?`___proto___`:e}function Me(e){return typeof e==`string`&&(e[0]===`'`||e[0]===`"`)&&e[e.length-1]===e[0]?e.substring(1,e.length-1):e}
|
|
31
31
|
/**
|
|
32
32
|
* @fileoverview Main entrypoint for libraries using yargs-parser in Node.js
|
|
33
33
|
* CJS and ESM environments.
|
|
@@ -36,8 +36,8 @@ let ke;var Ae=class{constructor(e){ke=e}parse(e,t){let n=Object.assign({alias:vo
|
|
|
36
36
|
* Copyright (c) 2016, Contributors
|
|
37
37
|
* SPDX-License-Identifier: ISC
|
|
38
38
|
*/
|
|
39
|
-
const Fe=process&&process.env&&process.env.YARGS_MIN_NODE_VERSION?Number(process.env.YARGS_MIN_NODE_VERSION):12,Ie=(process==null?void 0:process.versions)?.node??(process==null?void 0:process.version)?.slice(1);if(Ie&&Number(Ie.match(/^([^.]+)/)[1])<Fe)throw Error(`yargs parser supports a minimum Node.js version of ${Fe}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`);const Le=process?process.env:{},Re=new Ae({cwd:process.cwd,env:()=>Le,format:v,normalize:p,resolve:h,require:e=>{if(me!==void 0)return me(e);if(e.match(/\.json$/))return JSON.parse(g(e,`utf8`));throw Error(`only .json config files are supported in ESM`)}}),ze=function(e,t){return Re.parse(e.slice(),t).argv};ze.detailed=function(e,t){return Re.parse(e.slice(),t)},ze.camelCase=Te,ze.decamelize=Ee,ze.looksLikeNumber=De;function j(){return+!Be()}function Be(){return Ve()&&!process.defaultApp}function Ve(){return!!process.versions.electron}function He(){return process.argv[j()]}var M=class e extends Error{constructor(t){super(t||`yargs error`),this.name=`YError`,Error.captureStackTrace&&Error.captureStackTrace(this,e)}},Ue={fs:{readFileSync:g,writeFile:te},format:v,resolve:h,exists:e=>{try{return _(e).isFile()}catch{return!1}}};let We;var Ge=class{constructor(e){e||={},this.directory=e.directory||`./locales`,this.updateFiles=typeof e.updateFiles!=`boolean`||e.updateFiles,this.locale=e.locale||`en`,this.fallbackToLanguage=typeof e.fallbackToLanguage!=`boolean`||e.fallbackToLanguage,this.cache=Object.create(null),this.writeQueue=[]}__(...e){if(typeof arguments[0]!=`string`)return this._taggedLiteral(arguments[0],...arguments);let t=e.shift(),n=function(){};return typeof e[e.length-1]==`function`&&(n=e.pop()),n||=function(){},this.cache[this.locale]||this._readLocaleFile(),!this.cache[this.locale][t]&&this.updateFiles?(this.cache[this.locale][t]=t,this._enqueueWrite({directory:this.directory,locale:this.locale,cb:n})):n(),We.format.apply(We.format,[this.cache[this.locale][t]||t].concat(e))}__n(){let e=Array.prototype.slice.call(arguments),t=e.shift(),n=e.shift(),r=e.shift(),i=function(){};typeof e[e.length-1]==`function`&&(i=e.pop()),this.cache[this.locale]||this._readLocaleFile();let a=r===1?t:n;this.cache[this.locale][t]&&(a=this.cache[this.locale][t][r===1?`one`:`other`]),!this.cache[this.locale][t]&&this.updateFiles?(this.cache[this.locale][t]={one:t,other:n},this._enqueueWrite({directory:this.directory,locale:this.locale,cb:i})):i();let o=[a];return~a.indexOf(`%d`)&&o.push(r),We.format.apply(We.format,o.concat(e))}setLocale(e){this.locale=e}getLocale(){return this.locale}updateLocale(e){this.cache[this.locale]||this._readLocaleFile();for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&(this.cache[this.locale][t]=e[t])}_taggedLiteral(e,...t){let n=``;return e.forEach(function(e,r){let i=t[r+1];n+=e,i!==void 0&&(n+=`%s`)}),this.__.apply(this,[n].concat([].slice.call(t,1)))}_enqueueWrite(e){this.writeQueue.push(e),this.writeQueue.length===1&&this._processWriteQueue()}_processWriteQueue(){let e=this,t=this.writeQueue[0],n=t.directory,r=t.locale,i=t.cb,a=this._resolveLocaleFile(n,r),o=JSON.stringify(this.cache[r],null,2);We.fs.writeFile(a,o,`utf-8`,function(t){e.writeQueue.shift(),e.writeQueue.length>0&&e._processWriteQueue(),i(t)})}_readLocaleFile(){let e={},t=this._resolveLocaleFile(this.directory,this.locale);try{We.fs.readFileSync&&(e=JSON.parse(We.fs.readFileSync(t,`utf-8`)))}catch(n){if(n instanceof SyntaxError&&(n.message=`syntax error in `+t),n.code===`ENOENT`)e={};else throw n}this.cache[this.locale]=e}_resolveLocaleFile(e,t){let n=We.resolve(e,`./`,t+`.json`);if(this.fallbackToLanguage&&!this._fileExistsSync(n)&&~t.lastIndexOf(`_`)){let r=We.resolve(e,`./`,t.split(`_`)[0]+`.json`);this._fileExistsSync(r)&&(n=r)}return n}_fileExistsSync(e){return We.exists(e)}};function Ke(e,t){We=t;let n=new Ge(e);return{__:n.__.bind(n),__n:n.__n.bind(n),setLocale:n.setLocale.bind(n),getLocale:n.getLocale.bind(n),updateLocale:n.updateLocale.bind(n),locale:n.locale}}const qe=e=>Ke(e,Ue),Je=`loading a directory of commands is not supported yet for ESM`;let Ye;try{Ye=ne(import.meta.url)}catch{Ye=process.cwd()}const Xe=Ye.substring(0,Ye.lastIndexOf(`node_modules`));var Ze={assert:{notStrictEqual:c,strictEqual:l},cliui:Ce,findUp:we,getEnv:e=>process.env[e],inspect:y,getCallerFile:()=>{throw new M(Je)},getProcessArgvBin:He,mainFilename:Xe||process.cwd(),Parser:ze,path:{basename:u,dirname:d,extname:f,relative:m,resolve:h},process:{argv:()=>process.argv,cwd:process.cwd,emitWarning:(e,t)=>process.emitWarning(e,t),execPath:()=>process.execPath,exit:process.exit,nextTick:process.nextTick,stdColumns:process.stdout.columns===void 0?null:process.stdout.columns},readFileSync:g,require:()=>{throw new M(`require is not supported by ESM`)},requireDirectory:()=>{throw new M(Je)},stringWidth:e=>[...e].length,y18n:qe({directory:h(Ye,`../../../locales`),updateFiles:!1})};function Qe(e,t,n,r){n.assert.notStrictEqual(e,t,r)}function $e(e,t){t.assert.strictEqual(typeof e,`string`)}function et(e){return Object.keys(e)}function N(e){return!!e&&!!e.then&&typeof e.then==`function`}function tt(e){let t=e.replace(/\s{2,}/g,` `).split(/\s+(?![^[]*]|[^<]*>)/),n=/\.*[\][<>]/g,r=t.shift();if(!r)throw Error(`No command found in: ${e}`);let i={cmd:r.replace(n,``),demanded:[],optional:[]};return t.forEach((e,r)=>{let a=!1;e=e.replace(/\s/g,``),/\.+[\]>]/.test(e)&&r===t.length-1&&(a=!0),/^\[/.test(e)?i.optional.push({cmd:e.replace(n,``).split(`|`),variadic:a}):i.demanded.push({cmd:e.replace(n,``).split(`|`),variadic:a})}),i}const nt=[`first`,`second`,`third`,`fourth`,`fifth`,`sixth`];function P(e,t,n){function r(){return typeof e==`object`?[{demanded:[],optional:[]},e,t]:[tt(`cmd ${e}`),t,n]}try{let e=0,[t,n,i]=r(),a=[].slice.call(n);for(;a.length&&a[a.length-1]===void 0;)a.pop();let o=i||a.length;if(o<t.demanded.length)throw new M(`Not enough arguments provided. Expected ${t.demanded.length} but received ${a.length}.`);let s=t.demanded.length+t.optional.length;if(o>s)throw new M(`Too many arguments provided. Expected max ${s} but received ${o}.`);t.demanded.forEach(t=>{let n=rt(a.shift());t.cmd.filter(e=>e===n||e===`*`).length===0&&it(n,t.cmd,e),e+=1}),t.optional.forEach(t=>{if(a.length===0)return;let n=rt(a.shift());t.cmd.filter(e=>e===n||e===`*`).length===0&&it(n,t.cmd,e),e+=1})}catch(e){console.warn(e.stack)}}function rt(e){return Array.isArray(e)?`array`:e===null?`null`:typeof e}function it(e,t,n){throw new M(`Invalid ${nt[n]||`manyith`} argument. Expected ${t.join(` or `)} but received ${e}.`)}var at=class{constructor(e){this.globalMiddleware=[],this.frozens=[],this.yargs=e}addMiddleware(e,t,n=!0,r=!1){if(P(`<array|function> [boolean] [boolean] [boolean]`,[e,t,n],arguments.length),Array.isArray(e)){for(let r=0;r<e.length;r++){if(typeof e[r]!=`function`)throw Error(`middleware must be a function`);let i=e[r];i.applyBeforeValidation=t,i.global=n}Array.prototype.push.apply(this.globalMiddleware,e)}else if(typeof e==`function`){let i=e;i.applyBeforeValidation=t,i.global=n,i.mutates=r,this.globalMiddleware.push(e)}return this.yargs}addCoerceMiddleware(e,t){let n=this.yargs.getAliases();return this.globalMiddleware=this.globalMiddleware.filter(e=>{let r=[...n[t]||[],t];return!e.option||!r.includes(e.option)}),e.option=t,this.addMiddleware(e,!0,!0,!0)}getMiddleware(){return this.globalMiddleware}freeze(){this.frozens.push([...this.globalMiddleware])}unfreeze(){let e=this.frozens.pop();e!==void 0&&(this.globalMiddleware=e)}reset(){this.globalMiddleware=this.globalMiddleware.filter(e=>e.global)}};function ot(e){return e?e.map(e=>(e.applyBeforeValidation=!1,e)):[]}function st(e,t,n,r){return n.reduce((e,n)=>{if(n.applyBeforeValidation!==r)return e;if(n.mutates){if(n.applied)return e;n.applied=!0}if(N(e))return e.then(e=>Promise.all([e,n(e,t)])).then(([e,t])=>Object.assign(e,t));{let r=n(e,t);return N(r)?r.then(t=>Object.assign(e,t)):Object.assign(e,r)}},e)}function ct(e,t,n=e=>{throw e}){try{let n=lt(e)?e():e;return N(n)?n.then(e=>t(e)):t(n)}catch(e){return n(e)}}function lt(e){return typeof e==`function`}function ut(e){if(me===void 0)return null;for(let t=0,n=Object.keys(me.cache),r;t<n.length;t++)if(r=me.cache[n[t]],r.exports===e)return r;return null}const dt=/(^\*)|(^\$0)/;var ft=class{constructor(e,t,n,r){this.requireCache=/* @__PURE__ */ new Set,this.handlers={},this.aliasMap={},this.frozens=[],this.shim=r,this.usage=e,this.globalMiddleware=n,this.validation=t}addDirectory(e,t,n,r){r||={},typeof r.recurse!=`boolean`&&(r.recurse=!1),Array.isArray(r.extensions)||(r.extensions=[`js`]);let i=typeof r.visit==`function`?r.visit:e=>e;r.visit=(e,t,n)=>{let r=i(e,t,n);if(r){if(this.requireCache.has(t))return r;this.requireCache.add(t),this.addHandler(r)}return r},this.shim.requireDirectory({require:t,filename:n},e,r)}addHandler(e,t,n,r,i,a){let o=[],s=ot(i);if(r||=(()=>{}),Array.isArray(e)){if(ht(e))[e,...o]=e;else for(let t of e)this.addHandler(t)}else if(vt(e)){let t=Array.isArray(e.command)||typeof e.command==`string`?e.command:this.moduleName(e);e.aliases&&(t=[].concat(t,e.aliases)),this.addHandler(t,this.extractDesc(e),e.builder,e.handler,e.middlewares,e.deprecated);return}else if(mt(n)){this.addHandler([e].concat(o),t,n.builder,n.handler,n.middlewares,n.deprecated);return}if(typeof e==`string`){let i=tt(e);o=o.map(e=>tt(e).cmd);let c=!1,l=[i.cmd].concat(o).filter(e=>!dt.test(e)||(c=!0,!1));l.length===0&&c&&l.push(`$0`),c&&(i.cmd=l[0],o=l.slice(1),e=e.replace(dt,i.cmd)),o.forEach(e=>{this.aliasMap[e]=i.cmd}),t!==!1&&this.usage.command(e,t,c,o,a),this.handlers[i.cmd]={original:e,description:t,handler:r,builder:n||{},middlewares:s,deprecated:a,demanded:i.demanded,optional:i.optional},c&&(this.defaultCommand=this.handlers[i.cmd])}}getCommandHandlers(){return this.handlers}getCommands(){return Object.keys(this.handlers).concat(Object.keys(this.aliasMap))}hasDefaultCommand(){return!!this.defaultCommand}runCommand(e,t,n,r,i,a){let o=this.handlers[e]||this.handlers[this.aliasMap[e]]||this.defaultCommand,s=t.getInternalMethods().getContext(),c=s.commands.slice(),l=!e;e&&(s.commands.push(e),s.fullCommands.push(o.original));let u=this.applyBuilderUpdateUsageAndParse(l,o,t,n.aliases,c,r,i,a);return N(u)?u.then(e=>this.applyMiddlewareAndGetResult(l,o,e.innerArgv,s,i,e.aliases,t)):this.applyMiddlewareAndGetResult(l,o,u.innerArgv,s,i,u.aliases,t)}applyBuilderUpdateUsageAndParse(e,t,n,r,i,a,o,s){let c=t.builder,l=n;if(gt(c)){n.getInternalMethods().getUsageInstance().freeze();let u=c(n.getInternalMethods().reset(r),s);if(N(u))return u.then(r=>(l=Qn(r)?r:n,this.parseAndUpdateUsage(e,t,l,i,a,o)))}else _t(c)&&(n.getInternalMethods().getUsageInstance().freeze(),l=n.getInternalMethods().reset(r),Object.keys(t.builder).forEach(e=>{l.option(e,c[e])}));return this.parseAndUpdateUsage(e,t,l,i,a,o)}parseAndUpdateUsage(e,t,n,r,i,a){e&&n.getInternalMethods().getUsageInstance().unfreeze(!0),this.shouldUpdateUsage(n)&&n.getInternalMethods().getUsageInstance().usage(this.usageFromParentCommandsCommandHandler(r,t),t.description);let o=n.getInternalMethods().runYargsParserAndExecuteCommands(null,void 0,!0,i,a);return N(o)?o.then(e=>({aliases:n.parsed.aliases,innerArgv:e})):{aliases:n.parsed.aliases,innerArgv:o}}shouldUpdateUsage(e){return!e.getInternalMethods().getUsageInstance().getUsageDisabled()&&e.getInternalMethods().getUsageInstance().getUsage().length===0}usageFromParentCommandsCommandHandler(e,t){let n=dt.test(t.original)?t.original.replace(dt,``).trim():t.original,r=e.filter(e=>!dt.test(e));return r.push(n),`$0 ${r.join(` `)}`}handleValidationAndGetResult(e,t,n,r,i,a,o,s){if(!a.getInternalMethods().getHasOutput()){let t=a.getInternalMethods().runValidation(i,s,a.parsed.error,e);n=ct(n,e=>(t(e),e))}if(t.handler&&!a.getInternalMethods().getHasOutput()){a.getInternalMethods().setHasOutput();let r=!!a.getOptions().configuration[`populate--`];a.getInternalMethods().postProcess(n,r,!1,!1),n=st(n,a,o,!1),n=ct(n,e=>{let n=t.handler(e);return N(n)?n.then(()=>e):e}),e||a.getInternalMethods().getUsageInstance().cacheHelpMessage(),N(n)&&!a.getInternalMethods().hasParseCallback()&&n.catch(e=>{try{a.getInternalMethods().getUsageInstance().fail(null,e)}catch{}})}return e||(r.commands.pop(),r.fullCommands.pop()),n}applyMiddlewareAndGetResult(e,t,n,r,i,a,o){let s={};if(i)return n;o.getInternalMethods().getHasOutput()||(s=this.populatePositionals(t,n,r,o));let c=this.globalMiddleware.getMiddleware().slice(0).concat(t.middlewares),l=st(n,o,c,!0);return N(l)?l.then(n=>this.handleValidationAndGetResult(e,t,n,r,a,o,c,s)):this.handleValidationAndGetResult(e,t,l,r,a,o,c,s)}populatePositionals(e,t,n,r){t._=t._.slice(n.commands.length);let i=e.demanded.slice(0),a=e.optional.slice(0),o={};for(this.validation.positionalCount(i.length,t._.length);i.length;){let e=i.shift();this.populatePositional(e,t,o)}for(;a.length;){let e=a.shift();this.populatePositional(e,t,o)}return t._=n.commands.concat(t._.map(e=>``+e)),this.postProcessPositionals(t,o,this.cmdToParseOptions(e.original),r),o}populatePositional(e,t,n){let r=e.cmd[0];e.variadic?n[r]=t._.splice(0).map(String):t._.length&&(n[r]=[String(t._.shift())])}cmdToParseOptions(e){let t={array:[],default:{},alias:{},demand:{}},n=tt(e);return n.demanded.forEach(e=>{let[n,...r]=e.cmd;e.variadic&&(t.array.push(n),t.default[n]=[]),t.alias[n]=r,t.demand[n]=!0}),n.optional.forEach(e=>{let[n,...r]=e.cmd;e.variadic&&(t.array.push(n),t.default[n]=[]),t.alias[n]=r}),t}postProcessPositionals(e,t,n,r){let i=Object.assign({},r.getOptions());i.default=Object.assign(n.default,i.default);for(let e of Object.keys(n.alias))i.alias[e]=(i.alias[e]||[]).concat(n.alias[e]);i.array=i.array.concat(n.array),i.config={};let a=[];if(Object.keys(t).forEach(e=>{t[e].map(t=>{i.configuration[`unknown-options-as-args`]&&(i.key[e]=!0),a.push(`--${e}`),a.push(t)})}),!a.length)return;let o=Object.assign({},i.configuration,{"populate--":!1}),s=this.shim.Parser.detailed(a,Object.assign({},i,{configuration:o}));if(s.error)r.getInternalMethods().getUsageInstance().fail(s.error.message,s.error);else{let n=Object.keys(t);Object.keys(t).forEach(e=>{n.push(...s.aliases[e])}),Object.keys(s.argv).forEach(i=>{n.includes(i)&&(t[i]||(t[i]=s.argv[i]),e[i]=!this.isInConfigs(r,i)&&!this.isDefaulted(r,i)&&Object.prototype.hasOwnProperty.call(e,i)&&Object.prototype.hasOwnProperty.call(s.argv,i)&&(Array.isArray(e[i])||Array.isArray(s.argv[i]))?[].concat(e[i],s.argv[i]):s.argv[i])})}}isDefaulted(e,t){let{default:n}=e.getOptions();return Object.prototype.hasOwnProperty.call(n,t)||Object.prototype.hasOwnProperty.call(n,this.shim.Parser.camelCase(t))}isInConfigs(e,t){let{configObjects:n}=e.getOptions();return n.some(e=>Object.prototype.hasOwnProperty.call(e,t))||n.some(e=>Object.prototype.hasOwnProperty.call(e,this.shim.Parser.camelCase(t)))}runDefaultBuilderOn(e){if(!this.defaultCommand)return;if(this.shouldUpdateUsage(e)){let t=dt.test(this.defaultCommand.original)?this.defaultCommand.original:this.defaultCommand.original.replace(/^[^[\]<>]*/,`$0 `);e.getInternalMethods().getUsageInstance().usage(t,this.defaultCommand.description)}let t=this.defaultCommand.builder;if(gt(t))return t(e,!0);mt(t)||Object.keys(t).forEach(n=>{e.option(n,t[n])})}moduleName(e){let t=ut(e);if(!t)throw Error(`No command name given for module: ${this.shim.inspect(e)}`);return this.commandFromFilename(t.filename)}commandFromFilename(e){return this.shim.path.basename(e,this.shim.path.extname(e))}extractDesc({describe:e,description:t,desc:n}){for(let r of[e,t,n]){if(typeof r==`string`||r===!1)return r;Qe(r,!0,this.shim)}return!1}freeze(){this.frozens.push({handlers:this.handlers,aliasMap:this.aliasMap,defaultCommand:this.defaultCommand})}unfreeze(){let e=this.frozens.pop();Qe(e,void 0,this.shim),{handlers:this.handlers,aliasMap:this.aliasMap,defaultCommand:this.defaultCommand}=e}reset(){return this.handlers={},this.aliasMap={},this.defaultCommand=void 0,this.requireCache=/* @__PURE__ */ new Set,this}};function pt(e,t,n,r){return new ft(e,t,n,r)}function mt(e){return typeof e==`object`&&!!e.builder&&typeof e.handler==`function`}function ht(e){return e.every(e=>typeof e==`string`)}function gt(e){return typeof e==`function`}function _t(e){return typeof e==`object`}function vt(e){return typeof e==`object`&&!Array.isArray(e)}function yt(e={},t=()=>!0){let n={};return et(e).forEach(r=>{t(r,e[r])&&(n[r]=e[r])}),n}function bt(e){typeof process<`u`&&[process.stdout,process.stderr].forEach(t=>{let n=t;n._handle&&n.isTTY&&typeof n._handle.setBlocking==`function`&&n._handle.setBlocking(e)})}function xt(e){return typeof e==`boolean`}function St(e,t){let n=t.y18n.__,r={},i=[];r.failFn=function(e){i.push(e)};let a=null,o=null,s=!0;r.showHelpOnFail=function(t=!0,n){let[i,c]=typeof t==`string`?[!0,t]:[t,n];return e.getInternalMethods().isGlobalContext()&&(o=c),a=c,s=i,r};let c=!1;r.fail=function(t,n){let l=e.getInternalMethods().getLoggerInstance();if(i.length)for(let e=i.length-1;e>=0;--e){let a=i[e];if(xt(a)){if(n)throw n;if(t)throw Error(t)}else a(t,n,r)}else{if(e.getExitProcess()&&bt(!0),!c){c=!0,s&&(e.showHelp(`error`),l.error()),(t||n)&&l.error(t||n);let r=a||o;r&&((t||n)&&l.error(``),l.error(r))}if(n||=new M(t),e.getExitProcess())return e.exit(1);if(e.getInternalMethods().hasParseCallback())return e.exit(1,n);throw n}};let l=[],u=!1;r.usage=(e,t)=>e===null?(u=!0,l=[],r):(u=!1,l.push([e,t||``]),r),r.getUsage=()=>l,r.getUsageDisabled=()=>u,r.getPositionalGroupName=()=>n(`Positionals:`);let d=[];r.example=(e,t)=>{d.push([e,t||``])};let f=[];r.command=function(e,t,n,r,i=!1){n&&(f=f.map(e=>(e[2]=!1,e))),f.push([e,t||``,n,r,i])},r.getCommands=()=>f;let p={};r.describe=function(e,t){Array.isArray(e)?e.forEach(e=>{r.describe(e,t)}):typeof e==`object`?Object.keys(e).forEach(t=>{r.describe(t,e[t])}):p[e]=t},r.getDescriptions=()=>p;let m=[];r.epilog=e=>{m.push(e)};let h=!1,g;r.wrap=e=>{h=!0,g=e},r.getWrap=()=>t.getEnv(`YARGS_DISABLE_WRAP`)?null:(h||=(g=b(),!0),g);let ee=`__yargsString__:`;r.deferY18nLookup=e=>ee+e,r.help=function(){if(v)return v;te();let i=e.customScriptName?e.$0:t.path.basename(e.$0),a=e.getDemandedOptions(),o=e.getDemandedCommands(),s=e.getDeprecatedOptions(),c=e.getGroups(),h=e.getOptions(),g=[];g=g.concat(Object.keys(p)),g=g.concat(Object.keys(a)),g=g.concat(Object.keys(o)),g=g.concat(Object.keys(h.default)),g=g.filter(ne),g=Object.keys(g.reduce((e,t)=>(t!==`_`&&(e[t]=!0),e),{}));let b=r.getWrap(),x=t.cliui({width:b,wrap:!!b});if(!u){if(l.length)l.forEach(e=>{x.div({text:`${e[0].replace(/\$0/g,i)}`}),e[1]&&x.div({text:`${e[1]}`,padding:[1,0,0,0]})}),x.div();else if(f.length){let e=null;e=o._?`${i} <${n(`command`)}>\n`:`${i} [${n(`command`)}]\n`,x.div(`${e}`)}}if(f.length>1||f.length===1&&!f[0][2]){x.div(n(`Commands:`));let t=e.getInternalMethods().getContext(),r=t.commands.length?`${t.commands.join(` `)} `:``;e.getInternalMethods().getParserConfiguration()[`sort-commands`]===!0&&(f=f.sort((e,t)=>e[0].localeCompare(t[0])));let a=i?`${i} `:``;f.forEach(e=>{let t=`${a}${r}${e[0].replace(/^\$0 ?/,``)}`;x.span({text:t,padding:[0,2,0,2],width:_(f,b,`${i}${r}`)+4},{text:e[1]});let o=[];e[2]&&o.push(`[${n(`default`)}]`),e[3]&&e[3].length&&o.push(`[${n(`aliases:`)} ${e[3].join(`, `)}]`),e[4]&&(typeof e[4]==`string`?o.push(`[${n(`deprecated: %s`,e[4])}]`):o.push(`[${n(`deprecated`)}]`)),o.length?x.div({text:o.join(` `),padding:[0,0,0,2],align:`right`}):x.div()}),x.div()}let S=(Object.keys(h.alias)||[]).concat(Object.keys(e.parsed.newAliases)||[]);g=g.filter(t=>!e.parsed.newAliases[t]&&S.every(e=>(h.alias[e]||[]).indexOf(t)===-1));let ie=n(`Options:`);c[ie]||(c[ie]=[]),y(g,h.alias,c,ie);let C=e=>/^--/.test(Et(e)),ae=Object.keys(c).filter(e=>c[e].length>0).map(e=>({groupName:e,normalizedKeys:c[e].filter(ne).map(e=>{if(S.includes(e))return e;for(let t=0,n;(n=S[t])!==void 0;t++)if((h.alias[n]||[]).includes(e))return n;return e})})).filter(({normalizedKeys:e})=>e.length>0).map(({groupName:e,normalizedKeys:t})=>({groupName:e,normalizedKeys:t,switches:t.reduce((t,n)=>(t[n]=[n].concat(h.alias[n]||[]).map(t=>e===r.getPositionalGroupName()?t:(/^[0-9]$/.test(t)?h.boolean.includes(n)?`-`:`--`:t.length>1?`--`:`-`)+t).sort((e,t)=>C(e)===C(t)?0:C(e)?1:-1).join(`, `),t),{})}));if(ae.filter(({groupName:e})=>e!==r.getPositionalGroupName()).some(({normalizedKeys:e,switches:t})=>!e.every(e=>C(t[e])))&&ae.filter(({groupName:e})=>e!==r.getPositionalGroupName()).forEach(({normalizedKeys:e,switches:t})=>{e.forEach(e=>{C(t[e])&&(t[e]=wt(t[e],4))})}),ae.forEach(({groupName:t,normalizedKeys:i,switches:o})=>{x.div(t),i.forEach(t=>{let i=o[t],c=p[t]||``,l=null;c.includes(ee)&&(c=n(c.substring(16))),h.boolean.includes(t)&&(l=`[${n(`boolean`)}]`),h.count.includes(t)&&(l=`[${n(`count`)}]`),h.string.includes(t)&&(l=`[${n(`string`)}]`),h.normalize.includes(t)&&(l=`[${n(`string`)}]`),h.array.includes(t)&&(l=`[${n(`array`)}]`),h.number.includes(t)&&(l=`[${n(`number`)}]`);let u=[t in s?(e=>typeof e==`string`?`[${n(`deprecated: %s`,e)}]`:`[${n(`deprecated`)}]`)(s[t]):null,l,t in a?`[${n(`required`)}]`:null,h.choices&&h.choices[t]?`[${n(`choices:`)} ${r.stringifiedValues(h.choices[t])}]`:null,re(h.default[t],h.defaultDescription[t])].filter(Boolean).join(` `);x.span({text:Et(i),padding:[0,2,0,2+Tt(i)],width:_(o,b)+4},c);let d=e.getInternalMethods().getUsageConfiguration()[`hide-types`]===!0;u&&!d?x.div({text:u,padding:[0,0,0,2],align:`right`}):x.div()}),x.div()}),d.length&&(x.div(n(`Examples:`)),d.forEach(e=>{e[0]=e[0].replace(/\$0/g,i)}),d.forEach(e=>{e[1]===``?x.div({text:e[0],padding:[0,2,0,2]}):x.div({text:e[0],padding:[0,2,0,2],width:_(d,b)+4},{text:e[1]})}),x.div()),m.length>0){let e=m.map(e=>e.replace(/\$0/g,i)).join(`
|
|
40
|
-
`);x.div(`${e}\n`)}return x.toString().replace(/\s*$/,``)};function
|
|
39
|
+
const Ne=process&&process.env&&process.env.YARGS_MIN_NODE_VERSION?Number(process.env.YARGS_MIN_NODE_VERSION):12,Pe=(process==null?void 0:process.versions)?.node??(process==null?void 0:process.version)?.slice(1);if(Pe&&Number(Pe.match(/^([^.]+)/)[1])<Ne)throw Error(`yargs parser supports a minimum Node.js version of ${Ne}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`);const Fe=process?process.env:{},Ie=new Oe({cwd:process.cwd,env:()=>Fe,format:y,normalize:p,resolve:h,require:e=>{if(fe!==void 0)return fe(e);if(e.match(/\.json$/))return JSON.parse(g(e,`utf8`));throw Error(`only .json config files are supported in ESM`)}}),Le=function(e,t){return Ie.parse(e.slice(),t).argv};Le.detailed=function(e,t){return Ie.parse(e.slice(),t)},Le.camelCase=Ce,Le.decamelize=we,Le.looksLikeNumber=Te;function Re(){return+!ze()}function ze(){return Be()&&!process.defaultApp}function Be(){return!!process.versions.electron}function N(){return process.argv[Re()]}var P=class e extends Error{constructor(t){super(t||`yargs error`),this.name=`YError`,Error.captureStackTrace&&Error.captureStackTrace(this,e)}},Ve={fs:{readFileSync:g,writeFile:ee},format:y,resolve:h,exists:e=>{try{return v(e).isFile()}catch{return!1}}};let He;var Ue=class{constructor(e){e||={},this.directory=e.directory||`./locales`,this.updateFiles=typeof e.updateFiles!=`boolean`||e.updateFiles,this.locale=e.locale||`en`,this.fallbackToLanguage=typeof e.fallbackToLanguage!=`boolean`||e.fallbackToLanguage,this.cache=Object.create(null),this.writeQueue=[]}__(...e){if(typeof arguments[0]!=`string`)return this._taggedLiteral(arguments[0],...arguments);let t=e.shift(),n=function(){};return typeof e[e.length-1]==`function`&&(n=e.pop()),n||=function(){},this.cache[this.locale]||this._readLocaleFile(),!this.cache[this.locale][t]&&this.updateFiles?(this.cache[this.locale][t]=t,this._enqueueWrite({directory:this.directory,locale:this.locale,cb:n})):n(),He.format.apply(He.format,[this.cache[this.locale][t]||t].concat(e))}__n(){let e=Array.prototype.slice.call(arguments),t=e.shift(),n=e.shift(),r=e.shift(),i=function(){};typeof e[e.length-1]==`function`&&(i=e.pop()),this.cache[this.locale]||this._readLocaleFile();let a=r===1?t:n;this.cache[this.locale][t]&&(a=this.cache[this.locale][t][r===1?`one`:`other`]),!this.cache[this.locale][t]&&this.updateFiles?(this.cache[this.locale][t]={one:t,other:n},this._enqueueWrite({directory:this.directory,locale:this.locale,cb:i})):i();let o=[a];return~a.indexOf(`%d`)&&o.push(r),He.format.apply(He.format,o.concat(e))}setLocale(e){this.locale=e}getLocale(){return this.locale}updateLocale(e){this.cache[this.locale]||this._readLocaleFile();for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&(this.cache[this.locale][t]=e[t])}_taggedLiteral(e,...t){let n=``;return e.forEach(function(e,r){let i=t[r+1];n+=e,i!==void 0&&(n+=`%s`)}),this.__.apply(this,[n].concat([].slice.call(t,1)))}_enqueueWrite(e){this.writeQueue.push(e),this.writeQueue.length===1&&this._processWriteQueue()}_processWriteQueue(){let e=this,t=this.writeQueue[0],n=t.directory,r=t.locale,i=t.cb,a=this._resolveLocaleFile(n,r),o=JSON.stringify(this.cache[r],null,2);He.fs.writeFile(a,o,`utf-8`,function(t){e.writeQueue.shift(),e.writeQueue.length>0&&e._processWriteQueue(),i(t)})}_readLocaleFile(){let e={},t=this._resolveLocaleFile(this.directory,this.locale);try{He.fs.readFileSync&&(e=JSON.parse(He.fs.readFileSync(t,`utf-8`)))}catch(n){if(n instanceof SyntaxError&&(n.message=`syntax error in `+t),n.code===`ENOENT`)e={};else throw n}this.cache[this.locale]=e}_resolveLocaleFile(e,t){let n=He.resolve(e,`./`,t+`.json`);if(this.fallbackToLanguage&&!this._fileExistsSync(n)&&~t.lastIndexOf(`_`)){let r=He.resolve(e,`./`,t.split(`_`)[0]+`.json`);this._fileExistsSync(r)&&(n=r)}return n}_fileExistsSync(e){return He.exists(e)}};function We(e,t){He=t;let n=new Ue(e);return{__:n.__.bind(n),__n:n.__n.bind(n),setLocale:n.setLocale.bind(n),getLocale:n.getLocale.bind(n),updateLocale:n.updateLocale.bind(n),locale:n.locale}}const Ge=e=>We(e,Ve),Ke=`loading a directory of commands is not supported yet for ESM`;let qe;try{qe=ne(import.meta.url)}catch{qe=process.cwd()}const Je=qe.substring(0,qe.lastIndexOf(`node_modules`));var Ye={assert:{notStrictEqual:c,strictEqual:l},cliui:Se,findUp:j,getEnv:e=>process.env[e],inspect:te,getCallerFile:()=>{throw new P(Ke)},getProcessArgvBin:N,mainFilename:Je||process.cwd(),Parser:Le,path:{basename:u,dirname:d,extname:f,relative:m,resolve:h},process:{argv:()=>process.argv,cwd:process.cwd,emitWarning:(e,t)=>process.emitWarning(e,t),execPath:()=>process.execPath,exit:process.exit,nextTick:process.nextTick,stdColumns:process.stdout.columns===void 0?null:process.stdout.columns},readFileSync:g,require:()=>{throw new P(`require is not supported by ESM`)},requireDirectory:()=>{throw new P(Ke)},stringWidth:e=>[...e].length,y18n:Ge({directory:h(qe,`../../../locales`),updateFiles:!1})};function Xe(e,t,n,r){n.assert.notStrictEqual(e,t,r)}function Ze(e,t){t.assert.strictEqual(typeof e,`string`)}function Qe(e){return Object.keys(e)}function F(e){return!!e&&!!e.then&&typeof e.then==`function`}function $e(e){let t=e.replace(/\s{2,}/g,` `).split(/\s+(?![^[]*]|[^<]*>)/),n=/\.*[\][<>]/g,r=t.shift();if(!r)throw Error(`No command found in: ${e}`);let i={cmd:r.replace(n,``),demanded:[],optional:[]};return t.forEach((e,r)=>{let a=!1;e=e.replace(/\s/g,``),/\.+[\]>]/.test(e)&&r===t.length-1&&(a=!0),/^\[/.test(e)?i.optional.push({cmd:e.replace(n,``).split(`|`),variadic:a}):i.demanded.push({cmd:e.replace(n,``).split(`|`),variadic:a})}),i}const et=[`first`,`second`,`third`,`fourth`,`fifth`,`sixth`];function I(e,t,n){function r(){return typeof e==`object`?[{demanded:[],optional:[]},e,t]:[$e(`cmd ${e}`),t,n]}try{let e=0,[t,n,i]=r(),a=[].slice.call(n);for(;a.length&&a[a.length-1]===void 0;)a.pop();let o=i||a.length;if(o<t.demanded.length)throw new P(`Not enough arguments provided. Expected ${t.demanded.length} but received ${a.length}.`);let s=t.demanded.length+t.optional.length;if(o>s)throw new P(`Too many arguments provided. Expected max ${s} but received ${o}.`);t.demanded.forEach(t=>{let n=tt(a.shift());t.cmd.filter(e=>e===n||e===`*`).length===0&&nt(n,t.cmd,e),e+=1}),t.optional.forEach(t=>{if(a.length===0)return;let n=tt(a.shift());t.cmd.filter(e=>e===n||e===`*`).length===0&&nt(n,t.cmd,e),e+=1})}catch(e){console.warn(e.stack)}}function tt(e){return Array.isArray(e)?`array`:e===null?`null`:typeof e}function nt(e,t,n){throw new P(`Invalid ${et[n]||`manyith`} argument. Expected ${t.join(` or `)} but received ${e}.`)}var rt=class{constructor(e){this.globalMiddleware=[],this.frozens=[],this.yargs=e}addMiddleware(e,t,n=!0,r=!1){if(I(`<array|function> [boolean] [boolean] [boolean]`,[e,t,n],arguments.length),Array.isArray(e)){for(let r=0;r<e.length;r++){if(typeof e[r]!=`function`)throw Error(`middleware must be a function`);let i=e[r];i.applyBeforeValidation=t,i.global=n}Array.prototype.push.apply(this.globalMiddleware,e)}else if(typeof e==`function`){let i=e;i.applyBeforeValidation=t,i.global=n,i.mutates=r,this.globalMiddleware.push(e)}return this.yargs}addCoerceMiddleware(e,t){let n=this.yargs.getAliases();return this.globalMiddleware=this.globalMiddleware.filter(e=>{let r=[...n[t]||[],t];return!e.option||!r.includes(e.option)}),e.option=t,this.addMiddleware(e,!0,!0,!0)}getMiddleware(){return this.globalMiddleware}freeze(){this.frozens.push([...this.globalMiddleware])}unfreeze(){let e=this.frozens.pop();e!==void 0&&(this.globalMiddleware=e)}reset(){this.globalMiddleware=this.globalMiddleware.filter(e=>e.global)}};function it(e){return e?e.map(e=>(e.applyBeforeValidation=!1,e)):[]}function at(e,t,n,r){return n.reduce((e,n)=>{if(n.applyBeforeValidation!==r)return e;if(n.mutates){if(n.applied)return e;n.applied=!0}if(F(e))return e.then(e=>Promise.all([e,n(e,t)])).then(([e,t])=>Object.assign(e,t));{let r=n(e,t);return F(r)?r.then(t=>Object.assign(e,t)):Object.assign(e,r)}},e)}function ot(e,t,n=e=>{throw e}){try{let n=st(e)?e():e;return F(n)?n.then(e=>t(e)):t(n)}catch(e){return n(e)}}function st(e){return typeof e==`function`}function ct(e){if(fe===void 0)return null;for(let t=0,n=Object.keys(fe.cache),r;t<n.length;t++)if(r=fe.cache[n[t]],r.exports===e)return r;return null}const lt=/(^\*)|(^\$0)/;var ut=class{constructor(e,t,n,r){this.requireCache=/* @__PURE__ */ new Set,this.handlers={},this.aliasMap={},this.frozens=[],this.shim=r,this.usage=e,this.globalMiddleware=n,this.validation=t}addDirectory(e,t,n,r){r||={},typeof r.recurse!=`boolean`&&(r.recurse=!1),Array.isArray(r.extensions)||(r.extensions=[`js`]);let i=typeof r.visit==`function`?r.visit:e=>e;r.visit=(e,t,n)=>{let r=i(e,t,n);if(r){if(this.requireCache.has(t))return r;this.requireCache.add(t),this.addHandler(r)}return r},this.shim.requireDirectory({require:t,filename:n},e,r)}addHandler(e,t,n,r,i,a){let o=[],s=it(i);if(r||=(()=>{}),Array.isArray(e)){if(pt(e))[e,...o]=e;else for(let t of e)this.addHandler(t)}else if(gt(e)){let t=Array.isArray(e.command)||typeof e.command==`string`?e.command:this.moduleName(e);e.aliases&&(t=[].concat(t,e.aliases)),this.addHandler(t,this.extractDesc(e),e.builder,e.handler,e.middlewares,e.deprecated);return}else if(ft(n)){this.addHandler([e].concat(o),t,n.builder,n.handler,n.middlewares,n.deprecated);return}if(typeof e==`string`){let i=$e(e);o=o.map(e=>$e(e).cmd);let c=!1,l=[i.cmd].concat(o).filter(e=>!lt.test(e)||(c=!0,!1));l.length===0&&c&&l.push(`$0`),c&&(i.cmd=l[0],o=l.slice(1),e=e.replace(lt,i.cmd)),o.forEach(e=>{this.aliasMap[e]=i.cmd}),t!==!1&&this.usage.command(e,t,c,o,a),this.handlers[i.cmd]={original:e,description:t,handler:r,builder:n||{},middlewares:s,deprecated:a,demanded:i.demanded,optional:i.optional},c&&(this.defaultCommand=this.handlers[i.cmd])}}getCommandHandlers(){return this.handlers}getCommands(){return Object.keys(this.handlers).concat(Object.keys(this.aliasMap))}hasDefaultCommand(){return!!this.defaultCommand}runCommand(e,t,n,r,i,a){let o=this.handlers[e]||this.handlers[this.aliasMap[e]]||this.defaultCommand,s=t.getInternalMethods().getContext(),c=s.commands.slice(),l=!e;e&&(s.commands.push(e),s.fullCommands.push(o.original));let u=this.applyBuilderUpdateUsageAndParse(l,o,t,n.aliases,c,r,i,a);return F(u)?u.then(e=>this.applyMiddlewareAndGetResult(l,o,e.innerArgv,s,i,e.aliases,t)):this.applyMiddlewareAndGetResult(l,o,u.innerArgv,s,i,u.aliases,t)}applyBuilderUpdateUsageAndParse(e,t,n,r,i,a,o,s){let c=t.builder,l=n;if(mt(c)){n.getInternalMethods().getUsageInstance().freeze();let u=c(n.getInternalMethods().reset(r),s);if(F(u))return u.then(r=>(l=Qn(r)?r:n,this.parseAndUpdateUsage(e,t,l,i,a,o)))}else ht(c)&&(n.getInternalMethods().getUsageInstance().freeze(),l=n.getInternalMethods().reset(r),Object.keys(t.builder).forEach(e=>{l.option(e,c[e])}));return this.parseAndUpdateUsage(e,t,l,i,a,o)}parseAndUpdateUsage(e,t,n,r,i,a){e&&n.getInternalMethods().getUsageInstance().unfreeze(!0),this.shouldUpdateUsage(n)&&n.getInternalMethods().getUsageInstance().usage(this.usageFromParentCommandsCommandHandler(r,t),t.description);let o=n.getInternalMethods().runYargsParserAndExecuteCommands(null,void 0,!0,i,a);return F(o)?o.then(e=>({aliases:n.parsed.aliases,innerArgv:e})):{aliases:n.parsed.aliases,innerArgv:o}}shouldUpdateUsage(e){return!e.getInternalMethods().getUsageInstance().getUsageDisabled()&&e.getInternalMethods().getUsageInstance().getUsage().length===0}usageFromParentCommandsCommandHandler(e,t){let n=lt.test(t.original)?t.original.replace(lt,``).trim():t.original,r=e.filter(e=>!lt.test(e));return r.push(n),`$0 ${r.join(` `)}`}handleValidationAndGetResult(e,t,n,r,i,a,o,s){if(!a.getInternalMethods().getHasOutput()){let t=a.getInternalMethods().runValidation(i,s,a.parsed.error,e);n=ot(n,e=>(t(e),e))}if(t.handler&&!a.getInternalMethods().getHasOutput()){a.getInternalMethods().setHasOutput();let r=!!a.getOptions().configuration[`populate--`];a.getInternalMethods().postProcess(n,r,!1,!1),n=at(n,a,o,!1),n=ot(n,e=>{let n=t.handler(e);return F(n)?n.then(()=>e):e}),e||a.getInternalMethods().getUsageInstance().cacheHelpMessage(),F(n)&&!a.getInternalMethods().hasParseCallback()&&n.catch(e=>{try{a.getInternalMethods().getUsageInstance().fail(null,e)}catch{}})}return e||(r.commands.pop(),r.fullCommands.pop()),n}applyMiddlewareAndGetResult(e,t,n,r,i,a,o){let s={};if(i)return n;o.getInternalMethods().getHasOutput()||(s=this.populatePositionals(t,n,r,o));let c=this.globalMiddleware.getMiddleware().slice(0).concat(t.middlewares),l=at(n,o,c,!0);return F(l)?l.then(n=>this.handleValidationAndGetResult(e,t,n,r,a,o,c,s)):this.handleValidationAndGetResult(e,t,l,r,a,o,c,s)}populatePositionals(e,t,n,r){t._=t._.slice(n.commands.length);let i=e.demanded.slice(0),a=e.optional.slice(0),o={};for(this.validation.positionalCount(i.length,t._.length);i.length;){let e=i.shift();this.populatePositional(e,t,o)}for(;a.length;){let e=a.shift();this.populatePositional(e,t,o)}return t._=n.commands.concat(t._.map(e=>``+e)),this.postProcessPositionals(t,o,this.cmdToParseOptions(e.original),r),o}populatePositional(e,t,n){let r=e.cmd[0];e.variadic?n[r]=t._.splice(0).map(String):t._.length&&(n[r]=[String(t._.shift())])}cmdToParseOptions(e){let t={array:[],default:{},alias:{},demand:{}},n=$e(e);return n.demanded.forEach(e=>{let[n,...r]=e.cmd;e.variadic&&(t.array.push(n),t.default[n]=[]),t.alias[n]=r,t.demand[n]=!0}),n.optional.forEach(e=>{let[n,...r]=e.cmd;e.variadic&&(t.array.push(n),t.default[n]=[]),t.alias[n]=r}),t}postProcessPositionals(e,t,n,r){let i=Object.assign({},r.getOptions());i.default=Object.assign(n.default,i.default);for(let e of Object.keys(n.alias))i.alias[e]=(i.alias[e]||[]).concat(n.alias[e]);i.array=i.array.concat(n.array),i.config={};let a=[];if(Object.keys(t).forEach(e=>{t[e].map(t=>{i.configuration[`unknown-options-as-args`]&&(i.key[e]=!0),a.push(`--${e}`),a.push(t)})}),!a.length)return;let o=Object.assign({},i.configuration,{"populate--":!1}),s=this.shim.Parser.detailed(a,Object.assign({},i,{configuration:o}));if(s.error)r.getInternalMethods().getUsageInstance().fail(s.error.message,s.error);else{let n=Object.keys(t);Object.keys(t).forEach(e=>{n.push(...s.aliases[e])}),Object.keys(s.argv).forEach(i=>{n.includes(i)&&(t[i]||(t[i]=s.argv[i]),e[i]=!this.isInConfigs(r,i)&&!this.isDefaulted(r,i)&&Object.prototype.hasOwnProperty.call(e,i)&&Object.prototype.hasOwnProperty.call(s.argv,i)&&(Array.isArray(e[i])||Array.isArray(s.argv[i]))?[].concat(e[i],s.argv[i]):s.argv[i])})}}isDefaulted(e,t){let{default:n}=e.getOptions();return Object.prototype.hasOwnProperty.call(n,t)||Object.prototype.hasOwnProperty.call(n,this.shim.Parser.camelCase(t))}isInConfigs(e,t){let{configObjects:n}=e.getOptions();return n.some(e=>Object.prototype.hasOwnProperty.call(e,t))||n.some(e=>Object.prototype.hasOwnProperty.call(e,this.shim.Parser.camelCase(t)))}runDefaultBuilderOn(e){if(!this.defaultCommand)return;if(this.shouldUpdateUsage(e)){let t=lt.test(this.defaultCommand.original)?this.defaultCommand.original:this.defaultCommand.original.replace(/^[^[\]<>]*/,`$0 `);e.getInternalMethods().getUsageInstance().usage(t,this.defaultCommand.description)}let t=this.defaultCommand.builder;if(mt(t))return t(e,!0);ft(t)||Object.keys(t).forEach(n=>{e.option(n,t[n])})}moduleName(e){let t=ct(e);if(!t)throw Error(`No command name given for module: ${this.shim.inspect(e)}`);return this.commandFromFilename(t.filename)}commandFromFilename(e){return this.shim.path.basename(e,this.shim.path.extname(e))}extractDesc({describe:e,description:t,desc:n}){for(let r of[e,t,n]){if(typeof r==`string`||r===!1)return r;Xe(r,!0,this.shim)}return!1}freeze(){this.frozens.push({handlers:this.handlers,aliasMap:this.aliasMap,defaultCommand:this.defaultCommand})}unfreeze(){let e=this.frozens.pop();Xe(e,void 0,this.shim),{handlers:this.handlers,aliasMap:this.aliasMap,defaultCommand:this.defaultCommand}=e}reset(){return this.handlers={},this.aliasMap={},this.defaultCommand=void 0,this.requireCache=/* @__PURE__ */ new Set,this}};function dt(e,t,n,r){return new ut(e,t,n,r)}function ft(e){return typeof e==`object`&&!!e.builder&&typeof e.handler==`function`}function pt(e){return e.every(e=>typeof e==`string`)}function mt(e){return typeof e==`function`}function ht(e){return typeof e==`object`}function gt(e){return typeof e==`object`&&!Array.isArray(e)}function _t(e={},t=()=>!0){let n={};return Qe(e).forEach(r=>{t(r,e[r])&&(n[r]=e[r])}),n}function vt(e){typeof process<`u`&&[process.stdout,process.stderr].forEach(t=>{let n=t;n._handle&&n.isTTY&&typeof n._handle.setBlocking==`function`&&n._handle.setBlocking(e)})}function yt(e){return typeof e==`boolean`}function bt(e,t){let n=t.y18n.__,r={},i=[];r.failFn=function(e){i.push(e)};let a=null,o=null,s=!0;r.showHelpOnFail=function(t=!0,n){let[i,c]=typeof t==`string`?[!0,t]:[t,n];return e.getInternalMethods().isGlobalContext()&&(o=c),a=c,s=i,r};let c=!1;r.fail=function(t,n){let l=e.getInternalMethods().getLoggerInstance();if(i.length)for(let e=i.length-1;e>=0;--e){let a=i[e];if(yt(a)){if(n)throw n;if(t)throw Error(t)}else a(t,n,r)}else{if(e.getExitProcess()&&vt(!0),!c){c=!0,s&&(e.showHelp(`error`),l.error()),(t||n)&&l.error(t||n);let r=a||o;r&&((t||n)&&l.error(``),l.error(r))}if(n||=new P(t),e.getExitProcess())return e.exit(1);if(e.getInternalMethods().hasParseCallback())return e.exit(1,n);throw n}};let l=[],u=!1;r.usage=(e,t)=>e===null?(u=!0,l=[],r):(u=!1,l.push([e,t||``]),r),r.getUsage=()=>l,r.getUsageDisabled=()=>u,r.getPositionalGroupName=()=>n(`Positionals:`);let d=[];r.example=(e,t)=>{d.push([e,t||``])};let f=[];r.command=function(e,t,n,r,i=!1){n&&(f=f.map(e=>(e[2]=!1,e))),f.push([e,t||``,n,r,i])},r.getCommands=()=>f;let p={};r.describe=function(e,t){Array.isArray(e)?e.forEach(e=>{r.describe(e,t)}):typeof e==`object`?Object.keys(e).forEach(t=>{r.describe(t,e[t])}):p[e]=t},r.getDescriptions=()=>p;let m=[];r.epilog=e=>{m.push(e)};let h=!1,g;r.wrap=e=>{h=!0,g=e},r.getWrap=()=>t.getEnv(`YARGS_DISABLE_WRAP`)?null:(h||=(g=b(),!0),g);let _=`__yargsString__:`;r.deferY18nLookup=e=>_+e,r.help=function(){if(y)return y;ee();let i=e.customScriptName?e.$0:t.path.basename(e.$0),a=e.getDemandedOptions(),o=e.getDemandedCommands(),s=e.getDeprecatedOptions(),c=e.getGroups(),h=e.getOptions(),g=[];g=g.concat(Object.keys(p)),g=g.concat(Object.keys(a)),g=g.concat(Object.keys(o)),g=g.concat(Object.keys(h.default)),g=g.filter(ne),g=Object.keys(g.reduce((e,t)=>(t!==`_`&&(e[t]=!0),e),{}));let b=r.getWrap(),x=t.cliui({width:b,wrap:!!b});if(!u){if(l.length)l.forEach(e=>{x.div({text:`${e[0].replace(/\$0/g,i)}`}),e[1]&&x.div({text:`${e[1]}`,padding:[1,0,0,0]})}),x.div();else if(f.length){let e=null;e=o._?`${i} <${n(`command`)}>\n`:`${i} [${n(`command`)}]\n`,x.div(`${e}`)}}if(f.length>1||f.length===1&&!f[0][2]){x.div(n(`Commands:`));let t=e.getInternalMethods().getContext(),r=t.commands.length?`${t.commands.join(` `)} `:``;e.getInternalMethods().getParserConfiguration()[`sort-commands`]===!0&&(f=f.sort((e,t)=>e[0].localeCompare(t[0])));let a=i?`${i} `:``;f.forEach(e=>{let t=`${a}${r}${e[0].replace(/^\$0 ?/,``)}`;x.span({text:t,padding:[0,2,0,2],width:v(f,b,`${i}${r}`)+4},{text:e[1]});let o=[];e[2]&&o.push(`[${n(`default`)}]`),e[3]&&e[3].length&&o.push(`[${n(`aliases:`)} ${e[3].join(`, `)}]`),e[4]&&(typeof e[4]==`string`?o.push(`[${n(`deprecated: %s`,e[4])}]`):o.push(`[${n(`deprecated`)}]`)),o.length?x.div({text:o.join(` `),padding:[0,0,0,2],align:`right`}):x.div()}),x.div()}let ie=(Object.keys(h.alias)||[]).concat(Object.keys(e.parsed.newAliases)||[]);g=g.filter(t=>!e.parsed.newAliases[t]&&ie.every(e=>(h.alias[e]||[]).indexOf(t)===-1));let S=n(`Options:`);c[S]||(c[S]=[]),te(g,h.alias,c,S);let C=e=>/^--/.test(wt(e)),w=Object.keys(c).filter(e=>c[e].length>0).map(e=>({groupName:e,normalizedKeys:c[e].filter(ne).map(e=>{if(ie.includes(e))return e;for(let t=0,n;(n=ie[t])!==void 0;t++)if((h.alias[n]||[]).includes(e))return n;return e})})).filter(({normalizedKeys:e})=>e.length>0).map(({groupName:e,normalizedKeys:t})=>({groupName:e,normalizedKeys:t,switches:t.reduce((t,n)=>(t[n]=[n].concat(h.alias[n]||[]).map(t=>e===r.getPositionalGroupName()?t:(/^[0-9]$/.test(t)?h.boolean.includes(n)?`-`:`--`:t.length>1?`--`:`-`)+t).sort((e,t)=>C(e)===C(t)?0:C(e)?1:-1).join(`, `),t),{})}));if(w.filter(({groupName:e})=>e!==r.getPositionalGroupName()).some(({normalizedKeys:e,switches:t})=>!e.every(e=>C(t[e])))&&w.filter(({groupName:e})=>e!==r.getPositionalGroupName()).forEach(({normalizedKeys:e,switches:t})=>{e.forEach(e=>{C(t[e])&&(t[e]=St(t[e],4))})}),w.forEach(({groupName:t,normalizedKeys:i,switches:o})=>{x.div(t),i.forEach(t=>{let i=o[t],c=p[t]||``,l=null;c.includes(_)&&(c=n(c.substring(16))),h.boolean.includes(t)&&(l=`[${n(`boolean`)}]`),h.count.includes(t)&&(l=`[${n(`count`)}]`),h.string.includes(t)&&(l=`[${n(`string`)}]`),h.normalize.includes(t)&&(l=`[${n(`string`)}]`),h.array.includes(t)&&(l=`[${n(`array`)}]`),h.number.includes(t)&&(l=`[${n(`number`)}]`);let u=[t in s?(e=>typeof e==`string`?`[${n(`deprecated: %s`,e)}]`:`[${n(`deprecated`)}]`)(s[t]):null,l,t in a?`[${n(`required`)}]`:null,h.choices&&h.choices[t]?`[${n(`choices:`)} ${r.stringifiedValues(h.choices[t])}]`:null,re(h.default[t],h.defaultDescription[t])].filter(Boolean).join(` `);x.span({text:wt(i),padding:[0,2,0,2+Ct(i)],width:v(o,b)+4},c);let d=e.getInternalMethods().getUsageConfiguration()[`hide-types`]===!0;u&&!d?x.div({text:u,padding:[0,0,0,2],align:`right`}):x.div()}),x.div()}),d.length&&(x.div(n(`Examples:`)),d.forEach(e=>{e[0]=e[0].replace(/\$0/g,i)}),d.forEach(e=>{e[1]===``?x.div({text:e[0],padding:[0,2,0,2]}):x.div({text:e[0],padding:[0,2,0,2],width:v(d,b)+4},{text:e[1]})}),x.div()),m.length>0){let e=m.map(e=>e.replace(/\$0/g,i)).join(`
|
|
40
|
+
`);x.div(`${e}\n`)}return x.toString().replace(/\s*$/,``)};function v(e,n,r){let i=0;return Array.isArray(e)||(e=Object.values(e).map(e=>[e])),e.forEach(e=>{i=Math.max(t.stringWidth(r?`${r} ${wt(e[0])}`:wt(e[0]))+Ct(e[0]),i)}),n&&(i=Math.min(i,parseInt((n*.5).toString(),10))),i}function ee(){let t=e.getDemandedOptions(),n=e.getOptions();(Object.keys(n.alias)||[]).forEach(i=>{n.alias[i].forEach(a=>{p[a]&&r.describe(i,p[a]),a in t&&e.demandOption(i,t[a]),n.boolean.includes(a)&&e.boolean(i),n.count.includes(a)&&e.count(i),n.string.includes(a)&&e.string(i),n.normalize.includes(a)&&e.normalize(i),n.array.includes(a)&&e.array(i),n.number.includes(a)&&e.number(i)})})}let y;r.cacheHelpMessage=function(){y=this.help()},r.clearCachedHelpMessage=function(){y=void 0},r.hasCachedHelpMessage=function(){return!!y};function te(e,t,n,r){let i=[],a=null;return Object.keys(n).forEach(e=>{i=i.concat(n[e])}),e.forEach(e=>{a=[e].concat(t[e]),a.some(e=>i.indexOf(e)!==-1)||n[r].push(e)}),i}function ne(t){return e.getOptions().hiddenOptions.indexOf(t)<0||e.parsed.argv[e.getOptions().showHiddenOpt]}r.showHelp=t=>{let n=e.getInternalMethods().getLoggerInstance();t||=`error`,(typeof t==`function`?t:n[t])(r.help())},r.functionDescription=e=>[`(`,e.name?t.Parser.decamelize(e.name,`-`):n(`generated-value`),`)`].join(``),r.stringifiedValues=function(e,t){let n=``,r=t||`, `,i=[].concat(e);return!e||!i.length||i.forEach(e=>{n.length&&(n+=r),n+=JSON.stringify(e)}),n};function re(e,t){let r=`[${n(`default:`)} `;if(e===void 0&&!t)return null;if(t)r+=t;else switch(typeof e){case`string`:r+=`"${e}"`;break;case`object`:r+=JSON.stringify(e);break;default:r+=e}return`${r}]`}function b(){return t.process.stdColumns?Math.min(80,t.process.stdColumns):80}let x=null;r.version=e=>{x=e},r.showVersion=t=>{let n=e.getInternalMethods().getLoggerInstance();t||=`error`,(typeof t==`function`?t:n[t])(x)},r.reset=function(e){return a=null,c=!1,l=[],u=!1,m=[],d=[],f=[],p=_t(p,t=>!e[t]),r};let ie=[];return r.freeze=function(){ie.push({failMessage:a,failureOutput:c,usages:l,usageDisabled:u,epilogs:m,examples:d,commands:f,descriptions:p})},r.unfreeze=function(e=!1){let t=ie.pop();t&&(e?(p={...t.descriptions,...p},f=[...t.commands,...f],l=[...t.usages,...l],d=[...t.examples,...d],m=[...t.epilogs,...m]):{failMessage:a,failureOutput:c,usages:l,usageDisabled:u,epilogs:m,examples:d,commands:f,descriptions:p}=t)},r}function xt(e){return typeof e==`object`}function St(e,t){return xt(e)?{text:e.text,indentation:e.indentation+t}:{text:e,indentation:t}}function Ct(e){return xt(e)?e.indentation:0}function wt(e){return xt(e)?e.text:e}var Tt=class{constructor(e,t,n,r){this.yargs=e,this.usage=t,this.command=n,this.shim=r,this.completionKey=`get-yargs-completions`,this.aliases=null,this.customCompletionFunction=null,this.indexAfterLastReset=0,this.zshShell=(this.shim.getEnv(`SHELL`)?.includes(`zsh`)||this.shim.getEnv(`ZSH_NAME`)?.includes(`zsh`))??!1}defaultCompletion(e,t,n,r){let i=this.command.getCommandHandlers();for(let t=0,n=e.length;t<n;++t)if(i[e[t]]&&i[e[t]].builder){let n=i[e[t]].builder;if(mt(n)){this.indexAfterLastReset=t+1;let e=this.yargs.getInternalMethods().reset();return n(e,!0),e.argv}}let a=[];this.commandCompletions(a,e,n),this.optionCompletions(a,e,t,n),this.choicesFromOptionsCompletions(a,e,t,n),this.choicesFromPositionalsCompletions(a,e,t,n),r(null,a)}commandCompletions(e,t,n){let r=this.yargs.getInternalMethods().getContext().commands;!n.match(/^-/)&&r[r.length-1]!==n&&!this.previousArgHasChoices(t)&&this.usage.getCommands().forEach(n=>{let r=$e(n[0]).cmd;if(t.indexOf(r)===-1){if(!this.zshShell)e.push(r);else{let t=n[1]||``;e.push(r.replace(/:/g,`\\:`)+`:`+t)}}})}optionCompletions(e,t,n,r){if((r.match(/^-/)||r===``&&e.length===0)&&!this.previousArgHasChoices(t)){let n=this.yargs.getOptions(),i=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[];Object.keys(n.key).forEach(a=>{let o=!!n.configuration[`boolean-negation`]&&n.boolean.includes(a);!i.includes(a)&&!n.hiddenOptions.includes(a)&&!this.argsContainKey(t,a,o)&&this.completeOptionKey(a,e,r,o&&!!n.default[a])})}}choicesFromOptionsCompletions(e,t,n,r){if(this.previousArgHasChoices(t)){let n=this.getPreviousArgChoices(t);n&&n.length>0&&e.push(...n.map(e=>e.replace(/:/g,`\\:`)))}}choicesFromPositionalsCompletions(e,t,n,r){if(r===``&&e.length>0&&this.previousArgHasChoices(t))return;let i=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[],a=Math.max(this.indexAfterLastReset,this.yargs.getInternalMethods().getContext().commands.length+1),o=i[n._.length-a-1];if(!o)return;let s=this.yargs.getOptions().choices[o]||[];for(let t of s)t.startsWith(r)&&e.push(t.replace(/:/g,`\\:`))}getPreviousArgChoices(e){if(e.length<1)return;let t=e[e.length-1],n=``;if(!t.startsWith(`-`)&&e.length>1&&(n=t,t=e[e.length-2]),!t.startsWith(`-`))return;let r=t.replace(/^-+/,``),i=this.yargs.getOptions(),a=[r,...this.yargs.getAliases()[r]||[]],o;for(let e of a)if(Object.prototype.hasOwnProperty.call(i.key,e)&&Array.isArray(i.choices[e])){o=i.choices[e];break}if(o)return o.filter(e=>!n||e.startsWith(n))}previousArgHasChoices(e){let t=this.getPreviousArgChoices(e);return t!==void 0&&t.length>0}argsContainKey(e,t,n){let r=t=>e.indexOf((/^[^0-9]$/.test(t)?`-`:`--`)+t)!==-1;if(r(t)||n&&r(`no-${t}`))return!0;if(this.aliases){for(let e of this.aliases[t])if(r(e))return!0}return!1}completeOptionKey(e,t,n,r){let i=e;if(this.zshShell){let t=this.usage.getDescriptions(),n=((this===null||this===void 0?void 0:this.aliases)?.[e])?.find(e=>{let n=t[e];return typeof n==`string`&&n.length>0}),r=n?t[n]:void 0,a=t[e]??r??``;i=`${e.replace(/:/g,`\\:`)}:${a.replace(`__yargsString__:`,``).replace(/(\r\n|\n|\r)/gm,` `)}`}let a=!(e=>/^--/.test(e))(n)&&(e=>/^[^0-9]$/.test(e))(e)?`-`:`--`;t.push(a+i),r&&t.push(a+`no-`+i)}customCompletion(e,t,n,r){if(Xe(this.customCompletionFunction,null,this.shim),Dt(this.customCompletionFunction)){let e=this.customCompletionFunction(n,t);return F(e)?e.then(e=>{this.shim.process.nextTick(()=>{r(null,e)})}).catch(e=>{this.shim.process.nextTick(()=>{r(e,void 0)})}):r(null,e)}return Ot(this.customCompletionFunction)?this.customCompletionFunction(n,t,(i=r)=>this.defaultCompletion(e,t,n,i),e=>{r(null,e)}):this.customCompletionFunction(n,t,e=>{r(null,e)})}getCompletion(e,t){let n=e.length?e[e.length-1]:``,r=this.yargs.parse(e,!0),i=this.customCompletionFunction?r=>this.customCompletion(e,r,n,t):r=>this.defaultCompletion(e,r,n,t);return F(r)?r.then(i):i(r)}generateCompletionScript(e,t){let n=this.zshShell?`#compdef {{app_name}}
|
|
41
41
|
###-begin-{{app_name}}-completions-###
|
|
42
42
|
#
|
|
43
43
|
# yargs command completion script
|
|
@@ -84,11 +84,11 @@ _{{app_name}}_yargs_completions()
|
|
|
84
84
|
}
|
|
85
85
|
complete -o bashdefault -o default -F _{{app_name}}_yargs_completions {{app_name}}
|
|
86
86
|
###-end-{{app_name}}-completions-###
|
|
87
|
-
`,r=this.shim.path.basename(e);return e.match(/\.js$/)&&(e=`./${e}`),n=n.replace(/{{app_name}}/g,r),n=n.replace(/{{completion_command}}/g,t),n.replace(/{{app_path}}/g,e)}registerFunction(e){this.customCompletionFunction=e}setParsed(e){this.aliases=e.aliases}};function
|
|
88
|
-
`)}`:``;t.fail(i(`Missing required argument: %s`,`Missing required arguments: %s`,Object.keys(r).length,Object.keys(r).join(`, `)+n))}},a.unknownArguments=function(n,r,o,s,c=!0){let l=e.getInternalMethods().getCommandInstance().getCommands(),u=[],d=e.getInternalMethods().getContext();if(Object.keys(n).forEach(t=>{!Mt.includes(t)&&!Object.prototype.hasOwnProperty.call(o,t)&&!Object.prototype.hasOwnProperty.call(e.getInternalMethods().getParseContext(),t)&&!a.isValidAndSomeAliasIsNotNew(t,r)&&u.push(t)}),c&&(d.commands.length>0||l.length>0||s)&&n._.slice(d.commands.length).forEach(e=>{l.includes(``+e)||u.push(``+e)}),c){let t=e.getDemandedCommands()._?.max||0,r=d.commands.length+t;r<n._.length&&n._.slice(r).forEach(e=>{e=String(e),!d.commands.includes(e)&&!u.includes(e)&&u.push(e)})}u.length&&t.fail(i(`Unknown argument: %s`,`Unknown arguments: %s`,u.length,u.map(e=>e.trim()?e:`"${e}"`).join(`, `)))},a.unknownCommands=function(n){let r=e.getInternalMethods().getCommandInstance().getCommands(),a=[],o=e.getInternalMethods().getContext();return(o.commands.length>0||r.length>0)&&n._.slice(o.commands.length).forEach(e=>{r.includes(``+e)||a.push(``+e)}),a.length>0&&(t.fail(i(`Unknown command: %s`,`Unknown commands: %s`,a.length,a.join(`, `))),!0)},a.isValidAndSomeAliasIsNotNew=function(t,n){if(!Object.prototype.hasOwnProperty.call(n,t))return!1;let r=e.parsed.newAliases;return[t,...n[t]].some(e=>!Object.prototype.hasOwnProperty.call(r,e)||!r[t])},a.limitedChoices=function(n){let i=e.getOptions(),a={};if(!Object.keys(i.choices).length)return;Object.keys(n).forEach(e=>{Mt.indexOf(e)===-1&&Object.prototype.hasOwnProperty.call(i.choices,e)&&[].concat(n[e]).forEach(t=>{i.choices[e].indexOf(t)===-1&&t!==void 0&&(a[e]=(a[e]||[]).concat(t))})});let o=Object.keys(a);if(!o.length)return;let s=r(`Invalid values:`);o.forEach(e=>{s+=`\n ${r(`Argument: %s, Given: %s, Choices: %s`,e,t.stringifiedValues(a[e]),t.stringifiedValues(i.choices[e]))}`}),t.fail(s)};let o={};a.implies=function(t,r){P(`<string|object> [array|number|string]`,[t,r],arguments.length),typeof t==`object`?Object.keys(t).forEach(e=>{a.implies(e,t[e])}):(e.global(t),o[t]||(o[t]=[]),Array.isArray(r)?r.forEach(e=>a.implies(t,e)):(Qe(r,void 0,n),o[t].push(r)))},a.getImplied=function(){return o};function s(e,t){let n=Number(t);return t=isNaN(n)?t:n,typeof t==`number`?t=e._.length>=t:t.match(/^--no-.+/)?(t=t.match(/^--no-(.+)/)[1],t=!Object.prototype.hasOwnProperty.call(e,t)):t=Object.prototype.hasOwnProperty.call(e,t),t}a.implications=function(e){let n=[];if(Object.keys(o).forEach(t=>{let r=t;(o[t]||[]).forEach(t=>{let i=r,a=t;i=s(e,i),t=s(e,t),i&&!t&&n.push(` ${r} -> ${a}`)})}),n.length){let e=`${r(`Implications failed:`)}\n`;n.forEach(t=>{e+=t}),t.fail(e)}};let c={};a.conflicts=function(t,n){P(`<string|object> [array|string]`,[t,n],arguments.length),typeof t==`object`?Object.keys(t).forEach(e=>{a.conflicts(e,t[e])}):(e.global(t),c[t]||(c[t]=[]),Array.isArray(n)?n.forEach(e=>a.conflicts(t,e)):c[t].push(n))},a.getConflicting=()=>c,a.conflicting=function(i){Object.keys(i).forEach(e=>{c[e]&&c[e].forEach(n=>{n&&i[e]!==void 0&&i[n]!==void 0&&t.fail(r(`Arguments %s and %s are mutually exclusive`,e,n))})}),e.getInternalMethods().getParserConfiguration()[`strip-dashed`]&&Object.keys(c).forEach(e=>{c[e].forEach(a=>{a&&i[n.Parser.camelCase(e)]!==void 0&&i[n.Parser.camelCase(a)]!==void 0&&t.fail(r(`Arguments %s and %s are mutually exclusive`,e,a))})})},a.recommendCommands=function(e,n){n=n.sort((e,t)=>t.length-e.length);let i=null,a=1/0;for(let t=0,r;(r=n[t])!==void 0;t++){let t=jt(e,r);t<=3&&t<a&&(a=t,i=r)}i&&t.fail(r(`Did you mean %s?`,i))},a.reset=function(e){return o=yt(o,t=>!e[t]),c=yt(c,t=>!e[t]),a};let l=[];return a.freeze=function(){l.push({implied:o,conflicting:c})},a.unfreeze=function(){let e=l.pop();Qe(e,void 0,n),{implied:o,conflicting:c}=e},a}let Pt=[],Ft;function It(e,t,n,r){Ft=r;let i={};if(Object.prototype.hasOwnProperty.call(e,`extends`)){if(typeof e.extends!=`string`)return i;let r=/\.json|\..*rc$/.test(e.extends),a=null;if(r)a=Rt(t,e.extends);else try{a=me.resolve(e.extends)}catch{return e}Lt(a),Pt.push(a),i=r?JSON.parse(Ft.readFileSync(a,`utf8`)):me(e.extends),delete e.extends,i=It(i,Ft.path.dirname(a),n,Ft)}return Pt=[],n?zt(i,e):Object.assign({},i,e)}function Lt(e){if(Pt.indexOf(e)>-1)throw new M(`Circular extended configurations: '${e}'.`)}function Rt(e,t){return Ft.path.resolve(e,t)}function zt(e,t){let n={};function r(e){return e&&typeof e==`object`&&!Array.isArray(e)}Object.assign(n,e);for(let i of Object.keys(t))n[i]=r(t[i])&&r(n[i])?zt(e[i],t[i]):t[i];return n}var F=function(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n},I=function(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)},L,Bt,Vt,Ht,R,Ut,Wt,Gt,Kt,qt,Jt,Yt,Xt,z,Zt,Qt,$t,B,V,en,tn,nn,rn,an,on,sn,cn,H,ln,un,dn,U,fn,pn,W;function mn(e){return(t=[],n=e.process.cwd(),r)=>{let i=new Zn(t,n,r,e);return Object.defineProperty(i,"argv",{get:()=>i.parse(),enumerable:!0}),i.help(),i.version(),i}}const hn=Symbol(`copyDoubleDash`),gn=Symbol(`copyDoubleDash`),_n=Symbol(`deleteFromParserHintObject`),vn=Symbol(`emitWarning`),yn=Symbol(`freeze`),bn=Symbol(`getDollarZero`),xn=Symbol(`getParserConfiguration`),Sn=Symbol(`getUsageConfiguration`),Cn=Symbol(`guessLocale`),wn=Symbol(`guessVersion`),Tn=Symbol(`parsePositionalNumbers`),En=Symbol(`pkgUp`),Dn=Symbol(`populateParserHintArray`),On=Symbol(`populateParserHintSingleValueDictionary`),kn=Symbol(`populateParserHintArrayDictionary`),An=Symbol(`populateParserHintDictionary`),jn=Symbol(`sanitizeKey`),Mn=Symbol(`setKey`),Nn=Symbol(`unfreeze`),Pn=Symbol(`validateAsync`),Fn=Symbol(`getCommandInstance`),In=Symbol(`getContext`),Ln=Symbol(`getHasOutput`),Rn=Symbol(`getLoggerInstance`),zn=Symbol(`getParseContext`),Bn=Symbol(`getUsageInstance`),Vn=Symbol(`getValidationInstance`),Hn=Symbol(`hasParseCallback`),Un=Symbol(`isGlobalContext`),Wn=Symbol(`postProcess`),Gn=Symbol(`rebase`),Kn=Symbol(`reset`),qn=Symbol(`runYargsParserAndExecuteCommands`),Jn=Symbol(`runValidation`),Yn=Symbol(`setHasOutput`),Xn=Symbol(`kTrackManuallySetKeys`);var Zn=class{constructor(e=[],t,n,r){this.customScriptName=!1,this.parsed=!1,L.set(this,void 0),Bt.set(this,void 0),Vt.set(this,{commands:[],fullCommands:[]}),Ht.set(this,null),R.set(this,null),Ut.set(this,`show-hidden`),Wt.set(this,null),Gt.set(this,!0),Kt.set(this,{}),qt.set(this,!0),Jt.set(this,[]),Yt.set(this,void 0),Xt.set(this,{}),z.set(this,!1),Zt.set(this,null),Qt.set(this,!0),$t.set(this,void 0),B.set(this,``),V.set(this,void 0),en.set(this,void 0),tn.set(this,{}),nn.set(this,null),rn.set(this,null),an.set(this,{}),on.set(this,{}),sn.set(this,void 0),cn.set(this,!1),H.set(this,void 0),ln.set(this,!1),un.set(this,!1),dn.set(this,!1),U.set(this,void 0),fn.set(this,{}),pn.set(this,null),W.set(this,void 0),F(this,H,r,`f`),F(this,sn,e,`f`),F(this,Bt,t,`f`),F(this,en,n,`f`),F(this,Yt,new at(this),`f`),this.$0=this[bn](),this[Kn](),F(this,L,I(this,L,`f`),`f`),F(this,U,I(this,U,`f`),`f`),F(this,W,I(this,W,`f`),`f`),F(this,V,I(this,V,`f`),`f`),I(this,V,`f`).showHiddenOpt=I(this,Ut,`f`),F(this,$t,this[gn](),`f`)}addHelpOpt(e,t){return P(`[string|boolean] [string]`,[e,t],arguments.length),I(this,Zt,`f`)&&(this[_n](I(this,Zt,`f`)),F(this,Zt,null,`f`)),e===!1&&t===void 0||(F(this,Zt,typeof e==`string`?e:`help`,`f`),this.boolean(I(this,Zt,`f`)),this.describe(I(this,Zt,`f`),t||I(this,U,`f`).deferY18nLookup(`Show help`))),this}help(e,t){return this.addHelpOpt(e,t)}addShowHiddenOpt(e,t){if(P(`[string|boolean] [string]`,[e,t],arguments.length),e===!1&&t===void 0)return this;let n=typeof e==`string`?e:I(this,Ut,`f`);return this.boolean(n),this.describe(n,t||I(this,U,`f`).deferY18nLookup(`Show hidden options`)),I(this,V,`f`).showHiddenOpt=n,this}showHidden(e,t){return this.addShowHiddenOpt(e,t)}alias(e,t){return P(`<object|string|array> [string|array]`,[e,t],arguments.length),this[kn](this.alias.bind(this),`alias`,e,t),this}array(e){return P(`<array|string>`,[e],arguments.length),this[Dn](`array`,e),this[Xn](e),this}boolean(e){return P(`<array|string>`,[e],arguments.length),this[Dn](`boolean`,e),this[Xn](e),this}check(e,t){return P(`<function> [boolean]`,[e,t],arguments.length),this.middleware((t,n)=>ct(()=>e(t,n.getOptions()),n=>(n?(typeof n==`string`||n instanceof Error)&&I(this,U,`f`).fail(n.toString(),n):I(this,U,`f`).fail(I(this,H,`f`).y18n.__(`Argument check failed: %s`,e.toString())),t),e=>(I(this,U,`f`).fail(e.message?e.message:e.toString(),e),t)),!1,t),this}choices(e,t){return P(`<object|string|array> [string|array]`,[e,t],arguments.length),this[kn](this.choices.bind(this),`choices`,e,t),this}coerce(e,t){if(P(`<object|string|array> [function]`,[e,t],arguments.length),Array.isArray(e)){if(!t)throw new M(`coerce callback must be provided`);for(let n of e)this.coerce(n,t);return this}if(typeof e==`object`){for(let t of Object.keys(e))this.coerce(t,e[t]);return this}if(!t)throw new M(`coerce callback must be provided`);return I(this,V,`f`).key[e]=!0,I(this,Yt,`f`).addCoerceMiddleware((n,r)=>{let i;return Object.prototype.hasOwnProperty.call(n,e)?ct(()=>(i=r.getAliases(),t(n[e])),t=>{n[e]=t;let a=r.getInternalMethods().getParserConfiguration()[`strip-aliased`];if(i[e]&&a!==!0)for(let r of i[e])n[r]=t;return n},e=>{throw new M(e.message)}):n},e),this}conflicts(e,t){return P(`<string|object> [string|array]`,[e,t],arguments.length),I(this,W,`f`).conflicts(e,t),this}config(e=`config`,t,n){return P(`[object|string] [string|function] [function]`,[e,t,n],arguments.length),typeof e==`object`&&!Array.isArray(e)?(e=It(e,I(this,Bt,`f`),this[xn]()[`deep-merge-config`]||!1,I(this,H,`f`)),I(this,V,`f`).configObjects=(I(this,V,`f`).configObjects||[]).concat(e),this):(typeof t==`function`&&(n=t,t=void 0),this.describe(e,t||I(this,U,`f`).deferY18nLookup(`Path to JSON config file`)),(Array.isArray(e)?e:[e]).forEach(e=>{I(this,V,`f`).config[e]=n||!0}),this)}completion(e,t,n){return P(`[string] [string|boolean|function] [function]`,[e,t,n],arguments.length),typeof t==`function`&&(n=t,t=void 0),F(this,R,e||I(this,R,`f`)||`completion`,`f`),!t&&t!==!1&&(t=`generate completion script`),this.command(I(this,R,`f`),t),n&&I(this,Ht,`f`).registerFunction(n),this}command(e,t,n,r,i,a){return P(`<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]`,[e,t,n,r,i,a],arguments.length),I(this,L,`f`).addHandler(e,t,n,r,i,a),this}commands(e,t,n,r,i,a){return this.command(e,t,n,r,i,a)}commandDir(e,t){P(`<string> [object]`,[e,t],arguments.length);let n=I(this,en,`f`)||I(this,H,`f`).require;return I(this,L,`f`).addDirectory(e,n,I(this,H,`f`).getCallerFile(),t),this}count(e){return P(`<array|string>`,[e],arguments.length),this[Dn](`count`,e),this[Xn](e),this}default(e,t,n){return P(`<object|string|array> [*] [string]`,[e,t,n],arguments.length),n&&($e(e,I(this,H,`f`)),I(this,V,`f`).defaultDescription[e]=n),typeof t==`function`&&($e(e,I(this,H,`f`)),I(this,V,`f`).defaultDescription[e]||(I(this,V,`f`).defaultDescription[e]=I(this,U,`f`).functionDescription(t)),t=t.call()),this[On](this.default.bind(this),`default`,e,t),this}defaults(e,t,n){return this.default(e,t,n)}demandCommand(e=1,t,n,r){return P(`[number] [number|string] [string|null|undefined] [string|null|undefined]`,[e,t,n,r],arguments.length),typeof t!=`number`&&(n=t,t=1/0),this.global(`_`,!1),I(this,V,`f`).demandedCommands._={min:e,max:t,minMsg:n,maxMsg:r},this}demand(e,t,n){return Array.isArray(t)?(t.forEach(e=>{Qe(n,!0,I(this,H,`f`)),this.demandOption(e,n)}),t=1/0):typeof t!=`number`&&(n=t,t=1/0),typeof e==`number`?(Qe(n,!0,I(this,H,`f`)),this.demandCommand(e,t,n,n)):Array.isArray(e)?e.forEach(e=>{Qe(n,!0,I(this,H,`f`)),this.demandOption(e,n)}):typeof n==`string`?this.demandOption(e,n):(n===!0||n===void 0)&&this.demandOption(e),this}demandOption(e,t){return P(`<object|string|array> [string]`,[e,t],arguments.length),this[On](this.demandOption.bind(this),`demandedOptions`,e,t),this}deprecateOption(e,t){return P(`<string> [string|boolean]`,[e,t],arguments.length),I(this,V,`f`).deprecatedOptions[e]=t,this}describe(e,t){return P(`<object|string|array> [string]`,[e,t],arguments.length),this[Mn](e,!0),I(this,U,`f`).describe(e,t),this}detectLocale(e){return P(`<boolean>`,[e],arguments.length),F(this,Gt,e,`f`),this}env(e){return P(`[string|boolean]`,[e],arguments.length),e===!1?delete I(this,V,`f`).envPrefix:I(this,V,`f`).envPrefix=e||``,this}epilogue(e){return P(`<string>`,[e],arguments.length),I(this,U,`f`).epilog(e),this}epilog(e){return this.epilogue(e)}example(e,t){return P(`<string|array> [string]`,[e,t],arguments.length),Array.isArray(e)?e.forEach(e=>this.example(...e)):I(this,U,`f`).example(e,t),this}exit(e,t){F(this,z,!0,`f`),F(this,Wt,t,`f`),I(this,qt,`f`)&&I(this,H,`f`).process.exit(e)}exitProcess(e=!0){return P(`[boolean]`,[e],arguments.length),F(this,qt,e,`f`),this}fail(e){if(P(`<function|boolean>`,[e],arguments.length),typeof e==`boolean`&&e!==!1)throw new M(`Invalid first argument. Expected function or boolean 'false'`);return I(this,U,`f`).failFn(e),this}getAliases(){return this.parsed?this.parsed.aliases:{}}async getCompletion(e,t){return P(`<array> [function]`,[e,t],arguments.length),t?I(this,Ht,`f`).getCompletion(e,t):new Promise((t,n)=>{I(this,Ht,`f`).getCompletion(e,(e,r)=>{e?n(e):t(r)})})}getDemandedOptions(){return P([],0),I(this,V,`f`).demandedOptions}getDemandedCommands(){return P([],0),I(this,V,`f`).demandedCommands}getDeprecatedOptions(){return P([],0),I(this,V,`f`).deprecatedOptions}getDetectLocale(){return I(this,Gt,`f`)}getExitProcess(){return I(this,qt,`f`)}getGroups(){return Object.assign({},I(this,Xt,`f`),I(this,on,`f`))}getHelp(){if(F(this,z,!0,`f`),!I(this,U,`f`).hasCachedHelpMessage()){if(!this.parsed){let e=this[qn](I(this,sn,`f`),void 0,void 0,0,!0);if(N(e))return e.then(()=>I(this,U,`f`).help())}let e=I(this,L,`f`).runDefaultBuilderOn(this);if(N(e))return e.then(()=>I(this,U,`f`).help())}return Promise.resolve(I(this,U,`f`).help())}getOptions(){return I(this,V,`f`)}getStrict(){return I(this,ln,`f`)}getStrictCommands(){return I(this,un,`f`)}getStrictOptions(){return I(this,dn,`f`)}global(e,t){return P(`<string|array> [boolean]`,[e,t],arguments.length),e=[].concat(e),t===!1?e.forEach(e=>{I(this,V,`f`).local.includes(e)||I(this,V,`f`).local.push(e)}):I(this,V,`f`).local=I(this,V,`f`).local.filter(t=>e.indexOf(t)===-1),this}group(e,t){P(`<string|array> <string>`,[e,t],arguments.length);let n=I(this,on,`f`)[t]||I(this,Xt,`f`)[t];I(this,on,`f`)[t]&&delete I(this,on,`f`)[t];let r={};return I(this,Xt,`f`)[t]=(n||[]).concat(e).filter(e=>r[e]?!1:r[e]=!0),this}hide(e){return P(`<string>`,[e],arguments.length),I(this,V,`f`).hiddenOptions.push(e),this}implies(e,t){return P(`<string|object> [number|string|array]`,[e,t],arguments.length),I(this,W,`f`).implies(e,t),this}locale(e){return P(`[string]`,[e],arguments.length),e===void 0?(this[Cn](),I(this,H,`f`).y18n.getLocale()):(F(this,Gt,!1,`f`),I(this,H,`f`).y18n.setLocale(e),this)}middleware(e,t,n){return I(this,Yt,`f`).addMiddleware(e,!!t,n)}nargs(e,t){return P(`<string|object|array> [number]`,[e,t],arguments.length),this[On](this.nargs.bind(this),`narg`,e,t),this}normalize(e){return P(`<array|string>`,[e],arguments.length),this[Dn](`normalize`,e),this}number(e){return P(`<array|string>`,[e],arguments.length),this[Dn](`number`,e),this[Xn](e),this}option(e,t){if(P(`<string|object> [object]`,[e,t],arguments.length),typeof e==`object`)Object.keys(e).forEach(t=>{this.options(t,e[t])});else{typeof t!=`object`&&(t={}),this[Xn](e),I(this,pn,`f`)&&(e===`version`||t?.alias===`version`)&&this[vn]([`"version" is a reserved word.`,`Please do one of the following:`,'- Disable version with `yargs.version(false)` if using "version" as an option',"- Use the built-in `yargs.version` method instead (if applicable)",`- Use a different option key`,`https://yargs.js.org/docs/#api-reference-version`].join(`
|
|
89
|
-
`),void 0,`versionWarning`),
|
|
90
|
-
`,`f`),
|
|
91
|
-
`,`f`),F(this,B,I(this,B,`f`)+e.join(` `),`f`)}}}[_n](e){et(I(this,V,`f`)).forEach(t=>{if((e=>e===`configObjects`)(t))return;let n=I(this,V,`f`)[t];Array.isArray(n)?n.includes(e)&&n.splice(n.indexOf(e),1):typeof n==`object`&&delete n[e]}),delete I(this,U,`f`).getDescriptions()[e]}[vn](e,t,n){I(this,Kt,`f`)[n]||(I(this,H,`f`).process.emitWarning(e,t),I(this,Kt,`f`)[n]=!0)}[yn](){I(this,Jt,`f`).push({options:I(this,V,`f`),configObjects:I(this,V,`f`).configObjects.slice(0),exitProcess:I(this,qt,`f`),groups:I(this,Xt,`f`),strict:I(this,ln,`f`),strictCommands:I(this,un,`f`),strictOptions:I(this,dn,`f`),completionCommand:I(this,R,`f`),output:I(this,B,`f`),exitError:I(this,Wt,`f`),hasOutput:I(this,z,`f`),parsed:this.parsed,parseFn:I(this,nn,`f`),parseContext:I(this,rn,`f`)}),I(this,U,`f`).freeze(),I(this,W,`f`).freeze(),I(this,L,`f`).freeze(),I(this,Yt,`f`).freeze()}[bn](){let e=``,t;return t=/\b(node|iojs|electron)(\.exe)?$/.test(I(this,H,`f`).process.argv()[0])?I(this,H,`f`).process.argv().slice(1,2):I(this,H,`f`).process.argv().slice(0,1),e=t.map(e=>{let t=this[Gn](I(this,Bt,`f`),e);return e.match(/^(\/|([a-zA-Z]:)?\\)/)&&t.length<e.length?t:e}).join(` `).trim(),I(this,H,`f`).getEnv(`_`)&&I(this,H,`f`).getProcessArgvBin()===I(this,H,`f`).getEnv(`_`)&&(e=I(this,H,`f`).getEnv(`_`).replace(`${I(this,H,`f`).path.dirname(I(this,H,`f`).process.execPath())}/`,``)),e}[xn](){return I(this,tn,`f`)}[Sn](){return I(this,fn,`f`)}[Cn](){if(!I(this,Gt,`f`))return;let e=I(this,H,`f`).getEnv(`LC_ALL`)||I(this,H,`f`).getEnv(`LC_MESSAGES`)||I(this,H,`f`).getEnv(`LANG`)||I(this,H,`f`).getEnv(`LANGUAGE`)||`en_US`;this.locale(e.replace(/[.:].*/,``))}[wn](){return this[En]().version||`unknown`}[Tn](e){let t=e[`--`]?e[`--`]:e._;for(let e=0,n;(n=t[e])!==void 0;e++)I(this,H,`f`).Parser.looksLikeNumber(n)&&Number.isSafeInteger(Math.floor(parseFloat(`${n}`)))&&(t[e]=Number(n));return e}[En](e){let t=e||`*`;if(I(this,an,`f`)[t])return I(this,an,`f`)[t];let n={};try{let t=e||I(this,H,`f`).mainFilename;!e&&I(this,H,`f`).path.extname(t)&&(t=I(this,H,`f`).path.dirname(t));let r=I(this,H,`f`).findUp(t,(e,t)=>{if(t.includes(`package.json`))return`package.json`});Qe(r,void 0,I(this,H,`f`)),n=JSON.parse(I(this,H,`f`).readFileSync(r,`utf8`))}catch{}return I(this,an,`f`)[t]=n||{},I(this,an,`f`)[t]}[Dn](e,t){t=[].concat(t),t.forEach(t=>{t=this[jn](t),I(this,V,`f`)[e].push(t)})}[On](e,t,n,r){this[An](e,t,n,r,(e,t,n)=>{I(this,V,`f`)[e][t]=n})}[kn](e,t,n,r){this[An](e,t,n,r,(e,t,n)=>{I(this,V,`f`)[e][t]=(I(this,V,`f`)[e][t]||[]).concat(n)})}[An](e,t,n,r,i){if(Array.isArray(n))n.forEach(t=>{e(t,r)});else if((e=>typeof e==`object`)(n))for(let t of et(n))e(t,n[t]);else i(t,this[jn](n),r)}[jn](e){return e===`__proto__`?`___proto___`:e}[Mn](e,t){return this[On](this[Mn].bind(this),`key`,e,t),this}[Nn](){var e,t,n,r,i,a,o,s,c,l,u,d;let f=I(this,Jt,`f`).pop();Qe(f,void 0,I(this,H,`f`));let p;e=this,t=this,n=this,r=this,i=this,a=this,o=this,s=this,c=this,l=this,u=this,d=this,{options:{set value(t){F(e,V,t,`f`)}}.value,configObjects:p,exitProcess:{set value(e){F(t,qt,e,`f`)}}.value,groups:{set value(e){F(n,Xt,e,`f`)}}.value,output:{set value(e){F(r,B,e,`f`)}}.value,exitError:{set value(e){F(i,Wt,e,`f`)}}.value,hasOutput:{set value(e){F(a,z,e,`f`)}}.value,parsed:this.parsed,strict:{set value(e){F(o,ln,e,`f`)}}.value,strictCommands:{set value(e){F(s,un,e,`f`)}}.value,strictOptions:{set value(e){F(c,dn,e,`f`)}}.value,completionCommand:{set value(e){F(l,R,e,`f`)}}.value,parseFn:{set value(e){F(u,nn,e,`f`)}}.value,parseContext:{set value(e){F(d,rn,e,`f`)}}.value}=f,I(this,V,`f`).configObjects=p,I(this,U,`f`).unfreeze(),I(this,W,`f`).unfreeze(),I(this,L,`f`).unfreeze(),I(this,Yt,`f`).unfreeze()}[Pn](e,t){return ct(t,t=>(e(t),t))}getInternalMethods(){return{getCommandInstance:this[Fn].bind(this),getContext:this[In].bind(this),getHasOutput:this[Ln].bind(this),getLoggerInstance:this[Rn].bind(this),getParseContext:this[zn].bind(this),getParserConfiguration:this[xn].bind(this),getUsageConfiguration:this[Sn].bind(this),getUsageInstance:this[Bn].bind(this),getValidationInstance:this[Vn].bind(this),hasParseCallback:this[Hn].bind(this),isGlobalContext:this[Un].bind(this),postProcess:this[Wn].bind(this),reset:this[Kn].bind(this),runValidation:this[Jn].bind(this),runYargsParserAndExecuteCommands:this[qn].bind(this),setHasOutput:this[Yn].bind(this)}}[Fn](){return I(this,L,`f`)}[In](){return I(this,Vt,`f`)}[Ln](){return I(this,z,`f`)}[Rn](){return I(this,$t,`f`)}[zn](){return I(this,rn,`f`)||{}}[Bn](){return I(this,U,`f`)}[Vn](){return I(this,W,`f`)}[Hn](){return!!I(this,nn,`f`)}[Un](){return I(this,Qt,`f`)}[Wn](e,t,n,r){return n||N(e)||(t||(e=this[hn](e)),(this[xn]()[`parse-positional-numbers`]||this[xn]()[`parse-positional-numbers`]===void 0)&&(e=this[Tn](e)),r&&(e=st(e,this,I(this,Yt,`f`).getMiddleware(),!1))),e}[Kn](e={}){F(this,V,I(this,V,`f`)||{},`f`);let t={};t.local=I(this,V,`f`).local||[],t.configObjects=I(this,V,`f`).configObjects||[];let n={};return t.local.forEach(t=>{n[t]=!0,(e[t]||[]).forEach(e=>{n[e]=!0})}),Object.assign(I(this,on,`f`),Object.keys(I(this,Xt,`f`)).reduce((e,t)=>{let r=I(this,Xt,`f`)[t].filter(e=>!(e in n));return r.length>0&&(e[t]=r),e},{})),F(this,Xt,{},`f`),[`array`,`boolean`,`string`,`skipValidation`,`count`,`normalize`,`number`,`hiddenOptions`].forEach(e=>{t[e]=(I(this,V,`f`)[e]||[]).filter(e=>!n[e])}),[`narg`,`key`,`alias`,`default`,`defaultDescription`,`config`,`choices`,`demandedOptions`,`demandedCommands`,`deprecatedOptions`].forEach(e=>{t[e]=yt(I(this,V,`f`)[e],e=>!n[e])}),t.envPrefix=I(this,V,`f`).envPrefix,F(this,V,t,`f`),F(this,U,I(this,U,`f`)?I(this,U,`f`).reset(n):St(this,I(this,H,`f`)),`f`),F(this,W,I(this,W,`f`)?I(this,W,`f`).reset(n):Nt(this,I(this,U,`f`),I(this,H,`f`)),`f`),F(this,L,I(this,L,`f`)?I(this,L,`f`).reset():pt(I(this,U,`f`),I(this,W,`f`),I(this,Yt,`f`),I(this,H,`f`)),`f`),I(this,Ht,`f`)||F(this,Ht,Ot(this,I(this,U,`f`),I(this,L,`f`),I(this,H,`f`)),`f`),I(this,Yt,`f`).reset(),F(this,R,null,`f`),F(this,B,``,`f`),F(this,Wt,null,`f`),F(this,z,!1,`f`),this.parsed=!1,this}[Gn](e,t){return I(this,H,`f`).path.relative(e,t)}[qn](e,t,n,r=0,i=!1){let a=!!n||i;e||=I(this,sn,`f`),I(this,V,`f`).__=I(this,H,`f`).y18n.__,I(this,V,`f`).configuration=this[xn]();let o=!!I(this,V,`f`).configuration[`populate--`],s=Object.assign({},I(this,V,`f`).configuration,{"populate--":!0}),c=I(this,H,`f`).Parser.detailed(e,Object.assign({},I(this,V,`f`),{configuration:{"parse-positional-numbers":!1,...s}})),l=Object.assign(c.argv,I(this,rn,`f`)),u,d=c.aliases,f=!1,p=!1;Object.keys(l).forEach(e=>{e===I(this,Zt,`f`)&&l[e]?f=!0:e===I(this,pn,`f`)&&l[e]&&(p=!0)}),l.$0=this.$0,this.parsed=c,r===0&&I(this,U,`f`).clearCachedHelpMessage();try{if(this[Cn](),t)return this[Wn](l,o,!!n,!1);I(this,Zt,`f`)&&[I(this,Zt,`f`)].concat(d[I(this,Zt,`f`)]||[]).filter(e=>e.length>1).includes(``+l._[l._.length-1])&&(l._.pop(),f=!0),F(this,Qt,!1,`f`);let s=I(this,L,`f`).getCommands(),m=I(this,Ht,`f`).completionKey in l,h=f||m||i;if(l._.length){if(s.length){let e;for(let t=r||0,a;l._[t]!==void 0;t++){if(a=String(l._[t]),s.includes(a)&&a!==I(this,R,`f`)){let e=I(this,L,`f`).runCommand(a,this,c,t+1,i,f||p||i);return this[Wn](e,o,!!n,!1)}if(!e&&a!==I(this,R,`f`)){e=a;break}}!I(this,L,`f`).hasDefaultCommand()&&I(this,cn,`f`)&&e&&!h&&I(this,W,`f`).recommendCommands(e,s)}I(this,R,`f`)&&l._.includes(I(this,R,`f`))&&!m&&(I(this,qt,`f`)&&bt(!0),this.showCompletionScript(),this.exit(0))}if(I(this,L,`f`).hasDefaultCommand()&&!h){let e=I(this,L,`f`).runCommand(null,this,c,0,i,f||p||i);return this[Wn](e,o,!!n,!1)}if(m){I(this,qt,`f`)&&bt(!0),e=[].concat(e);let t=e.slice(e.indexOf(`--${I(this,Ht,`f`).completionKey}`)+1);return I(this,Ht,`f`).getCompletion(t,(e,t)=>{if(e)throw new M(e.message);(t||[]).forEach(e=>{I(this,$t,`f`).log(e)}),this.exit(0)}),this[Wn](l,!o,!!n,!1)}if(I(this,z,`f`)||(f?(I(this,qt,`f`)&&bt(!0),a=!0,this.showHelp(`log`),this.exit(0)):p&&(I(this,qt,`f`)&&bt(!0),a=!0,I(this,U,`f`).showVersion(`log`),this.exit(0))),!a&&I(this,V,`f`).skipValidation.length>0&&(a=Object.keys(l).some(e=>I(this,V,`f`).skipValidation.indexOf(e)>=0&&l[e]===!0)),!a){if(c.error)throw new M(c.error.message);if(!m){let e=this[Jn](d,{},c.error);n||(u=st(l,this,I(this,Yt,`f`).getMiddleware(),!0)),u=this[Pn](e,u??l),N(u)&&!n&&(u=u.then(()=>st(l,this,I(this,Yt,`f`).getMiddleware(),!1)))}}}catch(e){if(e instanceof M)I(this,U,`f`).fail(e.message,e);else throw e}return this[Wn](u??l,o,!!n,!0)}[Jn](e,t,n,r){let i={...this.getDemandedOptions()};return a=>{if(n)throw new M(n.message);I(this,W,`f`).nonOptionCount(a),I(this,W,`f`).requiredArguments(a,i);let o=!1;I(this,un,`f`)&&(o=I(this,W,`f`).unknownCommands(a)),I(this,ln,`f`)&&!o?I(this,W,`f`).unknownArguments(a,e,t,!!r):I(this,dn,`f`)&&I(this,W,`f`).unknownArguments(a,e,{},!1,!1),I(this,W,`f`).limitedChoices(a),I(this,W,`f`).implications(a),I(this,W,`f`).conflicting(a)}}[Yn](){F(this,z,!0,`f`)}[Xn](e){if(typeof e==`string`)I(this,V,`f`).key[e]=!0;else for(let t of e)I(this,V,`f`).key[t]=!0}};function Qn(e){return!!e&&typeof e.getInternalMethods==`function`}const $n=mn(Ze);var er=class extends Error{};function tr(e){if(!Number.isInteger(e)||e<60||e>600)throw new er(`Expected a whole number of seconds from 60 to 600.`);return e}function nr(e,t=`https://astralbeam.ai/api`){return`${t.replace(/\/+$/,``)}${e.replace(/^\/api(?=\/)/,``)}`}function rr(e,t){if(!e||typeof e!=`object`)return!1;let n=e;return n.status===t&&typeof n.type==`string`&&typeof n.title==`string`&&typeof n.detail==`string`&&(n.reference===void 0||typeof n.reference==`string`)&&(n.issues===void 0||Array.isArray(n.issues)&&n.issues.every(e=>e&&typeof e.path==`string`&&typeof e.message==`string`))}async function ir(e,t){let{apiUrl:n,apiKey:r,astralBeamToken:i,fetchClient:a=globalThis.fetch,...o}=t,s=new Headers,c=o.headers instanceof Headers?o.headers.entries():Array.isArray(o.headers)?o.headers:Object.entries(o.headers??{});for(let[e,t]of c)s.set(e,t);s.delete(`authorization`),s.delete(`x-api-key`),r&&s.set(`x-api-key`,r),i&&s.set(`authorization`,`Bearer ${i}`);let l=await a(nr(e,n),{...o,headers:s,...r?{redirect:`error`}:{}});if(l.ok)return l;let u=await l.json().catch(e=>{if(!(e instanceof SyntaxError))throw e}),d=rr(u,l.status)?u:void 0;throw Object.assign(Error(d?.detail??`AstralBeam API returned HTTP ${l.status}`),{name:`AstralBeamApiError`,status:l.status,headers:l.headers,body:d})}async function ar(e,t){let n=await ir(e,t);if(n.status!==204)return await n.json()}function or(e){return e instanceof Error&&e.name===`AstralBeamApiError`&&`status`in e&&typeof e.status==`number`}function sr(e,t=`https://astralbeam.ai/api`){return`${t.replace(/\/+$/,``)}${e.replace(/^\/api(?=\/)/,``)}`}function cr(e,t){if(!e||typeof e!=`object`)return!1;let n=e;return n.status===t&&typeof n.type==`string`&&typeof n.title==`string`&&typeof n.detail==`string`&&(n.reference===void 0||typeof n.reference==`string`)&&(n.issues===void 0||Array.isArray(n.issues)&&n.issues.every(e=>e&&typeof e.path==`string`&&typeof e.message==`string`))}async function lr(e,t){let{apiUrl:n,apiKey:r,astralBeamToken:i,fetchClient:a=globalThis.fetch,...o}=t,s=new Headers,c=o.headers instanceof Headers?o.headers.entries():Array.isArray(o.headers)?o.headers:Object.entries(o.headers??{});for(let[e,t]of c)s.set(e,t);s.delete(`authorization`),s.delete(`x-api-key`),r&&s.set(`x-api-key`,r),i&&s.set(`authorization`,`Bearer ${i}`);let l=await a(sr(e,n),{...o,headers:s,...r?{redirect:`error`}:{}});if(l.ok)return l;let u=await l.json().catch(e=>{if(!(e instanceof SyntaxError))throw e}),d=cr(u,l.status)?u:void 0;throw Object.assign(Error(d?.detail??`AstralBeam API returned HTTP ${l.status}`),{name:`AstralBeamApiError`,status:l.status,headers:l.headers,body:d})}async function ur(e,t){let n=await lr(e,t);if(n.status!==204)return await n.json()}function G(e,t){return ur(e,t)}async function dr(e,t){let n=await lr(e,t),r=n.status===204?n.headers.get(`location`):null;if(!r)return n;let i=await globalThis.fetch(r,{credentials:`omit`,redirect:`error`,referrerPolicy:`no-referrer`,signal:t.signal??null});if(!i.ok)throw Error(`The file could not be downloaded. Please try again.`);return i}function fr(e,t){return lr(e,t)}const pr=()=>`/api/v1/organization`,mr=e=>ur(pr(),{...e,method:`GET`}),hr=()=>`/api/v1/chat/files`,gr=(e,t)=>{let n=e=>{if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Symbol.iterator in e)return Object.fromEntries(Array.from(e,e=>Array.from(e)));let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t};return G(hr(),{...t,method:`POST`,headers:{"Content-Type":`application/json`,...n(t?.headers)},body:JSON.stringify(e)})},_r=e=>{let t=new URLSearchParams;Object.entries(e||{}).forEach(([e,n])=>{n!==void 0&&t.append(e,n===null?`null`:String(n))});let n=t.toString();return n.length>0?`/api/v1/chat/files?${n}`:`/api/v1/chat/files`},vr=(e,t)=>dr(_r(e),{...t,method:`GET`}),yr=()=>`/api/v1/chat`,br=e=>{let t=new URLSearchParams;Object.entries(e||{}).forEach(([e,n])=>{n!==void 0&&t.append(e,n===null?`null`:String(n))});let n=t.toString();return n.length>0?`/api/v1/chat/config?${n}`:`/api/v1/chat/config`},xr=(e,t)=>G(br(e),{...t,method:`GET`}),Sr=()=>`/api/v1/chat/threads`,Cr=(e,t)=>{let n=e=>{if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Symbol.iterator in e)return Object.fromEntries(Array.from(e,e=>Array.from(e)));let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t};return G(Sr(),{...t,method:`POST`,headers:{"Content-Type":`application/json`,...n(t?.headers)},body:JSON.stringify(e)})},wr=e=>{let t=new URLSearchParams;Object.entries(e||{}).forEach(([e,n])=>{n!==void 0&&t.append(e,n===null?`null`:String(n))});let n=t.toString();return n.length>0?`/api/v1/chat/threads?${n}`:`/api/v1/chat/threads`},Tr=(e,t)=>G(wr(e),{...t,method:`GET`}),Er=e=>`/api/v1/chat/threads/${encodeURIComponent(String(e))}`,Dr=(e,t,n)=>{let r=e=>{if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Symbol.iterator in e)return Object.fromEntries(Array.from(e,e=>Array.from(e)));let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t};return G(Er(e),{...n,method:`PATCH`,headers:{"Content-Type":`application/json`,...r(n?.headers)},body:JSON.stringify(t)})},Or=(e,t)=>{let n=new URLSearchParams;Object.entries(t||{}).forEach(([e,t])=>{t!==void 0&&n.append(e,t===null?`null`:String(t))});let r=n.toString();return r.length>0?`/api/v1/chat/threads/${encodeURIComponent(String(e))}?${r}`:`/api/v1/chat/threads/${encodeURIComponent(String(e))}`},kr=(e,t,n)=>G(Or(e,t),{...n,method:`DELETE`}),Ar=(e,t)=>{let n=new URLSearchParams;Object.entries(t||{}).forEach(([e,t])=>{t!==void 0&&n.append(e,t===null?`null`:String(t))});let r=n.toString();return r.length>0?`/api/v1/chat/threads/${encodeURIComponent(String(e))}/messages?${r}`:`/api/v1/chat/threads/${encodeURIComponent(String(e))}/messages`},jr=(e,t,n)=>G(Ar(e,t),{...n,method:`GET`}),Mr=e=>`/api/v1/chat/threads/${encodeURIComponent(String(e))}/tool-results`,Nr=()=>`/api/v1/me`,Pr=e=>G(Nr(),{...e,method:`POST`}),Fr=()=>`/api/v1/me/mcp/catalog`,Ir=e=>G(Fr(),{...e,method:`GET`}),Lr=()=>`/api/v1/me/mcp/connections`,Rr=(e,t)=>{let n=e=>{if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Symbol.iterator in e)return Object.fromEntries(Array.from(e,e=>Array.from(e)));let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t};return G(Lr(),{...t,method:`POST`,headers:{"Content-Type":`application/json`,...n(t?.headers)},body:JSON.stringify(e)})},zr=e=>`/api/v1/me/mcp/connections/${encodeURIComponent(String(e))}/headers`,Br=(e,t,n)=>{let r=e=>{if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Symbol.iterator in e)return Object.fromEntries(Array.from(e,e=>Array.from(e)));let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t};return G(zr(e),{...n,method:`POST`,headers:{"Content-Type":`application/json`,...r(n?.headers)},body:JSON.stringify(t)})},Vr=e=>`/api/v1/me/mcp/connections/${encodeURIComponent(String(e))}`,Hr=(e,t)=>G(Vr(e),{...t,method:`DELETE`}),Ur=e=>`/api/v1/me/mcp/connections/${encodeURIComponent(String(e))}/test`,Wr=(e,t)=>G(Ur(e),{...t,method:`POST`}),Gr=e=>`/api/v1/me/mcp/connections/${encodeURIComponent(String(e))}/authorize`,Kr=(e,t)=>G(Gr(e),{...t,method:`POST`}),qr=e=>`/api/v1/me/mcp/connections/${encodeURIComponent(String(e))}/oauth/bind`,Jr=(e,t,n)=>{let r=e=>{if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Symbol.iterator in e)return Object.fromEntries(Array.from(e,e=>Array.from(e)));let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t};return G(qr(e),{...n,method:`POST`,headers:{"Content-Type":`application/json`,...r(n?.headers)},body:JSON.stringify(t)})},Yr=e=>`/api/v1/me/mcp/connections/${encodeURIComponent(String(e))}/oauth/complete`,Xr=(e,t,n)=>{let r=e=>{if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Symbol.iterator in e)return Object.fromEntries(Array.from(e,e=>Array.from(e)));let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t};return G(Yr(e),{...n,method:`POST`,headers:{"Content-Type":`application/json`,...r(n?.headers)},body:JSON.stringify(t)})};var Zr=`0.30.0`;function Qr(e){s.write(`${JSON.stringify(e,null,2)}\n`)}function $r(e,t=``){let n=``;for(let r of e){let e=r.codePointAt(0)??0;n+=(e<32||e>=127&&e<160)&&!t.includes(r)?`\\u${e.toString(16).padStart(4,`0`)}`:r}return n}function ei(e){return e==null?``:$r(typeof e==`string`?e:JSON.stringify(e))}function ti(e){let t=Object.entries(e),n=Math.max(...t.map(([e])=>e.length));for(let[e,r]of t)s.write(`${e.padEnd(n)} ${ei(r)}\n`)}function ni(e,t){t?Qr(e):ti(e)}function ri(e,t){let n=e.map(e=>t.map(t=>ei(e[t]))),r=t.map((e,t)=>n.reduce((e,n)=>Math.max(e,n[t]?.length??0),e.length)),i=e=>`${e.map((e,t)=>e.padEnd(r[t]??0)).join(` `)}`.trimEnd();s.write(`${i(t.map(e=>e.toUpperCase()))}\n`);for(let e of n)s.write(`${i(e)}\n`)}function ii(e){if(e.status===401)return"The API key was rejected. It may be revoked or deleted, so create a new one and run `astralbeam auth login` again.";if(e.status===404&&e.body?.detail===`Resource not found.`)return`This server does not serve that endpoint. Check the API URL, or the server may run an older AstralBeam release than this CLI (${Zr}).`;if(e.status===429)return`The API rate limit was reached. Wait a few minutes and retry.`}function ai(e,t,n,r){let i=e instanceof Error?e.message:String(e);if(t){let t=or(e)?e.body??{status:e.status,detail:i}:{detail:i};a.write(`${JSON.stringify({error:t,context:n??null})}\n`);return}if(!or(e))return void a.write(`Error: ${$r(i)}\n`);let o=r?` from ${r}`:``;a.write(`Error: ${$r(i)} (HTTP ${e.status}${o})\n`);for(let t of e.body?.issues??[])a.write(` ${$r(t.path)}: ${$r(t.message)}\n`);let s=ii(e);s&&a.write(`${s}\n`)}const oi=`https://astralbeam.ai/api`,si=/^key_([0-9a-f-]{36})_[0-9a-f-]{36}_abo_[A-Za-z]{64}$/;function ci(){if(n.ASTRALBEAM_CONFIG_DIR)return se(n.ASTRALBEAM_CONFIG_DIR,`config.json`);let e=i===`win32`?n.APPDATA??oe():n.XDG_CONFIG_HOME??se(oe(),`.config`);return se(e,`astralbeam`,`config.json`)}function li(e){let t=si.exec(e)?.[1];if(!t)throw Error(`The API key must match key_<organizationId>_<id>_abo_<secret>.`);return t}function ui(e){let t;try{t=new URL(e)}catch{throw Error(`The API URL "${e}" is not a valid URL.`)}let n=t.hostname,r=n===`localhost`||n===`[::1]`||ae(n)&&n.startsWith(`127.`);if(t.protocol!==`https:`&&!(t.protocol===`http:`&&r))throw Error(`The API URL "${e}" must use https://, or http:// only for loopback hosts.`);return e}function di(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function fi(e){return di(e)&&Object.values(e).every(e=>di(e)&&typeof e.api_url==`string`&&typeof e.api_key==`string`&&di(e.organization)&&typeof e.organization.id==`string`&&typeof e.organization.name==`string`&&typeof e.organization.slug==`string`)}function pi(e){try{let t=JSON.parse(e);if(di(t)){let e=t.bindings===void 0?{}:t.bindings;if(fi(e))return{bindings:e}}}catch{}throw Error(`Invalid AstralBeam login bindings in ${ci()}`)}async function mi(){try{return pi(await b(ci(),`utf8`))}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return{bindings:{}};throw e}}async function hi(e){let t=ci();await re(w(t),{recursive:!0,mode:448});let n=`${t}.${r}.tmp`;try{await C(n,`${JSON.stringify(e,null,2)}\n`,{mode:384,flag:`wx`}),await S(n,t)}catch(e){throw await ie(n,{force:!0}),e}}async function gi(){return await x(t())}function _i(e,t){for(let n=t;;n=w(n)){let t=e.bindings[n];if(t)return{directory:n,binding:t};if(w(n)===n)return}}function vi(e){let t=oe();return e===t||e.startsWith(t+le)?`~${e.slice(t.length)}`:e}const K={json:!1,context:void 0,failedRequest:void 0};function yi(e){K.context={organization:e.organization,bound_directory:e.directory??null},K.json||a.write(bi(e))}function bi(e){let{organization:t,directory:n}=e,r=t.name?`${$r(t.name)} (${$r(t.slug??``)}) · `:``,i=n?`bound at ${vi(n)}`:`from ASTRALBEAM_API_KEY`;return`▸ ${r}org ${t.id} · ${i}\n`}async function xi(){let e=n.ASTRALBEAM_API_KEY,t;if(e)t={apiKey:e,apiUrl:ui(n.ASTRALBEAM_API_URL??`https://astralbeam.ai/api`),organization:{id:li(e)}};else{let e=await gi(),r=_i(await mi(),e);if(!r)throw Error(`No AstralBeam login covers ${vi(e)}. Run \`astralbeam auth login\` in this directory or a parent, or set ASTRALBEAM_API_KEY.`);let{binding:i}=r;t={apiKey:i.api_key,apiUrl:ui(n.ASTRALBEAM_API_URL??i.api_url),organization:i.organization,directory:r.directory}}return yi(t),t}function Si(e,t=[]){let n=(e,r)=>{if(Array.isArray(e)||typeof e!=`object`||!e)return e;let i=Object.entries(e).flatMap(([e,i])=>{let a=[...r,e],o=t.some(e=>e.length===a.length&&e.every((e,t)=>e===a[t])),s=o?i:n(i,a);return s===void 0||!o&&typeof s==`object`&&s&&!Array.isArray(s)&&Object.keys(s).length===0?[]:[[e,s]]});return Object.fromEntries(i)};return n(e,[])}function Ci(e,t){let n=t.startsWith(`--`)?t:`--${t}`,r=e;if(e.startsWith(`@`)){let t=e.slice(1);if(t.length===0)throw Error(`${n} '@' must be followed by a file path (got empty path)`);let i=ce(t);try{r=ue(i,`utf-8`)}catch(e){let r=e instanceof Error?e.message:`unknown read error`;throw Error(`${n}: cannot read file at '${t}': ${r}`)}}try{return JSON.parse(r)}catch{throw Error(`Invalid JSON in ${n}. Expected valid JSON.`)}}function wi(e,t=[]){let n=Ci(e,`body`);for(let{path:e,flag:r}of t){let t=n;for(let n of e)t=Ti(t)&&Object.hasOwn(t,n)?t[n]:void 0;if(!Ti(t))throw Error(`--body must include a JSON object at ${e.join(`.`)} (for --${r}).`)}return n}function Ti(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ei(e,t,n=!1){let r=t.startsWith(`--`)?t:`--${t}`;if(e===void 0){if(n)throw Error(`${r} is required (or pass --body with this field set).`);return}if(typeof e!=`string`)throw Error(`${r} must be provided once as a JSON object.`);let i=Ci(e,t);if(!Ti(i))throw Error(`${r} must be a JSON object.`);return i}function Di(e,t,n=`text`){if(e===void 0||!e.startsWith(`@`))return e;let r=e.slice(1);if(r.length===0)throw Error(`--${t} '@' must be followed by a file path (got empty path)`);let i=ce(r),a;try{a=ue(i)}catch(e){let n=e instanceof Error?e.message:`unknown read error`;throw Error(`--${t}: cannot read file at '${r}': ${n}`)}switch(n){case`text`:return a.toString(`utf-8`);case`binary`:return a;case`base64`:return a.toString(`base64`);case`json`:{let e=a.toString(`utf-8`);try{return JSON.parse(e)}catch(e){let n=e instanceof Error?e.message:`unknown JSON parse error`;throw Error(`--${t}: file at '${r}' is not valid JSON: ${n}`)}}}}function Oi(e){return e.replace(/^filter_(.+)$/,`filter[$1]`)}async function ki(e){let{apiKey:t,apiUrl:n}=await xi();return{send(e,r={}){let i=new URLSearchParams;for(let t of e.query??[]){let e=r[t];e!==void 0&&i.set(Oi(t),typeof e==`string`?e:JSON.stringify(e))}return ar(e.path(r)+(i.size?`?${i.toString()}`:``),{apiKey:t,apiUrl:n,method:e.method,...e.body?{headers:{"content-type":`application/json`},body:JSON.stringify(r.body)}:{}})}}}function q(e,t){if(e!==void 0){if(K.json||typeof e!=`object`||!e)return Qr(e);if(`items`in e&&Array.isArray(e.items)){let t=e.items;t.length?ri(t,Object.keys(t[0])):a.write(`No results.
|
|
87
|
+
`,r=this.shim.path.basename(e);return e.match(/\.js$/)&&(e=`./${e}`),n=n.replace(/{{app_name}}/g,r),n=n.replace(/{{completion_command}}/g,t),n.replace(/{{app_path}}/g,e)}registerFunction(e){this.customCompletionFunction=e}setParsed(e){this.aliases=e.aliases}};function Et(e,t,n,r){return new Tt(e,t,n,r)}function Dt(e){return e.length<3}function Ot(e){return e.length>3}function kt(e,t){if(e.length===0)return t.length;if(t.length===0)return e.length;let n=[],r=0;for(;r<=t.length;r++)n[r]=[r];let i=0;for(;i<=e.length;i++)n[0][i]=i;for(r=1;r<=t.length;r++)for(i=1;i<=e.length;i++)t.charAt(r-1)===e.charAt(i-1)?n[r][i]=n[r-1][i-1]:r>1&&i>1&&t.charAt(r-2)===e.charAt(i-1)&&t.charAt(r-1)===e.charAt(i-2)?n[r][i]=n[r-2][i-2]+1:n[r][i]=Math.min(n[r-1][i-1]+1,Math.min(n[r][i-1]+1,n[r-1][i]+1));return n[t.length][e.length]}const At=[`$0`,`--`,`_`];function jt(e,t,n){let r=n.y18n.__,i=n.y18n.__n,a={};a.nonOptionCount=function(n){let r=e.getDemandedCommands(),a=n._.length+(n[`--`]?n[`--`].length:0)-e.getInternalMethods().getContext().commands.length;r._&&(a<r._.min||a>r._.max)&&(a<r._.min?r._.minMsg===void 0?t.fail(i(`Not enough non-option arguments: got %s, need at least %s`,`Not enough non-option arguments: got %s, need at least %s`,a,a.toString(),r._.min.toString())):t.fail(r._.minMsg?r._.minMsg.replace(/\$0/g,a.toString()).replace(/\$1/,r._.min.toString()):null):a>r._.max&&(r._.maxMsg===void 0?t.fail(i(`Too many non-option arguments: got %s, maximum of %s`,`Too many non-option arguments: got %s, maximum of %s`,a,a.toString(),r._.max.toString())):t.fail(r._.maxMsg?r._.maxMsg.replace(/\$0/g,a.toString()).replace(/\$1/,r._.max.toString()):null)))},a.positionalCount=function(e,n){n<e&&t.fail(i(`Not enough non-option arguments: got %s, need at least %s`,`Not enough non-option arguments: got %s, need at least %s`,n,n+``,e+``))},a.requiredArguments=function(e,n){let r=null;for(let t of Object.keys(n))(!Object.prototype.hasOwnProperty.call(e,t)||e[t]===void 0)&&(r||={},r[t]=n[t]);if(r){let e=[];for(let t of Object.keys(r)){let n=r[t];n&&e.indexOf(n)<0&&e.push(n)}let n=e.length?`\n${e.join(`
|
|
88
|
+
`)}`:``;t.fail(i(`Missing required argument: %s`,`Missing required arguments: %s`,Object.keys(r).length,Object.keys(r).join(`, `)+n))}},a.unknownArguments=function(n,r,o,s,c=!0){let l=e.getInternalMethods().getCommandInstance().getCommands(),u=[],d=e.getInternalMethods().getContext();if(Object.keys(n).forEach(t=>{!At.includes(t)&&!Object.prototype.hasOwnProperty.call(o,t)&&!Object.prototype.hasOwnProperty.call(e.getInternalMethods().getParseContext(),t)&&!a.isValidAndSomeAliasIsNotNew(t,r)&&u.push(t)}),c&&(d.commands.length>0||l.length>0||s)&&n._.slice(d.commands.length).forEach(e=>{l.includes(``+e)||u.push(``+e)}),c){let t=e.getDemandedCommands()._?.max||0,r=d.commands.length+t;r<n._.length&&n._.slice(r).forEach(e=>{e=String(e),!d.commands.includes(e)&&!u.includes(e)&&u.push(e)})}u.length&&t.fail(i(`Unknown argument: %s`,`Unknown arguments: %s`,u.length,u.map(e=>e.trim()?e:`"${e}"`).join(`, `)))},a.unknownCommands=function(n){let r=e.getInternalMethods().getCommandInstance().getCommands(),a=[],o=e.getInternalMethods().getContext();return(o.commands.length>0||r.length>0)&&n._.slice(o.commands.length).forEach(e=>{r.includes(``+e)||a.push(``+e)}),a.length>0&&(t.fail(i(`Unknown command: %s`,`Unknown commands: %s`,a.length,a.join(`, `))),!0)},a.isValidAndSomeAliasIsNotNew=function(t,n){if(!Object.prototype.hasOwnProperty.call(n,t))return!1;let r=e.parsed.newAliases;return[t,...n[t]].some(e=>!Object.prototype.hasOwnProperty.call(r,e)||!r[t])},a.limitedChoices=function(n){let i=e.getOptions(),a={};if(!Object.keys(i.choices).length)return;Object.keys(n).forEach(e=>{At.indexOf(e)===-1&&Object.prototype.hasOwnProperty.call(i.choices,e)&&[].concat(n[e]).forEach(t=>{i.choices[e].indexOf(t)===-1&&t!==void 0&&(a[e]=(a[e]||[]).concat(t))})});let o=Object.keys(a);if(!o.length)return;let s=r(`Invalid values:`);o.forEach(e=>{s+=`\n ${r(`Argument: %s, Given: %s, Choices: %s`,e,t.stringifiedValues(a[e]),t.stringifiedValues(i.choices[e]))}`}),t.fail(s)};let o={};a.implies=function(t,r){I(`<string|object> [array|number|string]`,[t,r],arguments.length),typeof t==`object`?Object.keys(t).forEach(e=>{a.implies(e,t[e])}):(e.global(t),o[t]||(o[t]=[]),Array.isArray(r)?r.forEach(e=>a.implies(t,e)):(Xe(r,void 0,n),o[t].push(r)))},a.getImplied=function(){return o};function s(e,t){let n=Number(t);return t=isNaN(n)?t:n,typeof t==`number`?t=e._.length>=t:t.match(/^--no-.+/)?(t=t.match(/^--no-(.+)/)[1],t=!Object.prototype.hasOwnProperty.call(e,t)):t=Object.prototype.hasOwnProperty.call(e,t),t}a.implications=function(e){let n=[];if(Object.keys(o).forEach(t=>{let r=t;(o[t]||[]).forEach(t=>{let i=r,a=t;i=s(e,i),t=s(e,t),i&&!t&&n.push(` ${r} -> ${a}`)})}),n.length){let e=`${r(`Implications failed:`)}\n`;n.forEach(t=>{e+=t}),t.fail(e)}};let c={};a.conflicts=function(t,n){I(`<string|object> [array|string]`,[t,n],arguments.length),typeof t==`object`?Object.keys(t).forEach(e=>{a.conflicts(e,t[e])}):(e.global(t),c[t]||(c[t]=[]),Array.isArray(n)?n.forEach(e=>a.conflicts(t,e)):c[t].push(n))},a.getConflicting=()=>c,a.conflicting=function(i){Object.keys(i).forEach(e=>{c[e]&&c[e].forEach(n=>{n&&i[e]!==void 0&&i[n]!==void 0&&t.fail(r(`Arguments %s and %s are mutually exclusive`,e,n))})}),e.getInternalMethods().getParserConfiguration()[`strip-dashed`]&&Object.keys(c).forEach(e=>{c[e].forEach(a=>{a&&i[n.Parser.camelCase(e)]!==void 0&&i[n.Parser.camelCase(a)]!==void 0&&t.fail(r(`Arguments %s and %s are mutually exclusive`,e,a))})})},a.recommendCommands=function(e,n){n=n.sort((e,t)=>t.length-e.length);let i=null,a=1/0;for(let t=0,r;(r=n[t])!==void 0;t++){let t=kt(e,r);t<=3&&t<a&&(a=t,i=r)}i&&t.fail(r(`Did you mean %s?`,i))},a.reset=function(e){return o=_t(o,t=>!e[t]),c=_t(c,t=>!e[t]),a};let l=[];return a.freeze=function(){l.push({implied:o,conflicting:c})},a.unfreeze=function(){let e=l.pop();Xe(e,void 0,n),{implied:o,conflicting:c}=e},a}let Mt=[],Nt;function Pt(e,t,n,r){Nt=r;let i={};if(Object.prototype.hasOwnProperty.call(e,`extends`)){if(typeof e.extends!=`string`)return i;let r=/\.json|\..*rc$/.test(e.extends),a=null;if(r)a=It(t,e.extends);else try{a=fe.resolve(e.extends)}catch{return e}Ft(a),Mt.push(a),i=r?JSON.parse(Nt.readFileSync(a,`utf8`)):fe(e.extends),delete e.extends,i=Pt(i,Nt.path.dirname(a),n,Nt)}return Mt=[],n?Lt(i,e):Object.assign({},i,e)}function Ft(e){if(Mt.indexOf(e)>-1)throw new P(`Circular extended configurations: '${e}'.`)}function It(e,t){return Nt.path.resolve(e,t)}function Lt(e,t){let n={};function r(e){return e&&typeof e==`object`&&!Array.isArray(e)}Object.assign(n,e);for(let i of Object.keys(t))n[i]=r(t[i])&&r(n[i])?Lt(e[i],t[i]):t[i];return n}var L=function(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n},R=function(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)},z,Rt,zt,Bt,Vt,Ht,Ut,Wt,Gt,Kt,qt,Jt,Yt,Xt,Zt,Qt,$t,B,V,en,tn,nn,rn,an,on,sn,cn,H,ln,un,dn,U,fn,pn,W;function mn(e){return(t=[],n=e.process.cwd(),r)=>{let i=new Zn(t,n,r,e);return Object.defineProperty(i,"argv",{get:()=>i.parse(),enumerable:!0}),i.help(),i.version(),i}}const hn=Symbol(`copyDoubleDash`),gn=Symbol(`copyDoubleDash`),_n=Symbol(`deleteFromParserHintObject`),vn=Symbol(`emitWarning`),yn=Symbol(`freeze`),bn=Symbol(`getDollarZero`),xn=Symbol(`getParserConfiguration`),Sn=Symbol(`getUsageConfiguration`),Cn=Symbol(`guessLocale`),wn=Symbol(`guessVersion`),Tn=Symbol(`parsePositionalNumbers`),En=Symbol(`pkgUp`),Dn=Symbol(`populateParserHintArray`),On=Symbol(`populateParserHintSingleValueDictionary`),kn=Symbol(`populateParserHintArrayDictionary`),An=Symbol(`populateParserHintDictionary`),jn=Symbol(`sanitizeKey`),Mn=Symbol(`setKey`),Nn=Symbol(`unfreeze`),Pn=Symbol(`validateAsync`),Fn=Symbol(`getCommandInstance`),In=Symbol(`getContext`),Ln=Symbol(`getHasOutput`),Rn=Symbol(`getLoggerInstance`),zn=Symbol(`getParseContext`),Bn=Symbol(`getUsageInstance`),Vn=Symbol(`getValidationInstance`),Hn=Symbol(`hasParseCallback`),Un=Symbol(`isGlobalContext`),Wn=Symbol(`postProcess`),Gn=Symbol(`rebase`),Kn=Symbol(`reset`),qn=Symbol(`runYargsParserAndExecuteCommands`),Jn=Symbol(`runValidation`),Yn=Symbol(`setHasOutput`),Xn=Symbol(`kTrackManuallySetKeys`);var Zn=class{constructor(e=[],t,n,r){this.customScriptName=!1,this.parsed=!1,z.set(this,void 0),Rt.set(this,void 0),zt.set(this,{commands:[],fullCommands:[]}),Bt.set(this,null),Vt.set(this,null),Ht.set(this,`show-hidden`),Ut.set(this,null),Wt.set(this,!0),Gt.set(this,{}),Kt.set(this,!0),qt.set(this,[]),Jt.set(this,void 0),Yt.set(this,{}),Xt.set(this,!1),Zt.set(this,null),Qt.set(this,!0),$t.set(this,void 0),B.set(this,``),V.set(this,void 0),en.set(this,void 0),tn.set(this,{}),nn.set(this,null),rn.set(this,null),an.set(this,{}),on.set(this,{}),sn.set(this,void 0),cn.set(this,!1),H.set(this,void 0),ln.set(this,!1),un.set(this,!1),dn.set(this,!1),U.set(this,void 0),fn.set(this,{}),pn.set(this,null),W.set(this,void 0),L(this,H,r,`f`),L(this,sn,e,`f`),L(this,Rt,t,`f`),L(this,en,n,`f`),L(this,Jt,new rt(this),`f`),this.$0=this[bn](),this[Kn](),L(this,z,R(this,z,`f`),`f`),L(this,U,R(this,U,`f`),`f`),L(this,W,R(this,W,`f`),`f`),L(this,V,R(this,V,`f`),`f`),R(this,V,`f`).showHiddenOpt=R(this,Ht,`f`),L(this,$t,this[gn](),`f`)}addHelpOpt(e,t){return I(`[string|boolean] [string]`,[e,t],arguments.length),R(this,Zt,`f`)&&(this[_n](R(this,Zt,`f`)),L(this,Zt,null,`f`)),e===!1&&t===void 0||(L(this,Zt,typeof e==`string`?e:`help`,`f`),this.boolean(R(this,Zt,`f`)),this.describe(R(this,Zt,`f`),t||R(this,U,`f`).deferY18nLookup(`Show help`))),this}help(e,t){return this.addHelpOpt(e,t)}addShowHiddenOpt(e,t){if(I(`[string|boolean] [string]`,[e,t],arguments.length),e===!1&&t===void 0)return this;let n=typeof e==`string`?e:R(this,Ht,`f`);return this.boolean(n),this.describe(n,t||R(this,U,`f`).deferY18nLookup(`Show hidden options`)),R(this,V,`f`).showHiddenOpt=n,this}showHidden(e,t){return this.addShowHiddenOpt(e,t)}alias(e,t){return I(`<object|string|array> [string|array]`,[e,t],arguments.length),this[kn](this.alias.bind(this),`alias`,e,t),this}array(e){return I(`<array|string>`,[e],arguments.length),this[Dn](`array`,e),this[Xn](e),this}boolean(e){return I(`<array|string>`,[e],arguments.length),this[Dn](`boolean`,e),this[Xn](e),this}check(e,t){return I(`<function> [boolean]`,[e,t],arguments.length),this.middleware((t,n)=>ot(()=>e(t,n.getOptions()),n=>(n?(typeof n==`string`||n instanceof Error)&&R(this,U,`f`).fail(n.toString(),n):R(this,U,`f`).fail(R(this,H,`f`).y18n.__(`Argument check failed: %s`,e.toString())),t),e=>(R(this,U,`f`).fail(e.message?e.message:e.toString(),e),t)),!1,t),this}choices(e,t){return I(`<object|string|array> [string|array]`,[e,t],arguments.length),this[kn](this.choices.bind(this),`choices`,e,t),this}coerce(e,t){if(I(`<object|string|array> [function]`,[e,t],arguments.length),Array.isArray(e)){if(!t)throw new P(`coerce callback must be provided`);for(let n of e)this.coerce(n,t);return this}if(typeof e==`object`){for(let t of Object.keys(e))this.coerce(t,e[t]);return this}if(!t)throw new P(`coerce callback must be provided`);return R(this,V,`f`).key[e]=!0,R(this,Jt,`f`).addCoerceMiddleware((n,r)=>{let i;return Object.prototype.hasOwnProperty.call(n,e)?ot(()=>(i=r.getAliases(),t(n[e])),t=>{n[e]=t;let a=r.getInternalMethods().getParserConfiguration()[`strip-aliased`];if(i[e]&&a!==!0)for(let r of i[e])n[r]=t;return n},e=>{throw new P(e.message)}):n},e),this}conflicts(e,t){return I(`<string|object> [string|array]`,[e,t],arguments.length),R(this,W,`f`).conflicts(e,t),this}config(e=`config`,t,n){return I(`[object|string] [string|function] [function]`,[e,t,n],arguments.length),typeof e==`object`&&!Array.isArray(e)?(e=Pt(e,R(this,Rt,`f`),this[xn]()[`deep-merge-config`]||!1,R(this,H,`f`)),R(this,V,`f`).configObjects=(R(this,V,`f`).configObjects||[]).concat(e),this):(typeof t==`function`&&(n=t,t=void 0),this.describe(e,t||R(this,U,`f`).deferY18nLookup(`Path to JSON config file`)),(Array.isArray(e)?e:[e]).forEach(e=>{R(this,V,`f`).config[e]=n||!0}),this)}completion(e,t,n){return I(`[string] [string|boolean|function] [function]`,[e,t,n],arguments.length),typeof t==`function`&&(n=t,t=void 0),L(this,Vt,e||R(this,Vt,`f`)||`completion`,`f`),!t&&t!==!1&&(t=`generate completion script`),this.command(R(this,Vt,`f`),t),n&&R(this,Bt,`f`).registerFunction(n),this}command(e,t,n,r,i,a){return I(`<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]`,[e,t,n,r,i,a],arguments.length),R(this,z,`f`).addHandler(e,t,n,r,i,a),this}commands(e,t,n,r,i,a){return this.command(e,t,n,r,i,a)}commandDir(e,t){I(`<string> [object]`,[e,t],arguments.length);let n=R(this,en,`f`)||R(this,H,`f`).require;return R(this,z,`f`).addDirectory(e,n,R(this,H,`f`).getCallerFile(),t),this}count(e){return I(`<array|string>`,[e],arguments.length),this[Dn](`count`,e),this[Xn](e),this}default(e,t,n){return I(`<object|string|array> [*] [string]`,[e,t,n],arguments.length),n&&(Ze(e,R(this,H,`f`)),R(this,V,`f`).defaultDescription[e]=n),typeof t==`function`&&(Ze(e,R(this,H,`f`)),R(this,V,`f`).defaultDescription[e]||(R(this,V,`f`).defaultDescription[e]=R(this,U,`f`).functionDescription(t)),t=t.call()),this[On](this.default.bind(this),`default`,e,t),this}defaults(e,t,n){return this.default(e,t,n)}demandCommand(e=1,t,n,r){return I(`[number] [number|string] [string|null|undefined] [string|null|undefined]`,[e,t,n,r],arguments.length),typeof t!=`number`&&(n=t,t=1/0),this.global(`_`,!1),R(this,V,`f`).demandedCommands._={min:e,max:t,minMsg:n,maxMsg:r},this}demand(e,t,n){return Array.isArray(t)?(t.forEach(e=>{Xe(n,!0,R(this,H,`f`)),this.demandOption(e,n)}),t=1/0):typeof t!=`number`&&(n=t,t=1/0),typeof e==`number`?(Xe(n,!0,R(this,H,`f`)),this.demandCommand(e,t,n,n)):Array.isArray(e)?e.forEach(e=>{Xe(n,!0,R(this,H,`f`)),this.demandOption(e,n)}):typeof n==`string`?this.demandOption(e,n):(n===!0||n===void 0)&&this.demandOption(e),this}demandOption(e,t){return I(`<object|string|array> [string]`,[e,t],arguments.length),this[On](this.demandOption.bind(this),`demandedOptions`,e,t),this}deprecateOption(e,t){return I(`<string> [string|boolean]`,[e,t],arguments.length),R(this,V,`f`).deprecatedOptions[e]=t,this}describe(e,t){return I(`<object|string|array> [string]`,[e,t],arguments.length),this[Mn](e,!0),R(this,U,`f`).describe(e,t),this}detectLocale(e){return I(`<boolean>`,[e],arguments.length),L(this,Wt,e,`f`),this}env(e){return I(`[string|boolean]`,[e],arguments.length),e===!1?delete R(this,V,`f`).envPrefix:R(this,V,`f`).envPrefix=e||``,this}epilogue(e){return I(`<string>`,[e],arguments.length),R(this,U,`f`).epilog(e),this}epilog(e){return this.epilogue(e)}example(e,t){return I(`<string|array> [string]`,[e,t],arguments.length),Array.isArray(e)?e.forEach(e=>this.example(...e)):R(this,U,`f`).example(e,t),this}exit(e,t){L(this,Xt,!0,`f`),L(this,Ut,t,`f`),R(this,Kt,`f`)&&R(this,H,`f`).process.exit(e)}exitProcess(e=!0){return I(`[boolean]`,[e],arguments.length),L(this,Kt,e,`f`),this}fail(e){if(I(`<function|boolean>`,[e],arguments.length),typeof e==`boolean`&&e!==!1)throw new P(`Invalid first argument. Expected function or boolean 'false'`);return R(this,U,`f`).failFn(e),this}getAliases(){return this.parsed?this.parsed.aliases:{}}async getCompletion(e,t){return I(`<array> [function]`,[e,t],arguments.length),t?R(this,Bt,`f`).getCompletion(e,t):new Promise((t,n)=>{R(this,Bt,`f`).getCompletion(e,(e,r)=>{e?n(e):t(r)})})}getDemandedOptions(){return I([],0),R(this,V,`f`).demandedOptions}getDemandedCommands(){return I([],0),R(this,V,`f`).demandedCommands}getDeprecatedOptions(){return I([],0),R(this,V,`f`).deprecatedOptions}getDetectLocale(){return R(this,Wt,`f`)}getExitProcess(){return R(this,Kt,`f`)}getGroups(){return Object.assign({},R(this,Yt,`f`),R(this,on,`f`))}getHelp(){if(L(this,Xt,!0,`f`),!R(this,U,`f`).hasCachedHelpMessage()){if(!this.parsed){let e=this[qn](R(this,sn,`f`),void 0,void 0,0,!0);if(F(e))return e.then(()=>R(this,U,`f`).help())}let e=R(this,z,`f`).runDefaultBuilderOn(this);if(F(e))return e.then(()=>R(this,U,`f`).help())}return Promise.resolve(R(this,U,`f`).help())}getOptions(){return R(this,V,`f`)}getStrict(){return R(this,ln,`f`)}getStrictCommands(){return R(this,un,`f`)}getStrictOptions(){return R(this,dn,`f`)}global(e,t){return I(`<string|array> [boolean]`,[e,t],arguments.length),e=[].concat(e),t===!1?e.forEach(e=>{R(this,V,`f`).local.includes(e)||R(this,V,`f`).local.push(e)}):R(this,V,`f`).local=R(this,V,`f`).local.filter(t=>e.indexOf(t)===-1),this}group(e,t){I(`<string|array> <string>`,[e,t],arguments.length);let n=R(this,on,`f`)[t]||R(this,Yt,`f`)[t];R(this,on,`f`)[t]&&delete R(this,on,`f`)[t];let r={};return R(this,Yt,`f`)[t]=(n||[]).concat(e).filter(e=>r[e]?!1:r[e]=!0),this}hide(e){return I(`<string>`,[e],arguments.length),R(this,V,`f`).hiddenOptions.push(e),this}implies(e,t){return I(`<string|object> [number|string|array]`,[e,t],arguments.length),R(this,W,`f`).implies(e,t),this}locale(e){return I(`[string]`,[e],arguments.length),e===void 0?(this[Cn](),R(this,H,`f`).y18n.getLocale()):(L(this,Wt,!1,`f`),R(this,H,`f`).y18n.setLocale(e),this)}middleware(e,t,n){return R(this,Jt,`f`).addMiddleware(e,!!t,n)}nargs(e,t){return I(`<string|object|array> [number]`,[e,t],arguments.length),this[On](this.nargs.bind(this),`narg`,e,t),this}normalize(e){return I(`<array|string>`,[e],arguments.length),this[Dn](`normalize`,e),this}number(e){return I(`<array|string>`,[e],arguments.length),this[Dn](`number`,e),this[Xn](e),this}option(e,t){if(I(`<string|object> [object]`,[e,t],arguments.length),typeof e==`object`)Object.keys(e).forEach(t=>{this.options(t,e[t])});else{typeof t!=`object`&&(t={}),this[Xn](e),R(this,pn,`f`)&&(e===`version`||t?.alias===`version`)&&this[vn]([`"version" is a reserved word.`,`Please do one of the following:`,'- Disable version with `yargs.version(false)` if using "version" as an option',"- Use the built-in `yargs.version` method instead (if applicable)",`- Use a different option key`,`https://yargs.js.org/docs/#api-reference-version`].join(`
|
|
89
|
+
`),void 0,`versionWarning`),R(this,V,`f`).key[e]=!0,t.alias&&this.alias(e,t.alias);let n=t.deprecate||t.deprecated;n&&this.deprecateOption(e,n);let r=t.demand||t.required||t.require;r&&this.demand(e,r),t.demandOption&&this.demandOption(e,typeof t.demandOption==`string`?t.demandOption:void 0),t.conflicts&&this.conflicts(e,t.conflicts),`default`in t&&this.default(e,t.default),t.implies!==void 0&&this.implies(e,t.implies),t.nargs!==void 0&&this.nargs(e,t.nargs),t.config&&this.config(e,t.configParser),t.normalize&&this.normalize(e),t.choices&&this.choices(e,t.choices),t.coerce&&this.coerce(e,t.coerce),t.group&&this.group(e,t.group),(t.boolean||t.type===`boolean`)&&(this.boolean(e),t.alias&&this.boolean(t.alias)),(t.array||t.type===`array`)&&(this.array(e),t.alias&&this.array(t.alias)),(t.number||t.type===`number`)&&(this.number(e),t.alias&&this.number(t.alias)),(t.string||t.type===`string`)&&(this.string(e),t.alias&&this.string(t.alias)),(t.count||t.type===`count`)&&this.count(e),typeof t.global==`boolean`&&this.global(e,t.global),t.defaultDescription&&(R(this,V,`f`).defaultDescription[e]=t.defaultDescription),t.skipValidation&&this.skipValidation(e);let i=t.describe||t.description||t.desc,a=R(this,U,`f`).getDescriptions();(!Object.prototype.hasOwnProperty.call(a,e)||typeof i==`string`)&&this.describe(e,i),t.hidden&&this.hide(e),t.requiresArg&&this.requiresArg(e)}return this}options(e,t){return this.option(e,t)}parse(e,t,n){I(`[string|array] [function|boolean|object] [function]`,[e,t,n],arguments.length),this[yn](),e===void 0&&(e=R(this,sn,`f`)),typeof t==`object`&&(L(this,rn,t,`f`),t=n),typeof t==`function`&&(L(this,nn,t,`f`),t=!1),t||L(this,sn,e,`f`),R(this,nn,`f`)&&L(this,Kt,!1,`f`);let r=this[qn](e,!!t),i=this.parsed;return R(this,Bt,`f`).setParsed(this.parsed),F(r)?r.then(e=>(R(this,nn,`f`)&&R(this,nn,`f`).call(this,R(this,Ut,`f`),e,R(this,B,`f`)),e)).catch(e=>{throw R(this,nn,`f`)&&R(this,nn,`f`)(e,this.parsed.argv,R(this,B,`f`)),e}).finally(()=>{this[Nn](),this.parsed=i}):(R(this,nn,`f`)&&R(this,nn,`f`).call(this,R(this,Ut,`f`),r,R(this,B,`f`)),this[Nn](),this.parsed=i,r)}parseAsync(e,t,n){let r=this.parse(e,t,n);return F(r)?r:Promise.resolve(r)}parseSync(e,t,n){let r=this.parse(e,t,n);if(F(r))throw new P(`.parseSync() must not be used with asynchronous builders, handlers, or middleware`);return r}parserConfiguration(e){return I(`<object>`,[e],arguments.length),L(this,tn,e,`f`),this}pkgConf(e,t){I(`<string> [string]`,[e,t],arguments.length);let n=null,r=this[En](t||R(this,Rt,`f`));return r[e]&&typeof r[e]==`object`&&(n=Pt(r[e],t||R(this,Rt,`f`),this[xn]()[`deep-merge-config`]||!1,R(this,H,`f`)),R(this,V,`f`).configObjects=(R(this,V,`f`).configObjects||[]).concat(n)),this}positional(e,t){I(`<string> <object>`,[e,t],arguments.length);let n=[`default`,`defaultDescription`,`implies`,`normalize`,`choices`,`conflicts`,`coerce`,`type`,`describe`,`desc`,`description`,`alias`];t=_t(t,(e,t)=>e===`type`&&![`string`,`number`,`boolean`].includes(t)?!1:n.includes(e));let r=R(this,zt,`f`).fullCommands[R(this,zt,`f`).fullCommands.length-1],i=r?R(this,z,`f`).cmdToParseOptions(r):{array:[],alias:{},default:{},demand:{}};return Qe(i).forEach(n=>{let r=i[n];Array.isArray(r)?r.indexOf(e)!==-1&&(t[n]=!0):r[e]&&!(n in t)&&(t[n]=r[e])}),this.group(e,R(this,U,`f`).getPositionalGroupName()),this.option(e,t)}recommendCommands(e=!0){return I(`[boolean]`,[e],arguments.length),L(this,cn,e,`f`),this}required(e,t,n){return this.demand(e,t,n)}require(e,t,n){return this.demand(e,t,n)}requiresArg(e){return I(`<array|string|object> [number]`,[e],arguments.length),typeof e==`string`&&R(this,V,`f`).narg[e]||this[On](this.requiresArg.bind(this),`narg`,e,NaN),this}showCompletionScript(e,t){return I(`[string] [string]`,[e,t],arguments.length),e||=this.$0,R(this,$t,`f`).log(R(this,Bt,`f`).generateCompletionScript(e,t||R(this,Vt,`f`)||`completion`)),this}showHelp(e){if(I(`[string|function]`,[e],arguments.length),L(this,Xt,!0,`f`),!R(this,U,`f`).hasCachedHelpMessage()){if(!this.parsed){let t=this[qn](R(this,sn,`f`),void 0,void 0,0,!0);if(F(t))return t.then(()=>{R(this,U,`f`).showHelp(e)}),this}let t=R(this,z,`f`).runDefaultBuilderOn(this);if(F(t))return t.then(()=>{R(this,U,`f`).showHelp(e)}),this}return R(this,U,`f`).showHelp(e),this}scriptName(e){return this.customScriptName=!0,this.$0=e,this}showHelpOnFail(e,t){return I(`[boolean|string] [string]`,[e,t],arguments.length),R(this,U,`f`).showHelpOnFail(e,t),this}showVersion(e){return I(`[string|function]`,[e],arguments.length),R(this,U,`f`).showVersion(e),this}skipValidation(e){return I(`<array|string>`,[e],arguments.length),this[Dn](`skipValidation`,e),this}strict(e){return I(`[boolean]`,[e],arguments.length),L(this,ln,e!==!1,`f`),this}strictCommands(e){return I(`[boolean]`,[e],arguments.length),L(this,un,e!==!1,`f`),this}strictOptions(e){return I(`[boolean]`,[e],arguments.length),L(this,dn,e!==!1,`f`),this}string(e){return I(`<array|string>`,[e],arguments.length),this[Dn](`string`,e),this[Xn](e),this}terminalWidth(){return I([],0),R(this,H,`f`).process.stdColumns}updateLocale(e){return this.updateStrings(e)}updateStrings(e){return I(`<object>`,[e],arguments.length),L(this,Wt,!1,`f`),R(this,H,`f`).y18n.updateLocale(e),this}usage(e,t,n,r){if(I(`<string|null|undefined> [string|boolean] [function|object] [function]`,[e,t,n,r],arguments.length),t!==void 0){if(Xe(e,null,R(this,H,`f`)),(e||``).match(/^\$0( |$)/))return this.command(e,t,n,r);throw new P(`.usage() description must start with $0 if being used as alias for .command()`)}return R(this,U,`f`).usage(e),this}usageConfiguration(e){return I(`<object>`,[e],arguments.length),L(this,fn,e,`f`),this}version(e,t,n){let r=`version`;if(I(`[boolean|string] [string] [string]`,[e,t,n],arguments.length),R(this,pn,`f`)&&(this[_n](R(this,pn,`f`)),R(this,U,`f`).version(void 0),L(this,pn,null,`f`)),arguments.length===0)n=this[wn](),e=r;else if(arguments.length===1){if(e===!1)return this;n=e,e=r}else arguments.length===2&&(n=t,t=void 0);return L(this,pn,typeof e==`string`?e:r,`f`),t||=R(this,U,`f`).deferY18nLookup(`Show version number`),R(this,U,`f`).version(n||void 0),this.boolean(R(this,pn,`f`)),this.describe(R(this,pn,`f`),t),this}wrap(e){return I(`<number|null|undefined>`,[e],arguments.length),R(this,U,`f`).wrap(e),this}[(z=/* @__PURE__ */ new WeakMap,Rt=/* @__PURE__ */ new WeakMap,zt=/* @__PURE__ */ new WeakMap,Bt=/* @__PURE__ */ new WeakMap,Vt=/* @__PURE__ */ new WeakMap,Ht=/* @__PURE__ */ new WeakMap,Ut=/* @__PURE__ */ new WeakMap,Wt=/* @__PURE__ */ new WeakMap,Gt=/* @__PURE__ */ new WeakMap,Kt=/* @__PURE__ */ new WeakMap,qt=/* @__PURE__ */ new WeakMap,Jt=/* @__PURE__ */ new WeakMap,Yt=/* @__PURE__ */ new WeakMap,Xt=/* @__PURE__ */ new WeakMap,Zt=/* @__PURE__ */ new WeakMap,Qt=/* @__PURE__ */ new WeakMap,$t=/* @__PURE__ */ new WeakMap,B=/* @__PURE__ */ new WeakMap,V=/* @__PURE__ */ new WeakMap,en=/* @__PURE__ */ new WeakMap,tn=/* @__PURE__ */ new WeakMap,nn=/* @__PURE__ */ new WeakMap,rn=/* @__PURE__ */ new WeakMap,an=/* @__PURE__ */ new WeakMap,on=/* @__PURE__ */ new WeakMap,sn=/* @__PURE__ */ new WeakMap,cn=/* @__PURE__ */ new WeakMap,H=/* @__PURE__ */ new WeakMap,ln=/* @__PURE__ */ new WeakMap,un=/* @__PURE__ */ new WeakMap,dn=/* @__PURE__ */ new WeakMap,U=/* @__PURE__ */ new WeakMap,fn=/* @__PURE__ */ new WeakMap,pn=/* @__PURE__ */ new WeakMap,W=/* @__PURE__ */ new WeakMap,hn)](e){if(!e._||!e[`--`])return e;e._.push.apply(e._,e[`--`]);try{delete e[`--`]}catch{}return e}[gn](){return{log:(...e)=>{this[Hn]()||console.log(...e),L(this,Xt,!0,`f`),R(this,B,`f`).length&&L(this,B,R(this,B,`f`)+`
|
|
90
|
+
`,`f`),L(this,B,R(this,B,`f`)+e.join(` `),`f`)},error:(...e)=>{this[Hn]()||console.error(...e),L(this,Xt,!0,`f`),R(this,B,`f`).length&&L(this,B,R(this,B,`f`)+`
|
|
91
|
+
`,`f`),L(this,B,R(this,B,`f`)+e.join(` `),`f`)}}}[_n](e){Qe(R(this,V,`f`)).forEach(t=>{if((e=>e===`configObjects`)(t))return;let n=R(this,V,`f`)[t];Array.isArray(n)?n.includes(e)&&n.splice(n.indexOf(e),1):typeof n==`object`&&delete n[e]}),delete R(this,U,`f`).getDescriptions()[e]}[vn](e,t,n){R(this,Gt,`f`)[n]||(R(this,H,`f`).process.emitWarning(e,t),R(this,Gt,`f`)[n]=!0)}[yn](){R(this,qt,`f`).push({options:R(this,V,`f`),configObjects:R(this,V,`f`).configObjects.slice(0),exitProcess:R(this,Kt,`f`),groups:R(this,Yt,`f`),strict:R(this,ln,`f`),strictCommands:R(this,un,`f`),strictOptions:R(this,dn,`f`),completionCommand:R(this,Vt,`f`),output:R(this,B,`f`),exitError:R(this,Ut,`f`),hasOutput:R(this,Xt,`f`),parsed:this.parsed,parseFn:R(this,nn,`f`),parseContext:R(this,rn,`f`)}),R(this,U,`f`).freeze(),R(this,W,`f`).freeze(),R(this,z,`f`).freeze(),R(this,Jt,`f`).freeze()}[bn](){let e=``,t;return t=/\b(node|iojs|electron)(\.exe)?$/.test(R(this,H,`f`).process.argv()[0])?R(this,H,`f`).process.argv().slice(1,2):R(this,H,`f`).process.argv().slice(0,1),e=t.map(e=>{let t=this[Gn](R(this,Rt,`f`),e);return e.match(/^(\/|([a-zA-Z]:)?\\)/)&&t.length<e.length?t:e}).join(` `).trim(),R(this,H,`f`).getEnv(`_`)&&R(this,H,`f`).getProcessArgvBin()===R(this,H,`f`).getEnv(`_`)&&(e=R(this,H,`f`).getEnv(`_`).replace(`${R(this,H,`f`).path.dirname(R(this,H,`f`).process.execPath())}/`,``)),e}[xn](){return R(this,tn,`f`)}[Sn](){return R(this,fn,`f`)}[Cn](){if(!R(this,Wt,`f`))return;let e=R(this,H,`f`).getEnv(`LC_ALL`)||R(this,H,`f`).getEnv(`LC_MESSAGES`)||R(this,H,`f`).getEnv(`LANG`)||R(this,H,`f`).getEnv(`LANGUAGE`)||`en_US`;this.locale(e.replace(/[.:].*/,``))}[wn](){return this[En]().version||`unknown`}[Tn](e){let t=e[`--`]?e[`--`]:e._;for(let e=0,n;(n=t[e])!==void 0;e++)R(this,H,`f`).Parser.looksLikeNumber(n)&&Number.isSafeInteger(Math.floor(parseFloat(`${n}`)))&&(t[e]=Number(n));return e}[En](e){let t=e||`*`;if(R(this,an,`f`)[t])return R(this,an,`f`)[t];let n={};try{let t=e||R(this,H,`f`).mainFilename;!e&&R(this,H,`f`).path.extname(t)&&(t=R(this,H,`f`).path.dirname(t));let r=R(this,H,`f`).findUp(t,(e,t)=>{if(t.includes(`package.json`))return`package.json`});Xe(r,void 0,R(this,H,`f`)),n=JSON.parse(R(this,H,`f`).readFileSync(r,`utf8`))}catch{}return R(this,an,`f`)[t]=n||{},R(this,an,`f`)[t]}[Dn](e,t){t=[].concat(t),t.forEach(t=>{t=this[jn](t),R(this,V,`f`)[e].push(t)})}[On](e,t,n,r){this[An](e,t,n,r,(e,t,n)=>{R(this,V,`f`)[e][t]=n})}[kn](e,t,n,r){this[An](e,t,n,r,(e,t,n)=>{R(this,V,`f`)[e][t]=(R(this,V,`f`)[e][t]||[]).concat(n)})}[An](e,t,n,r,i){if(Array.isArray(n))n.forEach(t=>{e(t,r)});else if((e=>typeof e==`object`)(n))for(let t of Qe(n))e(t,n[t]);else i(t,this[jn](n),r)}[jn](e){return e===`__proto__`?`___proto___`:e}[Mn](e,t){return this[On](this[Mn].bind(this),`key`,e,t),this}[Nn](){var e,t,n,r,i,a,o,s,c,l,u,d;let f=R(this,qt,`f`).pop();Xe(f,void 0,R(this,H,`f`));let p;e=this,t=this,n=this,r=this,i=this,a=this,o=this,s=this,c=this,l=this,u=this,d=this,{options:{set value(t){L(e,V,t,`f`)}}.value,configObjects:p,exitProcess:{set value(e){L(t,Kt,e,`f`)}}.value,groups:{set value(e){L(n,Yt,e,`f`)}}.value,output:{set value(e){L(r,B,e,`f`)}}.value,exitError:{set value(e){L(i,Ut,e,`f`)}}.value,hasOutput:{set value(e){L(a,Xt,e,`f`)}}.value,parsed:this.parsed,strict:{set value(e){L(o,ln,e,`f`)}}.value,strictCommands:{set value(e){L(s,un,e,`f`)}}.value,strictOptions:{set value(e){L(c,dn,e,`f`)}}.value,completionCommand:{set value(e){L(l,Vt,e,`f`)}}.value,parseFn:{set value(e){L(u,nn,e,`f`)}}.value,parseContext:{set value(e){L(d,rn,e,`f`)}}.value}=f,R(this,V,`f`).configObjects=p,R(this,U,`f`).unfreeze(),R(this,W,`f`).unfreeze(),R(this,z,`f`).unfreeze(),R(this,Jt,`f`).unfreeze()}[Pn](e,t){return ot(t,t=>(e(t),t))}getInternalMethods(){return{getCommandInstance:this[Fn].bind(this),getContext:this[In].bind(this),getHasOutput:this[Ln].bind(this),getLoggerInstance:this[Rn].bind(this),getParseContext:this[zn].bind(this),getParserConfiguration:this[xn].bind(this),getUsageConfiguration:this[Sn].bind(this),getUsageInstance:this[Bn].bind(this),getValidationInstance:this[Vn].bind(this),hasParseCallback:this[Hn].bind(this),isGlobalContext:this[Un].bind(this),postProcess:this[Wn].bind(this),reset:this[Kn].bind(this),runValidation:this[Jn].bind(this),runYargsParserAndExecuteCommands:this[qn].bind(this),setHasOutput:this[Yn].bind(this)}}[Fn](){return R(this,z,`f`)}[In](){return R(this,zt,`f`)}[Ln](){return R(this,Xt,`f`)}[Rn](){return R(this,$t,`f`)}[zn](){return R(this,rn,`f`)||{}}[Bn](){return R(this,U,`f`)}[Vn](){return R(this,W,`f`)}[Hn](){return!!R(this,nn,`f`)}[Un](){return R(this,Qt,`f`)}[Wn](e,t,n,r){return n||F(e)||(t||(e=this[hn](e)),(this[xn]()[`parse-positional-numbers`]||this[xn]()[`parse-positional-numbers`]===void 0)&&(e=this[Tn](e)),r&&(e=at(e,this,R(this,Jt,`f`).getMiddleware(),!1))),e}[Kn](e={}){L(this,V,R(this,V,`f`)||{},`f`);let t={};t.local=R(this,V,`f`).local||[],t.configObjects=R(this,V,`f`).configObjects||[];let n={};return t.local.forEach(t=>{n[t]=!0,(e[t]||[]).forEach(e=>{n[e]=!0})}),Object.assign(R(this,on,`f`),Object.keys(R(this,Yt,`f`)).reduce((e,t)=>{let r=R(this,Yt,`f`)[t].filter(e=>!(e in n));return r.length>0&&(e[t]=r),e},{})),L(this,Yt,{},`f`),[`array`,`boolean`,`string`,`skipValidation`,`count`,`normalize`,`number`,`hiddenOptions`].forEach(e=>{t[e]=(R(this,V,`f`)[e]||[]).filter(e=>!n[e])}),[`narg`,`key`,`alias`,`default`,`defaultDescription`,`config`,`choices`,`demandedOptions`,`demandedCommands`,`deprecatedOptions`].forEach(e=>{t[e]=_t(R(this,V,`f`)[e],e=>!n[e])}),t.envPrefix=R(this,V,`f`).envPrefix,L(this,V,t,`f`),L(this,U,R(this,U,`f`)?R(this,U,`f`).reset(n):bt(this,R(this,H,`f`)),`f`),L(this,W,R(this,W,`f`)?R(this,W,`f`).reset(n):jt(this,R(this,U,`f`),R(this,H,`f`)),`f`),L(this,z,R(this,z,`f`)?R(this,z,`f`).reset():dt(R(this,U,`f`),R(this,W,`f`),R(this,Jt,`f`),R(this,H,`f`)),`f`),R(this,Bt,`f`)||L(this,Bt,Et(this,R(this,U,`f`),R(this,z,`f`),R(this,H,`f`)),`f`),R(this,Jt,`f`).reset(),L(this,Vt,null,`f`),L(this,B,``,`f`),L(this,Ut,null,`f`),L(this,Xt,!1,`f`),this.parsed=!1,this}[Gn](e,t){return R(this,H,`f`).path.relative(e,t)}[qn](e,t,n,r=0,i=!1){let a=!!n||i;e||=R(this,sn,`f`),R(this,V,`f`).__=R(this,H,`f`).y18n.__,R(this,V,`f`).configuration=this[xn]();let o=!!R(this,V,`f`).configuration[`populate--`],s=Object.assign({},R(this,V,`f`).configuration,{"populate--":!0}),c=R(this,H,`f`).Parser.detailed(e,Object.assign({},R(this,V,`f`),{configuration:{"parse-positional-numbers":!1,...s}})),l=Object.assign(c.argv,R(this,rn,`f`)),u,d=c.aliases,f=!1,p=!1;Object.keys(l).forEach(e=>{e===R(this,Zt,`f`)&&l[e]?f=!0:e===R(this,pn,`f`)&&l[e]&&(p=!0)}),l.$0=this.$0,this.parsed=c,r===0&&R(this,U,`f`).clearCachedHelpMessage();try{if(this[Cn](),t)return this[Wn](l,o,!!n,!1);R(this,Zt,`f`)&&[R(this,Zt,`f`)].concat(d[R(this,Zt,`f`)]||[]).filter(e=>e.length>1).includes(``+l._[l._.length-1])&&(l._.pop(),f=!0),L(this,Qt,!1,`f`);let s=R(this,z,`f`).getCommands(),m=R(this,Bt,`f`).completionKey in l,h=f||m||i;if(l._.length){if(s.length){let e;for(let t=r||0,a;l._[t]!==void 0;t++){if(a=String(l._[t]),s.includes(a)&&a!==R(this,Vt,`f`)){let e=R(this,z,`f`).runCommand(a,this,c,t+1,i,f||p||i);return this[Wn](e,o,!!n,!1)}if(!e&&a!==R(this,Vt,`f`)){e=a;break}}!R(this,z,`f`).hasDefaultCommand()&&R(this,cn,`f`)&&e&&!h&&R(this,W,`f`).recommendCommands(e,s)}R(this,Vt,`f`)&&l._.includes(R(this,Vt,`f`))&&!m&&(R(this,Kt,`f`)&&vt(!0),this.showCompletionScript(),this.exit(0))}if(R(this,z,`f`).hasDefaultCommand()&&!h){let e=R(this,z,`f`).runCommand(null,this,c,0,i,f||p||i);return this[Wn](e,o,!!n,!1)}if(m){R(this,Kt,`f`)&&vt(!0),e=[].concat(e);let t=e.slice(e.indexOf(`--${R(this,Bt,`f`).completionKey}`)+1);return R(this,Bt,`f`).getCompletion(t,(e,t)=>{if(e)throw new P(e.message);(t||[]).forEach(e=>{R(this,$t,`f`).log(e)}),this.exit(0)}),this[Wn](l,!o,!!n,!1)}if(R(this,Xt,`f`)||(f?(R(this,Kt,`f`)&&vt(!0),a=!0,this.showHelp(`log`),this.exit(0)):p&&(R(this,Kt,`f`)&&vt(!0),a=!0,R(this,U,`f`).showVersion(`log`),this.exit(0))),!a&&R(this,V,`f`).skipValidation.length>0&&(a=Object.keys(l).some(e=>R(this,V,`f`).skipValidation.indexOf(e)>=0&&l[e]===!0)),!a){if(c.error)throw new P(c.error.message);if(!m){let e=this[Jn](d,{},c.error);n||(u=at(l,this,R(this,Jt,`f`).getMiddleware(),!0)),u=this[Pn](e,u??l),F(u)&&!n&&(u=u.then(()=>at(l,this,R(this,Jt,`f`).getMiddleware(),!1)))}}}catch(e){if(e instanceof P)R(this,U,`f`).fail(e.message,e);else throw e}return this[Wn](u??l,o,!!n,!0)}[Jn](e,t,n,r){let i={...this.getDemandedOptions()};return a=>{if(n)throw new P(n.message);R(this,W,`f`).nonOptionCount(a),R(this,W,`f`).requiredArguments(a,i);let o=!1;R(this,un,`f`)&&(o=R(this,W,`f`).unknownCommands(a)),R(this,ln,`f`)&&!o?R(this,W,`f`).unknownArguments(a,e,t,!!r):R(this,dn,`f`)&&R(this,W,`f`).unknownArguments(a,e,{},!1,!1),R(this,W,`f`).limitedChoices(a),R(this,W,`f`).implications(a),R(this,W,`f`).conflicting(a)}}[Yn](){L(this,Xt,!0,`f`)}[Xn](e){if(typeof e==`string`)R(this,V,`f`).key[e]=!0;else for(let t of e)R(this,V,`f`).key[t]=!0}};function Qn(e){return!!e&&typeof e.getInternalMethods==`function`}const $n=mn(Ye);var er=class extends Error{};function tr(e){if(!Number.isInteger(e)||e<60||e>600)throw new er(`Expected a whole number of seconds from 60 to 600.`);return e}function nr(e,t=`https://astralbeam.ai/api`){return`${t.replace(/\/+$/,``)}${e.replace(/^\/api(?=\/)/,``)}`}function rr(e,t){if(!e||typeof e!=`object`)return!1;let n=e;return n.status===t&&typeof n.type==`string`&&typeof n.title==`string`&&typeof n.detail==`string`&&(n.reference===void 0||typeof n.reference==`string`)&&(n.issues===void 0||Array.isArray(n.issues)&&n.issues.every(e=>e&&typeof e.path==`string`&&typeof e.message==`string`))}async function ir(e,t){let{apiUrl:n,apiKey:r,astralBeamToken:i,fetchClient:a=globalThis.fetch,...o}=t,s=new Headers,c=o.headers instanceof Headers?o.headers.entries():Array.isArray(o.headers)?o.headers:Object.entries(o.headers??{});for(let[e,t]of c)s.set(e,t);s.delete(`authorization`),s.delete(`x-api-key`),r&&s.set(`x-api-key`,r),i&&s.set(`authorization`,`Bearer ${i}`);let l=await a(nr(e,n),{...o,headers:s,...r?{redirect:`error`}:{}});if(l.ok)return l;let u=await l.json().catch(e=>{if(!(e instanceof SyntaxError))throw e}),d=rr(u,l.status)?u:void 0;throw Object.assign(Error(d?.detail??`AstralBeam API returned HTTP ${l.status}`),{name:`AstralBeamApiError`,status:l.status,headers:l.headers,body:d})}async function ar(e,t){let n=await ir(e,t);if(n.status!==204)return await n.json()}function or(e){return e instanceof Error&&e.name===`AstralBeamApiError`&&`status`in e&&typeof e.status==`number`}function sr(e,t=`https://astralbeam.ai/api`){return`${t.replace(/\/+$/,``)}${e.replace(/^\/api(?=\/)/,``)}`}function cr(e,t){if(!e||typeof e!=`object`)return!1;let n=e;return n.status===t&&typeof n.type==`string`&&typeof n.title==`string`&&typeof n.detail==`string`&&(n.reference===void 0||typeof n.reference==`string`)&&(n.issues===void 0||Array.isArray(n.issues)&&n.issues.every(e=>e&&typeof e.path==`string`&&typeof e.message==`string`))}async function lr(e,t){let{apiUrl:n,apiKey:r,astralBeamToken:i,fetchClient:a=globalThis.fetch,...o}=t,s=new Headers,c=o.headers instanceof Headers?o.headers.entries():Array.isArray(o.headers)?o.headers:Object.entries(o.headers??{});for(let[e,t]of c)s.set(e,t);s.delete(`authorization`),s.delete(`x-api-key`),r&&s.set(`x-api-key`,r),i&&s.set(`authorization`,`Bearer ${i}`);let l=await a(sr(e,n),{...o,headers:s,...r?{redirect:`error`}:{}});if(l.ok)return l;let u=await l.json().catch(e=>{if(!(e instanceof SyntaxError))throw e}),d=cr(u,l.status)?u:void 0;throw Object.assign(Error(d?.detail??`AstralBeam API returned HTTP ${l.status}`),{name:`AstralBeamApiError`,status:l.status,headers:l.headers,body:d})}async function ur(e,t){let n=await lr(e,t);if(n.status!==204)return await n.json()}function G(e,t){return ur(e,t)}async function dr(e,t){let n=await lr(e,t),r=n.status===204?n.headers.get(`location`):null;if(!r)return n;let i=await globalThis.fetch(r,{credentials:`omit`,redirect:`error`,referrerPolicy:`no-referrer`,signal:t.signal??null});if(!i.ok)throw Error(`The file could not be downloaded. Please try again.`);return i}function fr(e,t){return lr(e,t)}const pr=()=>`/api/v1/organization`,mr=e=>ur(pr(),{...e,method:`GET`}),hr=()=>`/api/v1/chat/files`,gr=(e,t)=>{let n=e=>{if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Symbol.iterator in e)return Object.fromEntries(Array.from(e,e=>Array.from(e)));let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t};return G(hr(),{...t,method:`POST`,headers:{"Content-Type":`application/json`,...n(t?.headers)},body:JSON.stringify(e)})},_r=e=>{let t=new URLSearchParams;Object.entries(e||{}).forEach(([e,n])=>{n!==void 0&&t.append(e,n===null?`null`:String(n))});let n=t.toString();return n.length>0?`/api/v1/chat/files?${n}`:`/api/v1/chat/files`},vr=(e,t)=>dr(_r(e),{...t,method:`GET`}),yr=()=>`/api/v1/chat`,br=e=>{let t=new URLSearchParams;Object.entries(e||{}).forEach(([e,n])=>{n!==void 0&&t.append(e,n===null?`null`:String(n))});let n=t.toString();return n.length>0?`/api/v1/chat/config?${n}`:`/api/v1/chat/config`},xr=(e,t)=>G(br(e),{...t,method:`GET`}),Sr=()=>`/api/v1/chat/threads`,Cr=(e,t)=>{let n=e=>{if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Symbol.iterator in e)return Object.fromEntries(Array.from(e,e=>Array.from(e)));let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t};return G(Sr(),{...t,method:`POST`,headers:{"Content-Type":`application/json`,...n(t?.headers)},body:JSON.stringify(e)})},wr=e=>{let t=new URLSearchParams;Object.entries(e||{}).forEach(([e,n])=>{n!==void 0&&t.append(e,n===null?`null`:String(n))});let n=t.toString();return n.length>0?`/api/v1/chat/threads?${n}`:`/api/v1/chat/threads`},Tr=(e,t)=>G(wr(e),{...t,method:`GET`}),Er=e=>`/api/v1/chat/threads/${encodeURIComponent(String(e))}`,Dr=(e,t,n)=>{let r=e=>{if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Symbol.iterator in e)return Object.fromEntries(Array.from(e,e=>Array.from(e)));let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t};return G(Er(e),{...n,method:`PATCH`,headers:{"Content-Type":`application/json`,...r(n?.headers)},body:JSON.stringify(t)})},Or=(e,t)=>{let n=new URLSearchParams;Object.entries(t||{}).forEach(([e,t])=>{t!==void 0&&n.append(e,t===null?`null`:String(t))});let r=n.toString();return r.length>0?`/api/v1/chat/threads/${encodeURIComponent(String(e))}?${r}`:`/api/v1/chat/threads/${encodeURIComponent(String(e))}`},kr=(e,t,n)=>G(Or(e,t),{...n,method:`DELETE`}),Ar=(e,t)=>{let n=new URLSearchParams;Object.entries(t||{}).forEach(([e,t])=>{t!==void 0&&n.append(e,t===null?`null`:String(t))});let r=n.toString();return r.length>0?`/api/v1/chat/threads/${encodeURIComponent(String(e))}/messages?${r}`:`/api/v1/chat/threads/${encodeURIComponent(String(e))}/messages`},jr=(e,t,n)=>G(Ar(e,t),{...n,method:`GET`}),Mr=e=>`/api/v1/chat/threads/${encodeURIComponent(String(e))}/tool-results`,Nr=()=>`/api/v1/me`,Pr=e=>G(Nr(),{...e,method:`POST`}),Fr=()=>`/api/v1/me/mcp/catalog`,Ir=e=>G(Fr(),{...e,method:`GET`}),Lr=()=>`/api/v1/me/mcp/connections`,Rr=(e,t)=>{let n=e=>{if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Symbol.iterator in e)return Object.fromEntries(Array.from(e,e=>Array.from(e)));let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t};return G(Lr(),{...t,method:`POST`,headers:{"Content-Type":`application/json`,...n(t?.headers)},body:JSON.stringify(e)})},zr=e=>`/api/v1/me/mcp/connections/${encodeURIComponent(String(e))}/headers`,Br=(e,t,n)=>{let r=e=>{if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Symbol.iterator in e)return Object.fromEntries(Array.from(e,e=>Array.from(e)));let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t};return G(zr(e),{...n,method:`POST`,headers:{"Content-Type":`application/json`,...r(n?.headers)},body:JSON.stringify(t)})},Vr=e=>`/api/v1/me/mcp/connections/${encodeURIComponent(String(e))}`,Hr=(e,t)=>G(Vr(e),{...t,method:`DELETE`}),Ur=e=>`/api/v1/me/mcp/connections/${encodeURIComponent(String(e))}/test`,Wr=(e,t)=>G(Ur(e),{...t,method:`POST`}),Gr=e=>`/api/v1/me/mcp/connections/${encodeURIComponent(String(e))}/authorize`,Kr=(e,t)=>G(Gr(e),{...t,method:`POST`}),qr=e=>`/api/v1/me/mcp/connections/${encodeURIComponent(String(e))}/oauth/bind`,Jr=(e,t,n)=>{let r=e=>{if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Symbol.iterator in e)return Object.fromEntries(Array.from(e,e=>Array.from(e)));let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t};return G(qr(e),{...n,method:`POST`,headers:{"Content-Type":`application/json`,...r(n?.headers)},body:JSON.stringify(t)})},Yr=e=>`/api/v1/me/mcp/connections/${encodeURIComponent(String(e))}/oauth/complete`,Xr=(e,t,n)=>{let r=e=>{if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Symbol.iterator in e)return Object.fromEntries(Array.from(e,e=>Array.from(e)));let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t};return G(Yr(e),{...n,method:`POST`,headers:{"Content-Type":`application/json`,...r(n?.headers)},body:JSON.stringify(t)})};var Zr=`0.30.4`;function Qr(e){s.write(`${JSON.stringify(e,null,2)}\n`)}function $r(e,t=``){let n=``;for(let r of e){let e=r.codePointAt(0)??0;n+=(e<32||e>=127&&e<160)&&!t.includes(r)?`\\u${e.toString(16).padStart(4,`0`)}`:r}return n}function ei(e){return e==null?``:$r(typeof e==`string`?e:JSON.stringify(e))}function ti(e){let t=Object.entries(e),n=Math.max(...t.map(([e])=>e.length));for(let[e,r]of t)s.write(`${e.padEnd(n)} ${ei(r)}\n`)}function ni(e,t){t?Qr(e):ti(e)}function ri(e,t){let n=e.map(e=>t.map(t=>ei(e[t]))),r=t.map((e,t)=>n.reduce((e,n)=>Math.max(e,n[t]?.length??0),e.length)),i=e=>`${e.map((e,t)=>e.padEnd(r[t]??0)).join(` `)}`.trimEnd();s.write(`${i(t.map(e=>e.toUpperCase()))}\n`);for(let e of n)s.write(`${i(e)}\n`)}function ii(e){if(e.status===401)return"The API key was rejected. It may be revoked or deleted, so create a new one and run `astralbeam auth login` again.";if(e.status===404&&e.body?.detail===`Resource not found.`)return`This server does not serve that endpoint. Check the API URL, or the server may run an older AstralBeam release than this CLI (${Zr}).`;if(e.status===429)return`The API rate limit was reached. Wait a few minutes and retry.`}function ai(e,t,n,r){let i=e instanceof Error?e.message:String(e);if(t){let t=or(e)?e.body??{status:e.status,detail:i}:{detail:i};a.write(`${JSON.stringify({error:t,context:n??null})}\n`);return}if(!or(e))return void a.write(`Error: ${$r(i)}\n`);let o=r?` from ${r}`:``;a.write(`Error: ${$r(i)} (HTTP ${e.status}${o})\n`);for(let t of e.body?.issues??[])a.write(` ${$r(t.path)}: ${$r(t.message)}\n`);let s=ii(e);s&&a.write(`${s}\n`)}const oi=`https://astralbeam.ai/api`,si=/^key_([0-9a-f-]{36})_[0-9a-f-]{36}_abo_[A-Za-z]{64}$/;function ci(){if(n.ASTRALBEAM_CONFIG_DIR)return se(n.ASTRALBEAM_CONFIG_DIR,`config.json`);let e=i===`win32`?n.APPDATA??ae():n.XDG_CONFIG_HOME??se(ae(),`.config`);return se(e,`astralbeam`,`config.json`)}function li(e){let t=si.exec(e)?.[1];if(!t)throw Error(`The API key must match key_<organizationId>_<id>_abo_<secret>.`);return t}function ui(e){let t;try{t=new URL(e)}catch{throw Error(`The API URL "${e}" is not a valid URL.`)}let n=t.hostname,r=n===`localhost`||n===`[::1]`||w(n)&&n.startsWith(`127.`);if(t.protocol!==`https:`&&!(t.protocol===`http:`&&r))throw Error(`The API URL "${e}" must use https://, or http:// only for loopback hosts.`);return e}function di(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function fi(e){return di(e)&&Object.values(e).every(e=>di(e)&&typeof e.api_url==`string`&&typeof e.api_key==`string`&&di(e.organization)&&typeof e.organization.id==`string`&&typeof e.organization.name==`string`&&typeof e.organization.slug==`string`)}function pi(e){try{let t=JSON.parse(e);if(di(t)){let e=t.bindings===void 0?{}:t.bindings;if(fi(e))return{bindings:e}}}catch{}throw Error(`Invalid AstralBeam login bindings in ${ci()}`)}async function mi(){try{return pi(await b(ci(),`utf8`))}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return{bindings:{}};throw e}}async function hi(e){let t=ci();await re(oe(t),{recursive:!0,mode:448});let n=`${t}.${r}.tmp`;try{await C(n,`${JSON.stringify(e,null,2)}\n`,{mode:384,flag:`wx`}),await ie(n,t)}catch(e){throw await S(n,{force:!0}),e}}async function gi(){return await x(t())}function _i(e,t){for(let n=t;;n=oe(n)){let t=e.bindings[n];if(t)return{directory:n,binding:t};if(oe(n)===n)return}}function vi(e){let t=ae();return e===t||e.startsWith(t+T)?`~${e.slice(t.length)}`:e}const K={json:!1,context:void 0,failedRequest:void 0};function yi(e){K.context={organization:e.organization,bound_directory:e.directory??null},K.json||a.write(bi(e))}function bi(e){let{organization:t,directory:n}=e,r=t.name?`${$r(t.name)} (${$r(t.slug??``)}) · `:``,i=n?`bound at ${vi(n)}`:`from ASTRALBEAM_API_KEY`;return`▸ ${r}org ${t.id} · ${i}\n`}async function xi(){let e=n.ASTRALBEAM_API_KEY,t;if(e)t={apiKey:e,apiUrl:ui(n.ASTRALBEAM_API_URL??`https://astralbeam.ai/api`),organization:{id:li(e)}};else{let e=await gi(),r=_i(await mi(),e);if(!r)throw Error(`No AstralBeam login covers ${vi(e)}. Run \`astralbeam auth login\` in this directory or a parent, or set ASTRALBEAM_API_KEY.`);let{binding:i}=r;t={apiKey:i.api_key,apiUrl:ui(n.ASTRALBEAM_API_URL??i.api_url),organization:i.organization,directory:r.directory}}return yi(t),t}function Si(e,t=[]){let n=(e,r)=>{if(Array.isArray(e)||typeof e!=`object`||!e)return e;let i=Object.entries(e).flatMap(([e,i])=>{let a=[...r,e],o=t.some(e=>e.length===a.length&&e.every((e,t)=>e===a[t])),s=o?i:n(i,a);return s===void 0||!o&&typeof s==`object`&&s&&!Array.isArray(s)&&Object.keys(s).length===0?[]:[[e,s]]});return Object.fromEntries(i)};return n(e,[])}function Ci(e,t){let n=t.startsWith(`--`)?t:`--${t}`,r=e;if(e.startsWith(`@`)){let t=e.slice(1);if(t.length===0)throw Error(`${n} '@' must be followed by a file path (got empty path)`);let i=ce(t);try{r=le(i,`utf-8`)}catch(e){let r=e instanceof Error?e.message:`unknown read error`;throw Error(`${n}: cannot read file at '${t}': ${r}`)}}try{return JSON.parse(r)}catch{throw Error(`Invalid JSON in ${n}. Expected valid JSON.`)}}function wi(e,t=[]){let n=Ci(e,`body`);for(let{path:e,flag:r}of t){let t=n;for(let n of e)t=Ti(t)&&Object.hasOwn(t,n)?t[n]:void 0;if(!Ti(t))throw Error(`--body must include a JSON object at ${e.join(`.`)} (for --${r}).`)}return n}function Ti(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ei(e,t,n=!1){let r=t.startsWith(`--`)?t:`--${t}`;if(e===void 0){if(n)throw Error(`${r} is required (or pass --body with this field set).`);return}if(typeof e!=`string`)throw Error(`${r} must be provided once as a JSON object.`);let i=Ci(e,t);if(!Ti(i))throw Error(`${r} must be a JSON object.`);return i}function Di(e,t,n=`text`){if(e===void 0||!e.startsWith(`@`))return e;let r=e.slice(1);if(r.length===0)throw Error(`--${t} '@' must be followed by a file path (got empty path)`);let i=ce(r),a;try{a=le(i)}catch(e){let n=e instanceof Error?e.message:`unknown read error`;throw Error(`--${t}: cannot read file at '${r}': ${n}`)}switch(n){case`text`:return a.toString(`utf-8`);case`binary`:return a;case`base64`:return a.toString(`base64`);case`json`:{let e=a.toString(`utf-8`);try{return JSON.parse(e)}catch(e){let n=e instanceof Error?e.message:`unknown JSON parse error`;throw Error(`--${t}: file at '${r}' is not valid JSON: ${n}`)}}}}function Oi(e){return e.replace(/^filter_(.+)$/,`filter[$1]`)}async function ki(e){let{apiKey:t,apiUrl:n}=await xi();return{send(e,r={}){let i=new URLSearchParams;for(let t of e.query??[]){let e=r[t];e!==void 0&&i.set(Oi(t),typeof e==`string`?e:JSON.stringify(e))}return ar(e.path(r)+(i.size?`?${i.toString()}`:``),{apiKey:t,apiUrl:n,method:e.method,...e.body?{headers:{"content-type":`application/json`},body:JSON.stringify(r.body)}:{}})}}}function q(e,t){if(e!==void 0){if(K.json||typeof e!=`object`||!e)return Qr(e);if(`items`in e&&Array.isArray(e.items)){let t=e.items;t.length?ri(t,Object.keys(t[0])):a.write(`No results.
|
|
92
92
|
`),`page_after`in e&&typeof e.page_after==`string`&&a.write(`More results: --page-after ${$r(e.page_after)}\n`)}else ni(e,!1)}}function J(e,t){return t()}let Ai=``;async function ji(e,t,n){return t.dryRun&&(Ai=(await xi()).apiUrl),n()}function Mi(e){e.query&&=Object.fromEntries(Object.entries(e.query).map(([e,t])=>[Oi(e),t])),Qr({...e,note:`Local request preview only. No HTTP request or server-side validation is performed.`,command:e.command.replace(/^cf /,`astralbeam `),url:nr(new URL(e.url).pathname.replace(/^\/client\/v4/,``),Ai)})}function Ni(e,t){throw Error(`Missing required option --${e} (or pass --body).`)}var Pi={method:`GET`,path:()=>`/api/v1/docs/search`,query:[`q`],errors:{400:`BadRequestError`,401:`UnauthorizedError`,403:`ForbiddenError`,404:`NotFoundError`,409:`ConflictError`,413:`ContentTooLargeError`,415:`UnsupportedMediaTypeError`,422:`UnprocessableEntityError`,429:`TooManyRequestsError`,500:`InternalServerError`,503:`ServiceUnavailableError`}};function Fi(e){return e.usage(`$0 docs search
|
|
93
93
|
|
|
94
94
|
Search the published guides and API reference. Returns up to five matching pages with relative URLs and the best matching section. Accepts the same credentials as the resource APIs.`).option(`q`,{type:`string`,description:`Q`,demandOption:!0}).option(`dry-run`,{type:`boolean`,description:`Validate and show what would happen without executing`,default:!1})}const Ii={command:`search`,describe:`Search documentation`,builder:Fi,handler:async e=>ji({command:`docs search`,classification:{safeFlags:[`dry-run`]}},e,async()=>{let t={q:e.q};if(e.dryRun){Mi({command:`cf docs search`,method:`GET`,url:`https://api.cloudflare.com/client/v4/api/v1/docs/search`,pathParams:{},query:t,bodyKind:`none`});return}let n=await ki(e);q(await J(`Loading`,async()=>n.send(Pi,t)),{successLabel:`Loaded`})})},Li={command:`docs`,describe:`docs`,builder:e=>e.command(Ii).demandCommand(1,`Please specify a subcommand`),handler:()=>{}};var Ri={method:`GET`,path:()=>`/api/v1/organization`,errors:{400:`BadRequestError`,401:`UnauthorizedError`,403:`ForbiddenError`,404:`NotFoundError`,409:`ConflictError`,413:`ContentTooLargeError`,415:`UnsupportedMediaTypeError`,422:`UnprocessableEntityError`,429:`TooManyRequestsError`,500:`InternalServerError`,503:`ServiceUnavailableError`}};function zi(e){return e.usage(`$0 organization get
|
|
@@ -115,12 +115,12 @@ Update supplied name/metadata fields only. Requires an organization API key or o
|
|
|
115
115
|
|
|
116
116
|
Read conversation history for administration`).option(`tenant-id`,{type:`string`,description:`TenantId`,demandOption:!0}).option(`id`,{type:`string`,description:`ID`,demandOption:!0}).option(`page-size`,{type:`number`,description:`Positive integer, default 20. Values above 100 are accepted and capped. page_after and page_before are mutually exclusive.`}).option(`page-after`,{type:`string`,description:`Page after`}).option(`page-before`,{type:`string`,description:`Page before`}).option(`dry-run`,{type:`boolean`,description:`Validate and show what would happen without executing`,default:!1})}const ba={command:`list`,describe:`Read conversation history for administration`,builder:ya,handler:async e=>ji({command:`tenants threads messages list`,classification:{safeFlags:[`dry-run`]}},e,async()=>{let t={page_size:e[`page-size`],page_after:e[`page-after`],page_before:e[`page-before`]};if(e.dryRun){Mi({command:`cf tenants threads messages list`,method:`GET`,url:`https://api.cloudflare.com/client/v4/api/v1/tenants/${e[`tenant-id`]==null?`<tenant-id>`:encodeURIComponent(String(e[`tenant-id`]))}/threads/${e.id==null?`<id>`:encodeURIComponent(String(e.id))}/messages`,pathParams:{"tenant-id":String(e[`tenant-id`]??``),id:String(e.id??``)},query:t,bodyKind:`none`});return}let n=await ki(e);q(await J(`Loading`,async()=>n.send(va,{tenantId:e[`tenant-id`],id:e.id,...t})),{successLabel:`Loaded`})})},xa={command:`messages`,describe:`Operations for threads.messages`,builder:e=>e.command(ba).demandCommand(1,`Please specify a subcommand`),handler:()=>{}},Sa={command:`threads`,describe:`Operations for threads`,builder:e=>e.command(xa).demandCommand(1,`Please specify a subcommand`),handler:()=>{}},Ca={command:`tenants`,describe:`tenants`,builder:e=>e.command(ca).command(da).command(ma).command(_a).command(Sa).demandCommand(1,`Please specify a subcommand`),handler:()=>{}};var wa={method:`GET`,path:()=>`/api/v1/threads`,query:[`page_size`,`page_after`,`page_before`,`q`,`filter_tenant_id`],errors:{400:`BadRequestError`,401:`UnauthorizedError`,403:`ForbiddenError`,404:`NotFoundError`,409:`ConflictError`,413:`ContentTooLargeError`,415:`UnsupportedMediaTypeError`,422:`UnprocessableEntityError`,429:`TooManyRequestsError`,500:`InternalServerError`,503:`ServiceUnavailableError`}};function Ta(e){return e.usage(`$0 threads list
|
|
117
117
|
|
|
118
|
-
List nonempty conversations by activity, Tenant ID and thread ID descending. q searches titles as a case-insensitive literal substring. filter[tenant_id] narrows the verified scope. Keep filters unchanged when reusing cursors. This is a live listing, not a snapshot.`).option(`page-size`,{type:`number`,description:`Positive integer, default 20. Values above 100 are accepted and capped. page_after and page_before are mutually exclusive.`}).option(`page-after`,{type:`string`,description:`Page after`}).option(`page-before`,{type:`string`,description:`Page before`}).option(`q`,{type:`string`,description:`Case-insensitive literal substring of the conversation title. Trimmed, blank means no search.`}).option(`tenant-id`,{type:`string`,description:`Filter tenant ID`}).option(`dry-run`,{type:`boolean`,description:`Validate and show what would happen without executing`,default:!1})}const Ea={command:`list`,describe:`List conversations for administration`,builder:Ta,handler:async e=>ji({command:`threads list`,classification:{safeFlags:[`dry-run`]}},e,async()=>{let t={page_size:e[`page-size`],page_after:e[`page-after`],page_before:e[`page-before`],q:e.q,filter_tenant_id:e[`tenant-id`]};if(e.dryRun){Mi({command:`cf threads list`,method:`GET`,url:`https://api.cloudflare.com/client/v4/api/v1/threads`,pathParams:{},query:t,bodyKind:`none`});return}let n=await ki(e);q(await J(`Loading`,async()=>n.send(wa,t)),{successLabel:`Loaded`})})},Da={command:`threads`,describe:`threads`,builder:e=>e.command(Ea).demandCommand(1,`Please specify a subcommand`),handler:()=>{}};var Oa=/* @__PURE__ */
|
|
118
|
+
List nonempty conversations by activity, Tenant ID and thread ID descending. q searches titles as a case-insensitive literal substring. filter[tenant_id] narrows the verified scope. Keep filters unchanged when reusing cursors. This is a live listing, not a snapshot.`).option(`page-size`,{type:`number`,description:`Positive integer, default 20. Values above 100 are accepted and capped. page_after and page_before are mutually exclusive.`}).option(`page-after`,{type:`string`,description:`Page after`}).option(`page-before`,{type:`string`,description:`Page before`}).option(`q`,{type:`string`,description:`Case-insensitive literal substring of the conversation title. Trimmed, blank means no search.`}).option(`tenant-id`,{type:`string`,description:`Filter tenant ID`}).option(`dry-run`,{type:`boolean`,description:`Validate and show what would happen without executing`,default:!1})}const Ea={command:`list`,describe:`List conversations for administration`,builder:Ta,handler:async e=>ji({command:`threads list`,classification:{safeFlags:[`dry-run`]}},e,async()=>{let t={page_size:e[`page-size`],page_after:e[`page-after`],page_before:e[`page-before`],q:e.q,filter_tenant_id:e[`tenant-id`]};if(e.dryRun){Mi({command:`cf threads list`,method:`GET`,url:`https://api.cloudflare.com/client/v4/api/v1/threads`,pathParams:{},query:t,bodyKind:`none`});return}let n=await ki(e);q(await J(`Loading`,async()=>n.send(wa,t)),{successLabel:`Loaded`})})},Da={command:`threads`,describe:`threads`,builder:e=>e.command(Ea).demandCommand(1,`Please specify a subcommand`),handler:()=>{}};var Oa=/* @__PURE__ */ D({command0:()=>Li,command1:()=>Vi,command2:()=>aa,command3:()=>Ca,command4:()=>Da});function ka(e){o.setRawMode(!0),a.write(e),o.setEncoding(`utf8`),o.resume();let t=``;return new Promise((e,n)=>{let r=()=>{o.off(`data`,i),o.setRawMode(!1),o.pause(),a.write(`
|
|
119
119
|
`)},i=i=>{for(let a of i){if(a===`\r`||a===`
|
|
120
|
-
`)return r(),e(t.trim());if(a===``)return r(),n(/* @__PURE__ */ Error(`Cancelled.`));t=a===``||a===`\b`?t.slice(0,-1):t+a}};o.on(`data`,i)})}async function Aa(){return o.isTTY?await ka(`Paste an organization API key: `):(await
|
|
120
|
+
`)return r(),e(t.trim());if(a===``)return r(),n(/* @__PURE__ */ Error(`Cancelled.`));t=a===``||a===`\b`?t.slice(0,-1):t+a}};o.on(`data`,i)})}async function Aa(){return o.isTTY?await ka(`Paste an organization API key: `):(await ue(o)).trim()}async function ja(e,t){let n=li(e),{id:r,name:i,slug:a}=await mr({apiKey:e,apiUrl:t});if(r!==n)throw Error(`The API returned a different organization.`);return{id:r,name:i,slug:a}}function Ma(e){return`${e.slice(0,e.indexOf(`_abo_`)+5)}…${e.slice(-4)}`}function Na(e){return e.command(`login`,`Verify an API key, read from a hidden prompt or stdin, and bind it to this directory and everything below it`,e=>e.option(`api-url`,{type:`string`,description:`API base URL, ending in /api (default ${oi})`}),async e=>{let t=ui(e.apiUrl??n.ASTRALBEAM_API_URL??`https://astralbeam.ai/api`),r=await Aa(),i=await ja(r,t),a=await gi(),o=await mi();o.bindings[a]={api_url:t,api_key:r,organization:i},await hi(o),yi({apiKey:r,apiUrl:t,organization:i,directory:a}),ni({directory:a,organization:i,api_url:t},K.json)}),e.command({command:`logout`,describe:`Remove the binding that covers this directory`,handler:async()=>{let e=await mi(),t=_i(e,await gi());if(!t)throw Error(`No AstralBeam login covers this directory.`);delete e.bindings[t.directory],await hi(e);let{organization:n}=t.binding;ni({directory:t.directory,organization:n},K.json)}}),e.command({command:`status`,describe:`Show which organization commands here use, and verify the key against the API`,handler:async()=>{let{apiKey:e,apiUrl:t,directory:n}=await xi(),r=await ja(e,t);if(K.context&&(K.context.organization=r),n){let e=await mi(),t=e.bindings[n];t&&JSON.stringify(t.organization)!==JSON.stringify(r)&&(t.organization=r,await hi(e))}ni({organization:r,api_url:t,api_key:Ma(e),source:n??`ASTRALBEAM_API_KEY`},K.json)}}),e.command({command:`list`,describe:`List every directory binding`,handler:async()=>{let{bindings:e}=await mi(),t=Object.entries(e).map(([e,t])=>({directory:e,organization:t.organization,api_url:t.api_url}));if(K.json)return Qr({items:t});if(t.length===0)return void a.write(`No bindings.
|
|
121
121
|
`);ri(t.map(({directory:e,organization:t,api_url:n})=>({directory:vi(e),name:t.name,slug:t.slug,organization_id:t.id,api_url:n})),[`directory`,`name`,`slug`,`organization_id`,`api_url`])}}),e.demandCommand(1)}const Pa=new TextEncoder,Fa=new TextDecoder,Ia=new TextDecoder(`utf-8`,{fatal:!0});function La(...e){let t=e.reduce((e,{length:t})=>e+t,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}const Ra=/[^\x00-\x7f]/;function za(e){if(typeof e==`string`&&e.length>=128){if(Ra.test(e))throw TypeError(`non-ASCII string encountered in encode()`);return Pa.encode(e)}let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r>127)throw TypeError(`non-ASCII string encountered in encode()`);t[n]=r}return t}function Ba(e,t=!1){if(Uint8Array.prototype.toBase64)return e.toBase64({alphabet:t?`base64url`:`base64`,omitPadding:t});let n=32768,r=[];for(let t=0;t<e.length;t+=n)r.push(String.fromCharCode.apply(null,e.subarray(t,t+n)));let i=btoa(r.join(``));return t?i.replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`):i}function Va(e,t=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e,{alphabet:t?`base64url`:`base64`});if(t){if(e.includes(`+`)||e.includes(`/`))throw TypeError(`Invalid base64url`);e=e.replace(/-/g,`+`).replace(/_/g,`/`)}let n=atob(e),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r}var Ha=class extends Error{static code=`ERR_JOSE_GENERIC`;code=`ERR_JOSE_GENERIC`;constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},Ua=class extends Ha{static code=`ERR_JOSE_NOT_SUPPORTED`;code=`ERR_JOSE_NOT_SUPPORTED`},Wa=class extends Ha{static code=`ERR_JWS_INVALID`;code=`ERR_JWS_INVALID`},Ga=class extends Ha{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`};function Ka(e){try{return Va(typeof e==`string`?e:Fa.decode(e),!0)}catch(e){throw TypeError(`The input to be decoded is not correctly encoded.`,{cause:e})}}function qa(e){return Ba(typeof e==`string`?Pa.encode(e):e,!0)}function Ja(e){if(typeof e!=`object`||!e||Object.prototype.toString.call(e)!==`[object Object]`)return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}function Ya(...e){let t=/* @__PURE__ */ new Set;for(let n of e)if(n)for(let e of Object.keys(n)){if(t.has(e))return!1;t.add(e)}return!0}function Xa(e,t){if(e!==void 0)throw TypeError(`${t} can only be called once`)}const Za={__proto__:null,b64:!0};function Qa(e,t){let{crit:n}=t??{};if(Array.isArray(n)&&new Set(n).size!==n.length)throw new e(`"crit" (Critical) Header Parameter MUST NOT contain duplicate values`)}function $a(e,t,n,r,i){if(i.crit!==void 0&&r?.crit===void 0)throw new e(`"crit" (Critical) Header Parameter MUST be integrity protected`);if(!r||r.crit===void 0)return[];if(!Array.isArray(r.crit)||r.crit.length===0||r.crit.some(e=>typeof e!=`string`||e.length===0))throw new e(`"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present`);let a=n===void 0?t:{__proto__:null,...n,...t};for(let t of r.crit){if(!(t in a))throw new Ua(`Extension Header Parameter "${t}" is not recognized`);if(!Object.hasOwn(i,t)||i[t]===void 0)throw new e(`Extension Header Parameter "${t}" is missing`);if(a[t]&&(!Object.hasOwn(r,t)||r[t]===void 0))throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return r.crit}function eo(e,t){if(t.includes(`b64`)){let t=e.b64;if(typeof t!=`boolean`)throw new Wa(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);return t}return!0}function to(e,t){let n,r;try{n=JSON.stringify(t),r=JSON.parse(n)}catch(t){throw new e(`JOSE Header is not valid JSON`,{cause:t})}if(!Ja(r))throw new e(`JOSE Header is not a JSON object`);return[r,n]}var no=Object.defineProperty,ro=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports),io=(e,t)=>{let n={};for(var r in e)no(n,r,{get:e[r],enumerable:!0});return t||no(n,Symbol.toStringTag,{value:`Module`}),n};function ao(e){if(typeof e!=`string`)throw new Ga(`JWTs must use Compact JWS serialization, JWT must be a string`);let{1:t,length:n}=e.split(`.`);if(n===5)throw new Ga(`Only JWTs using Compact JWS serialization can be decoded`);if(n!==3)throw new Ga(`Invalid JWT`);if(!t)throw new Ga(`JWTs must contain a payload`);let r;try{r=Ka(t)}catch(e){throw new Ga(`Failed to base64url decode the payload`,{cause:e})}let i;try{i=JSON.parse(Ia.decode(r))}catch(e){throw new Ga(`Failed to parse the decoded payload as JSON`,{cause:e})}if(!Ja(i))throw new Ga(`Invalid JWT Claims Set`);return i}/* @__NO_SIDE_EFFECTS__ */
|
|
122
122
|
function oo({update:e,notify:t,unwatched:n}){return{link:r,unlink:i,propagate:a,checkDirty:o,shallowPropagate:s};function r(e,t,n){let r=t.depsTail;if(r!==void 0&&r.dep===e)return;let i=r===void 0?t.deps:r.nextDep;if(i!==void 0&&i.dep===e){i.version=n,t.depsTail=i;return}let a=e.subsTail;if(a!==void 0&&a.version===n&&a.sub===t)return;let o=t.depsTail=e.subsTail={version:n,dep:e,sub:t,prevDep:r,nextDep:i,prevSub:a,nextSub:void 0};i!==void 0&&(i.prevDep=o),r===void 0?t.deps=o:r.nextDep=o,a===void 0?e.subs=o:a.nextSub=o}function i(e,t=e.sub){let r=e.dep,i=e.prevDep,a=e.nextDep,o=e.nextSub,s=e.prevSub;return a===void 0?t.depsTail=i:a.prevDep=i,i===void 0?t.deps=a:i.nextDep=a,o===void 0?r.subsTail=s:o.prevSub=s,s===void 0?(r.subs=o)===void 0&&n(r):s.nextSub=o,a}function a(e){let n=e.nextSub,r;top:do{let i=e.sub,a=i.flags;if(a&60?a&12?a&4?!(a&48)&&c(e,i)?(i.flags=a|40,a&=1):a=0:i.flags=a&-9|32:a=0:i.flags=a|32,a&2&&t(i),a&1){let t=i.subs;if(t!==void 0){let i=(e=t).nextSub;i!==void 0&&(r={value:n,prev:r},n=i);continue}}if((e=n)!==void 0)n=e.nextSub;else{for(;r!==void 0;)if(e=r.value,r=r.prev,e!==void 0){n=e.nextSub;continue top}break}}while(1)}function o(t,n){let r,i=0,a=!1;top:do{let o=t.dep,c=o.flags;if(n.flags&16)a=!0;else if((c&17)==17){if(e(o)){let e=o.subs;e.nextSub!==void 0&&s(e),a=!0}}else if((c&33)==33){(t.nextSub!==void 0||t.prevSub!==void 0)&&(r={value:t,prev:r}),t=o.deps,n=o,++i;continue}if(!a){let e=t.nextDep;if(e!==void 0){t=e;continue}}for(;i--;){let i=n.subs,o=i.nextSub!==void 0;if(o?(t=r.value,r=r.prev):t=i,a){if(e(n)){o&&s(i),n=t.sub;continue}a=!1}else n.flags&=-33;n=t.sub;let c=t.nextDep;if(c!==void 0){t=c;continue top}}return a}while(1)}function s(e){do{let n=e.sub,r=n.flags;(r&48)==32&&(n.flags=r|16,(r&6)==2&&t(n))}while((e=e.nextSub)!==void 0)}function c(e,t){let n=t.depsTail;for(;n!==void 0;){if(n===e)return!0;n=n.prevDep}return!1}}function so(e,t,n){let r=typeof e==`object`,i=r?e:void 0;return{next:(r?e.next:e)?.bind(i),error:(r?e.error:t)?.bind(i),complete:(r?e.complete:n)?.bind(i)}}const co=[];let lo=0;const{link:uo,unlink:fo,propagate:po,checkDirty:mo,shallowPropagate:ho}=/* @__PURE__ */ oo({update(e){return e._update()},notify(e){co[_o++]=e,e.flags&=-3},unwatched(e){e.depsTail!==void 0&&(e.depsTail=void 0,e.flags=17,yo(e))}});let go=0,_o=0,vo;function yo(e){let t=e.depsTail,n=t===void 0?e.deps:t.nextDep;for(;n!==void 0;)n=fo(n,e)}function bo(){for(;go<_o;){let e=co[go];co[go++]=void 0,e.notify()}go=0,_o=0}function xo(e,t){let n=typeof e==`function`,r=e,i={_snapshot:n?void 0:e,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:+!n,get(){return vo!==void 0&&uo(i,vo,lo),i._snapshot},subscribe(e){let t=so(e),n={current:!1},r=So(()=>{i.get(),n.current?(vo=void 0,t.next?.(i._snapshot)):n.current=!0});return{unsubscribe:()=>{r.stop()}}},_update(e){let a=vo,o=t?.compare??Object.is;if(n)vo=i,++lo,i.depsTail=void 0;else if(e===void 0)return!1;n&&(i.flags=5);try{let t=i._snapshot,a=typeof e==`function`?e(t):e===void 0&&n?r(t):e;return t===void 0||!o(t,a)?(i._snapshot=a,!0):!1}finally{vo=a,n&&(i.flags&=-5),yo(i)}}};return n?(i.flags=17,i.get=function(){let e=i.flags;if(e&16||e&32&&mo(i.deps,i)){if(i._update()){let e=i.subs;e!==void 0&&ho(e)}}else e&32&&(i.flags=e&-33);return vo!==void 0&&uo(i,vo,lo),i._snapshot}):i.set=function(e){if(i._update(e)){let e=i.subs;e!==void 0&&(po(e),ho(e),bo())}},i}function So(e){let t=()=>{let t=vo;vo=n,++lo,n.depsTail=void 0,n.flags=6;try{return e()}finally{vo=t,n.flags&=-5,yo(n)}},n={deps:void 0,depsTail:void 0,subs:void 0,subsTail:void 0,flags:6,notify(){let e=this.flags;e&16||e&32&&mo(this.deps,this)?t():this.flags=2},stop(){this.flags=0,this.depsTail=void 0,yo(this)}};return t(),n}function Co(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function wo(e){typeof globalThis.reportError==`function`?globalThis.reportError(e):console.error(e)}function To(e){if(Array.isArray(e))return Object.freeze(e.map(To));if(!Co(e))return e;let t={};for(let n of Object.keys(e))t[n]=To(e[n]);return Object.freeze(t)}function Eo(e,t=/* @__PURE__ */ new WeakMap){let n=e,r={...n};if(Co(n.source)&&(r.source=Object.freeze({...n.source})),n.type===`tool-call`&&Co(n.approval)&&(r.approval=Object.freeze({...n.approval})),n.type===`tool-result`&&Array.isArray(n.content)&&(r.content=Object.freeze(n.content.map(e=>typeof e==`object`&&e?Eo(e,t):e))),`input`in n&&(r.input=To(n.input)),`output`in n&&(r.output=To(n.output)),n.type===`subagent`&&Co(n.subagent)){let e=n.subagent;r.subagent=Object.freeze(Array.isArray(e.messages)?{...e,messages:Oo(t,e.messages)}:{...e})}return Object.freeze(r)}function Do(e,t,n){let r=e.get(t);return r||(r=n(t),e.set(t,r)),r}function Oo(e,t){return Object.freeze(t.map(t=>Do(e,t,()=>Object.freeze({...t,parts:Object.freeze(t.parts.map(t=>Do(e,t,()=>Eo(t,e))))}))))}function ko(e,t){e.set(e=>{let n=!1,r={...e};for(let i of Object.keys(t))Object.is(e[i],t[i])||(r[i]=t[i],n=!0);return n?Object.freeze(r):e})}var Ao=8;function jo(e,t){let{unsubscribe:n}=e.subscribe(()=>{let n,r=0;do{n=e.get();try{t()}catch(e){wo(e)}r++}while(e.get()!==n&&r<Ao)});return n}new TextEncoder,new TextDecoder;var Mo=class extends Error{missingFeature;constructor(e){super(No(e)),this.name=`UnsupportedResponseStreamError`,this.missingFeature=e}};function No(e){return`Streaming fetch responses are not supported in this runtime because ${e} is unavailable. React Native users need a compatible fetch/stream/TextDecoder polyfill, or should use a fetch, XHR, or custom transport that can deliver streaming chunks.`}function Po(e){if(!e.body)throw new Mo(`Response.body`);if(typeof e.body.getReader!=`function`)throw new Mo(`Response.body.getReader`);return e.body.getReader()}function Fo(){if(typeof globalThis.TextDecoder!=`function`)throw new Mo(`TextDecoder`);return new globalThis.TextDecoder}function Io(e){if(!e.startsWith(`data:`))return e;let t=e.slice(5);return t.startsWith(` `)?t.slice(1):t}function Lo(e){if(e instanceof Date)return Number.isNaN(e.getTime())?void 0:e;if(typeof e!=`string`)return;let t=new Date(e);return Number.isNaN(t.getTime())?void 0:t}function Ro(e){let t=Lo(e.createdAt),n=e.parts.map(e=>{if(e.type!==`tool-result`)return e;let t=Lo(e.createdAt),{createdAt:n,...r}=e;return t?{...r,createdAt:t}:r}),{createdAt:r,...i}=e;return t?{...i,parts:n,createdAt:t}:{...i,parts:n}}function zo(e){return e.map(Ro)}function Bo(e){return Object.keys(e).length>0?e:void 0}function Vo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&`promptTokens`in e}function Ho(e,t){return Vo(e)?e:Uo(Array.isArray(e)?e:void 0,t)}function Uo(e,t){let n=e?.reduce((e,t)=>{for(let n of[`inputTokens`,`outputTokens`,`totalTokens`,`cachedInputTokens`,`cacheWriteInputTokens`,`reasoningTokens`])t[n]!==void 0&&(e[n]=(e[n]??0)+t[n]);return e},{});if((e===void 0||e.length===0)&&t==null)return;let{promptTokensDetails:r,completionTokensDetails:i,...a}=t??{},o=Bo({...n?.cachedInputTokens===void 0?{}:{cachedTokens:n.cachedInputTokens},...n?.cacheWriteInputTokens===void 0?{}:{cacheWriteTokens:n.cacheWriteInputTokens},...r}),s=Bo({...n?.reasoningTokens===void 0?{}:{reasoningTokens:n.reasoningTokens},...i});return{promptTokens:n?.inputTokens??0,completionTokens:n?.outputTokens??0,totalTokens:n?.totalTokens??0,...a,...o===void 0?{}:{promptTokensDetails:o},...s===void 0?{}:{completionTokensDetails:s}}}function Wo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Go(e,t){if(t==null)return e;if(e==null)return{...t};let n={...e,...t};return Wo(e.tanstack)&&Wo(t.tanstack)&&(n.tanstack={...e.tanstack,...t.tanstack}),n}function Y(e){if(e==null)return;let t=`metadata`in e?e.metadata:void 0,n=(typeof t==`object`&&t&&!Array.isArray(t)?t:e).tanstack;if(typeof n==`object`&&n&&!Array.isArray(n))return n}function Ko(e,t){let n=e.metadata,r=Y(e)??{};return{...e,metadata:{...n??{},tanstack:{...r,...t}}}}let X=/* @__PURE__ */ function(e){return e.TEXT_MESSAGE_START=`TEXT_MESSAGE_START`,e.TEXT_MESSAGE_CONTENT=`TEXT_MESSAGE_CONTENT`,e.TEXT_MESSAGE_END=`TEXT_MESSAGE_END`,e.TEXT_MESSAGE_CHUNK=`TEXT_MESSAGE_CHUNK`,e.TOOL_CALL_START=`TOOL_CALL_START`,e.TOOL_CALL_ARGS=`TOOL_CALL_ARGS`,e.TOOL_CALL_END=`TOOL_CALL_END`,e.TOOL_CALL_CHUNK=`TOOL_CALL_CHUNK`,e.TOOL_CALL_RESULT=`TOOL_CALL_RESULT`,e.STATE_SNAPSHOT=`STATE_SNAPSHOT`,e.STATE_DELTA=`STATE_DELTA`,e.MESSAGES_SNAPSHOT=`MESSAGES_SNAPSHOT`,e.ACTIVITY_SNAPSHOT=`ACTIVITY_SNAPSHOT`,e.ACTIVITY_DELTA=`ACTIVITY_DELTA`,e.RAW=`RAW`,e.CUSTOM=`CUSTOM`,e.RUN_STARTED=`RUN_STARTED`,e.RUN_FINISHED=`RUN_FINISHED`,e.RUN_ERROR=`RUN_ERROR`,e.STEP_STARTED=`STEP_STARTED`,e.STEP_FINISHED=`STEP_FINISHED`,e.REASONING_START=`REASONING_START`,e.REASONING_MESSAGE_START=`REASONING_MESSAGE_START`,e.REASONING_MESSAGE_CONTENT=`REASONING_MESSAGE_CONTENT`,e.REASONING_MESSAGE_END=`REASONING_MESSAGE_END`,e.REASONING_MESSAGE_CHUNK=`REASONING_MESSAGE_CHUNK`,e.REASONING_END=`REASONING_END`,e.REASONING_ENCRYPTED_VALUE=`REASONING_ENCRYPTED_VALUE`,e.SUBAGENT_STARTED=`SUBAGENT_STARTED`,e.SUBAGENT_FINISHED=`SUBAGENT_FINISHED`,e.SUBAGENT_ERROR=`SUBAGENT_ERROR`,e}({});function qo(e,t){if(Object.is(e,t))return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((e,n)=>qo(e,t[n]));if(e===null||t===null||typeof e!=`object`||typeof t!=`object`||Array.isArray(e)||Array.isArray(t))return!1;let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>Object.prototype.hasOwnProperty.call(t,n)&&qo(Reflect.get(e,n),Reflect.get(t,n)))}function Jo(e,t){let n=0,r=()=>{for(;e[n]===` `||e[n]===` `||e[n]===`\r`||e[n]===`
|
|
123
|
-
`;)n++},i=()=>{let t=n++;for(;n<e.length;)if(e[n]===`\\`)n+=2;else if(e[n++]===`"`)break;return e.slice(t,n)},a=t=>{r();let o=n;if(e[n]===`{`){n++,r();let s=/* @__PURE__ */ new Map;for(;e[n]!==`}`;){let o=i(),c=JSON.parse(o);r(),n++;let l=typeof t==`object`&&t&&typeof c==`string`?Reflect.get(t,c):void 0,u=a(l);if(typeof c==`string`&&s.set(c,{...u,keyToken:o}),r(),e[n]!==`,`)break;n++,r()}return n++,{start:o,end:n,value:t,properties:s}}if(e[n]===`[`){n++,r();let i=[];for(;e[n]!==`]`&&(i.push(a(Array.isArray(t)?t[i.length]:void 0)),r(),e[n]===`,`);)n++;return n++,{start:o,end:n,value:t,items:i}}if(e[n]===`"`)i();else for(;n<e.length&&!/[\s,}\]]/.test(e[n]??``);)n++;return{start:o,end:n,value:t}};return a(t)}function Yo(e,t,n,r){if(n&&qo(n.value,e))return t.slice(n.start,n.end);if(typeof e==`number`)return Object.is(e,-0)?`-0`:e===1/0?`1e999`:e===-1/0?`-1e999`:JSON.stringify(e);if(typeof e!=`object`||!e)return JSON.stringify(e);if(r.has(e))throw TypeError(`Cannot serialize circular tool input`);r.add(e);try{if(Array.isArray(e))return`[`+Array.from(e,(e,i)=>Yo(e,t,n?.items?.[i],r)??`null`).join(`,`)+`]`;let i=[];for(let a of Object.keys(e)){let o=Yo(Reflect.get(e,a),t,n?.properties?.get(a),r);o!==void 0&&i.push((n?.properties?.get(a)?.keyToken??JSON.stringify(a))+`:`+o)}return`{`+i.join(`,`)+`}`}finally{r.delete(e)}}function Xo(e,t){if(t===void 0)return e??``;if(e===void 0)return Yo(t,``,void 0,/* @__PURE__ */ new Set)??``;let n;try{n=JSON.parse(e)}catch{return e.trim()===``?Yo(t,``,void 0,/* @__PURE__ */ new Set)??e:e}return qo(n,t)?e:Yo(t,e,Jo(e,n),/* @__PURE__ */ new Set)??e}function Zo(e){if(e.trim()===``)return{};try{return JSON.parse(e)??void 0}catch{return}}function Qo(e,t){let n=Y(t),r=t.args??n?.args,i=typeof r==`string`?r:void 0,a=t.input??n?.input,o=typeof a==`object`&&a?a:void 0,s=i??e;if(i===void 0&&o!==void 0)try{JSON.parse(s)}catch{s=void 0}let c;try{c=Xo(s,o)}catch{c=s??e}return{args:c,input:Zo(c)}}var $o=`redacted_thinking-`;function es(e){return typeof e==`string`&&e.startsWith(`redacted_thinking-`)}var ts=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function ns(e,t){return e>>>t|e<<32-t}function rs(e){let t=new TextEncoder().encode(e),n=t.length*8,r=t.length+1,i=r+(56-r%64+64)%64+8,a=new Uint8Array(i);a.set(t),a[t.length]=128;let o=new DataView(a.buffer);o.setUint32(i-8,Math.floor(n/4294967296)),o.setUint32(i-4,n>>>0);let s=1779033703,c=3144134277,l=1013904242,u=2773480762,d=1359893119,f=2600822924,p=528734635,m=1541459225,h=/* @__PURE__ */ new Uint32Array(64);for(let e=0;e<i;e+=64){for(let t=0;t<16;t++)h[t]=o.getUint32(e+t*4);for(let e=16;e<64;e++){let t=h[e-15]??0,n=h[e-2]??0,r=ns(t,7)^ns(t,18)^t>>>3,i=ns(n,17)^ns(n,19)^n>>>10;h[e]=(h[e-16]??0)+r+(h[e-7]??0)+i>>>0}let t=s,n=c,r=l,i=u,a=d,g=f,ee=p,_=m;for(let e=0;e<64;e++){let o=ns(a,6)^ns(a,11)^ns(a,25),s=a&g^~a&ee,c=_+o+s+(ts[e]??0)+(h[e]??0)>>>0,l=(ns(t,2)^ns(t,13)^ns(t,22))+(t&n^t&r^n&r)>>>0;_=ee,ee=g,g=a,a=i+c>>>0,i=r,r=n,n=t,t=c+l>>>0}s=s+t>>>0,c=c+n>>>0,l=l+r>>>0,u=u+i>>>0,d=d+a>>>0,f=f+g>>>0,p=p+ee>>>0,m=m+_>>>0}let g=e=>(e>>>0).toString(16).padStart(8,`0`);return g(s)+g(c)+g(l)+g(u)+g(d)+g(f)+g(p)+g(m)}function is(e){return`sha256:${rs(e)}`}function as(e,t){if(e===null)return`null`;if(typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return JSON.stringify(e);if(typeof e!=`object`)throw TypeError(`Interrupt values must be JSON-compatible.`);if(t.has(e))throw TypeError(`Interrupt values must not cycle.`);if(!Array.isArray(e)&&Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw TypeError(`Interrupt values must use plain JSON objects.`);t.add(e);let n;if(Array.isArray(e)){let r=[];for(let n=0;n<e.length;n++)r.push(as(e[n],t));n=`[${r.join(`,`)}]`}else{let r=e;n=`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${as(r[e],t)}`).join(`,`)}}`}return t.delete(e),n}function os(e){return as(e,/* @__PURE__ */ new WeakSet)}function ss(e,t=is){if(typeof e!=`string`)throw TypeError(`Interrupt digests require canonical JSON text.`);return t(e)}function cs(e){typeof e==`object`&&e&&!Object.isFrozen(e)&&(Object.values(e).forEach(cs),Object.freeze(e))}function Z(e){let t=JSON.parse(os(e));return cs(t),t}function ls(e){let t=Z([...e].sort((e,t)=>e.interruptId.localeCompare(t.interruptId))),n=os(t);return Object.freeze({resolutions:t,canonicalResolutions:n,fingerprint:ss(n)})}function us(e){let t={};for(let[n,r]of Object.entries(e))n!==`$schema`&&(t[n]=r);return t}function ds(e){return(typeof e==`object`||typeof e==`function`)&&e!==null}function fs(e){if(!ds(e)||!(`~standard`in e))return!1;let t=e[`~standard`];return typeof t!=`object`||!t||!(`version`in t)||t.version!==1||!(`jsonSchema`in t)||typeof t.jsonSchema!=`object`||t.jsonSchema===null||!(`input`in t.jsonSchema)?!1:typeof t.jsonSchema.input==`function`}function ps(e){return ds(e)&&`~standard`in e&&typeof e[`~standard`]==`object`&&e[`~standard`]!==null&&`version`in e[`~standard`]&&e[`~standard`].version===1&&`validate`in e[`~standard`]&&typeof e[`~standard`].validate==`function`}function ms(e){return Object.keys(e).length>0?e:void 0}function hs(e){if(Array.isArray(e)){let t=e.map(e=>gs(e,e.required||[])),n=t.map(e=>e.nullWidening??{});return{schema:t.map(e=>e.schema),itemMap:n.some(e=>Object.keys(e).length>0)?n:void 0}}let t=gs(e,e.required||[]);return{schema:t.schema,itemMap:t.nullWidening}}function gs(e,t=[]){let n={...e},r={};if(n.type===`object`&&n.properties){let e={...n.properties},i=Object.keys(e),a={};for(let n of i){let r=e[n];if(!r)continue;let i=!t.includes(n),o=!1,s;if(r.type===`object`&&r.properties){let t=gs(r,r.required||[]);e[n]=i?{...t.schema,type:[`object`,`null`]}:t.schema,o=i,s=t.nullWidening}else if(r.type===`array`&&r.items){let t=hs(r.items);e[n]={...r,items:t.schema,...i?{type:[`array`,`null`]}:{}},o=i,s=t.itemMap?{items:t.itemMap}:void 0}else i&&(r.type&&!Array.isArray(r.type)?(e[n]={...r,type:[r.type,`null`]},o=!0):Array.isArray(r.type)&&!r.type.includes(`null`)&&(e[n]={...r,type:[...r.type,`null`]},o=!0));(o||s)&&(a[n]={...s??{},...o?{widened:!0}:{}})}n.properties=e,n.required=i,n.additionalProperties=!1,Object.keys(a).length>0&&(r.properties=a)}if(n.type===`array`&&n.items){let e=hs(n.items);n.items=e.schema,e.itemMap&&(r.items=e.itemMap)}return{schema:n,nullWidening:ms(r)}}function _s(e,t=`input`){if(fs(e)){let n=us(e[`~standard`].jsonSchema[t]({target:`draft-07`}));return`properties`in n&&!n.type&&(n.type=`object`),n.type===`object`&&!(`properties`in n)&&(n.properties={}),n.type===`object`&&!(`required`in n)&&(n.required=[]),n}if(ps(e))throw Error("Schema is a Standard Schema validator but does not expose a JSON Schema converter on `~standard.jsonSchema`. Use Zod v4.2+, ArkType v2.1.28+, or wrap a Valibot schema with `toStandardJsonSchema()` from `@valibot/to-json-schema` before passing it as `outputSchema`.");return typeof e==`object`?us(e):e}function vs(e,t={}){if(!e)return;let{forStructuredOutput:n=!1,io:r}=t;if(!n&&!fs(e)&&!ps(e))return e;let i=_s(e,r);return!i||typeof i!=`object`||!n?i:gs(i,i.required||[]).schema}async function ys(e,t){if(!ps(e))return{success:!0,data:t};let n=await e[`~standard`].validate(t);return n.issues?{success:!1,issues:n.issues.map(e=>({message:e.message||`Validation failed`,path:e.path?.map(String)}))}:{success:!0,data:n.value}}var bs=/* @__PURE__ */ new Set([`$schema`,`$id`,`$ref`,`$defs`,`type`,`properties`,`required`,`additionalProperties`,`items`,`oneOf`,`anyOf`,`allOf`,`enum`,`const`,`format`,`minimum`,`maximum`,`minLength`,`maxLength`,`pattern`]);function xs(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null)}function Ss(e){return xs(e)&&Object.keys(e).some(e=>bs.has(e))}function Cs(e){return ps(e)||fs(e)||Ss(e)}function ws(e){if(!xs(e))return!1;let t=Object.keys(e);return t.length>0&&t.every(e=>e===`approve`||e===`reject`)&&t.every(t=>Cs(e[t]))}function Ts(e){let t={};for(let[n,r]of Object.entries(e))t[n]=r;return t}function Es(e){if(ps(e)){let t=fs(e)?Ts(e[`~standard`].jsonSchema.input({target:`draft-2020-12`})):void 0;return{source:e,validator:e,...t!==void 0&&{jsonSchema:t}}}if(Ss(e))return{source:e,jsonSchema:e};throw TypeError(`Expected a supported SchemaInput.`)}function Ds(e){let t={approved:{const:e.approved}},n=[`approved`];return e.approved&&e.inputSchema&&(t.editedArgs=e.inputSchema.jsonSchema??{}),e.payload&&(t.payload=e.payload.jsonSchema??{},n.push(`payload`)),{type:`object`,properties:t,required:n,additionalProperties:!1}}function Os(e,t){let n=t===void 0?null:Es(t),r=null,i=null;if(e!==void 0){if(ps(e)||Ss(e))r=Es(e),i=r;else if(ws(e))r=e.approve===void 0?null:Es(e.approve),i=e.reject===void 0?null:Es(e.reject);else throw TypeError(`approvalSchema must be a SchemaInput or a nonempty map containing approve or reject.`)}let a={oneOf:[Ds({approved:!0,payload:r,inputSchema:n}),Ds({approved:!1,payload:i,inputSchema:null})]},o=os(a),s=os({approve:r?.jsonSchema??null,reject:i?.jsonSchema??null});return{branches:{approve:r,reject:i},responseSchema:a,responseSchemaHash:ss(o),approvalSchemaHash:ss(s)}}function ks(e){return ss(e===void 0?`undefined`:os(Es(e).jsonSchema??{standardValidator:`unserialized`}))}var As=`tanstack:interruptBinding`,js=As;function Ms(e){return e&&typeof e==`object`?e:null}function Q(e,t){return typeof e[t]==`string`?e[t]:void 0}function Ns(e){let t=e.v;return t===void 0||t===1}function Ps(e){let t=Ms(e.metadata),n=t?Ms(t[js]):null;if(!n||Q(n,`interruptId`)!==e.id||!Ns(n))return;let r=Q(n,`kind`),i=Q(n,`interruptId`),a=Q(n,`responseSchemaHash`),o=Q(n,`expiresAt`);if(!i||a===``||o!==void 0&&!Number.isFinite(Date.parse(o)))return;if(r===`generic`){let e=Q(n,`definitionId`),t=Q(n,`key`),s=n.batchIndex,c=Q(n,`payloadSchemaHash`);return(e!==void 0||t!==void 0||s!==void 0||c!==void 0)&&(!e||!t||typeof s!=`number`||!Number.isInteger(s)||s<0)?void 0:{v:1,kind:r,interruptId:i,...a?{responseSchemaHash:a}:{},...o?{expiresAt:o}:{},...e?{definitionId:e}:{},...t?{key:t}:{},...typeof s==`number`?{batchIndex:s}:{},...c?{payloadSchemaHash:c}:{}}}if(!a)return;let s=Q(n,`toolName`),c=Q(n,`toolCallId`);if(s&&c){if(r===`client-tool-execution`){let e=Q(n,`outputSchemaHash`);return e?{v:1,kind:r,interruptId:i,toolName:s,toolCallId:c,outputSchemaHash:e,responseSchemaHash:a,...o?{expiresAt:o}:{}}:void 0}if(r===`tool-approval`){let e=Q(n,`inputSchemaHash`),t=Q(n,`approvalSchemaHash`);return!e||!t?void 0:{v:1,kind:r,interruptId:i,toolName:s,toolCallId:c,originalArgs:n.originalArgs,inputSchemaHash:e,approvalSchemaHash:t,responseSchemaHash:a,...o?{expiresAt:o}:{}}}}}function Fs(e){let t=Ps(e);if(!t)return;let n=Ms(e.metadata),r=n?Ms(n[js]):null;if(!r)return;let i=Q(r,`interruptedRunId`),a=r.generation;if(!(!i||typeof a!=`number`||!Number.isInteger(a)||a<0))return{...t,interruptedRunId:i,generation:a}}var Is=`tanstack:interruptPayload`;function Ls(e,t){if(!fs(e))throw TypeError(`${t} must be a Standard Schema with a JSON Schema converter.`);try{let t=e[`~standard`].jsonSchema.input({target:`draft-07`});if(t===void 0)throw TypeError(`The exported schema is undefined.`);if(typeof t==`function`)throw TypeError(`The exported schema must not be a function.`);if(Array.isArray(t)||!t||typeof t!=`object`||![Object.prototype,null].includes(Object.getPrototypeOf(t)))throw TypeError(`The exported schema must be a plain JSON object.`);let n={};for(let[e,r]of Object.entries(t))e!==`$schema`&&(n[e]=r);return{json:n,canonicalJson:os(n)}}catch(e){throw TypeError(`${t} could not export compatible JSON Schema: ${e instanceof Error?e.message:String(e)}`)}}function Rs(e){return ss(Ls(e,`Interrupt schema`).canonicalJson)}var zs=`tanstack:interruptContinuation`;function Bs(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Vs(e){return{[zs]:e}}function Hs(e){let t=Ps(e);if(t?.kind!==`generic`||t.definitionId===void 0||t.key===void 0||t.batchIndex===void 0)return;let n=Bs(e.metadata)?e.metadata:void 0,r=n!==void 0&&Object.prototype.hasOwnProperty.call(n,`tanstack:interruptPayload`);return{v:1,definitionId:t.definitionId,key:t.key,batchIndex:t.batchIndex,reason:e.reason,message:e.message??``,...e.expiresAt===void 0?{}:{expiresAt:e.expiresAt},...t.responseSchemaHash===void 0?{}:{responseSchemaHash:t.responseSchemaHash},...t.payloadSchemaHash===void 0?{}:{payloadSchemaHash:t.payloadSchemaHash},...r?{payload:n[Is]}:{}}}function Us(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Ws=`subagentInput`;function Gs(e){if(Us(e)&&Us(e.tanstack))return e.tanstack[Ws]}function Ks(e){if(!Us(e)||`parts`in e)return;let t=e.subagentRunId;return typeof t==`string`&&t!==``?t:void 0}function qs(e){if(!Us(e)||!Us(e.metadata))return;let t=e.metadata.tanstack;if(!Us(t)||!Us(t.subagent))return;let{name:n,status:r,error:i,interruptIds:a}=t.subagent;if(typeof n!=`string`||!Js(r))return;let{description:o,parentSubagentRunId:s,parentToolCallId:c,metadata:l,placeholder:u}=t.subagent;return{name:n,status:r,...typeof o==`string`&&{description:o},...Us(i)&&typeof i.message==`string`&&{error:{message:i.message,...typeof i.code==`string`&&{code:i.code}}},...Array.isArray(a)&&{interruptIds:a.filter(e=>typeof e==`string`)},...typeof s==`string`&&{parentSubagentRunId:s},...typeof c==`string`&&{parentToolCallId:c},...Us(l)&&{metadata:l},...u===!0&&{placeholder:!0}}}function Js(e){return e===`running`||e===`finished`||e===`error`||e===`suspended`}function Ys(e){if(!Us(e))return e;let{subagentRunId:t,...n}=e,r=Us(n.metadata)?n.metadata:void 0,i=Us(r?.tanstack)?r.tanstack:void 0;if(!r||!i||!(`subagent`in i))return n;let{subagent:a,...o}=i;return{...n,metadata:{...r,tanstack:o}}}function Xs(e){let t=/* @__PURE__ */ new Map;for(let n of e){let e=Ks(n);e!==void 0&&!t.has(e)&&t.set(e,qs(n)?.parentSubagentRunId)}let n=e=>{let n=e;for(let e=0;e<64;e++){let e=t.get(n);if(e===void 0||!t.has(e))return n;n=e}return n},r=[],i=/* @__PURE__ */ new Map;for(let t of e){let e=Ks(t);if(e===void 0){r.push(t);continue}let a=n(e),o=i.get(a);if(o||(o={id:a,info:{name:`subagent`,status:`finished`},messages:[],hostIndex:r.length-1},i.set(a,o)),e!==a){o.messages.push(t);continue}let s=qs(t);s&&(o.info=s),s?.placeholder||o.messages.push(Ys(t))}return{top:r,groups:[...i.values()]}}function Zs(e){let t=e?.metadata;return typeof t==`object`&&t&&t.providerExecuted===!0?t:null}function Qs(e){return Zs(e)!==null}function $s(e,t){return e?.startsWith(`${t}-segment-`)===!0}var ec=/* @__PURE__ */ new Set([`text`,`image`,`audio`,`video`,`document`]);function tc(e){return e===`cancelled`||e===`denied`}function nc(e){if(typeof e!=`object`||!e)return!1;let t=e;if(typeof t.type!=`string`||!ec.has(t.type))return!1;if(t.type===`text`)return typeof t.content==`string`;let n=t.source;if(typeof n!=`object`||!n)return!1;let r=n;return typeof r.value==`string`?r.type===`file`?r.value.length>0&&(r.provider===void 0||typeof r.provider==`string`):r.type===`data`?typeof r.mimeType==`string`:r.type===`url`:!1}function rc(e){return Array.isArray(e)&&e.length>0&&e.every(nc)}function ic(e){return e&&typeof e==`object`&&`error`in e&&typeof e.error==`string`?e.error:typeof e==`string`?e:`Tool execution failed`}function ac(e){return typeof e==`string`||rc(e)?e:JSON.stringify(e)}function oc(e){let t=[],n=0,r=!0;for(let i of e){let e=t.at(-1);if(i.type===`thinking`)e!==void 0&&e.type!==`thinking`&&(r=!1),t.push({type:`thinking`,index:n++});else if(i.type===`text`){if(i.text===``)continue;if(e?.type===`text`){e.length+=i.text.length;continue}e?.type===`tool-call`&&(r=!1),t.push({type:`text`,length:i.text.length})}else t.push({type:`tool-call`,id:i.id})}return r?void 0:t}function sc(e){let t=e.blockOrder;if(!Array.isArray(t)||t.length===0)return;let n=e.content??``;if(typeof n!=`string`)return;let r=e.thinking??[],i=e.toolCalls??[],a=/* @__PURE__ */ new Set,o=/* @__PURE__ */ new Set,s=[],c=0;for(let e of t){if(typeof e!=`object`||!e)return;if(e.type===`thinking`){let t=Number.isInteger(e.index)?r[e.index]:void 0;if(t===void 0||a.has(e.index))return;a.add(e.index),s.push({type:`thinking`,thinking:t})}else if(e.type===`text`){let t=c+e.length;if(!Number.isInteger(e.length)||e.length<=0||t>n.length)return;s.push({type:`text`,text:n.slice(c,t)}),c=t}else if(e.type===`tool-call`){let t=i.find(t=>t.id===e.id);if(t===void 0||o.has(e.id))return;o.add(e.id),s.push({type:`tool-call`,toolCall:t})}else return}if(c===n.length&&a.size===r.length&&o.size===i.length)return s}function cc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function lc(e){return e.type===`text`||e.type===`image`||e.type===`audio`||e.type===`video`||e.type===`document`}function uc(e){try{return JSON.stringify(e)??``}catch{return``}}function dc(e){return typeof e==`string`&&e!==``?e:void 0}function fc(e){if(`encryptedValue`in e){let t=dc(e.encryptedValue);if(t!==void 0)return t}return dc(Y(e)?.signature)}function pc(e){return`id`in e&&es(e.id)?{redacted:!0}:{}}function mc(e){return e.length===0?null:e.every(e=>e.type===`text`)?e.map(e=>e.content).join(``)||null:e}function hc(e){return e==null?``:typeof e==`string`?e:e.filter(e=>e.type===`text`).map(e=>e.content).join(``)}function gc(e){let t=[];for(let n of e)if(n.type===`text`&&n.content!==``)t.push(n.content);else if(n.type===`structured-output`&&n.status===`complete`&&n.raw!==``)t.push(n.raw);else if(n.type===`subagent`){let e=_c(n);e!==``&&t.push(e)}return t.join(`
|
|
123
|
+
`;)n++},i=()=>{let t=n++;for(;n<e.length;)if(e[n]===`\\`)n+=2;else if(e[n++]===`"`)break;return e.slice(t,n)},a=t=>{r();let o=n;if(e[n]===`{`){n++,r();let s=/* @__PURE__ */ new Map;for(;e[n]!==`}`;){let o=i(),c=JSON.parse(o);r(),n++;let l=typeof t==`object`&&t&&typeof c==`string`?Reflect.get(t,c):void 0,u=a(l);if(typeof c==`string`&&s.set(c,{...u,keyToken:o}),r(),e[n]!==`,`)break;n++,r()}return n++,{start:o,end:n,value:t,properties:s}}if(e[n]===`[`){n++,r();let i=[];for(;e[n]!==`]`&&(i.push(a(Array.isArray(t)?t[i.length]:void 0)),r(),e[n]===`,`);)n++;return n++,{start:o,end:n,value:t,items:i}}if(e[n]===`"`)i();else for(;n<e.length&&!/[\s,}\]]/.test(e[n]??``);)n++;return{start:o,end:n,value:t}};return a(t)}function Yo(e,t,n,r){if(n&&qo(n.value,e))return t.slice(n.start,n.end);if(typeof e==`number`)return Object.is(e,-0)?`-0`:e===1/0?`1e999`:e===-1/0?`-1e999`:JSON.stringify(e);if(typeof e!=`object`||!e)return JSON.stringify(e);if(r.has(e))throw TypeError(`Cannot serialize circular tool input`);r.add(e);try{if(Array.isArray(e))return`[`+Array.from(e,(e,i)=>Yo(e,t,n?.items?.[i],r)??`null`).join(`,`)+`]`;let i=[];for(let a of Object.keys(e)){let o=Yo(Reflect.get(e,a),t,n?.properties?.get(a),r);o!==void 0&&i.push((n?.properties?.get(a)?.keyToken??JSON.stringify(a))+`:`+o)}return`{`+i.join(`,`)+`}`}finally{r.delete(e)}}function Xo(e,t){if(t===void 0)return e??``;if(e===void 0)return Yo(t,``,void 0,/* @__PURE__ */ new Set)??``;let n;try{n=JSON.parse(e)}catch{return e.trim()===``?Yo(t,``,void 0,/* @__PURE__ */ new Set)??e:e}return qo(n,t)?e:Yo(t,e,Jo(e,n),/* @__PURE__ */ new Set)??e}function Zo(e){if(e.trim()===``)return{};try{return JSON.parse(e)??void 0}catch{return}}function Qo(e,t){let n=Y(t),r=t.args??n?.args,i=typeof r==`string`?r:void 0,a=t.input??n?.input,o=typeof a==`object`&&a?a:void 0,s=i??e;if(i===void 0&&o!==void 0)try{JSON.parse(s)}catch{s=void 0}let c;try{c=Xo(s,o)}catch{c=s??e}return{args:c,input:Zo(c)}}var $o=`redacted_thinking-`;function es(e){return typeof e==`string`&&e.startsWith(`redacted_thinking-`)}var ts=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function ns(e,t){return e>>>t|e<<32-t}function rs(e){let t=new TextEncoder().encode(e),n=t.length*8,r=t.length+1,i=r+(56-r%64+64)%64+8,a=new Uint8Array(i);a.set(t),a[t.length]=128;let o=new DataView(a.buffer);o.setUint32(i-8,Math.floor(n/4294967296)),o.setUint32(i-4,n>>>0);let s=1779033703,c=3144134277,l=1013904242,u=2773480762,d=1359893119,f=2600822924,p=528734635,m=1541459225,h=/* @__PURE__ */ new Uint32Array(64);for(let e=0;e<i;e+=64){for(let t=0;t<16;t++)h[t]=o.getUint32(e+t*4);for(let e=16;e<64;e++){let t=h[e-15]??0,n=h[e-2]??0,r=ns(t,7)^ns(t,18)^t>>>3,i=ns(n,17)^ns(n,19)^n>>>10;h[e]=(h[e-16]??0)+r+(h[e-7]??0)+i>>>0}let t=s,n=c,r=l,i=u,a=d,g=f,_=p,v=m;for(let e=0;e<64;e++){let o=ns(a,6)^ns(a,11)^ns(a,25),s=a&g^~a&_,c=v+o+s+(ts[e]??0)+(h[e]??0)>>>0,l=(ns(t,2)^ns(t,13)^ns(t,22))+(t&n^t&r^n&r)>>>0;v=_,_=g,g=a,a=i+c>>>0,i=r,r=n,n=t,t=c+l>>>0}s=s+t>>>0,c=c+n>>>0,l=l+r>>>0,u=u+i>>>0,d=d+a>>>0,f=f+g>>>0,p=p+_>>>0,m=m+v>>>0}let g=e=>(e>>>0).toString(16).padStart(8,`0`);return g(s)+g(c)+g(l)+g(u)+g(d)+g(f)+g(p)+g(m)}function is(e){return`sha256:${rs(e)}`}function as(e,t){if(e===null)return`null`;if(typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return JSON.stringify(e);if(typeof e!=`object`)throw TypeError(`Interrupt values must be JSON-compatible.`);if(t.has(e))throw TypeError(`Interrupt values must not cycle.`);if(!Array.isArray(e)&&Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw TypeError(`Interrupt values must use plain JSON objects.`);t.add(e);let n;if(Array.isArray(e)){let r=[];for(let n=0;n<e.length;n++)r.push(as(e[n],t));n=`[${r.join(`,`)}]`}else{let r=e;n=`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${as(r[e],t)}`).join(`,`)}}`}return t.delete(e),n}function os(e){return as(e,/* @__PURE__ */ new WeakSet)}function ss(e,t=is){if(typeof e!=`string`)throw TypeError(`Interrupt digests require canonical JSON text.`);return t(e)}function cs(e){typeof e==`object`&&e&&!Object.isFrozen(e)&&(Object.values(e).forEach(cs),Object.freeze(e))}function Z(e){let t=JSON.parse(os(e));return cs(t),t}function ls(e){let t=Z([...e].sort((e,t)=>e.interruptId.localeCompare(t.interruptId))),n=os(t);return Object.freeze({resolutions:t,canonicalResolutions:n,fingerprint:ss(n)})}function us(e){let t={};for(let[n,r]of Object.entries(e))n!==`$schema`&&(t[n]=r);return t}function ds(e){return(typeof e==`object`||typeof e==`function`)&&e!==null}function fs(e){if(!ds(e)||!(`~standard`in e))return!1;let t=e[`~standard`];return typeof t!=`object`||!t||!(`version`in t)||t.version!==1||!(`jsonSchema`in t)||typeof t.jsonSchema!=`object`||t.jsonSchema===null||!(`input`in t.jsonSchema)?!1:typeof t.jsonSchema.input==`function`}function ps(e){return ds(e)&&`~standard`in e&&typeof e[`~standard`]==`object`&&e[`~standard`]!==null&&`version`in e[`~standard`]&&e[`~standard`].version===1&&`validate`in e[`~standard`]&&typeof e[`~standard`].validate==`function`}function ms(e){return Object.keys(e).length>0?e:void 0}function hs(e){if(Array.isArray(e)){let t=e.map(e=>gs(e,e.required||[])),n=t.map(e=>e.nullWidening??{});return{schema:t.map(e=>e.schema),itemMap:n.some(e=>Object.keys(e).length>0)?n:void 0}}let t=gs(e,e.required||[]);return{schema:t.schema,itemMap:t.nullWidening}}function gs(e,t=[]){let n={...e},r={};if(n.type===`object`&&n.properties){let e={...n.properties},i=Object.keys(e),a={};for(let n of i){let r=e[n];if(!r)continue;let i=!t.includes(n),o=!1,s;if(r.type===`object`&&r.properties){let t=gs(r,r.required||[]);e[n]=i?{...t.schema,type:[`object`,`null`]}:t.schema,o=i,s=t.nullWidening}else if(r.type===`array`&&r.items){let t=hs(r.items);e[n]={...r,items:t.schema,...i?{type:[`array`,`null`]}:{}},o=i,s=t.itemMap?{items:t.itemMap}:void 0}else i&&(r.type&&!Array.isArray(r.type)?(e[n]={...r,type:[r.type,`null`]},o=!0):Array.isArray(r.type)&&!r.type.includes(`null`)&&(e[n]={...r,type:[...r.type,`null`]},o=!0));(o||s)&&(a[n]={...s??{},...o?{widened:!0}:{}})}n.properties=e,n.required=i,n.additionalProperties=!1,Object.keys(a).length>0&&(r.properties=a)}if(n.type===`array`&&n.items){let e=hs(n.items);n.items=e.schema,e.itemMap&&(r.items=e.itemMap)}return{schema:n,nullWidening:ms(r)}}function _s(e,t=`input`){if(fs(e)){let n=us(e[`~standard`].jsonSchema[t]({target:`draft-07`}));return`properties`in n&&!n.type&&(n.type=`object`),n.type===`object`&&!(`properties`in n)&&(n.properties={}),n.type===`object`&&!(`required`in n)&&(n.required=[]),n}if(ps(e))throw Error("Schema is a Standard Schema validator but does not expose a JSON Schema converter on `~standard.jsonSchema`. Use Zod v4.2+, ArkType v2.1.28+, or wrap a Valibot schema with `toStandardJsonSchema()` from `@valibot/to-json-schema` before passing it as `outputSchema`.");return typeof e==`object`?us(e):e}function vs(e,t={}){if(!e)return;let{forStructuredOutput:n=!1,io:r}=t;if(!n&&!fs(e)&&!ps(e))return e;let i=_s(e,r);return!i||typeof i!=`object`||!n?i:gs(i,i.required||[]).schema}async function ys(e,t){if(!ps(e))return{success:!0,data:t};let n=await e[`~standard`].validate(t);return n.issues?{success:!1,issues:n.issues.map(e=>({message:e.message||`Validation failed`,path:e.path?.map(String)}))}:{success:!0,data:n.value}}var bs=/* @__PURE__ */ new Set([`$schema`,`$id`,`$ref`,`$defs`,`type`,`properties`,`required`,`additionalProperties`,`items`,`oneOf`,`anyOf`,`allOf`,`enum`,`const`,`format`,`minimum`,`maximum`,`minLength`,`maxLength`,`pattern`]);function xs(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null)}function Ss(e){return xs(e)&&Object.keys(e).some(e=>bs.has(e))}function Cs(e){return ps(e)||fs(e)||Ss(e)}function ws(e){if(!xs(e))return!1;let t=Object.keys(e);return t.length>0&&t.every(e=>e===`approve`||e===`reject`)&&t.every(t=>Cs(e[t]))}function Ts(e){let t={};for(let[n,r]of Object.entries(e))t[n]=r;return t}function Es(e){if(ps(e)){let t=fs(e)?Ts(e[`~standard`].jsonSchema.input({target:`draft-2020-12`})):void 0;return{source:e,validator:e,...t!==void 0&&{jsonSchema:t}}}if(Ss(e))return{source:e,jsonSchema:e};throw TypeError(`Expected a supported SchemaInput.`)}function Ds(e){let t={approved:{const:e.approved}},n=[`approved`];return e.approved&&e.inputSchema&&(t.editedArgs=e.inputSchema.jsonSchema??{}),e.payload&&(t.payload=e.payload.jsonSchema??{},n.push(`payload`)),{type:`object`,properties:t,required:n,additionalProperties:!1}}function Os(e,t){let n=t===void 0?null:Es(t),r=null,i=null;if(e!==void 0){if(ps(e)||Ss(e))r=Es(e),i=r;else if(ws(e))r=e.approve===void 0?null:Es(e.approve),i=e.reject===void 0?null:Es(e.reject);else throw TypeError(`approvalSchema must be a SchemaInput or a nonempty map containing approve or reject.`)}let a={oneOf:[Ds({approved:!0,payload:r,inputSchema:n}),Ds({approved:!1,payload:i,inputSchema:null})]},o=os(a),s=os({approve:r?.jsonSchema??null,reject:i?.jsonSchema??null});return{branches:{approve:r,reject:i},responseSchema:a,responseSchemaHash:ss(o),approvalSchemaHash:ss(s)}}function ks(e){return ss(e===void 0?`undefined`:os(Es(e).jsonSchema??{standardValidator:`unserialized`}))}var As=`tanstack:interruptBinding`,js=As;function Ms(e){return e&&typeof e==`object`?e:null}function Q(e,t){return typeof e[t]==`string`?e[t]:void 0}function Ns(e){let t=e.v;return t===void 0||t===1}function Ps(e){let t=Ms(e.metadata),n=t?Ms(t[js]):null;if(!n||Q(n,`interruptId`)!==e.id||!Ns(n))return;let r=Q(n,`kind`),i=Q(n,`interruptId`),a=Q(n,`responseSchemaHash`),o=Q(n,`expiresAt`);if(!i||a===``||o!==void 0&&!Number.isFinite(Date.parse(o)))return;if(r===`generic`){let e=Q(n,`definitionId`),t=Q(n,`key`),s=n.batchIndex,c=Q(n,`payloadSchemaHash`);return(e!==void 0||t!==void 0||s!==void 0||c!==void 0)&&(!e||!t||typeof s!=`number`||!Number.isInteger(s)||s<0)?void 0:{v:1,kind:r,interruptId:i,...a?{responseSchemaHash:a}:{},...o?{expiresAt:o}:{},...e?{definitionId:e}:{},...t?{key:t}:{},...typeof s==`number`?{batchIndex:s}:{},...c?{payloadSchemaHash:c}:{}}}if(!a)return;let s=Q(n,`toolName`),c=Q(n,`toolCallId`);if(s&&c){if(r===`client-tool-execution`){let e=Q(n,`outputSchemaHash`);return e?{v:1,kind:r,interruptId:i,toolName:s,toolCallId:c,outputSchemaHash:e,responseSchemaHash:a,...o?{expiresAt:o}:{}}:void 0}if(r===`tool-approval`){let e=Q(n,`inputSchemaHash`),t=Q(n,`approvalSchemaHash`);return!e||!t?void 0:{v:1,kind:r,interruptId:i,toolName:s,toolCallId:c,originalArgs:n.originalArgs,inputSchemaHash:e,approvalSchemaHash:t,responseSchemaHash:a,...o?{expiresAt:o}:{}}}}}function Fs(e){let t=Ps(e);if(!t)return;let n=Ms(e.metadata),r=n?Ms(n[js]):null;if(!r)return;let i=Q(r,`interruptedRunId`),a=r.generation;if(!(!i||typeof a!=`number`||!Number.isInteger(a)||a<0))return{...t,interruptedRunId:i,generation:a}}var Is=`tanstack:interruptPayload`;function Ls(e,t){if(!fs(e))throw TypeError(`${t} must be a Standard Schema with a JSON Schema converter.`);try{let t=e[`~standard`].jsonSchema.input({target:`draft-07`});if(t===void 0)throw TypeError(`The exported schema is undefined.`);if(typeof t==`function`)throw TypeError(`The exported schema must not be a function.`);if(Array.isArray(t)||!t||typeof t!=`object`||![Object.prototype,null].includes(Object.getPrototypeOf(t)))throw TypeError(`The exported schema must be a plain JSON object.`);let n={};for(let[e,r]of Object.entries(t))e!==`$schema`&&(n[e]=r);return{json:n,canonicalJson:os(n)}}catch(e){throw TypeError(`${t} could not export compatible JSON Schema: ${e instanceof Error?e.message:String(e)}`)}}function Rs(e){return ss(Ls(e,`Interrupt schema`).canonicalJson)}var zs=`tanstack:interruptContinuation`;function Bs(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Vs(e){return{[zs]:e}}function Hs(e){let t=Ps(e);if(t?.kind!==`generic`||t.definitionId===void 0||t.key===void 0||t.batchIndex===void 0)return;let n=Bs(e.metadata)?e.metadata:void 0,r=n!==void 0&&Object.prototype.hasOwnProperty.call(n,`tanstack:interruptPayload`);return{v:1,definitionId:t.definitionId,key:t.key,batchIndex:t.batchIndex,reason:e.reason,message:e.message??``,...e.expiresAt===void 0?{}:{expiresAt:e.expiresAt},...t.responseSchemaHash===void 0?{}:{responseSchemaHash:t.responseSchemaHash},...t.payloadSchemaHash===void 0?{}:{payloadSchemaHash:t.payloadSchemaHash},...r?{payload:n[Is]}:{}}}function Us(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Ws=`subagentInput`;function Gs(e){if(Us(e)&&Us(e.tanstack))return e.tanstack[Ws]}function Ks(e){if(!Us(e)||`parts`in e)return;let t=e.subagentRunId;return typeof t==`string`&&t!==``?t:void 0}function qs(e){if(!Us(e)||!Us(e.metadata))return;let t=e.metadata.tanstack;if(!Us(t)||!Us(t.subagent))return;let{name:n,status:r,error:i,interruptIds:a}=t.subagent;if(typeof n!=`string`||!Js(r))return;let{description:o,parentSubagentRunId:s,parentToolCallId:c,metadata:l,placeholder:u}=t.subagent;return{name:n,status:r,...typeof o==`string`&&{description:o},...Us(i)&&typeof i.message==`string`&&{error:{message:i.message,...typeof i.code==`string`&&{code:i.code}}},...Array.isArray(a)&&{interruptIds:a.filter(e=>typeof e==`string`)},...typeof s==`string`&&{parentSubagentRunId:s},...typeof c==`string`&&{parentToolCallId:c},...Us(l)&&{metadata:l},...u===!0&&{placeholder:!0}}}function Js(e){return e===`running`||e===`finished`||e===`error`||e===`suspended`}function Ys(e){if(!Us(e))return e;let{subagentRunId:t,...n}=e,r=Us(n.metadata)?n.metadata:void 0,i=Us(r?.tanstack)?r.tanstack:void 0;if(!r||!i||!(`subagent`in i))return n;let{subagent:a,...o}=i;return{...n,metadata:{...r,tanstack:o}}}function Xs(e){let t=/* @__PURE__ */ new Map;for(let n of e){let e=Ks(n);e!==void 0&&!t.has(e)&&t.set(e,qs(n)?.parentSubagentRunId)}let n=e=>{let n=e;for(let e=0;e<64;e++){let e=t.get(n);if(e===void 0||!t.has(e))return n;n=e}return n},r=[],i=/* @__PURE__ */ new Map;for(let t of e){let e=Ks(t);if(e===void 0){r.push(t);continue}let a=n(e),o=i.get(a);if(o||(o={id:a,info:{name:`subagent`,status:`finished`},messages:[],hostIndex:r.length-1},i.set(a,o)),e!==a){o.messages.push(t);continue}let s=qs(t);s&&(o.info=s),s?.placeholder||o.messages.push(Ys(t))}return{top:r,groups:[...i.values()]}}function Zs(e){let t=e?.metadata;return typeof t==`object`&&t&&t.providerExecuted===!0?t:null}function Qs(e){return Zs(e)!==null}function $s(e,t){return e?.startsWith(`${t}-segment-`)===!0}var ec=/* @__PURE__ */ new Set([`text`,`image`,`audio`,`video`,`document`]);function tc(e){return e===`cancelled`||e===`denied`}function nc(e){if(typeof e!=`object`||!e)return!1;let t=e;if(typeof t.type!=`string`||!ec.has(t.type))return!1;if(t.type===`text`)return typeof t.content==`string`;let n=t.source;if(typeof n!=`object`||!n)return!1;let r=n;return typeof r.value==`string`?r.type===`file`?r.value.length>0&&(r.provider===void 0||typeof r.provider==`string`):r.type===`data`?typeof r.mimeType==`string`:r.type===`url`:!1}function rc(e){return Array.isArray(e)&&e.length>0&&e.every(nc)}function ic(e){return e&&typeof e==`object`&&`error`in e&&typeof e.error==`string`?e.error:typeof e==`string`?e:`Tool execution failed`}function ac(e){return typeof e==`string`||rc(e)?e:JSON.stringify(e)}function oc(e){let t=[],n=0,r=!0;for(let i of e){let e=t.at(-1);if(i.type===`thinking`)e!==void 0&&e.type!==`thinking`&&(r=!1),t.push({type:`thinking`,index:n++});else if(i.type===`text`){if(i.text===``)continue;if(e?.type===`text`){e.length+=i.text.length;continue}e?.type===`tool-call`&&(r=!1),t.push({type:`text`,length:i.text.length})}else t.push({type:`tool-call`,id:i.id})}return r?void 0:t}function sc(e){let t=e.blockOrder;if(!Array.isArray(t)||t.length===0)return;let n=e.content??``;if(typeof n!=`string`)return;let r=e.thinking??[],i=e.toolCalls??[],a=/* @__PURE__ */ new Set,o=/* @__PURE__ */ new Set,s=[],c=0;for(let e of t){if(typeof e!=`object`||!e)return;if(e.type===`thinking`){let t=Number.isInteger(e.index)?r[e.index]:void 0;if(t===void 0||a.has(e.index))return;a.add(e.index),s.push({type:`thinking`,thinking:t})}else if(e.type===`text`){let t=c+e.length;if(!Number.isInteger(e.length)||e.length<=0||t>n.length)return;s.push({type:`text`,text:n.slice(c,t)}),c=t}else if(e.type===`tool-call`){let t=i.find(t=>t.id===e.id);if(t===void 0||o.has(e.id))return;o.add(e.id),s.push({type:`tool-call`,toolCall:t})}else return}if(c===n.length&&a.size===r.length&&o.size===i.length)return s}function cc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function lc(e){return e.type===`text`||e.type===`image`||e.type===`audio`||e.type===`video`||e.type===`document`}function uc(e){try{return JSON.stringify(e)??``}catch{return``}}function dc(e){return typeof e==`string`&&e!==``?e:void 0}function fc(e){if(`encryptedValue`in e){let t=dc(e.encryptedValue);if(t!==void 0)return t}return dc(Y(e)?.signature)}function pc(e){return`id`in e&&es(e.id)?{redacted:!0}:{}}function mc(e){return e.length===0?null:e.every(e=>e.type===`text`)?e.map(e=>e.content).join(``)||null:e}function hc(e){return e==null?``:typeof e==`string`?e:e.filter(e=>e.type===`text`).map(e=>e.content).join(``)}function gc(e){let t=[];for(let n of e)if(n.type===`text`&&n.content!==``)t.push(n.content);else if(n.type===`structured-output`&&n.status===`complete`&&n.raw!==``)t.push(n.raw);else if(n.type===`subagent`){let e=_c(n);e!==``&&t.push(e)}return t.join(`
|
|
124
124
|
|
|
125
125
|
`)}function _c(e){let t=[];for(let n of e.subagent.messages){if(!(`parts`in n))continue;let e=gc(n.parts).trim();e!==``&&t.push(e)}return t.length===0?``:`${e.subagent.name}:\n${t.join(`
|
|
126
126
|
|
|
@@ -144,14 +144,14 @@ var Hl=/* @__PURE__ */ io({compare:()=>$l,generate:()=>Zl,observe:()=>Xl,unobser
|
|
|
144
144
|
`);r=s.pop()||``;for(let e of s){let t=e.endsWith(`\r`)?e.slice(0,-1):e;t.trim()&&(yield t)}}if(r+=n.decode(),r.trim()&&!t?.aborted)throw new ku}finally{try{e.cancel().catch(()=>{})}catch{}e.releaseLock()}}async function*Gu(e){let t;for await(let n of e){if(n===`id`||n.startsWith(`id:`)){let e=n===`id`?``:n.slice(3);t=e.startsWith(` `)?e.slice(1):e;continue}if(n.startsWith(`:`)||n.startsWith(`event:`)||n.startsWith(`retry:`))continue;let e=Io(n),r=ul(JSON.parse(e)),i=t;t=void 0,yield{chunk:r,...i===void 0?{}:{id:i}}}}async function Ku(e){if(!e.ok){if(e.status===401){let t=await e.clone().json().catch(()=>null);if(Eu(t))throw new xu(t.error.provider)}throw new Pu(`HTTP error! status: ${e.status} ${e.statusText}`,e.status,e.headers.get(`retry-after`))}}function qu(e,t){let n={threadId:e};return t?.limit!==void 0&&(n.limit=String(t.limit)),t?.before!==void 0&&(n.before=t.before),n}function Ju(e){return typeof e!=`object`||!e||!(`truncated`in e)||e.truncated!==!0||!(`cursor`in e)||typeof e.cursor!=`string`||e.cursor===``?{truncated:!1}:{truncated:!0,cursor:e.cursor}}async function Yu(e,t,n,r,i,a){let o=await e(Uu(t,qu(i,a)),{method:`GET`,headers:{Accept:`application/json`,...n},credentials:r});await Ku(o);let s=await o.json(),c=s.activeRun&&typeof s.activeRun.runId==`string`?{runId:s.activeRun.runId}:null,l=s.interrupts&&typeof s.interrupts.runId==`string`&&Array.isArray(s.interrupts.pending)&&s.interrupts.pending.length>0?{runId:s.interrupts.runId,pending:s.interrupts.pending}:null;return{messages:Array.isArray(s.messages)?zo(s.messages):[],activeRun:c,interrupts:l,page:Ju(s.page)}}async function Xu(e,t,n,r,i){let a=await e(Uu(t,{threadId:i}),{method:`GET`,headers:{Accept:`application/json`,...n},credentials:r});await Ku(a);let o=await a.json();if(o===null)return{resumeSnapshot:null,activeRun:null};if(typeof o!=`object`||Array.isArray(o))throw Error(`Generation hydration expected a JSON object from ${t}, received ${Array.isArray(o)?`an array`:typeof o}.`);let s=o,c=s.activeRun&&typeof s.activeRun.runId==`string`?{runId:s.activeRun.runId}:null;return{resumeSnapshot:s.resumeSnapshot??null,activeRun:c}}async function*Zu(e,t){await Ku(e),yield*Gu(Wu(Po(e),t))}async function*Qu(e,t){for await(let{chunk:n}of Zu(e,t))yield n}function $u(e,t,n,r){return async function*(i,a){let o;try{o=await e(t,{...n,headers:{...n.headers,...i},...a?{signal:a}:{}})}catch(e){throw new Au(e)}yield*r(o,a)}}async function*ed(e,t,n){let r=Ru(n);for(;;){if(t?.aborted)return;let n=r.lastEventId===void 0?{}:{"Last-Event-ID":r.lastEventId},i=!1,a=!1;try{for await(let{chunk:o,id:s}of e(n,t))r.note(s)!==`duplicate`&&(a=!0,(o.type===`RUN_FINISHED`||o.type===`RUN_ERROR`)&&(i=!0),yield o)}catch(e){if(t?.aborted)return;if((e instanceof ku||e instanceof Au||Iu(e))&&r.lastEventId!==void 0){await r.waitBeforeReconnect(a,t,Iu(e)?e.retryAfterMs:void 0);continue}throw e}if(t?.aborted||i)return;if(r.lastEventId!==void 0){if(a){await r.waitBeforeReconnect(!0,t);continue}throw new ju}return}}function td(e){if(!e)throw Error(`Connection adapter is required`);let t=`connect`in e,n=`subscribe`in e,r=`send`in e;if(t&&(n||r))throw Error(`Connection adapter must provide either connect or both subscribe and send, not both modes`);if(n&&r){let t=e.joinRun?.bind(e),n=e.hydrate?.bind(e);return{subscribe:e.subscribe.bind(e),send:e.send.bind(e),...t?{joinRun:t}:{},...n?{hydrate:n}:{}}}if(!t)throw Error(`Connection adapter must provide either connect or both subscribe and send`);let i=[],a=[],o;function s(e,t){t&&Du.set(e,t);let n=a.shift();n?n(e):i.push(e)}async function c(e){let t=()=>o!==a||i.length===0&&(a.length>0||e?.aborted);for(let n=0;n<16&&!e?.aborted;n++){if(t())return;await Promise.resolve()}for(;!e?.aborted;){if(t())return;await new Promise(e=>setTimeout(e,0))}}return{subscribe(e){let t=i.splice(0),n=[];return i=t,a=n,(async function*(){o=n;try{for(;!e?.aborted;){let r,i=t.shift();r=i===void 0?await new Promise(t=>{let r=()=>t(null);n.push(n=>{e?.removeEventListener(`abort`,r),t(n)}),e?.addEventListener(`abort`,r,{once:!0})}):i,r!==null&&(yield r)}}finally{o===n&&(o=void 0)}})()},async send(t,n,r,i){let a=!1,o,l;try{let c=e.connect(t,n,r,i);for await(let e of c)`threadId`in e&&typeof e.threadId==`string`&&(o=e.threadId),`runId`in e&&typeof e.runId==`string`&&(l=e.runId),(e.type===`RUN_FINISHED`||e.type===`RUN_ERROR`)&&(a=!0),s(e,i.runId);!r?.aborted&&!a&&s(Ko({type:X.RUN_FINISHED,threadId:o??i.threadId,runId:l??i.runId,timestamp:Date.now()},{finishReason:`stop`,model:`connect-wrapper`}),i.runId)}catch(e){if(!r?.aborted&&!a){let t=e instanceof Error?e.message:`Unknown error in connect()`;s({type:X.RUN_ERROR,threadId:o??i.threadId,runId:l??i.runId,timestamp:Date.now(),message:t},i.runId)}throw e}await c(r)},...typeof e.joinRun==`function`?{joinRun:(t,n)=>e.joinRun(t,n)}:{},...(()=>{let t=e.hydrate;return typeof t==`function`?{hydrate:(e,n)=>t(e,n)}:{}})()}}function nd(e,t,n,r){if(!n)throw Error(`Connection adapter: connect() and send() need a run context with a threadId. ChatClient and the generation clients pass one. Pass it when you call the adapter yourself.`);let i=Kc(e),a={...r.body,...n.forwardedProps,...t};return{threadId:n.threadId,runId:n.runId,...n.parentRunId!==void 0&&{parentRunId:n.parentRunId},...n.resume!==void 0&&{resume:n.resume},state:{},messages:i,tools:n.clientTools??[],context:[],forwardedProps:a}}function rd(e,t={}){return{async*connect(n,r,i,a){let o=typeof e==`function`?e():e,s=typeof t==`function`?await t():t,c={"Content-Type":`application/json`,...Bu(s.headers),...Bu(a.headers),...Hu(a.runId)},l=nd(n,r,a,s),u=s.fetchClient??fetch,d=i||s.signal;yield*ed($u(u,o,{method:`POST`,headers:c,body:JSON.stringify(l),credentials:s.credentials||`same-origin`},Zu),d,s.reconnect)},async*joinRun(n,r){let i=typeof e==`function`?e():e,a=typeof t==`function`?await t():t,o=Uu(i,{offset:`-1`,runId:n}),s={...Bu(a.headers)},c=a.fetchClient??fetch,l=r||a.signal;yield*ed($u(c,o,{method:`GET`,headers:s,credentials:a.credentials||`same-origin`},Zu),l,a.reconnect)},async hydrate(n,r){let i=typeof e==`function`?e():e,a=typeof t==`function`?await t():t;return Yu(a.fetchClient??fetch,i,Bu(a.headers),a.credentials||`same-origin`,n,r)},async hydrateGeneration(n){let r=typeof e==`function`?e():e,i=typeof t==`function`?await t():t;return Xu(i.fetchClient??fetch,r,Bu(i.headers),i.credentials||`same-origin`,n)}}}function id(e){return{async*connect(t,n,r,i){if(!r)throw Error(`fetcherToConnectionAdapter requires an AbortSignal — the chat client always supplies one.`);if(!i)throw Error(`fetcherToConnectionAdapter requires a RunAgentInputContext — the chat client always supplies one.`);let a=await e({messages:t,data:n,threadId:i.threadId,runId:i.runId,...i.parentRunId===void 0?{}:{parentRunId:i.parentRunId},...i.resume===void 0?{}:{resume:i.resume}},{signal:r,headers:i.headers});a instanceof Response?yield*Qu(a,r):yield*ad(a,r)}}}async function*ad(e,t){if(t.aborted)return;let n=e[Symbol.asyncIterator](),r=new Promise(e=>{t.addEventListener(`abort`,()=>e({done:!0,value:void 0}),{once:!0})});try{for(;;){let e=await Promise.race([n.next(),r]);if(e.done)return;yield e.value}}finally{await n.return?.()}}function od(e){return e.resumable}function sd(e,t){let n=Hs(e.descriptor);return n?{...t,metadata:Vs(n)}:t}function cd(e){return`cancel`in e&&`clearResolution`in e}var ld=/* @__PURE__ */ new Set([`invalid-payload`,`invalid-edited-args`,`invalid-tool-output`,`invalid-response-schema`,`unknown-interrupt`,`expired`,`stale`,`conflict`]),ud=/* @__PURE__ */ new Set([`incomplete-batch`,`item-validation-failed`,`unsupported-bulk-operation`,`async-resolver`,`inactive-transaction`,`mixed-provenance`,`transport`,`server`,`protocol`,`invalid-response-schema`,`expired`,`stale`,`conflict`]);function dd(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function fd(e){return Fs(e)}function pd(e){if(!dd(e.metadata))return!1;let t=e.metadata[As];return!dd(t)||t.v!==void 0&&t.v!==1?!1:t.kind===`generic`||t.kind===`tool-approval`||t.kind===`client-tool-execution`||`definitionId`in t||`key`in t||`batchIndex`in t||`payloadSchemaHash`in t}function md(e){if(!dd(e.metadata))return!1;let t=e.metadata[As];return!dd(t)||t.kind!==`generic`?!1:`definitionId`in t||`key`in t||`batchIndex`in t||`payloadSchemaHash`in t}function hd(e){return e.metadata?.[`tanstack:interruptPayload`]}function gd(e){if(e.responseSchema!==void 0)try{return ss(os(e.responseSchema))}catch{return}}function _d(e){if(e!==void 0)try{return Rs(e)}catch{return}}function vd(e){return e!==null&&(typeof e==`object`||typeof e==`function`)&&`then`in e&&typeof e.then==`function`}function yd(e,t,n){if(e===void 0)return{valid:!0,payload:t};if(ps(e)){let r=e[`~standard`].validate(t),i=e=>e.issues?{code:n,message:e.issues[0]?.message??`Schema validation failed.`}:{valid:!0,payload:e.value};return vd(r)?Promise.resolve(r).then(i):i(r)}return{valid:!0,payload:t}}function bd(e){for(let t of ld)if(t===e)return!0;return!1}function xd(e){for(let t of ud)if(t===e)return!0;return!1}function Sd(e){if(!dd(e))return!1;let t=e.scope,n=e.code;return typeof n!=`string`||typeof e.message!=`string`||typeof e.retryable!=`boolean`||typeof e.threadId!=`string`||typeof e.interruptedRunId!=`string`||typeof e.generation!=`number`?!1:t===`item`?bd(n)&&typeof e.interruptId==`string`&&(e.source===`client`||e.source===`server`):t===`batch`&&xd(n)&&Array.isArray(e.interruptIds)&&e.interruptIds.every(e=>typeof e==`string`)&&(e.source===`client`||e.source===`server`||e.source===`transport`)}function Cd(e){return Sd(e)?[e]:!dd(e)||!Array.isArray(e.errors)?[]:e.errors.every(Sd)?e.errors:[]}function wd(e,t){if(e.length!==t.length)return!1;let n=[...e].sort(),r=[...t].sort();return n.every((e,t)=>e===r[t])}function Td(e,t){return e.threadId===t.threadId&&e.interruptedRunId===t.interruptedRunId&&e.generation===t.generation&&wd(e.interruptIds,t.interruptIds)}function Ed(e,t,n){let r=n.filter(e=>e.source!==`transport`),i=e=>t.includes(e)&&r.some(t=>Td(e,t)),a=e.filter(e=>!i(e)),o=t.filter(e=>!r.some(t=>Td(e,t)));return Object.freeze({rootErrors:Object.freeze([...a,...n]),submissionRootErrors:Object.freeze([...o,...r])})}function Dd(e,t){if(e.threadId!==t.threadId||e.interruptedRunId!==t.interruptedRunId||e.generation!==t.generation)return!1;let n=t.resolutions.map(e=>e.interruptId);return e.scope===`item`?n.includes(e.interruptId):wd(e.interruptIds,n)}function Od(e,t,n){let r=gd(e)??n?.responseSchemaHash;return Z({v:1,kind:`generic`,interruptId:e.id,interruptedRunId:t.interruptedRunId,generation:t.generation,...r===void 0?{}:{responseSchemaHash:r},...e.expiresAt===void 0?{}:{expiresAt:e.expiresAt}})}function kd(e,t){let n=Z(e.descriptor),r=e.error===void 0?Object.freeze([]):Object.freeze([Z(e.error)]);return{id:n.id,interruptId:n.id,reason:n.reason,...n.message===void 0?{}:{message:n.message},...n.responseSchema===void 0?{}:{responseSchema:n.responseSchema},...n.expiresAt===void 0?{}:{expiresAt:n.expiresAt},...n.metadata===void 0?{}:{metadata:n.metadata},threadId:t.threadId,interruptedRunId:t.interruptedRunId,generation:t.generation,status:e.status,errors:r,canResolve:e.canResolve}}var Ad=class{options;hydration;items=[];snapshot=Object.freeze([]);rootErrors=Object.freeze([]);submissionRootErrors=Object.freeze([]);state=Object.freeze({interrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:!1});activeTransaction;activeSubmissionOperation;retrySubmission;resuming=!1;warnedSchemaMismatches=/* @__PURE__ */ new Set;tools;interruptDefinitions;constructor(e){this.options=e,this.tools=e.tools;let t=/* @__PURE__ */ new Map;for(let n of e.interrupts??[]){if(t.has(n.id))throw Error(`Duplicate interrupt definition id: ${n.id}`);t.set(n.id,n)}this.interruptDefinitions=t}updateTools(e){this.tools=e}hydrate(e,t=`live`){this.activeSubmissionOperation=void 0,this.hydration={threadId:e.threadId,interruptedRunId:e.interruptedRunId,generation:e.generation,interrupts:Z(e.interrupts)};let n=/* @__PURE__ */ new Map;for(let t of e.interrupts){let e=fd(t);e?.kind===`generic`&&e.definitionId!==void 0&&e.key!==void 0&&e.batchIndex!==void 0&&n.set(e.batchIndex,(n.get(e.batchIndex)??0)+1)}this.items=e.interrupts.map(t=>this.hydrateInterrupt(t,e,n)),this.rootErrors=Object.freeze([]),this.submissionRootErrors=Object.freeze([]),this.retrySubmission=void 0,this.resuming=!1,this.publish(t)}getInterrupts(){return this.snapshot}getState(){return this.state}getDescriptors(){return this.hydration?.interrupts??Object.freeze([])}hasValidatedFirstPartyGenericBatch(){return this.items.some(e=>e.kind===`generic`&&e.definition!==void 0)}reset(e){this.activeSubmissionOperation=void 0,this.hydration=void 0,this.items=[],this.snapshot=Object.freeze([]),e?.preserveRootErrors!==!0&&(this.rootErrors=Object.freeze([]),this.submissionRootErrors=Object.freeze([])),this.retrySubmission=void 0,this.resuming=!1,this.state=Object.freeze({interrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:!1}),this.options.onChange?.(e?.source??`live`)}getInterruptErrors(){return this.rootErrors}getResuming(){return this.resuming}resolve(e){this.assertRootMutable(),typeof e==`boolean`?this.resolveBooleanBulk(e):this.resolveTransaction(e)}cancel(){this.assertRootMutable(),this.invalidateRetry();for(let e of this.items)od(e)&&(e.validationGeneration++,e.resolution=Object.freeze(sd(e,{interruptId:e.descriptor.id,status:`cancelled`})),e.status=`staged`,e.error=void 0);this.publish(),this.maybeSubmit()}retry(){if(this.resuming)throw Error(`Interrupt submission is already active.`);let e=this.retrySubmission;e?this.submitBatch(e):this.addRootError(`transport`,`There is no retryable interrupt submission.`,!1)}resolveClientToolOutput(e,t){return this.resolveClientToolResult(e,{state:`output-available`,output:t})}resolveClientToolError(e,t){return this.resolveClientToolResult(e,{state:`output-error`,errorText:t})}resolveClientToolResult(e,t){let n=this.items.find(t=>t.kind===`client-tool-execution`&&t.binding?.kind===`client-tool-execution`&&t.binding.toolCallId===e)??this.items.find(t=>t.kind===`generic`&&t.canResolve&&t.descriptor.toolCallId===e);return n?t.state===`output-available`?(this.resolveItem(n.descriptor.id,t.output),!0):(this.stageClientToolError(n,t.errorText),!0):!1}stageClientToolError(e,t){this.assertItemMutable(),this.invalidateRetry(),e.canResolve?(e.validationGeneration++,e.resolution=Z(Ko(sd(e,{interruptId:e.descriptor.id,status:`resolved`,payload:{error:t}}),{state:`output-error`})),e.status=`staged`,e.error=void 0,this.publish(),this.maybeSubmit()):(e.status=`error`,e.error=this.itemError(e.descriptor.id,`invalid-response-schema`,`The interrupt response schema is invalid and cannot be resolved.`),this.publish())}warnSchemaMismatch(e,t,n){this.warnedSchemaMismatches.has(e)||(this.warnedSchemaMismatches.add(e),console.warn(`[TanStack AI] Interrupt "${e}" for tool "${t}": the server and client tool schemas differ, so it is handled as a generic interrupt. Use the same tool definition on the server and the client.`,...n===void 0?[]:[n]))}hydrateInterrupt(e,t,n){let r=Z(e),i=fd(r);if(i===void 0)return pd(r)?{descriptor:r,binding:Od(r,t,void 0),kind:`generic`,status:`error`,canResolve:!1,resumable:!1,error:this.itemError(r.id,`stale`,`The interrupt binding is invalid or incomplete.`),validationGeneration:0}:{descriptor:r,binding:void 0,kind:`unbound`,status:`pending`,canResolve:!1,resumable:!1,validationGeneration:0};let a=i.interruptId===r.id&&i.interruptedRunId===t.interruptedRunId&&i.generation===t.generation&&gd(r)===i.responseSchemaHash,o=i.interruptId===r.id&&i.interruptedRunId===t.interruptedRunId&&i.generation===t.generation&&i.responseSchemaHash===(gd(r)??i.responseSchemaHash);if(md(r)&&(!o||i.kind!==`generic`||i.definitionId===void 0||i.key===void 0||i.batchIndex===void 0))return{descriptor:r,binding:Od(r,t,i),kind:`generic`,status:`error`,canResolve:!1,resumable:!1,error:this.itemError(r.id,`stale`,`The interrupt binding does not match this interrupted run.`),validationGeneration:0};if(o&&i.kind===`tool-approval`){let e=this.tools?.find(e=>e.name===i.toolName);if(e?.needsApproval===!0&&r.toolCallId===i.toolCallId)try{let t=Os(e.approvalSchema,e.inputSchema);if(ks(e.inputSchema)===i.inputSchemaHash&&t.approvalSchemaHash===i.approvalSchemaHash&&t.responseSchemaHash===i.responseSchemaHash)return{descriptor:r,binding:Z(i),kind:`tool-approval`,status:`pending`,canResolve:!0,resumable:!0,tool:e,validationGeneration:0};this.warnSchemaMismatch(r.id,i.toolName)}catch(e){this.warnSchemaMismatch(r.id,i.toolName,e)}}if(o&&i.kind===`client-tool-execution`){let e=this.tools?.find(e=>e.name===i.toolName);if(e!==void 0&&r.toolCallId===i.toolCallId){if(ks(e.outputSchema)===i.outputSchemaHash)return{descriptor:r,binding:Z(i),kind:`client-tool-execution`,status:`pending`,canResolve:!0,resumable:!0,tool:e,validationGeneration:0};this.warnSchemaMismatch(r.id,i.toolName)}}if(i.kind===`generic`&&i.definitionId!==void 0&&i.key!==void 0&&i.batchIndex!==void 0&&i.key.length>0&&n.get(i.batchIndex)!==1)return{descriptor:r,binding:Z(i),kind:`generic`,status:`error`,canResolve:!1,resumable:!1,error:this.itemError(r.id,`stale`,`Generic interrupt batch contains a duplicate batchIndex.`),validationGeneration:0};if(a&&i.kind===`generic`&&i.definitionId!==void 0&&i.key!==void 0&&i.batchIndex!==void 0&&i.key.length>0&&n.get(i.batchIndex)===1){let e=this.interruptDefinitions.get(i.definitionId);if(e!==void 0&&_d(e.responseSchema)===i.responseSchemaHash&&(e.payloadSchema===void 0?i.payloadSchemaHash===void 0:i.payloadSchemaHash===_d(e.payloadSchema))){let t=hd(r);return{descriptor:r,binding:Z(i),definition:e,kind:`generic`,status:`pending`,canResolve:!0,resumable:!0,...t===void 0?{}:{payload:Z(t)},validationGeneration:0}}}let s=i.interruptId===r.id&&i.interruptedRunId===t.interruptedRunId&&i.generation===t.generation&&(i.kind!==`generic`||gd(r)===void 0||i.responseSchemaHash===gd(r));return{descriptor:r,binding:Od(r,t,i),kind:`generic`,status:`pending`,canResolve:s,resumable:s,validationGeneration:0}}buildSnapshot(e){let t=this.requireHydration(),n=this.items.filter(e=>e.kind!==`client-tool-execution`&&e.status!==`submitting`).map(n=>{let r=kd(n,t);if(n.kind===`unbound`||n.binding===void 0){let e={...r,kind:`unbound`,canResolve:!1};return Object.freeze(e)}if(n.kind===`tool-approval`&&n.binding.kind===`tool-approval`){let t=Z(n.binding),i={...r,kind:`tool-approval`,binding:t,toolName:n.binding.toolName,toolCallId:n.binding.toolCallId,originalArgs:Z(n.binding.originalArgs),cancel:()=>this.cancelItem(n.descriptor.id,e),clearResolution:()=>this.clearItem(n.descriptor.id,e),resolveInterrupt:(t,r)=>{let i=dd(r)?r:void 0;this.resolveItem(n.descriptor.id,{approved:t,...t&&i?.editedArgs!==void 0?{editedArgs:i.editedArgs}:{},...i?.payload===void 0?{}:{payload:i.payload}},e)}};return Object.freeze(i)}let i=n.binding.kind===`generic`?Z(n.binding):Z({v:1,kind:`generic`,interruptId:n.descriptor.id,interruptedRunId:t.interruptedRunId,generation:t.generation,...typeof n.binding.responseSchemaHash==`string`?{responseSchemaHash:n.binding.responseSchemaHash}:{}});if(n.definition!==void 0&&n.binding.kind===`generic`){let t={...r,kind:`generic`,definitionId:n.definition.id,key:n.binding.key??``,payload:n.payload,binding:i,cancel:()=>this.cancelItem(n.descriptor.id,e),clearResolution:()=>this.clearItem(n.descriptor.id,e),resolveInterrupt:t=>this.resolveItem(n.descriptor.id,t,e)};return Object.freeze(t)}let a={...r,kind:`generic`,binding:i,cancel:()=>this.cancelItem(n.descriptor.id,e),clearResolution:()=>this.clearItem(n.descriptor.id,e),resolveInterrupt:t=>this.resolveItem(n.descriptor.id,t,e)};return Object.freeze(a)});return Object.freeze(n)}publish(e=`live`){this.hydration?(this.snapshot=this.buildSnapshot(),this.state=Object.freeze({interrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:this.resuming}),this.options.onChange?.(e)):(this.snapshot=Object.freeze([]),this.state=Object.freeze({interrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:this.resuming}),this.options.onChange?.(e))}resolveItem(e,t,n){this.assertItemMutable(n);let r=this.findItem(e);if(this.invalidateRetry(),!r.canResolve){r.status=`error`,r.error=this.itemError(e,`invalid-response-schema`,`The interrupt response schema is invalid and cannot be resolved.`),n||this.publish();return}let i=++r.validationGeneration,a=this.validateCandidate(r,t);vd(a)?(r.status=`validating`,r.error=void 0,n||this.publish(),Promise.resolve(a).then(e=>{i===r.validationGeneration&&this.applyValidation(r,e,n)}).catch(e=>{i===r.validationGeneration&&this.applyValidation(r,{code:this.validationCode(r),message:e instanceof Error?e.message:String(e)},n)})):this.applyValidation(r,a,n)}cancelItem(e,t){this.assertItemMutable(t);let n=this.findItem(e);this.invalidateRetry(),n.validationGeneration++,n.resolution=Object.freeze(sd(n,{interruptId:e,status:`cancelled`})),n.status=`staged`,n.error=void 0,t||(this.publish(),this.maybeSubmit())}clearItem(e,t){this.assertItemMutable(t);let n=this.findItem(e);this.invalidateRetry(),n.validationGeneration++,n.resolution=void 0,n.error=void 0,n.status=`pending`,t||this.publish()}maybeSubmit(){let e=this.items.some(e=>e.kind===`generic`),t=this.items.filter(t=>od(t)&&!(e&&t.kind===`client-tool-execution`));if(t.length===0||t.some(e=>e.resolution===void 0||e.status!==`staged`))return;let n=this.requireHydration(),r=ls(t.map(e=>e.resolution).filter(e=>e!==void 0)),i=Object.freeze({threadId:n.threadId,interruptedRunId:n.interruptedRunId,generation:n.generation,resolutions:r.resolutions,canonicalResolutions:r.canonicalResolutions,fingerprint:r.fingerprint});this.submitBatch(i)}applyValidation(e,t,n){if(`valid`in t)e.resolution=Z(sd(e,{interruptId:e.descriptor.id,status:`resolved`,payload:t.payload})),e.status=`staged`,e.error=void 0,n||(this.publish(),this.maybeSubmit());else{e.status=`error`;let r=this.itemError(e.descriptor.id,t.code,t.message,t.path);e.error=r,e.kind===`client-tool-execution`&&(this.rootErrors=Object.freeze([...this.rootErrors.filter(t=>!(t.code===`item-validation-failed`&&t.interruptIds.includes(e.descriptor.id))),Object.freeze({scope:`batch`,code:`item-validation-failed`,message:r.message,source:`client`,retryable:!1,interruptIds:Object.freeze([e.descriptor.id]),threadId:r.threadId,interruptedRunId:r.interruptedRunId,generation:r.generation})])),n||this.publish()}}validateCandidate(e,t){if(e.kind===`generic`){let n=yd(e.definition?.responseSchema??e.descriptor.responseSchema,t,`invalid-payload`);if(e.definition===void 0)return n;let r=e=>`valid`in e?{valid:!0,payload:t}:e;return vd(n)?Promise.resolve(n).then(r):r(n)}if(e.kind===`client-tool-execution`){let n=yd(e.tool?.outputSchema,t,`invalid-tool-output`),r=e=>{if(!(`valid`in e))return e;try{return{valid:!0,payload:Z(e.payload)}}catch(e){return{code:`invalid-tool-output`,message:e instanceof Error?e.message:String(e)}}};return vd(n)?Promise.resolve(n).then(r):r(n)}return this.validateApprovalCandidate(e,t)}validateApprovalCandidate(e,t){if(!dd(t)||typeof t.approved!=`boolean`)return{code:`invalid-payload`,message:`Tool approval resolutions require an approved boolean.`};let n=t.approved,r=t.editedArgs;if(!n&&r!==void 0)return{code:`invalid-edited-args`,message:`Rejected tool approvals cannot edit tool arguments.`};if(n&&r!==void 0){let n=yd(e.tool?.inputSchema,r,`invalid-edited-args`);return vd(n)?Promise.resolve(n).then(n=>`valid`in n?this.validateApprovalPayload(e,t,n.payload):n):`valid`in n?this.validateApprovalPayload(e,t,n.payload):n}return this.validateApprovalPayload(e,t,void 0)}validateApprovalPayload(e,t,n){let r=t.approved===!0,i=this.approvalBranchSchema(e.tool,r),a=t.payload;if(i===void 0&&a!==void 0)return{code:`invalid-payload`,message:`This approval branch does not accept a payload.`};if(i!==void 0&&a===void 0)return{code:`invalid-payload`,message:`This approval branch requires a payload.`};let o=yd(i,a,`invalid-payload`),s=e=>`valid`in e?{valid:!0,payload:{approved:r,...n===void 0?{}:{editedArgs:n},...i===void 0?{}:{payload:e.payload}}}:e;return vd(o)?Promise.resolve(o).then(s):s(o)}approvalBranchSchema(e,t){let n=e?.approvalSchema;return!dd(n)||!(`approve`in n||`reject`in n)?n:t?n.approve:n.reject}validationCode(e){return e.kind===`client-tool-execution`?`invalid-tool-output`:`invalid-payload`}resolveBooleanBulk(e){let t=this.items.filter(e=>od(e)&&e.kind!==`client-tool-execution`);if(!t.every(t=>t.kind===`tool-approval`&&this.approvalBranchSchema(t.tool,e)===void 0)||t.length===0)this.addRootError(`unsupported-bulk-operation`,`Boolean bulk resolution requires payloadless tool approvals.`,!1);else{this.invalidateRetry();for(let n of t)n.validationGeneration++,n.resolution=Z({interruptId:n.descriptor.id,status:`resolved`,payload:{approved:e}}),n.status=`staged`,n.error=void 0;this.publish(),this.maybeSubmit()}}resolveTransaction(e){let t=this.items.map(e=>({status:e.status,...e.resolution===void 0?{}:{resolution:e.resolution},...e.error===void 0?{}:{error:e.error},validationGeneration:e.validationGeneration})),n={active:!0};this.activeTransaction=n;let r=this.buildSnapshot(n).filter(cd),i;try{for(let t of r){let n=e(t);if(n!==void 0){i={code:vd(n)?`async-resolver`:`inactive-transaction`,message:vd(n)?`Interrupt transaction resolvers must be synchronous.`:`Interrupt transaction resolvers must return literal undefined.`};break}}i===void 0&&this.items.some(e=>od(e)&&e.kind!==`client-tool-execution`&&(e.resolution===void 0||e.status!==`staged`))&&(i={code:`incomplete-batch`,message:`Interrupt transaction did not resolve every item.`})}catch(e){i={code:`item-validation-failed`,message:e instanceof Error?e.message:String(e)}}finally{n.active=!1,this.activeTransaction=void 0}i?(this.restoreCheckpoints(t),this.addRootError(i.code,i.message,!1)):(this.publish(),this.maybeSubmit())}restoreCheckpoints(e){this.items.forEach((t,n)=>{let r=e[n];r&&(t.status=r.status,t.resolution=r.resolution,t.error=r.error,t.validationGeneration=r.validationGeneration+1)}),this.publish()}assertItemMutable(e){if(e&&!e.active||this.activeTransaction&&e!==this.activeTransaction)throw Error(`Interrupt transaction is inactive.`);if(this.resuming)throw Error(`Interrupts cannot be mutated while submitting.`)}assertRootMutable(){if(this.activeTransaction)throw Error(`Interrupt transaction is already active.`);if(this.resuming)throw Error(`Interrupts cannot be mutated while submitting.`)}invalidateRetry(){this.retrySubmission=void 0}submitBatch(e){let t={submission:e};this.activeSubmissionOperation=t,this.resuming=!0,this.retrySubmission=void 0;for(let e of this.items)od(e)&&(e.status=`submitting`);this.publish(),this.performSubmission(t)}async performSubmission(e){try{await this.options.submit(e.submission)}catch(t){if(this.activeSubmissionOperation!==e)return;this.handleSubmissionFailure(t,e.submission)}finally{this.activeSubmissionOperation===e&&(this.activeSubmissionOperation=void 0,this.resuming=!1,this.publish())}}handleSubmissionFailure(e,t){let n=Cd(e);if(n.length===0){let n=e instanceof Error?e.message:String(e);this.addRootError(`transport`,n,!0,`transport`),this.retrySubmission=t;for(let e of this.items)od(e)&&(e.status=`error`);return}let r=n.filter(e=>Dd(e,t));r.length!==n.length&&this.addRootError(`protocol`,`Interrupt submission errors did not match the active batch.`,!1);let i=!1,a=!1,o=[];for(let e of r)if((e.code===`stale`||e.code===`expired`||e.code===`conflict`)&&(i=!0),a||=e.retryable,e.scope===`item`){let t=this.items.find(t=>od(t)&&t.descriptor.id===e.interruptId);t&&(t.status=`error`,t.error=Z(e))}else o.push(Z(e));let s=Ed(this.rootErrors,this.submissionRootErrors,o);this.rootErrors=s.rootErrors,this.submissionRootErrors=s.submissionRootErrors;for(let e of this.items)od(e)&&e.status===`submitting`&&(e.status=`error`);this.retrySubmission=a&&!i?t:void 0}addRootError(e,t,n,r=`client`){let i=this.requireHydration();this.rootErrors=Object.freeze([...this.rootErrors,Object.freeze({scope:`batch`,code:e,message:t,source:r,retryable:n,interruptIds:Object.freeze(this.items.filter(od).map(e=>e.descriptor.id)),threadId:i.threadId,interruptedRunId:i.interruptedRunId,generation:i.generation})]),this.publish()}findItem(e){let t=this.items.find(t=>t.descriptor.id===e);if(!t)throw Error(`Unknown interrupt: ${e}`);return t}requireHydration(){if(!this.hydration)throw Error(`InterruptManager is not hydrated.`);return this.hydration}itemError(e,t,n,r){let i=this.requireHydration();return Object.freeze({scope:`item`,interruptId:e,code:t,message:n,...r===void 0?{}:{path:Object.freeze([...r])},source:`client`,retryable:!1,threadId:i.threadId,interruptedRunId:i.interruptedRunId,generation:i.generation})}},jd=/* @__PURE__ */ new WeakMap;function Md(e){let t=Object.entries(e.keys()).filter(e=>!!e[1]).map(e=>e[0]).filter(Tu);if(t.length===1)return t[0];let n=jd.get(e)??[];if(n.length===1)return n[0]}function Nd(e,...t){let n=e?.();if(Tu(n))return n;for(let e of t)if(Tu(e))return e}async function Pd(e,t){if(!t)throw new Cu;return await e.prepare(t),e.headers(t)}var Fd=class{clientId;constructor(e){this.clientId=e}clientCreated(e){this.emitEvent(`client:created`,{initialMessageCount:e})}loadingChanged(e){this.emitEvent(`client:loading:changed`,{isLoading:e})}errorChanged(e){this.emitEvent(`client:error:changed`,{error:e})}textUpdated(e,t,n,r){this.emitEvent(`text:chunk:content`,{streamId:e,messageId:t,content:n,...r})}toolCallStateChanged(e,t,n,r,i,a,o){this.emitEvent(`tools:call:updated`,{streamId:e,messageId:t,toolCallId:n,toolName:r,state:i,arguments:a,...o})}thinkingUpdated(e,t,n,r,i){this.emitEvent(`text:chunk:thinking`,{streamId:e,messageId:t,content:n,delta:r,...i})}structuredOutputChanged(e,t,n,r,i){this.emitEvent(e,{streamId:t,messageId:n,...r,...i})}approvalRequested(e,t,n,r,i,a,o){this.emitEvent(`tools:approval:requested`,{streamId:e,messageId:t,toolCallId:n,toolName:r,input:i,approvalId:a,...o})}messageAppended(e,t,n){let r=e.parts.filter(e=>e.type===`text`).map(e=>e.content).join(` `);this.emitEvent(`text:message:created`,{streamId:t,messageId:e.id,role:e.role,content:r,parts:e.parts,...n})}messageSent(e,t){let n=typeof t==`string`?t:t.filter(e=>e.type===`text`).map(e=>e.content).join(``);this.emitEvent(`text:message:created`,{messageId:e,role:`user`,content:n,...Array.isArray(t)&&{parts:t}}),this.emitEvent(`text:message:user`,{messageId:e,role:`user`,content:n,...Array.isArray(t)&&{parts:t}})}reloaded(e){this.emitEvent(`client:reloaded`,{fromMessageIndex:e})}stopped(){this.emitEvent(`client:stopped`)}messagesCleared(){this.emitEvent(`client:messages:cleared`)}toolResultAdded(e,t,n,r,i){this.emitEvent(`tools:result:added`,{toolCallId:e,toolName:t,output:n,state:r,...i})}toolFixtureApplied(e){this.emitEvent(`devtools:tool-fixture:applied`,{...e})}},Id=class extends Fd{emitEvent(){}},Ld=class{events;constructor(e){this.events=new Id(e.clientId)}emitRegistered(){}emitUpdated(){}emitSnapshot(){}emitToolsRegistered(){}emitRunLifecycle(e,t,n,r){}deactivate(){}supersede(){}dispose(){}mountWithTools(e){}notifyToolsChanged(){}setCurrentStreamId(e){}recordStreamId(e){}getCurrentStreamId(){return null}getLastStreamId(){return null}resolveStreamId(){return``}observeChunk(e){}recordMemoryState(e){}recordCompactionEvent(e,t){}recordCompactionState(e){}recordSkillsState(e){}beginRun(e,t){}getCurrentRunEventContext(){}getCurrentOrLastRunEventContext(){}findToolCallContext(e){return{toolCallId:e}}async applyFixture(e){}},Rd=e=>new Ld(e);function zd(e){return`toolCallId`in e&&typeof e.toolCallId==`string`?e.toolCallId:void 0}function Bd(e){return`messageId`in e&&typeof e.messageId==`string`?e.messageId:void 0}function Vd(e){return`parentMessageId`in e&&typeof e.parentMessageId==`string`?e.parentMessageId:void 0}var Hd=class{adapter;id;applyMessages;applyResume;skipNextPersist=!1;generation=0;queue=Promise.resolve();queuePending=!1;messagesGeneration=0;lastMessages=[];lastResume=null;legacyStored=!1;clearedMessageIds=/* @__PURE__ */ new Set;clearedRunIds=/* @__PURE__ */ new Set;ignoredActiveRunIds=/* @__PURE__ */ new Set;clearedToolCallIds=/* @__PURE__ */ new Set;currentRunlessRunId=null;constructor(e,t,n,r){this.adapter=e,this.id=t,this.applyMessages=n,this.applyResume=r}writeState(){if(this.legacyStored)return;let e=[...this.lastMessages];if(e.length===0&&!this.lastResume){let e=this.generation;this.runOperation(()=>{if(e===this.generation)return this.adapter.removeItem(this.id)});return}let t=this.generation,n={messages:e,...this.lastResume?{resume:this.lastResume}:{}};this.runOperation(()=>{if(t===this.generation)return this.adapter.setItem(this.id,n)})}normalize(e){if(Array.isArray(e))this.legacyStored=!0,console.error(`[TanStack AI] The stored chat for threadId "${this.id}" is in the 0.x format (a bare message array). TanStack AI 1.0 does not read this format, so the chat starts empty and the stored value is not overwritten. Clear the chat or the stored value to start saving again.`);else if(e&&Array.isArray(e.messages))return e}readInitial(){try{let e=this.adapter.getItem(this.id);if(e instanceof Promise)return e.then(e=>this.normalize(e)).catch(()=>void 0);let t=this.normalize(e);return t&&(this.lastMessages=t.messages,this.lastResume=t.resume??null),t}catch{return}}hydrateAsync(e){if(!(e instanceof Promise))return;let t=this.messagesGeneration;return e.then(e=>{e&&this.messagesGeneration===t&&(this.lastResume=e.resume??null,this.lastMessages=e.messages,this.applyMessages(e.messages),e.resume&&this.applyResume&&this.applyResume(e.resume))}).catch(()=>{})}notifyMessagesChanged(e){this.messagesGeneration++,this.lastMessages=[...e],this.skipNextPersist?this.skipNextPersist=!1:this.writeState()}persistResumeSnapshot(e){this.lastResume=e,!this.skipNextPersist&&this.writeState()}remove(){this.legacyStored=!1,this.lastMessages=[],this.lastResume=null;let e=++this.generation;this.runOperation(()=>{if(e===this.generation)return this.adapter.removeItem(this.id)})}runOperation(e){if(this.queuePending){let t=this.queue.then(e).catch(()=>{});this.queue=t,t.finally(()=>{this.queue===t&&(this.queuePending=!1)})}else try{let t=e();if(t instanceof Promise){this.queuePending=!0;let e=t.catch(()=>{});this.queue=e,e.finally(()=>{this.queue===e&&(this.queuePending=!1)})}}catch{}}snapshotClear(e){for(let t of e.messages)this.clearedMessageIds.add(t.id);for(let t of e.activeRunIds)this.clearedRunIds.add(t),this.ignoredActiveRunIds.add(t);e.currentRunId&&(this.clearedRunIds.add(e.currentRunId),this.ignoredActiveRunIds.add(e.currentRunId))}beginClear(){this.skipNextPersist=!0}shouldIgnoreChunk(e){let t=Ou(e);if(t&&this.clearedRunIds.has(t))return e.type===`RUN_STARTED`&&(this.ignoredActiveRunIds.add(t),this.currentRunlessRunId=t),this.markIgnoredChunkIds(e),!0;if(t&&this.ignoredActiveRunIds.has(t)||this.isRunlessChunkFromIgnoredRun(e))return this.markIgnoredChunkIds(e),!0;let n=zd(e);if(n&&this.clearedToolCallIds.has(n))return!0;let r=Vd(e);if(r&&this.clearedMessageIds.has(r))return n&&this.clearedToolCallIds.add(n),!0;let i=Bd(e);return i?!!this.clearedMessageIds.has(i):!1}onRunStarted(e){this.currentRunlessRunId=e}onRunSettled(e){this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId===e&&(this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null)}onSessionRunError(){this.ignoredActiveRunIds.clear(),this.currentRunlessRunId=null}resetIgnored(){this.ignoredActiveRunIds.clear()}takeRunlessRunId(){let e=this.currentRunlessRunId;return e?(this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null,e):null}markIgnoredChunkIds(e){let t=Bd(e);t&&this.clearedMessageIds.add(t);let n=zd(e);n&&this.clearedToolCallIds.add(n)}isRunlessChunkFromIgnoredRun(e){return Ou(e)||!this.currentRunlessRunId||!this.ignoredActiveRunIds.has(this.currentRunlessRunId)&&!this.clearedRunIds.has(this.currentRunlessRunId)?!1:e.type===`TEXT_MESSAGE_START`||e.type===`TEXT_MESSAGE_CONTENT`||e.type===`TEXT_MESSAGE_CHUNK`||e.type===`TOOL_CALL_START`||e.type===`TOOL_CALL_ARGS`||e.type===`TOOL_CALL_END`||e.type===`TOOL_CALL_RESULT`||e.type===`TOOL_CALL_CHUNK`||e.type===`MESSAGES_SNAPSHOT`||e.type===`RUN_ERROR`}};function Ud(e){return`toolCallId`in e&&typeof e.toolCallId==`string`?e.toolCallId:void 0}function Wd(e){return`messageId`in e&&typeof e.messageId==`string`?e.messageId:void 0}function Gd(e){return`parentMessageId`in e&&typeof e.parentMessageId==`string`?e.parentMessageId:void 0}var Kd=class{clearedMessageIds=/* @__PURE__ */ new Set;clearedRunIds=/* @__PURE__ */ new Set;ignoredActiveRunIds=/* @__PURE__ */ new Set;clearedToolCallIds=/* @__PURE__ */ new Set;currentRunlessRunId=null;snapshotClear(e){for(let t of e.messages)this.clearedMessageIds.add(t.id);for(let t of e.activeRunIds)this.clearedRunIds.add(t),this.ignoredActiveRunIds.add(t);e.currentRunId&&(this.clearedRunIds.add(e.currentRunId),this.ignoredActiveRunIds.add(e.currentRunId))}shouldIgnoreChunk(e){let t=Ou(e);if(t&&this.clearedRunIds.has(t))return e.type===`RUN_STARTED`&&(this.ignoredActiveRunIds.add(t),this.currentRunlessRunId=t),this.markIgnoredChunkIds(e),!0;if(t&&this.ignoredActiveRunIds.has(t)||this.isRunlessChunkFromIgnoredRun(e))return this.markIgnoredChunkIds(e),!0;let n=Ud(e);if(n&&this.clearedToolCallIds.has(n))return!0;let r=Gd(e);if(r&&this.clearedMessageIds.has(r))return n&&this.clearedToolCallIds.add(n),!0;let i=Wd(e);return!!(i&&this.clearedMessageIds.has(i))}onRunStarted(e){this.currentRunlessRunId=e}onRunSettled(e){this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId===e&&(this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null)}onSessionRunError(){this.ignoredActiveRunIds.clear(),this.currentRunlessRunId=null}resetActiveRuns(){this.ignoredActiveRunIds.clear(),this.currentRunlessRunId=null}takeRunlessRunId(){let e=this.currentRunlessRunId;return e?(this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null,e):null}markIgnoredChunkIds(e){let t=Wd(e);t&&this.clearedMessageIds.add(t);let n=Ud(e);n&&this.clearedToolCallIds.add(n)}isRunlessChunkFromIgnoredRun(e){return Ou(e)||!this.currentRunlessRunId||!this.ignoredActiveRunIds.has(this.currentRunlessRunId)&&!this.clearedRunIds.has(this.currentRunlessRunId)?!1:e.type===`TEXT_MESSAGE_START`||e.type===`TEXT_MESSAGE_CONTENT`||e.type===`TEXT_MESSAGE_CHUNK`||e.type===`TOOL_CALL_START`||e.type===`TOOL_CALL_ARGS`||e.type===`TOOL_CALL_END`||e.type===`TOOL_CALL_RESULT`||e.type===`TOOL_CALL_CHUNK`||e.type===`MESSAGES_SNAPSHOT`||e.type===`RUN_ERROR`}},qd=8;function Jd(){let{scheduler:e}=globalThis;return e?.yield?e.yield():new Promise(e=>setTimeout(e,0))}function Yd(e){let t=/* @__PURE__ */ new Set;for(let n of e??[]){if(t.has(n.id))throw Error(`Duplicate interrupt definition id: ${n.id}`);t.add(n.id)}}function Xd(e){let{connection:t,fetcher:n}=e;if(t&&n)throw Error("ChatClient: pass either `connection` or `fetcher`, not both.");if(t)return t;if(n)return id(n);throw Error("ChatClient: either `connection` or `fetcher` is required.")}function Zd(e){return`connect`in e}function Qd(e){if(e.type!==`RUN_FINISHED`||e.outcome?.type===`interrupt`)return!1;let t=e;return t.finishReason===void 0?Y(e)?.finishReason===`tool_calls`:t.finishReason===`tool_calls`}function $d(e){let t={whenBusy:`queue`,drain:`fifo`,onOverflow:`reject`};if(!e)return t;if(typeof e==`string`)return{...t,whenBusy:e};if(typeof e==`function`)return{...t,strategy:e};let n=e.maxSize;if(n!==void 0&&(!Number.isInteger(n)||n<0))throw Error(`ChatClient: queue.maxSize must be a non-negative integer`);return{whenBusy:e.whenBusy??`queue`,drain:e.drain??`fifo`,onOverflow:e.onOverflow??`reject`,...n===void 0?{}:{maxSize:n}}}function ef(e){let t=e.at(-1)?.body,n=[];for(let t of e){if(typeof t.content!=`string`)break;n.push(t.content)}if(n.length===e.length)return{content:n.join(`
|
|
145
145
|
`),...t===void 0?{}:{body:t}};let r=[],i;for(let t of e)typeof t.content==`string`?r.push({type:`text`,content:t.content}):(typeof t.content.content==`string`?r.push({type:`text`,content:t.content.content}):r.push(...t.content.content),i=Go(i,t.content.metadata));return{content:{content:r,...i===void 0?{}:{metadata:i}},...t===void 0?{}:{body:t}}}function tf(e){if(typeof e==`object`&&e&&!Array.isArray(e)&&`approved`in e&&typeof e.approved==`boolean`)return e.approved}function nf(e){let t=e;if(typeof t!=`object`||!t||!(`resumeState`in t))return;let n=t.resumeState;if(typeof n==`object`&&n&&`threadId`in n&&typeof n.threadId==`string`&&n.threadId.length!==0&&`runId`in n&&typeof n.runId==`string`&&n.runId.length!==0)return{threadId:n.threadId,runId:n.runId}}var rf=2e3,af=/* @__PURE__ */ new Set([`TEXT_MESSAGE_START`,`TEXT_MESSAGE_CONTENT`,`TEXT_MESSAGE_CHUNK`,`REASONING_MESSAGE_CONTENT`,`REASONING_MESSAGE_CHUNK`,`TOOL_CALL_START`,`TOOL_CALL_CHUNK`,`MESSAGES_SNAPSHOT`,`SUBAGENT_STARTED`]);function of(e){return e.type===`REASONING_ENCRYPTED_VALUE`?e.subtype===`message`&&typeof e.encryptedValue==`string`&&e.encryptedValue.length>0:af.has(e.type)}function sf(e){return e.map(e=>({...e,parts:e.parts.map(e=>Object.isFrozen(e)?e.type===`subagent`?{...e,subagent:{...e.subagent,messages:sf(e.subagent.messages)}}:{...e}:e)}))}function cf(e){let t=[];for(let n of e)for(let e of n.parts)e.type===`subagent`&&(t.push(e),t.push(...cf(e.subagent.messages)));return t}function lf(e){if(`subagentRunId`in e&&typeof e.subagentRunId==`string`)return e.subagentRunId}var uf=64;function df(e){if(Array.isArray(e))return e.map(df);if(e instanceof Date)return new Date(e.getTime());if(typeof e!=`object`||!e)return e;let t={};for(let[n,r]of Object.entries(e))typeof r!=`function`&&(t[n]=df(r));return t}var ff=class{processor;subagentHandles=/* @__PURE__ */ new Map;stoppedSubagentIds=/* @__PURE__ */ new Set;connection;threadId;persistor;clearedStreamTracker=new Kd;snapshotAtom=xo({messages:[],status:`ready`,isLoading:!1,error:void 0,isSubscribed:!1,connectionStatus:`disconnected`,sessionGenerating:!1,queue:[],runId:null,hasOlderMessages:!1,isHydrating:!1,interruptState:{interrupts:Object.freeze([]),interruptErrors:Object.freeze([]),resuming:!1}});get status(){return this.snapshotAtom.get().status}get isLoading(){return this.snapshotAtom.get().isLoading}get error(){return this.snapshotAtom.get().error}get isSubscribed(){return this.snapshotAtom.get().isSubscribed}get connectionStatus(){return this.snapshotAtom.get().connectionStatus}get sessionGenerating(){return this.snapshotAtom.get().sessionGenerating}get hasOlderMessages(){return this.snapshotAtom.get().hasOlderMessages}get isHydrating(){return this.snapshotAtom.get().isHydrating}get currentRunId(){return this.snapshotAtom.get().runId}lastResume=null;runParents=/* @__PURE__ */ new Map;supersededInterruptRunIds=/* @__PURE__ */ new Set;rejoinedRunId=null;interruptManager;activeInterruptSubmission;interruptSubmissionFailure;joinedRunWaiters=/* @__PURE__ */ new Map;pendingResumeParentRunId=null;pendingResumeThreadId=null;pendingResumeItems=null;activeResumeThreadId=null;activeResumeRunId=null;forwardedPropsOption={};byok;byokProvider;context=void 0;pendingMessageBody=void 0;queueConfig;messageQueue=[];sendInFlight=!1;messageQueueDraining=!1;stopMessageQueueDrain=!1;deliverClaim=!1;abortController=null;clientToolsRef;devtoolsBridge;events;currentStreamId=null;currentMessageId=null;postStreamActions=[];pendingToolExecutions=/* @__PURE__ */ new Map;handingOverPendingToolCalls=!1;activeClientTools=null;activeContext=void 0;continuationPending=!1;subscriptionAbortController=null;processingResolve=null;connectionDrainsOnSend=!1;errorReportedGeneration=null;streamGeneration=0;continuationGeneration=0;streamContinuationGeneration=0;continuationSkipped=!1;draining=!1;activeRunIds=/* @__PURE__ */ new Set;disposed=!1;hydrationError;tailing=!1;hydrationInFlight;storeHydrating=!1;rejoinRunId;cachesMessages;historyPageSize;olderMessagesCursor;knownServerMessageIds=/* @__PURE__ */ new Set;loadOlderMessagesInFlight=!1;historyGeneration=0;devtoolsMounted=!1;callbacksRef;constructor(e){if(Yd(e.interrupts),typeof e.threadId!=`string`||e.threadId===``)throw Error(`ChatClient: threadId is required (a non-empty string).`);this.threadId=e.threadId;let t=!0;e.persistence===!0?(t=!1,this.historyPageSize=e.history?.pageSize):(e.persistence&&(this.persistor=new Hd(e.persistence,e.threadId,e=>this.processor.setMessages(e),e=>this.applyPersistedResume(e))),this.historyPageSize=void 0),this.forwardedPropsOption=e.forwardedProps||{},this.byok=e.byok,this.byokProvider=e.byokProvider,this.context=e.context,this.queueConfig=$d(e.queue);let n=Xd(e);if(this.connectionDrainsOnSend=Zd(n),this.connection=td(n),this.clientToolsRef={current:/* @__PURE__ */ new Map},e.tools)for(let t of e.tools)this.clientToolsRef.current.set(t.name,t);this.devtoolsBridge=(e.devtoolsBridgeFactory??Rd)(this.buildDevtoolsBridgeOptions(e.devtools)),this.events=this.devtoolsBridge.events,this.callbacksRef={current:{onResponse:e.onResponse||(()=>{}),onChunk:e.onChunk||(()=>{}),onFinish:e.onFinish||(()=>{}),onError:e.onError||(()=>{}),onMessagesChange:e.onMessagesChange||(()=>{}),onLoadingChange:e.onLoadingChange||(()=>{}),onErrorChange:e.onErrorChange||(()=>{}),onStatusChange:e.onStatusChange||(()=>{}),onSubscriptionChange:e.onSubscriptionChange||(()=>{}),onConnectionStatusChange:e.onConnectionStatusChange||(()=>{}),onSessionGeneratingChange:e.onSessionGeneratingChange||(()=>{}),onHydratingChange:e.onHydratingChange||(()=>{}),onQueueChange:e.onQueueChange||(()=>{}),onResumeStateChange:e.onResumeStateChange||(()=>{}),onRunIdChange:e.onRunIdChange||(()=>{}),onInterruptStateChange:e.onInterruptStateChange||(()=>{}),onCustomEvent:e.onCustomEvent||(()=>{})}},this.interruptManager=new Ad({...e.tools===void 0?{}:{tools:e.tools},...e.interrupts===void 0?{}:{interrupts:e.interrupts},submit:e=>this.submitInterruptBatch(e),onChange:e=>this.notifyResumeStateChange(e)}),e.initialResumeSnapshot&&this.applyResumeSnapshot(e.initialResumeSnapshot);let r=this.persistor?.readInitial(),i=r instanceof Promise?void 0:r,a=i?i.messages:e.initialMessages&&sf(e.initialMessages),o=null;if(i?.resume){let e=i.resume;Array.isArray(e.pendingInterrupts)&&e.pendingInterrupts.length>0?this.applyResumeSnapshot(e):e.resumeState.runId&&(o=e.resumeState.runId)}if(!o&&e.initialResumeSnapshot){let t=e.initialResumeSnapshot;!(Array.isArray(t.pendingInterrupts)&&t.pendingInterrupts.length>0)&&t.resumeState.runId&&(o=t.resumeState.runId)}this.processor=new yu({...e.streamProcessor?.chunkStrategy?{chunkStrategy:e.streamProcessor.chunkStrategy}:{},...a?{initialMessages:a}:{},events:{onMessagesChange:e=>{this.syncSubagentHandles(),this.persistor?.notifyMessagesChanged(e),ko(this.snapshotAtom,{messages:Oo(this.frozenMessages,e)}),this.callbacksRef.current.onMessagesChange(e),this.queueDevtoolsSnapshot()},onStreamStart:()=>{this.setStatus(`streaming`);let e=this.processor.getCurrentAssistantMessageId();if(!e)return;let t=this.processor.getMessages().find(t=>t.id===e);t&&(this.currentMessageId=t.id,this.events.messageAppended(t,this.currentStreamId||void 0))},onStreamEnd:e=>{this.callbacksRef.current.onFinish(e),this.setStatus(`ready`),this.resolveProcessing()},onError:e=>{this.reportStreamError(e)},onTextUpdate:(e,t)=>{this.currentStreamId&&this.events.textUpdated(this.currentStreamId,e,t)},onThinkingUpdate:(e,t)=>{this.currentStreamId&&this.events.thinkingUpdated(this.currentStreamId,e,t,void 0)},onStructuredOutputChange:e=>{let t=this.devtoolsBridge.resolveStreamId(),n=e.phase===`start`?`structured-output:started`:e.phase===`complete`?`structured-output:completed`:e.phase===`error`?`structured-output:errored`:`structured-output:updated`;this.currentMessageId=e.messageId,this.events.structuredOutputChanged(n,t,e.messageId,{status:e.status,raw:e.raw,...e.partial===void 0?{}:{partial:e.partial},...e.data===void 0?{}:{data:e.data},...e.reasoning===void 0?{}:{reasoning:e.reasoning},...e.errorMessage===void 0?{}:{errorMessage:e.errorMessage},...e.delta===void 0?{}:{delta:e.delta}})},onToolCallStateChange:(e,t,n,r)=>{let i=this.processor.getMessages().find(t=>t.id===e)?.parts.find(e=>e.type===`tool-call`&&e.id===t)?.name||`unknown`;this.currentStreamId&&this.events.toolCallStateChanged(this.currentStreamId,e,t,i,n,r)},onToolCall:e=>{let t=(this.activeClientTools??this.clientToolsRef.current).get(e.toolName),n=t?.execute;if(this.handingOverPendingToolCalls&&t?.needsApproval===!0)console.warn(`[ChatClient] Did not run tool call ${e.toolCallId}: ${e.toolName} needs approval, and the server did not ask for it`);else if(n){let r=this.continuationGeneration,i=this.devtoolsBridge.getCurrentRunEventContext(),a=(async()=>{try{let a=this.activeClientTools===null?this.context:this.activeContext,o=await n(e.input,{toolCallId:e.toolCallId,threadId:this.threadId,context:a,emitCustomEvent:()=>{}});await this.addToolResultForClientTool({toolCallId:e.toolCallId,tool:e.toolName,output:o,state:`output-available`},t,r,i)}catch(n){await this.addToolResultForClientTool({toolCallId:e.toolCallId,tool:e.toolName,output:null,state:`output-error`,errorText:n.message},t,r,i)}finally{this.pendingToolExecutions.delete(e.toolCallId)}})();this.pendingToolExecutions.set(e.toolCallId,a)}},onApprovalRequest:e=>{let t=this.devtoolsBridge.resolveStreamId(),n=this.findMessageIdForToolCall(e.toolCallId)??this.currentMessageId??``;this.events.approvalRequested(t,n,e.toolCallId,e.toolName,e.input,e.approvalId)},onCustomEvent:(e,t,n)=>{e===`memory:state`&&this.devtoolsBridge.recordMemoryState(t),(e===`compaction:started`||e===`compaction:state`||e===`compaction:ended`)&&this.devtoolsBridge.recordCompactionEvent(e,t),e===`skills:state`&&this.devtoolsBridge.recordSkillsState(t),this.callbacksRef.current.onCustomEvent(e,t,n)}}}),this.syncSubagentHandles();let s=this.persistor?.hydrateAsync(r);s&&(this.storeHydrating=!0,s.finally(()=>{this.storeHydrating=!1,this.syncIsHydrating()})),this.rejoinRunId=o,this.cachesMessages=t,this.snapshotAtom.set(this.readSnapshot(this.storeHydrating||!t&&!!this.connection.hydrate))}attach(){this.disposed||this.tailing||(this.tailing=!0,this.rejoinRunId&&this.maybeRejoinInFlight(this.rejoinRunId),!this.cachesMessages&&this.connection.hydrate&&this.hydrateFromServer())}detach(){this.tailing&&(this.tailing=!1,this.cancelInFlightStream({setReadyStatus:!0}),this.rejoinedRunId=null)}applyResumeSnapshot(e){let t=nf(e);if(t===void 0){this.interruptManager.reset({source:`hydrate`});return}this.lastResume=t;let n=Array.isArray(e.pendingInterrupts)?e.pendingInterrupts:[];if(n.length===0){this.interruptManager.reset({source:`hydrate`});return}let r=this.interruptGeneration(n);this.interruptManager.hydrate({threadId:t.threadId,interruptedRunId:t.runId,generation:r,interrupts:n},`hydrate`)}applyPersistedResume(e){this.applyResumeSnapshot(e);let t=Array.isArray(e.pendingInterrupts)&&e.pendingInterrupts.length>0,n=e.resumeState?.runId;!t&&n&&this.maybeRejoinInFlight(n)}maybeRejoinInFlight(e){this.connection.joinRun&&!this.disposed&&this.tailing&&this.rejoinedRunId!==e&&(this.isLoading||this.abortController||(this.rejoinedRunId=e,this.resumeInFlightRun(e)))}hydrateFromServer(){let e=this.connection.hydrate;if(!e||this.isLoading||this.abortController||this.disposed){this.syncIsHydrating();return}if(this.hydrationInFlight===this.historyGeneration)return;let t=this.historyPageSize,n=t===void 0?void 0:{limit:t};(async()=>{let t,r=this.historyGeneration;this.hydrationInFlight=r,this.syncIsHydrating();let i=()=>this.hydrationInFlight===r&&r===this.historyGeneration,a;try{t=await e(this.threadId,n)}catch(e){i()&&this.failHydration(e);return}finally{a=i(),this.hydrationInFlight===r&&(this.hydrationInFlight=void 0)}if(a&&!this.disposed&&this.tailing&&!(this.isLoading||this.abortController)){if(this.hydrationError&&this.error===this.hydrationError&&(this.setError(void 0),this.setStatus(`ready`)),this.hydrationError=void 0,this.applyHydrationPage(t.page),t.messages.length>0){let e=zo(t.messages);this.processor.setMessages(e),this.rememberServerMessageIds(e)}t.interrupts&&t.interrupts.pending.length>0&&(!t.activeRun?.runId||t.activeRun.runId===t.interrupts.runId)?this.applyResumeSnapshot({resumeState:{threadId:this.threadId,runId:t.interrupts.runId},pendingInterrupts:t.interrupts.pending}):t.activeRun?.runId&&this.maybeRejoinInFlight(t.activeRun.runId)}})().finally(()=>this.syncIsHydrating())}failHydration(e){if(this.disposed||!this.tailing||this.isLoading||this.abortController)return;let t=e instanceof Error?e:Error(String(e));t instanceof xu&&this.byok?.request(t.provider,`missing`),t instanceof Su&&t.reason===`locked`&&this.byok?.request(t.provider,`locked`),this.hydrationError=t,this.setStatus(`error`),this.setError(t),this.callbacksRef.current.onError(t)}mountDevtools(){this.devtoolsMounted||(this.devtoolsMounted=!0,this.devtoolsBridge.mountWithTools(this.processor.getMessages().length))}drainIgnoredRunlessChunk(e){if(e.type!==`RUN_ERROR`)return;let t=this.clearedStreamTracker.takeRunlessRunId();t&&(this.activeRunIds.delete(t),this.setSessionGenerating(this.activeRunIds.size>0),this.resolveProcessing())}retireIgnoredClearedTerminalChunk(e){if(e.type!==`RUN_FINISHED`&&e.type!==`RUN_ERROR`)return;let t=Ou(e)??this.clearedStreamTracker.takeRunlessRunId();t&&(this.activeRunIds.delete(t),this.setSessionGenerating(this.activeRunIds.size>0),Ou(e)||this.resolveProcessing())}updateRunLifecycle(e,t){if(e.type===`RUN_STARTED`){let t=Ou(e)??e.runId,n=`parentRunId`in e&&typeof e.parentRunId==`string`?e.parentRunId:void 0;n&&(this.runParents.set(t,n),this.supersededInterruptRunIds.has(t)&&this.markLineageAnswered(n)),this.activeResumeThreadId=`threadId`in e&&typeof e.threadId==`string`?e.threadId:this.activeResumeThreadId,this.activeResumeRunId=t;let r=this.supersededInterruptRunIds.has(t)&&!this.isLoading;r||(this.activeRunIds.add(t),this.clearedStreamTracker.onRunStarted(t),this.setSessionGenerating(!0)),this.persistor&&this.connection.joinRun&&!this.lastResume&&!r&&this.persistResumeSnapshot({threadId:this.activeResumeThreadId??this.threadId,runId:t}),this.lastResume&&this.supersededInterruptRunIds.has(this.lastResume.runId)&&(this.lastResume=null,this.persistor?.persistResumeSnapshot(null),this.interruptManager.reset());return}if(e.type!==`RUN_FINISHED`&&e.type!==`RUN_ERROR`)return;let n=Ou(e);n?(this.activeRunIds.delete(n),this.clearedStreamTracker.onRunSettled(n)):e.type===`RUN_ERROR`&&(this.activeRunIds.clear(),this.clearedStreamTracker.onSessionRunError()),this.setSessionGenerating(this.activeRunIds.size>0);let r=e.type===`RUN_FINISHED`&&Qd(e);t?.resolveProcessing!==!1&&!r&&this.resolveProcessing()}observeInterruptState(e){if(e.type!==`RUN_FINISHED`&&e.type!==`RUN_ERROR`||this.activeInterruptSubmission&&e.type===`RUN_ERROR`)return;let t=Ou(e),n=`threadId`in e&&typeof e.threadId==`string`?e.threadId:this.activeResumeThreadId;if(t&&!Qd(e)&&(e.type===`RUN_ERROR`||e.type===`RUN_FINISHED`&&e.outcome?.type!==`interrupt`)&&this.markLineageAnswered(t),e.type===`RUN_FINISHED`&&e.outcome?.type===`interrupt`){let r=this.currentRunId??t??this.activeResumeRunId??``;if(r&&this.supersededInterruptRunIds.has(r))return;this.lastResume={threadId:n??this.threadId,runId:r},this.interruptManager.hydrate({threadId:this.lastResume.threadId,interruptedRunId:r,generation:this.interruptGeneration(e.outcome.interrupts),interrupts:e.outcome.interrupts},`live`);return}let r=e.type===`RUN_ERROR`&&!t,i=!!(t&&this.lastResume?.runId===t),a=!!(t&&this.currentRunId===t||this.currentRunId&&this.lastResume?.runId===this.currentRunId),o=!(!this.isLoading||!t||t!==this.activeResumeRunId&&t!==this.currentRunId),s=this.isLoading&&e.type===`RUN_FINISHED`&&!t,c=!!(this.activeInterruptSubmission&&this.isLoading&&e.type===`RUN_FINISHED`&&e.outcome?.type!==`interrupt`),l=!!(this.lastResume&&this.supersededInterruptRunIds.has(this.lastResume.runId));r||i||a||o||s||c||l?(this.lastResume=null,this.persistor?.persistResumeSnapshot(null),this.interruptManager.reset()):this.notifyResumeStateChange(`live`)}markLineageAnswered(e){let t=e,n=0;for(;t!==void 0&&n<uf;){if(this.supersededInterruptRunIds.has(t))return;this.supersededInterruptRunIds.add(t),t=this.runParents.get(t),n++}}getResumeState(){return this.lastResume?{...this.lastResume}:null}getCurrentRunId(){return this.currentRunId}setCurrentRunId(e){this.currentRunId!==e&&(ko(this.snapshotAtom,{runId:e}),this.callbacksRef.current.onRunIdChange(e))}getInterruptState(){return this.interruptManager.getState()}getInterrupts(){return this.interruptManager.getInterrupts()}resolveInterrupts(e){this.interruptManager.resolve(e)}cancelInterrupts(){this.interruptManager.cancel()}retryInterrupts(){this.interruptManager.retry()}resumeInterruptsUnsafe(e,t){let n=t??this.lastResume;return n?this.resumeInterruptsUnsafeForGeneration(e,n,this.continuationGeneration):Promise.resolve(!1)}resumeInterruptsUnsafeForGeneration(e,t,n){return n===this.continuationGeneration?this.isLoading?new Promise((r,i)=>{this.queuePostStreamAction(async()=>{try{r(await this.resumeInterruptsUnsafeForGeneration(e,t,n))}catch(e){i(e)}})}):(this.pendingResumeThreadId=t.threadId,this.pendingResumeParentRunId=t.runId,this.pendingResumeItems=[...e],this.streamResponse()):Promise.resolve(!1)}async submitInterruptBatch(e){let t=this.continuationGeneration;this.activeInterruptSubmission=e,this.interruptSubmissionFailure=void 0;for(let t of e.resolutions){let e=tf(t.payload);if(e===void 0)continue;let n=t.interruptId;this.processor.addToolApprovalResponse(n,e)}let n=await this.resumeInterruptsUnsafeForGeneration([...e.resolutions],{threadId:e.threadId,runId:e.interruptedRunId},t).finally(()=>{this.activeInterruptSubmission===e&&(this.activeInterruptSubmission=void 0)});if(t!==this.continuationGeneration)return;let r=this.takeInterruptSubmissionFailure();if(r!==void 0)throw{errors:r.errors};if(!n)throw Error(`Interrupt continuation could not be started.`);this.lastResume?.runId===e.interruptedRunId&&(this.lastResume=null,this.interruptManager.reset())}takeInterruptSubmissionFailure(){let e=this.interruptSubmissionFailure;return this.interruptSubmissionFailure=void 0,e}interruptGeneration(e){let t;for(let n of e){let e=n.metadata?.[`tanstack:interruptBinding`];if(typeof e!=`object`||!e||!(`generation`in e)||typeof e.generation!=`number`||!Number.isInteger(e.generation)||e.generation<0||t!==void 0&&t!==e.generation)return 0;t=e.generation}return t??0}generateUniqueId(e){return`${e}-${Date.now()}-${Math.random().toString(36).substring(7)}`}frozenMessages=/* @__PURE__ */ new WeakMap;freezeSnapshotQueue(e){return Object.freeze(e.map(e=>{if(typeof e.content!=`object`)return Object.freeze({...e});let t=Array.isArray(e.content.content)?Object.freeze(e.content.content.map(e=>Eo(e))):e.content.content;return Object.freeze({...e,content:Object.freeze({...e.content,content:t})})}))}readSnapshot(e){return Object.freeze({...this.snapshotAtom.get(),messages:Oo(this.frozenMessages,this.processor.getMessages()),queue:this.freezeSnapshotQueue(this.getQueue()),isHydrating:e,interruptState:this.interruptManager.getState()})}subscribeSnapshot=e=>jo(this.snapshotAtom,e);getSnapshot=()=>this.snapshotAtom.get();setIsLoading(e){ko(this.snapshotAtom,{isLoading:e}),this.callbacksRef.current.onLoadingChange(e),this.events.loadingChanged(e),e&&this.supersedeHydration()}supersedeHydration(){this.hydrationInFlight=void 0,this.storeHydrating=!1,this.syncIsHydrating()}setStatus(e){ko(this.snapshotAtom,{status:e}),this.callbacksRef.current.onStatusChange(e),this.devtoolsBridge.emitSnapshot()}setIsSubscribed(e){ko(this.snapshotAtom,{isSubscribed:e}),this.callbacksRef.current.onSubscriptionChange(e),this.devtoolsBridge.emitSnapshot()}setConnectionStatus(e){ko(this.snapshotAtom,{connectionStatus:e}),this.callbacksRef.current.onConnectionStatusChange(e),this.devtoolsBridge.emitSnapshot()}syncIsHydrating(){let e=this.hydrationInFlight!==void 0||this.storeHydrating;this.isHydrating!==e&&(ko(this.snapshotAtom,{isHydrating:e}),this.callbacksRef.current.onHydratingChange(e))}setSessionGenerating(e){this.sessionGenerating!==e&&(ko(this.snapshotAtom,{sessionGenerating:e}),this.callbacksRef.current.onSessionGeneratingChange(e),this.devtoolsBridge.emitSnapshot())}notifyResumeStateChange(e){let t=this.getResumeState(),n=this.interruptManager.getState();ko(this.snapshotAtom,{interruptState:n}),this.persistResumeSnapshot(t),this.callbacksRef.current.onResumeStateChange(t,n.interrupts),this.callbacksRef.current.onInterruptStateChange(n,{source:e})}persistResumeSnapshot(e){if(!this.persistor)return;if(!e){this.persistor.persistResumeSnapshot(null);return}let t=this.interruptManager.getDescriptors();this.persistor.persistResumeSnapshot({resumeState:e,...t.length>0?{pendingInterrupts:[...t]}:{}})}resetSessionGenerating(e){this.activeRunIds.clear(),e?.preserveClearedStreamTracking||this.clearedStreamTracker.resetActiveRuns(),this.setSessionGenerating(!1)}setError(e){ko(this.snapshotAtom,{error:e}),this.callbacksRef.current.onErrorChange(e),this.events.errorChanged(e?.message||null)}buildDevtoolsBridgeOptions(e){return{hookId:this.threadId,clientId:this.threadId,threadId:this.threadId,metadata:{hookName:e?.hookName??`useChat`,outputKind:e?.outputKind??`chat`,...e?.framework?{framework:e.framework}:{},...e?.name?{name:e.name}:{}},getSnapshot:()=>this.getDevtoolsSnapshot(),getTools:()=>this.clientToolsRef.current.values(),getMessages:()=>this.processor.getMessages(),setMessages:e=>{this.processor.setMessages(e)},addToolResult:(e,t,n)=>{this.processor.addToolResult(e,t,n)},generateId:e=>this.generateUniqueId(e)}}getDevtoolsSnapshot(){return{messages:df(this.processor.getMessages()),status:this.status,isLoading:this.isLoading,isSubscribed:this.isSubscribed,connectionStatus:this.connectionStatus,sessionGenerating:this.sessionGenerating,activeRunIds:Array.from(this.activeRunIds),queue:this.getQueue(),...this.error?{error:this.error.message}:{}}}findMessageIdForToolCall(e){let t=this.processor.getMessages();for(let n of t)if(n.parts.find(t=>t.type===`tool-call`&&t.id===e))return n.id}abortSubscriptionLoop(){this.subscriptionAbortController?.abort(),this.subscriptionAbortController=null}resolveProcessing(){this.processingResolve?.(),this.processingResolve=null}cancelInFlightStream(e){this.abortController?.abort(),this.abortController=null,e?.abortSubscription&&this.abortSubscriptionLoop(),this.resolveProcessing(),this.setIsLoading(!1),this.deliverClaim=!1,e?.setReadyStatus&&this.setStatus(`ready`)}reportStreamError(e){let t=this.errorReportedGeneration===this.streamGeneration;this.setError(e),(this.isLoading||this.status===`submitted`||this.status===`streaming`)&&this.setStatus(`error`),t||(this.errorReportedGeneration=this.streamGeneration,this.callbacksRef.current.onError(e))}startSubscription(){this.subscriptionAbortController=new AbortController;let e=this.subscriptionAbortController.signal;this.consumeSubscription(e).catch(e=>{e instanceof Error&&e.name!==`AbortError`&&(this.setConnectionStatus(`error`),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.reportStreamError(e)),this.resolveProcessing()}).finally(()=>{this.subscriptionAbortController?.signal===e&&(this.subscriptionAbortController=null,!e.aborted&&this.isSubscribed&&(this.setIsSubscribed(!1),this.connectionStatus!==`error`&&this.setConnectionStatus(`disconnected`)))})}async consumeSubscription(e){let t=this.connection.subscribe(e),n=0;for await(let r of t){if(e.aborted)break;let t=performance.now();this.processIncomingChunk(r),n+=performance.now()-t,!(n<qd)&&(n=0,!(typeof document<`u`&&document.hidden)&&await Jd())}}resumeInFlightRun(e){let t=this.connection.joinRun;if(!t)return;let n=new AbortController;this.abortController=n,this.setCurrentRunId(e),this.lastResume={threadId:this.threadId,runId:e},this.streamContinuationGeneration=this.continuationGeneration,this.setIsLoading(!0),this.setStatus(`streaming`),(async()=>{let r=!1,i=!1,a=!1,o=setTimeout(()=>{i||n.abort()},rf);try{for await(let a of t(e,n.signal)){if(n.signal.aborted)break;i||(i=!0,clearTimeout(o)),!r&&of(a)&&(r=!0,this.dropTrailingInFlightAssistant()),this.processIncomingChunk(a)}this.pendingToolExecutions.size>0&&await Promise.all(this.pendingToolExecutions.values())}catch(e){let t=e instanceof Error&&(e.name===`AbortError`||e.name===`TimeoutError`);!i&&!t&&(a=!0),i&&!t&&this.reportStreamError(e instanceof Error?e:Error(String(e)))}finally{clearTimeout(o),!i&&a&&this.tailing&&!this.disposed&&(this.lastResume=null,this.persistor?.persistResumeSnapshot(null)),this.abortController===n&&(this.abortController=null,this.setIsLoading(!1),this.status===`streaming`&&this.setStatus(`ready`),await this.drainPostStreamActions())}})()}dropTrailingInFlightAssistant(){let e=this.processor.getMessages(),t=e[e.length-1];t&&t.role===`assistant`&&this.processor.setMessages(e.slice(0,-1))}processIncomingChunk(e){if(e=ul(e),e.type===`RUN_ERROR`&&this.isActiveInterruptSubmissionFailure(e)){let t=Y(e)?.interruptErrors;this.interruptSubmissionFailure={errors:Array.isArray(t)?t:[]}}if(this.connectionStatus===`connecting`&&this.setConnectionStatus(`connected`),this.clearedStreamTracker.shouldIgnoreChunk(e)){(e.type===`RUN_FINISHED`||e.type===`RUN_ERROR`)&&(Ou(e)?this.updateRunLifecycle(e,{resolveProcessing:!1}):this.drainIgnoredRunlessChunk(e),this.retireIgnoredClearedTerminalChunk(e),this.resolveJoinedRun(e));return}this.callbacksRef.current.onChunk(e),this.devtoolsBridge.observeChunk(e);let t=lf(e);if(t&&e.type===X.SUBAGENT_STARTED&&this.stoppedSubagentIds.delete(t),t&&this.stoppedSubagentIds.has(t))this.updateRunLifecycle(e),this.resolveJoinedRun(e);else{this.handingOverPendingToolCalls=e.type===`RUN_FINISHED`&&e.outcome?.type!==`interrupt`;try{this.processor.processChunk(e)}finally{this.handingOverPendingToolCalls=!1}this.syncSubagentHandles(),this.updateRunLifecycle(e),this.observeInterruptState(e),this.resolveJoinedRun(e)}}isActiveInterruptSubmissionFailure(e){let t=this.activeInterruptSubmission,n=Y(e)?.interruptErrors;if(!t||!Array.isArray(n)||n.length===0)return!1;let r=Ou(e);return r!==void 0&&r!==this.currentRunId||typeof e.threadId==`string`&&e.threadId!==t.threadId?!1:n.every(e=>typeof e!=`object`||!e||typeof e.threadId!=`string`||typeof e.interruptedRunId!=`string`||typeof e.generation!=`number`?!1:e.threadId===t.threadId&&e.interruptedRunId===t.interruptedRunId&&e.generation===t.generation)}resolveJoinedRun(e){if(e.type!==`RUN_FINISHED`&&e.type!==`RUN_ERROR`)return;let t=Ou(e);if(t===void 0)return;let n=this.joinedRunWaiters.get(t);n!==void 0&&(this.joinedRunWaiters.delete(t),n())}ensureSubscription(){this.isSubscribed?(!this.subscriptionAbortController||this.subscriptionAbortController.signal.aborted)&&this.subscribe({restart:!0}):this.subscribe()}waitForProcessing(){return this.resolveProcessing(),new Promise(e=>{this.processingResolve=e})}async sendMessage(e,t,n){if(this.mountDevtools(),typeof e==`string`&&!e.trim())return;if(this.hasPendingInterrupts())throw Error(`ChatClient: cannot send normal input while pending interrupts exist. Resolve the interrupts first.`);let r={...t,...n?.body};if(this.isSendBusy()){let{action:t,id:i}=this.decideWhenBusy(e,n);if(t===`drop`)return;if(t===`queue`){this.enqueueMessage(e,r,i);return}this.stopMessageQueueDrain=!0,this.sendInFlight=!0,this.cancelInFlightStream({setReadyStatus:!0}),this.resetSessionGenerating()}else this.sendInFlight=!0;try{await this.deliverMessage(e,r)}finally{this.sendInFlight=!1}}hasPendingInterrupts(){return this.interruptManager.getDescriptors().length>0}isSendBusy(){return this.isLoading||this.sendInFlight||this.messageQueueDraining}resolveBusyReason(){return this.isLoading?`streaming`:this.messageQueueDraining?`draining`:`sendInFlight`}async deliverMessage(e,t){if(this.isLoading||this.deliverClaim)return!1;this.deliverClaim=!0;try{let n=this.normalizeMessageInput(e);this.pendingMessageBody=t;let r=this.processor.addUserMessage(n.content,n.id,n.metadata);return this.events.messageSent(r.id,n.content),await this.streamResponse()}finally{this.deliverClaim=!1}}decideWhenBusy(e,t){let n=this.generateUniqueId(`queued`);if(t?.whenBusy)return{action:t.whenBusy,id:n};let{strategy:r,whenBusy:i}=this.queueConfig;if(r){let{action:t}=r({pending:{id:n,content:e,createdAt:Date.now()},busyReason:this.resolveBusyReason(),queued:this.getQueue()});return{action:t,id:n}}return{action:i,id:n}}enqueueMessage(e,t,n){let{maxSize:r,onOverflow:i}=this.queueConfig;if(r!==void 0&&this.messageQueue.length>=r){if(i===`reject`||r===0)return;this.messageQueue.shift()}this.messageQueue.push({id:n??this.generateUniqueId(`queued`),content:e,createdAt:Date.now(),...t===void 0?{}:{body:t}}),this.emitQueueChange()}normalizeMessageInput(e){return typeof e==`string`?{content:e.trim()}:{content:e.content,id:e.id,...e.metadata===void 0?{}:{metadata:e.metadata}}}async append(e){if(this.mountDevtools(),this.hasPendingInterrupts())throw Error(`ChatClient: cannot append normal input while pending interrupts exist. Resolve the interrupts first.`);let t=Hc(e,Uc);if(t.role===`system`)return;if(t.role===`activity`){let e=t;this.events.messageAppended(e);let n=this.processor.getMessages();this.processor.setMessages([...n,e]),this.devtoolsBridge.emitSnapshot();return}let n=t;this.events.messageAppended(n);let r=this.processor.getMessages();this.processor.setMessages([...r,n]),this.devtoolsBridge.emitSnapshot(),this.isLoading?this.queuePostStreamAction(async()=>{await this.streamResponse()}):await this.streamResponse()}async streamResponse(){if(this.isLoading)return!1;let e=++this.streamGeneration;this.streamContinuationGeneration=this.continuationGeneration;let t=this.pendingResumeThreadId,n=this.pendingResumeParentRunId,r=this.pendingResumeItems;this.pendingResumeThreadId=null,this.pendingResumeParentRunId=null,this.pendingResumeItems=null;let i=`run-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.setCurrentRunId(i),this.activeResumeThreadId=t??this.threadId,this.activeResumeRunId=i,this.setIsLoading(!0),this.deliverClaim=!1,this.setStatus(`submitted`),this.setError(void 0),this.errorReportedGeneration=null,this.abortController=new AbortController;let a=this.abortController.signal;this.pendingToolExecutions.clear();let o=!1,s=null,c=!1;try{let l=this.messagesForSend(this.processor.getMessages()),u=new Map(this.clientToolsRef.current),d=this.context;if(await this.callbacksRef.current.onResponse(),a.aborted)return!1;let f={...this.forwardedPropsOption,...this.pendingMessageBody};this.pendingMessageBody=void 0,this.currentStreamId=this.generateUniqueId(`stream`),this.devtoolsBridge.setCurrentStreamId(this.currentStreamId),this.currentMessageId=null,this.activeClientTools=u,this.activeContext=d,this.processor.prepareAssistantMessage(),this.ensureSubscription();let p=this.waitForProcessing(),m;if(this.byok){let e=Nd(this.byokProvider,f.provider,Md(this.byok));m=await Pd(this.byok,e)}let h={threadId:t??this.threadId,runId:i,...n===null?{}:{parentRunId:n},clientTools:Array.from(u.values()).map(e=>({name:e.name,description:e.description,parameters:e.inputSchema?vs(e.inputSchema):{type:`object`}})),forwardedProps:{...f},...r?{resume:r}:{},...m?{headers:m}:{}};if(this.devtoolsBridge.beginRun(h.runId,h.threadId),s=h.runId,this.devtoolsBridge.emitRunLifecycle(`run:created`,h.runId,`created`),this.devtoolsBridge.emitRunLifecycle(`run:started`,h.runId,`started`),this.devtoolsBridge.emitSnapshot(),await this.connection.send(l,f,a,h),e!==this.streamGeneration||a.aborted||(this.connectionDrainsOnSend&&this.resolveProcessing(),await p,e!==this.streamGeneration))return!1;if(this.status===`error`)return s&&(this.devtoolsBridge.emitRunLifecycle(`run:errored`,s,`errored`,this.error?{error:this.error.message}:{}),c=!0),!1;this.pendingToolExecutions.size>0&&await Promise.all(this.pendingToolExecutions.values()),this.processor.finalizeStream(),o=!0}catch(t){let n=t instanceof Error?t:Error(String(t));if(n.name===`AbortError`)return s&&(this.devtoolsBridge.emitRunLifecycle(`run:cancelled`,s,`cancelled`),c=!0),!1;if(n instanceof xu&&this.byok?.request(n.provider,`missing`),n instanceof Su&&n.reason===`locked`&&this.byok?.request(n.provider,`locked`),e===this.streamGeneration&&(this.reportStreamError(n),s&&(this.devtoolsBridge.emitRunLifecycle(`run:errored`,s,`errored`,{error:n.message}),c=!0)),e===this.streamGeneration&&(n instanceof xu||n instanceof Su||n instanceof Cu))throw n}finally{e===this.streamGeneration&&(this.currentStreamId=null,this.devtoolsBridge.setCurrentStreamId(null),this.currentMessageId=null,this.setCurrentRunId(null),this.activeClientTools=null,this.activeContext=void 0,this.abortController=null,this.setIsLoading(!1),this.pendingMessageBody=void 0,s&&!c&&(o?this.devtoolsBridge.emitRunLifecycle(`run:completed`,s,`completed`):a.aborted&&this.devtoolsBridge.emitRunLifecycle(`run:cancelled`,s,`cancelled`)),await this.drainPostStreamActions(),o?(this.rememberProcessorMessageIds(),this.status!==`ready`&&this.setStatus(`ready`),this.messageQueueDraining||await this.drainQueue()):this.flushQueue())}return o}subscribe(e){let t=e?.restart===!0;(!this.isSubscribed||t)&&(this.isSubscribed&&t&&this.abortSubscriptionLoop(),this.setIsSubscribed(!0),this.setConnectionStatus(`connecting`),this.startSubscription())}unsubscribe(){this.cancelInFlightStream({setReadyStatus:!0,abortSubscription:!0}),this.discardPendingSends(),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.setConnectionStatus(`disconnected`)}async reload(){let e=this.processor.getMessages();if(e.length===0)return;let t=e.findLastIndex(e=>e.role===`user`);t!==-1&&(this.isLoading&&this.cancelInFlightStream(),this.discardPendingSends(),this.events.reloaded(t),this.processor.removeMessagesAfter(t),this.devtoolsBridge.emitSnapshot(),await this.streamResponse())}stop(){this.continuationGeneration++;let e=this.abortController!==null;this.cancelInFlightStream({setReadyStatus:!0}),this.discardPendingSends(),this.lastResume=null,this.activeInterruptSubmission=void 0,this.interruptManager.reset(),e&&this.resetSessionGenerating(),this.events.stopped()}clear(){let e=this.abortController!==null;this.clearedStreamTracker.snapshotClear({messages:this.processor.getMessages(),activeRunIds:this.activeRunIds,currentRunId:this.currentRunId}),this.isLoading||e?(this.cancelInFlightStream({setReadyStatus:!0}),this.resetSessionGenerating({preserveClearedStreamTracking:!0})):this.activeRunIds.size>0&&this.resetSessionGenerating({preserveClearedStreamTracking:!0}),this.persistor?.beginClear(),this.processor.clearMessages(),this.resetHistoryPaging(),this.supersedeHydration(),this.discardPendingSends(),this.persistor?.remove(),this.stoppedSubagentIds.clear(),this.lastResume=null,this.interruptManager.reset(),this.pendingResumeThreadId=null,this.pendingResumeParentRunId=null,this.pendingResumeItems=null,this.setError(void 0),this.events.messagesCleared()}async addToolResult(e){let t=this.clientToolsRef.current.get(e.tool);await this.addToolResultForClientTool(e,t,this.streamContinuationGeneration)}async addToolResultForClientTool(e,t,n,r){if(e.state!==`output-error`)try{let n=t?.outputSchema&&ps(t.outputSchema)?await this.validateClientToolOutput(t,e.output):e.output;this.interruptManager.getDescriptors().some(t=>t.toolCallId===e.toolCallId)&&(n=Z(n)),e={...e,output:n}}catch(t){e={...e,output:null,state:`output-error`,errorText:t.message}}this.events.toolResultAdded(e.toolCallId,e.tool,e.output,e.state||`output-available`,r),n===this.continuationGeneration&&(this.processor.addToolResult(e.toolCallId,e.output,e.state===`output-error`?e.errorText||`Tool execution failed`:void 0),this.devtoolsBridge.emitSnapshot(),!(e.state===`output-error`?this.interruptManager.resolveClientToolError(e.toolCallId,e.errorText||`Tool execution failed`):this.interruptManager.resolveClientToolOutput(e.toolCallId,e.output))&&(this.isLoading?this.queuePostStreamAction(()=>n===this.continuationGeneration?this.checkForContinuation():Promise.resolve()):await this.checkForContinuation()))}async validateClientToolOutput(e,t){let n=await ys(e.outputSchema,t);if(!n.success)throw Error(n.issues.map(e=>e.message).join(`, `));return n.data}queuePostStreamAction(e){let t=this.continuationGeneration;this.postStreamActions.push(async()=>{t===this.continuationGeneration&&await e()})}async drainPostStreamActions(){if(!this.draining){this.draining=!0;try{let e;for(;(e=this.postStreamActions.shift())!==void 0;)await e()}finally{this.draining=!1}}}async checkForContinuation(){if(this.streamContinuationGeneration===this.continuationGeneration&&!this.hasPendingInterrupts()){if(this.continuationPending||this.isLoading)this.continuationSkipped=!0;else if(this.shouldAutoSend()){this.continuationPending=!0,this.continuationSkipped=!1;let e=!1;try{e=await this.streamResponse()}finally{this.continuationPending=!1}this.continuationSkipped&&e&&(this.continuationSkipped=!1,await this.checkForContinuation())}}}shouldAutoSend(){if(this.lastResume||this.activeInterruptSubmission&&this.hasPendingInterrupts()||this.interruptManager.getInterrupts().length>0)return!1;let e=this.processor.getMessages().findLast(e=>e.role===`assistant`);return!e||!e.parts.some(e=>e.type===`tool-call`)?!1:this.processor.areAllToolsComplete()}getMessages(){return this.processor.getMessages()}getSubagents(){return[...this.subagentHandles.values()]}devtoolsSnapshotQueued=!1;queueDevtoolsSnapshot(){this.devtoolsSnapshotQueued||(this.devtoolsSnapshotQueued=!0,queueMicrotask(()=>{this.devtoolsSnapshotQueued=!1,this.devtoolsBridge.emitSnapshot()}))}syncSubagentHandles(){let e=e=>{let{input:t,...n}=e,r=Gs(n.metadata);return r===void 0?n:{...n,input:r}},t=cf(this.processor.getMessages()),n=new Set(t.map(e=>e.subagent.id));for(let e of this.subagentHandles.keys())n.has(e)||this.subagentHandles.delete(e);for(let n of t){let t=n.subagent.id,r=this.subagentHandles.get(t);if(r){if(n.subagent===r)continue;let{stop:t}=r;for(let e of Object.keys(r))Reflect.deleteProperty(r,e);Object.assign(r,e(n.subagent),{stop:t}),n.subagent=r;continue}let i={...e(n.subagent),stop:()=>{this.stopSubagent(t)}};this.subagentHandles.set(t,i),n.subagent=i}}stopSubagent(e){let t=this.subagentHandles.get(e);t&&t.status===`running`&&(this.stoppedSubagentIds.add(e),this.processor.processChunk({type:X.SUBAGENT_ERROR,subagentRunId:e,message:`Stopped`,timestamp:Date.now()}),this.syncSubagentHandles(),t.status=`error`,t.error={message:`Stopped`},this.abortController?.abort())}getHasOlderMessages(){return this.hasOlderMessages}async loadOlderMessages(){let e=this.connection.hydrate;if(e===void 0||this.disposed||!this.hasOlderMessages)return;let t=this.olderMessagesCursor;if(t===void 0||this.loadOlderMessagesInFlight)return;let n={before:t};this.historyPageSize!==void 0&&(n.limit=this.historyPageSize),this.loadOlderMessagesInFlight=!0;let r=this.historyGeneration;try{let t=await e(this.threadId,n);if(this.disposed||r!==this.historyGeneration)return;let i=zo(t.messages);if(i.length===0)throw Error(`Older page was empty`);this.applyHydrationPage(t.page),this.processor.prependMessages(i),this.rememberServerMessageIds(i)}finally{this.loadOlderMessagesInFlight=!1}}setHasOlderMessages(e){ko(this.snapshotAtom,{hasOlderMessages:e})}resetHistoryPaging(){this.setHasOlderMessages(!1),this.olderMessagesCursor=void 0,this.knownServerMessageIds.clear(),this.historyGeneration++}applyHydrationPage(e){e?.truncated===!0?(this.setHasOlderMessages(!0),this.olderMessagesCursor=e.cursor):(this.setHasOlderMessages(!1),this.olderMessagesCursor=void 0)}rememberServerMessageIds(e){let t=e.map(e=>e.id);for(let e of t)this.knownServerMessageIds.add(e)}rememberProcessorMessageIds(){this.historyPageSize!==void 0&&this.rememberServerMessageIds(this.processor.getMessages())}messagesForSend(e){let t=e.filter(e=>e.role!==`activity`);if(this.historyPageSize===void 0)return t;let n=[];for(let e of t)this.knownServerMessageIds.has(e.id)||n.push(e);if(n.length>0)return n;let r=t.findLastIndex(e=>e.role===`user`);return r===-1?[]:t.slice(r)}shouldAbortMessageQueueDrain(){return this.isLoading||this.stopMessageQueueDrain}async drainQueue(){if(!(this.messageQueueDraining||this.isLoading||this.messageQueue.length===0)){this.messageQueueDraining=!0,this.stopMessageQueueDrain=!1;try{if(this.queueConfig.drain===`batch`){for(;this.messageQueue.length>0;){if(this.shouldAbortMessageQueueDrain())return;let e=this.messageQueue.splice(0);this.emitQueueChange();let t=ef(e);if(!await this.deliverMessage(t.content,t.body)||this.shouldAbortMessageQueueDrain())return}return}for(;this.messageQueue.length>0;){if(this.shouldAbortMessageQueueDrain())return;let e=this.messageQueue.shift();if(e===void 0||(this.emitQueueChange(),!await this.deliverMessage(e.content,e.body)||this.shouldAbortMessageQueueDrain()))return}}finally{this.messageQueueDraining=!1,this.stopMessageQueueDrain=!1}}}discardPendingSends(){this.sendInFlight=!1,this.flushQueue()}getQueue(){return this.messageQueue.map(({id:e,content:t,createdAt:n})=>({id:e,content:t,createdAt:n}))}emitQueueChange(){let e=this.getQueue();ko(this.snapshotAtom,{queue:this.freezeSnapshotQueue(e)}),this.callbacksRef.current.onQueueChange(e),this.devtoolsBridge.emitSnapshot()}cancelQueued(e){let t=this.messageQueue.findIndex(t=>t.id===e);t!==-1&&(this.messageQueue.splice(t,1),this.emitQueueChange())}flushQueue(){this.messageQueue.length!==0&&(this.messageQueue=[],this.emitQueueChange())}getIsLoading(){return this.isLoading}getStatus(){return this.status}getIsSubscribed(){return this.isSubscribed}getConnectionStatus(){return this.connectionStatus}getSessionGenerating(){return this.sessionGenerating}getIsHydrating(){return this.isHydrating}getError(){return this.error}setMessagesManually(e){this.processor.setMessages(sf(e)),this.devtoolsBridge.emitSnapshot()}updateOptions(e){if(e.connection!==void 0||e.fetcher!==void 0){let t=this.isSubscribed;this.isLoading?this.cancelInFlightStream({setReadyStatus:!0,abortSubscription:!0}):t&&this.abortSubscriptionLoop(),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.setConnectionStatus(`disconnected`);let n=Xd({connection:e.connection,fetcher:e.fetcher});this.connectionDrainsOnSend=Zd(n),this.connection=td(n),t&&this.subscribe()}if(e.forwardedProps!==void 0&&(this.forwardedPropsOption=e.forwardedProps),e.byok!==void 0&&(this.byok=e.byok),e.byokProvider!==void 0&&(this.byokProvider=e.byokProvider),`context`in e&&(this.context=e.context),e.tools!==void 0){this.interruptManager.updateTools(e.tools),this.clientToolsRef.current=/* @__PURE__ */ new Map;for(let t of e.tools)this.clientToolsRef.current.set(t.name,t);this.devtoolsBridge.notifyToolsChanged()}e.queue!==void 0&&(this.queueConfig=$d(e.queue)),e.onResponse!==void 0&&(this.callbacksRef.current.onResponse=e.onResponse),e.onChunk!==void 0&&(this.callbacksRef.current.onChunk=e.onChunk),e.onFinish!==void 0&&(this.callbacksRef.current.onFinish=e.onFinish),e.onError!==void 0&&(this.callbacksRef.current.onError=e.onError),e.onSubscriptionChange!==void 0&&(this.callbacksRef.current.onSubscriptionChange=e.onSubscriptionChange),e.onConnectionStatusChange!==void 0&&(this.callbacksRef.current.onConnectionStatusChange=e.onConnectionStatusChange),e.onSessionGeneratingChange!==void 0&&(this.callbacksRef.current.onSessionGeneratingChange=e.onSessionGeneratingChange),e.onHydratingChange!==void 0&&(this.callbacksRef.current.onHydratingChange=e.onHydratingChange),e.onQueueChange!==void 0&&(this.callbacksRef.current.onQueueChange=e.onQueueChange),e.onResumeStateChange!==void 0&&(this.callbacksRef.current.onResumeStateChange=e.onResumeStateChange),e.onRunIdChange!==void 0&&(this.callbacksRef.current.onRunIdChange=e.onRunIdChange),e.onInterruptStateChange!==void 0&&(this.callbacksRef.current.onInterruptStateChange=e.onInterruptStateChange),e.onCustomEvent!==void 0&&(this.callbacksRef.current.onCustomEvent=e.onCustomEvent)}dispose(){this.disposed=!0,this.unsubscribe(),this.devtoolsBridge.dispose(),this.devtoolsMounted=!1}};const pf=e=>`background:${e};color:#fff;border-radius:3px;padding:1px 5px`,mf=`${pf(`#7c3aed`)};font-weight:600`,hf={mount:`#7c3aed`,auth:`#be185d`,theme:`#8b5cf6`,send:`#2563eb`,run:`#0891b2`,stream:`#0e7490`,text:`#16a34a`,reasoning:`#64748b`,tool:`#d97706`,widget:`#db2777`,attachment:`#0d9488`,sandbox:`#0369a1`,questionnaire:`#9333ea`,status:`#475569`,error:`#dc2626`};function gf(e){if(e)return(e,t,n)=>{console.log(`%cAstralBeam%c ${(/* @__PURE__ */ new Date()).toISOString().slice(11,19)} %c${e}%c ${t}`,mf,`color:#94a3b8;font-weight:400`,pf(hf[e]),``,...n===void 0?[]:[n])}}function _f(){let e=crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function vf(e,t=!0){return{id:e.id,title:e.title,agentId:e.agent_id,version:e.version,role:e.role,writerActive:e.writer_active,hasMessages:t,updatedAt:e.updated_at}}function yf(e,t,n){return`saved:${e}:${t}${n?`:${n}`:``}`}async function bf(e,t,n,r=/* @__PURE__ */ new Map){let i=await jr(e,{page_size:100,...n?{page_after:n}:{}},t),a=i.pending_interactions.map(e=>({sourceMessageId:e.source_message_id,sourcePartId:e.source_part_id,responseTargetId:e.response_target_id,toolCallId:r.get(e.tool_call_id)===e.source_message_id?e.tool_call_id:yf(e.source_message_id,e.source_part_id,e.response_target_id),targetTenantUserId:e.target_tenant_user_id,targetClientId:e.target_client_id,executionLocation:e.execution_location}));return{...i,pendingInteractions:a}}function xf(e,t=[],n=/* @__PURE__ */ new Map){let r=[],i=/* @__PURE__ */ new Map;for(let a of e){if(a.role===`tool`){for(let e of a.parts){let t=i.get(yf(a.source_assistant_message_id,a.source_tool_part_id,a.response_target_id));t&&(t.output=e.output??null,Object.assign(t,{resultOutcome:e.outcome}),t.state=e.outcome===`succeeded`?`complete`:`error`)}continue}let e=a.parts.flatMap(e=>{let r=e.source;if(typeof e.type==`string`&&[`image`,`document`,`audio`,`video`].includes(e.type)&&r&&typeof r==`object`&&!Array.isArray(r)&&`type`in r&&r.type===`attachment`)return[{...e,source:{...r,type:`url`,value:``},fileId:`id`in r&&typeof r.id==`string`?r.id:void 0}];if(e.type!==`tool-call`||e.executionLocation===`provider`)return[e];let o=String(e.toolCallId),s=Array.isArray(e.targets)?e.targets.flatMap(e=>e&&typeof e==`object`&&!Array.isArray(e)&&`id`in e&&typeof e.id==`string`?[e.id]:[]):t.filter(t=>t.sourceMessageId===a.id&&t.sourcePartId===e.id).map(e=>e.responseTargetId);return(s.length?s:[void 0]).map(t=>{let r=yf(a.id,String(e.id),t),s={...e,savedToolTitle:e.declaration&&typeof e.declaration==`object`&&!Array.isArray(e.declaration)&&`title`in e.declaration&&typeof e.declaration.title==`string`?e.declaration.title:void 0,id:n.get(o)===a.id?o:r,upstreamToolCallId:o,applicationPartId:e.id,sourceMessageId:a.id,responseTargetId:t};return i.set(r,s),s})});r.push({id:a.id,role:a.role,parts:e,createdAt:new Date(a.created_at),metadata:{astralbeam:{state:a.state,authorTenantUserId:a.author_tenant_user_id}}})}return r}function Sf(e){return e.placementKey??e.agentId??`default`}function Cf(e,t){try{if(t===void 0)return globalThis.sessionStorage?.getItem(e)??void 0;t===null?globalThis.sessionStorage?.removeItem(e):globalThis.sessionStorage?.setItem(e,t)}catch{}}let wf;function Tf(e,t,n){if(!n){if(!wf)try{let e=`astralbeam:draft-session`;wf=globalThis.sessionStorage?.getItem(e)??_f(),globalThis.sessionStorage?.setItem(e,wf)}catch{wf??=_f()}n=`new:${wf}`}return JSON.stringify([e.replace(/\/+$/,``),t,n])}function Ef(e){return typeof e==`object`&&!!e&&`id`in e&&typeof e.id==`string`&&`name`in e&&typeof e.name==`string`&&`size`in e&&typeof e.size==`number`&&Number.isFinite(e.size)&&e.size>=0&&`mimeType`in e&&typeof e.mimeType==`string`&&`status`in e&&e.status===`ready`&&`fileId`in e&&typeof e.fileId==`string`&&(!(`kind`in e)||typeof e.kind==`string`&&[`image`,`pdf`,`text`,`data`,`office`].includes(e.kind))&&(!(`error`in e)||typeof e.error==`string`)}function Df(e,t,n,r,i=`draft`){if(!t)return``;let a=`astralbeam:${i}:${Tf(e,t,n)}`;try{if(r===void 0)return globalThis.localStorage?.getItem(a)??``;r?globalThis.localStorage?.setItem(a,r):globalThis.localStorage?.removeItem(a)}catch{}return``}function Of({apiUrl:e,identity:t,threadId:n,update:r,moveTo:i}){let a=()=>{if(!t)return[];let a=`astralbeam:attachments:${Tf(e,t,n)}`,o=e=>{let t=JSON.parse(globalThis.localStorage?.getItem(e)??`[]`);if(!Array.isArray(t)||!t.every(Ef))throw TypeError(`Stored attachment draft is invalid`);return t},s=o(a);if(r&&(s=r(s).filter(e=>e.status===`ready`&&e.fileId!==void 0)),i!==void 0){let n=`astralbeam:attachments:${Tf(e,t,i)}`;s=[...new Map([...o(n),...s].map(e=>[e.id,e])).values()],globalThis.localStorage?.setItem(n,JSON.stringify(s)),globalThis.localStorage?.removeItem(a)}else r&&(s.length?globalThis.localStorage?.setItem(a,JSON.stringify(s)):globalThis.localStorage?.removeItem(a));return s};return globalThis.navigator?.locks?navigator.locks.request(`astralbeam:attachment-drafts`,a):Promise.resolve().then(a)}function kf(e){return e?`~standard`in e?`jsonSchema`in e[`~standard`]?vs(e):{type:`object`}:e:{type:`object`,properties:{}}}async function Af(e,t){let n=await ys(e,t);return n.success?n.data??{}:null}const jf=Symbol(`Host tool was not executed`);function Mf(e,t,n,r,i){return[...Object.keys(e).length>0?[Nf(e,n)]:[],Pf(),...Ff(t,r,i)]}function Nf(e,t){return dl({name:`render_widget`,description:`Render one of the host application's own UI widgets inline in the conversation. The widget appears in the transcript at the point of the call, so prefer it over describing the same information in text. Available widgets:
|
|
146
146
|
`+Object.entries(e).map(([e,{description:t,parameters:n}])=>`- ${e}: ${t} Props schema: ${JSON.stringify(kf(n))}`).join(`
|
|
147
|
-
`),inputSchema:{type:`object`,properties:{widget:{type:`string`,enum:Object.keys(e),description:`Name of the widget to render.`},props:{type:`object`,description:`Props for the widget, matching its props schema.`}},required:[`widget`]}}).client((e,n)=>t(e,n?.toolCallId??``))}function Pf(){return dl({name:`ask_questionnaire`,description:`Ask the user a short structured questionnaire rendered inline in the chat. Use it when the next step genuinely depends on their choices instead of asking in prose. The call stays pending until the user submits; their answers arrive as the tool output. Skipped optional questions come back with an empty answers array. An output with skipped: true means the user dismissed the questionnaire by continuing the conversation instead — do not re-ask; address their next message.`,inputSchema:{type:`object`,properties:{items:{type:`array`,minItems:1,description:`Questions shown one at a time, in order.`,items:{type:`object`,properties:{name:{type:`string`,description:`Unique key identifying the question.`},title:{type:`string`,description:`The question itself.`},description:{type:`string`,description:`Optional helper text.`},required:{type:`boolean`,description:`Whether an answer is mandatory.`},multiple:{type:`boolean`,description:`Whether several choices may be selected.`},choices:{type:`array`,minItems:1,items:{type:`object`,properties:{value:{type:`string`},label:{type:`string`},description:{type:`string`}},required:[`value`,`label`]}},input:{type:`object`,description:`Optional free-form alternative to the fixed choices.`,properties:{label:{type:`string`},placeholder:{type:`string`}},required:[`label`,`placeholder`]}},required:[`name`,`title`,`choices`]}}},required:[`items`]}}).client()}function Ff(e,t,n){return Object.entries(e).map(([e,r])=>dl({name:e,description:r.description,inputSchema:kf(r.parameters),...r.metadata?{metadata:r.metadata}:{}}).client(async(i,a)=>{let o=!1;try{let s=n?.(e,r,a?.toolCallId);t?.(`tool`,`executing host tool "${e}"`,{input:i});let c=await Af(r.parameters,i??{});if(c==null)throw t?.(`error`,`input for host tool "${e}" failed schema validation`,{input:i}),Error(`Input for tool "${e}" failed schema validation`);a?.abortSignal?.throwIfAborted();let l=s?.()??r;o=!0;let u=await l.execute(c);try{os(u)}catch{throw Error(`Tool "${e}" ran, but its result is not JSON-compatible. Its changes may already be applied. Read current state before retrying. Return plain JSON values and omit undefined fields.`)}return t?.(`tool`,`host tool "${e}" returned`,{output:u}),u}catch(n){throw t?.(`error`,`host tool "${e}" threw`,{error:n}),!o&&n instanceof Error&&Object.assign(n,{[jf]:!0}),n}}))}function If(e){if(e.length>16384)throw Error(`The chat auth token is too large`);let{exp:t,iat:n,user:r}=ao(e);if(!Number.isInteger(t)||Number(t)<=0)throw Error(`The chat auth token has no valid expiry`);let i=Number(t)*1e3,a=n===void 0?3e5:i-n*1e3,o=Math.min(6e4,a*.2),s=r?.admin===!0;return{expiresAt:i,refreshAt:i-o,tenantAdmin:s}}async function Lf(e,t){let{fetchAstralBeamToken:n,fetchClient:r}=e;if(typeof n==`function`)return(await n())?.token;if(!n)throw Error(`Provide fetchAstralBeamToken.`);let{url:i,...a}=n,o=new Headers(a.headers);o.has(`accept`)||o.set(`accept`,`application/json`);let s=await r(i,{method:`POST`,credentials:`include`,cache:`no-store`,...a,headers:o,signal:a.signal?AbortSignal.any([t,a.signal]):t});if(!s.ok)throw Object.assign(/* @__PURE__ */ Error(`Authentication endpoint returned HTTP ${s.status}`),{status:s.status,headers:s.headers});return(await s.json())?.token}const Rf={status:`loading`};function zf(e){return{...e,fetchAstralBeamToken:e.fetchAstralBeamToken,session:{cached:void 0,refreshPromise:void 0,abortController:new AbortController,state:Rf,listeners:/* @__PURE__ */ new Set},fetchClient:globalThis.fetch.bind(globalThis),debug:void 0}}function Bf(e){return e.session.state}function Vf(e,t){let{listeners:n}=e.session;return n.add(t),()=>{n.delete(t)}}function Hf(e,t){e.session.state=t;for(let t of e.session.listeners)t()}function Uf(e,t){e.apiUrl!==t.apiUrl&&(Yf(e),e.session.abortController=new AbortController,Hf(e,{status:`loading`})),e.apiUrl=t.apiUrl,e.fetchAstralBeamToken=t.fetchAstralBeamToken}function Wf(e,t){return JSON.stringify([e.scope,e.organization.id,e.scope===`tenant`?e.tenant.id:null,e.user.id,t===void 0?null:e.scope===`tenant`?t:e.user.role])}async function Gf(e){let{session:t,debug:n,apiUrl:r}=e,{signal:i}=t.abortController,a=typeof e.fetchAstralBeamToken==`function`?`fetchAstralBeamToken`:`Authentication endpoint`;try{for(let o=0;o<2;o++){let s=await Lf(e,i);if(i.throwIfAborted(),typeof s!=`string`||!s)throw Error(`${a} did not return a token`);let{expiresAt:c,refreshAt:l,tenantAdmin:u}=If(s);if(c<=Date.now())throw Error(`${a} returned an expired token`);if(!Number.isFinite(l)||l<=Date.now()||c-Date.now()<5e3)throw Error(`${a} returned a token too close to expiry`);let d;try{d=await Pr({apiUrl:r,astralBeamToken:s,fetchClient:e.fetchClient,signal:i,cache:`no-store`,credentials:`omit`})}catch(t){if(!o&&e.retryUnauthorized!==!1&&or(t)&&t.status===401)continue;throw t}if(i.throwIfAborted(),e.scope&&e.scope!==d.scope)throw Error(`Expected ${e.scope} authentication`);return t.cached={value:s,expiresAt:c,refreshAt:l,synchronizedAt:Date.now(),tenantAdmin:u},Hf(e,{status:`ready`,currentUser:d}),n?.(`auth`,`authentication ready`,{expiresAt:new Date(c)}),s}throw Error(`Authentication failed`)}catch(n){i.throwIfAborted();let r=n instanceof Error?n:/* @__PURE__ */ Error(`Authentication failed`);throw or(r)&&r.status===401&&(r.message=`AstralBeam rejected the chat token after renewal. Check that apiUrl matches the deployment that issued your API key. If the key was revoked or expired, create a replacement in API Keys and update your server's secret.`),t.cached=void 0,Hf(e,{status:`error`,error:r}),r}}async function Kf(e){let{session:t,force:n=!1}=e;if(t.abortController.signal.throwIfAborted(),t.refreshPromise)return await t.refreshPromise;if(!n&&t.cached&&t.cached.refreshAt>Date.now())return t.cached.value;(!t.cached||t.cached.expiresAt<=Date.now())&&Hf(e,{status:`loading`});let r=Gf(e);t.refreshPromise=r;try{return await r}finally{t.refreshPromise===r&&(t.refreshPromise=void 0)}}function qf(e,t){let n=!t||e.session.cached?.value===t;return n&&(e.session.cached=void 0),Kf({...e,force:n,retryUnauthorized:!1})}async function Jf(e){e.session.abortController.signal.aborted&&(e.session.abortController=new AbortController),await Kf(e)}function Yf({session:e}){e.abortController.abort(),e.refreshPromise=void 0,e.cached=void 0,e.state=Rf}async function Xf(e){let{input:t,init:n,session:r,fetchClient:i,debug:a}=e,o=Bf(e),s=await i(t,n);if(s.status!==401||r.abortController.signal.aborted)return s;let c=new Headers(n?.headers),l=c.get(`authorization`),u=l?.startsWith(`Bearer `)?l.slice(7):void 0;a?.(`auth`,`chat auth token was rejected; refreshing once`),await s.body?.cancel();let d=await qf(e,u),f=Bf(e);if(o.status!==`ready`||f.status!==`ready`||Wf(o.currentUser)!==Wf(f.currentUser))throw new DOMException(`Identity changed`,`AbortError`);return n?.signal?.throwIfAborted(),c.set(`authorization`,`Bearer ${d}`),await i(t,{...n,headers:c})}function Zf(e){let t,n=new AbortController,r=0,i=()=>typeof document>`u`||document.visibilityState!==`hidden`&&globalThis.navigator?.onLine!==!1,a=()=>{!n.signal.aborted&&i()&&Kf({...e,force:!0}).catch(()=>{})},o=()=>{if(clearTimeout(t),n.signal.aborted||typeof document>`u`||!i())return;let o=Bf(e);if(o.status===`ready`)r=0,t=setTimeout(a,Math.max(1e3,e.session.cached.refreshAt-Date.now()));else if(o.status===`error`&&r<3){let e=o.error;if(e.status!==void 0&&e.status!==429&&e.status<500||e.status===void 0&&!(e instanceof TypeError))return;let n=e.headers?.get(`retry-after`),i=n?/^\d+$/.test(n)?Number(n)*1e3:Date.parse(n)-Date.now():0;t=setTimeout(a,Math.max(1e3*2**r++,Number.isFinite(i)?i:0))}},s=()=>{if(!i()){clearTimeout(t);return}let n=e.session.cached;!n||Date.now()-n.synchronizedAt>=6e4||n.refreshAt<=Date.now()?a():o()},c=Vf(e,o);if(typeof document<`u`){for(let e of[`focus`,`online`,`offline`])globalThis.addEventListener(e,s,{signal:n.signal});document.addEventListener(`visibilitychange`,s,{signal:n.signal})}return Jf(e).catch(()=>{}),o(),()=>{n.abort(),clearTimeout(t),c()}}async function Qf(e,t){switch(e.action){case`connect`:return Rr({mcp_server_id:e.mcpServerId},t);case`headers`:{let n=await Rr({mcp_server_id:e.mcpServerId},t);return await Br(n.id,{lock_version:n.lock_version,headers:e.headers},t),{id:n.id}}case`disconnect`:return Hr(e.id,t);case`test`:return Wr(e.id,t)}}async function $f(e,t){let n=window.open(`about:blank`,`_blank`,`popup,width=600,height=720`);if(!n)throw Error(`Allow popups to authorize this connection.`);try{let r=e.id??(await Rr({mcp_server_id:e.mcpServerId},await t())).id,i=await Kr(r,await t()),a={organizationId:i.attempt.organization_id,tenantId:i.attempt.tenant_id,connectionId:i.attempt.connection_id,id:i.attempt.id},o=new URL(i.popup_url);return o.searchParams.set(`origin`,window.location.origin),await new Promise((e,i)=>{let s,c=!1,l=!1,u=!1,d=()=>{l=!0,window.removeEventListener(`message`,m),clearInterval(h),clearTimeout(g)},f=e=>{d(),i(e instanceof Error?e:/* @__PURE__ */ Error(`Authorization failed.`))},p=async()=>{if(!(u||l)){u=!0;try{if(s){if(c||=(await Jr(r,{attempt_id:a.id,challenge:s},await t()),!0),l)return;let n=await Xr(r,{attempt_id:a.id},await t());if(l)return;if(n){d(),e();return}}n.closed&&f(/* @__PURE__ */ Error(`Authorization window closed.`))}catch(e){let t=e instanceof Error?e.status:void 0;!(e instanceof TypeError)&&t!==429&&(t??0)<500&&f(e)}finally{u=!1}}},m=e=>{if(e.source!==n||e.origin!==o.origin)return;let t=e.data;t?.attempt&&t.attempt.id===a.id&&t.attempt.organizationId===a.organizationId&&t.attempt.tenantId===a.tenantId&&t.attempt.connectionId===a.connectionId&&t.type===`mcp-browser-challenge`&&!s&&typeof t.challenge==`string`&&(s=t.challenge,p())},h=setInterval(()=>void p(),5e3),g=setTimeout(()=>f(/* @__PURE__ */ Error(`Authorization expired. Try connecting again.`)),6e5);window.addEventListener(`message`,m),n.location.replace(o.href)}),r}finally{n.close()}}function ep(e){return e.state===`complete`||e.state===`error`||e.output!==void 0}function tp(e){return e.metadata??{}}function np(e,t){return typeof e==`object`&&e&&t in e?e[t]:void 0}function rp(e,t){let n=np(e,t);return typeof n==`string`?n:void 0}function ip(e,t){let n=np(e,t);return typeof n==`number`?n:void 0}function ap(e){return rp(e.output,`refusal`)}function op(e){if(e.name!==`sandbox_write_file`)return;let t=rp(e.output,`path`)??rp(e.input,`path`);if(t===void 0)return;let n=rp(e.input,`content`)??``;return{toolCallId:e.id,path:t,label:sp(e)??t,content:n,lines:n.length===0?0:n.split(`
|
|
148
|
-
`).length,written:e.output!=null&&ap(e)===void 0}}function sp(e){let t=rp(e.output,`relativePath`);return t!==void 0&&t!==`.`?t:rp(e.output,`path`)??rp(e.input,`path`)}function cp(e){if(e.name!==`sandbox_run_command`)return;let t=rp(e.input,`command`);if(t===void 0)return;let n=e.output;return{toolCallId:e.id,command:t,cwd:rp(e.input,`cwd`),exitCode:ip(n,`exitCode`),stdout:rp(n,`stdout`)??``,stderr:rp(n,`stderr`)??``,durationMs:ip(n,`durationMs`),timedOut:np(n,`timedOut`)===!0,truncated:np(n,`truncated`)===!0,finished:n!=null}}function lp(e){let t=/* @__PURE__ */ new Map,n=[];for(let r of e)for(let e of r.parts){if(e.type!==`tool-call`)continue;let r=op(e);r?.written&&t.set(r.path,r);let i=cp(e);i&&ap(e)===void 0&&n.push(i)}return{files:[...t.values()],commands:n}}const up=`Reopen this conversation or start a new one before sending.`;function dp(e,t){return e.length===t.length&&e.every((e,n)=>e.name===t[n]?.name&&e.title===t[n]?.title)}function fp(e,t=!1){let n={...e},r=gf(n.debug),i=/* @__PURE__ */ new Set,a,o=()=>a?.options??n,s={messages:[],status:`ready`,error:void 0,auth:{status:`loading`},capabilities:{attachments:!0},agentTools:[],sandboxStatus:void 0,usageLimitReached:void 0,sandbox:{files:[],commands:[]},thread:void 0,history:`idle`,messagesCursor:void 0,olderMessagesLoading:!1,submission:void 0,activeToolCallIds:[],pendingInteractions:[]},c,l=/* @__PURE__ */ new Map,u=`ready`,d,f=e=>{let t=d||c?.phase===`submitting`?u===`streaming`||s.status===`streaming`?`streaming`:`submitted`:u;s={...s,...e,status:t};for(let e of i)e()},p=e=>{d===e&&(d=void 0,f({}))},m=({id:e,content:t,phase:n,error:r})=>({id:e,content:t,phase:n,...r?{error:r}:{}}),h={submitting:[`accepted`,`failed`,`refused`],failed:[`submitting`],accepted:[],refused:[]},g=(e,t,n)=>h[e.phase].includes(t)?(e.phase=t,e.error=n,e===c&&f({submission:m(e)}),!0):!1,ee=(e,t)=>e===c&&d===t,_=(e,t)=>ee(e,t)&&e.phase===`submitting`,te=(e,t)=>g(e,e.tools?`failed`:`refused`,t??(e.tools?/* @__PURE__ */ Error(`This message may not have been sent. Retry to send it.`):void 0)),v=e=>{let t=c;return t?.phase===`submitting`&&te(t,t.tools?void 0:Error(e)),t?.phase===`refused`&&t.onRefused?.(),c=void 0,t},y=zf({apiUrl:n.apiUrl,scope:`tenant`,fetchAstralBeamToken:n.fetchAstralBeamToken??{url:`/api/astralbeam/token`}}),ne,re,b,x=!1,S=0,ie=0,C=0,ae=Promise.resolve(),oe=new AbortController,w,se=!1,ce=[],le=/* @__PURE__ */ new Map,ue=0,de=/* @__PURE__ */ new WeakMap,fe=e=>{for(let t of e){if(t.role!==`user`||le.get(t.id)?.attachmentParts||!t.parts.some(e=>`fileId`in e))continue;let e=t.parts.map(e=>Object.freeze({...e}));Object.freeze(e),le.set(t.id,{...le.get(t.id),attachmentParts:e}),ue++}},pe=_f(),T=()=>{c&&g(c,`accepted`)&&(s.thread&&f({thread:{...s.thread,hasMessages:!0}}),c.callbacks?.onAccepted?.())},me=e=>{let t=[...j.getSnapshot().messages],n=t.findLastIndex(e=>e.role===`user`);n!==-1&&(t[n]=xf([e])[0],fe([t[n]]),j.setMessagesManually(t),Be&&M())},he=/* @__PURE__ */ new Set,E=/* @__PURE__ */ new Map,ge=/* @__PURE__ */ new Map,D=/* @__PURE__ */ new Map,_e=/* @__PURE__ */ new Map,ve=e=>{let t=E.get(e);return t?`live:${t}:${e}`:e},ye=e=>{let t=/* @__PURE__ */ new Map;for(let n of e.pending_interactions){let e=`live:${n.source_message_id}:${n.tool_call_id}`,r=yf(n.source_message_id,n.source_part_id,n.response_target_id),i=D.get(e)??D.get(r);i&&(t.set(r,i),E.get(n.tool_call_id)===n.source_message_id&&t.set(e,i))}D.clear();for(let[e,n]of t)D.set(e,n)},O=e=>{(s.auth.status!==`error`||s.auth.error!==e)&&n.streamCallbacks?.onError?.(e)},be=e=>{if(e instanceof Error&&e.name===`AbortError`)return;let t=e instanceof Error?e:Error(String(e));f({error:t}),O(t)},xe=e=>{f({unavailableMcpConnections:s.unavailableMcpConnections?.filter(t=>t!==e)??[]})},k=async(e=!0)=>{let t=S,n=y.session.abortController.signal,r=await Kf(y);if(n.throwIfAborted(),e&&t!==S)throw new DOMException(`Conversation changed`,`AbortError`);return{apiUrl:y.apiUrl,astralBeamToken:r,cache:`no-store`,signal:e?AbortSignal.any([oe.signal,n]):n,fetchClient:(e,t)=>Xf({...y,input:e,init:t})}},Se=0,Ce,we=async()=>{let e=++Se,t=S;if(s.thread?.agentId===null){f({capabilities:{attachments:!1}});return}let i=s.thread?s.thread.agentId:n.agentId;try{let n=await k();if(e!==Se||t!==S)return;let a=await xr(i?{agentId:i}:{},n);if(e!==Se||t!==S)return;let o=a.capabilities?.attachments!==!1;f({capabilities:{attachments:o}}),r?.(`mount`,`agent capabilities resolved`,{attachments:o})}catch(e){r?.(`error`,`agent capabilities could not be resolved; keeping the defaults`,e)}},Te=/* @__PURE__ */ new Map,Ee=/* @__PURE__ */ new Set,De=/* @__PURE__ */ new Set,Oe=0,A=()=>{Oe++;for(let e of Te.values())e();Te.clear(),Ee.clear(),De.clear()},ke=async(e,t)=>{if(!o().onRenderWidget)return{widget:e.widget,rendered:!1};let n=S,r=Oe,i=o().widgets??{};if(!Object.hasOwn(i,e.widget))throw Error(`Unknown widget "${e.widget}"`);let a=i[e.widget],c=await Af(a?.parameters,e.props??{});if(n!==S||r!==Oe||s.thread?.role===`viewer`)return{widget:e.widget,rendered:!1};if(a!==o().widgets?.[e.widget])return ke(e,t);if(c==null)throw Error(`Props for widget "${e.widget}" failed validation`);let l=o().onRenderWidget;if(!l)return{widget:e.widget,rendered:!1};Te.get(t)?.(),Te.delete(t);let u,d=l({widget:e.widget,props:c,toolCallId:t,release:()=>{Te.get(t)===u&&Te.delete(t)}});return d&&(u=d,Te.set(t,d)),Ee.add(t),{widget:e.widget,rendered:!0}},Ae=e=>Object.freeze(e.map(e=>{let t=le.get(e.id),n=de.get(e);if(n&&n.presentation===t)return n.message;let r=t?.attachmentParts??e.parts,i=t?.renderIds,a=r.map(t=>{if(t.type!==`tool-call`||t.name!==`render_widget`||t.state!==`complete`||!t.input)return t;let n=t,r=yf(e.id,t.id),a=n.applicationPartId?yf(e.id,n.applicationPartId,n.responseTargetId):r,o=n.upstreamToolCallId,s=n.widgetRenderId??i?.get(r)??i?.get(a)??(o&&E.get(o)===e.id&&Ee.has(o)?o:t.id);return(i?.get(r)!==s||i.get(a)!==s)&&(i=new Map(i).set(r,s).set(a,s)),n.widgetRenderId===s?t:Object.freeze({...t,widgetRenderId:s})});a.some((e,t)=>e!==r[t])&&(Object.freeze(a),r=a),i&&i!==t?.renderIds&&(t={...t,renderIds:i},le.set(e.id,t),ue++);let o=r===e.parts?e:Object.freeze({...e,parts:r});return de.set(e,{presentation:t,message:o}),o})),je=e=>{if(s.thread?.role!==`viewer`)for(let t of e)for(let e of t.parts){if(e.type!==`tool-call`||e.name!==`render_widget`||e.state!==`complete`||!e.input)continue;let t=e.widgetRenderId??e.id;if(Ee.has(t)||De.has(t))continue;De.add(t);let n=S,i=Oe,{widgets:a,onRenderWidget:c}=o();ke(e.input,t).catch(e=>r?.(`error`,`Saved widget could not be rendered`,e)).finally(()=>{n===S&&i===Oe&&(De.delete(t),(a!==o().widgets||c!==o().onRenderWidget)&&je(s.messages))})}},Me=()=>{let e=S;return Mf(o().widgets??{},n.tools??{},ke,r,(t,r,i)=>{let a=ie,o=j,c=b,l=y.apiUrl;return()=>{let u=n.tools&&Object.hasOwn(n.tools,t)?n.tools[t]:void 0;if(e!==S||a!==ie||o!==j||c!==b||l!==y.apiUrl||s.thread?.role===`viewer`||!i||!he.has(i)||!u||u.parameters!==r.parameters)throw new DOMException(`Host tool authority changed`,`AbortError`);return u}}).map(e=>{if(!e.execute)return e;let t=e.execute;return{...e,execute:async(e,n)=>{let r=n?.toolCallId;if(!r||!he.has(r))throw Error(`A saved tool call cannot execute again. Send a new message to request it.`);let i=D,a=ve(r),o=b,s=y.apiUrl;try{let r=await t(e,n);return b===o&&y.apiUrl===s&&i.set(a,{outcome:`succeeded`,output:r??null}),r}catch(e){throw!(e instanceof Error&&jf in e)&&b===o&&y.apiUrl===s&&i.set(a,{outcome:`unknown`,output:{error:e instanceof Error?e.message:String(e)}}),e}}}})},Ne=()=>{let e=Me(),t=e.map(e=>{let t=e.metadata?.title;return{name:e.name,title:typeof t==`string`&&t.length>0?t:void 0}});return dp(s.agentTools,t)||f({agentTools:t}),e},Pe=()=>n.debug?{debug:!0}:{},Fe=async(e,t)=>{let n=s.thread;if(!n||typeof e.body!=`string`)throw Error(`Open a conversation before sending.`);let r=S,i=JSON.parse(e.body),a=yr(),o,l=i.messages.at(-1)?.role===`user`&&c?.phase===`submitting`?c:void 0,u=l?.tools!==void 0;if(l)o={...i,threadId:n.id,resume:void 0,parentRunId:void 0,messages:[i.messages.at(-1)],tools:l.tools??=i.tools,forwardedProps:{...i.forwardedProps,clientId:pe}};else{Ge();let e=await bf(n.id,t,void 0,E);if(r!==S)throw new DOMException(`Conversation changed`,`AbortError`);f({thread:vf(e.thread,e.messages.length>0)}),ye(e);let s=e.pendingInteractions.filter(e=>D.has(ve(e.toolCallId))),c=s.find(e=>e.toolCallId===i.messages.at(-1)?.toolCallId)??s[0],l=e.pendingInteractions.flatMap(e=>{let t=D.get(ve(e.toolCallId));return t&&e.sourceMessageId===c?.sourceMessageId?[{source_message_id:e.sourceMessageId,source_part_id:e.sourcePartId,response_target_id:e.responseTargetId,...t}]:[]});if(l.length===0)return new Response(``,{headers:{"Content-Type":`text/event-stream`}});a=Mr(n.id),o={client_id:pe,run_id:i.runId,...i.parentRunId?{parent_run_id:i.parentRunId}:{},results:l}}he.clear(),f({activeToolCallIds:[]});let d=new Headers(e.headers);l&&d.set(`Idempotency-Key`,l.key);let p=await fr(a,{...t,...e,headers:d,body:JSON.stringify(o)}).catch(e=>{let t=or(e)?e.body?.usage_limit:void 0;throw t&&f({usageLimitReached:{name:t.name,resetsAt:t.resets_at}}),l&&!u&&or(e)&&(e.status===400||e.status===413||e.status===429)&&delete l.tools,e});if(r!==S)throw new DOMException(`Conversation changed`,`AbortError`);if(p.headers.get(`Content-Type`)?.includes(`application/json`)){let e=await p.json();if(r!==S)throw new DOMException(`Conversation changed`,`AbortError`);if(f({thread:{...s.thread,version:e.thread_version},...e.usage_limit?{usageLimitReached:{name:e.usage_limit.name,resetsAt:e.usage_limit.resets_at}}:{}}),l){let i=await bf(n.id,t,void 0,E);if(r!==S)throw new DOMException(`Conversation changed`,`AbortError`);let a=i.messages.find(t=>t.id===e.accepted_message_id);a&&me(a),T()}return new Response(``,{headers:{"Content-Type":`text/event-stream`}})}return p},Ie=rd(()=>sr(yr(),y.apiUrl),async()=>{let e=b,t=await Kf(y);if(e!==void 0&&e!==b)throw new DOMException(`Identity changed`,`AbortError`);return{fetchClient:(e,n)=>{let r={apiUrl:y.apiUrl,astralBeamToken:t,...n?.signal?{signal:n.signal}:{},cache:`no-store`,fetchClient:(e,t)=>Xf({...y,input:e,init:t})};return Fe(n??{},r)}}}),Le=Ie.connect;Ie.connect=async function*(...e){try{for await(let t of Le(...e)){if(t.type===X.TOOL_CALL_START&&t.parentMessageId&&E.set(t.toolCallId,t.parentMessageId),t.type!==X.MESSAGES_SNAPSHOT){yield t;continue}let e;yield{...t,messages:t.messages.map(t=>t.role===`assistant`?(e=ge.get(t.id),e&&t.toolCalls?{...t,toolCalls:t.toolCalls.map(t=>({...t,id:e?.get(t.id)??t.id}))}:t):t.role===`tool`?{...t,toolCallId:e?.get(t.toolCallId)??t.toolCallId}:(e=void 0,t))}}}catch(e){throw e instanceof Error&&or(e.cause)?e.cause:e}};let Re=()=>{let e=new ff({connection:{...Ie,hydrate:(t,n)=>{let r=ze;if(!r)return Promise.resolve({messages:[],activeRun:null,interrupts:null,page:{truncated:!1}});let i=n?.before!==void 0,a=i?C:++C;n?.before||f({olderMessagesLoading:!1,history:s.messages.length>0||s.thread?.hasMessages===!1?`refreshing`:`loading`});let o=(async()=>{let t=await bf(r,await k(),n?.before,E);for(;n?.before&&t.messages.every(e=>e.role===`tool`)&&t.page_after;){let e=await bf(r,await k(),t.page_after,E);t={...e,messages:[...e.messages,...t.messages]}}if(j!==e||a!==C)throw new DOMException(`Conversation changed`,`AbortError`);i||ye(t),ce=i?[...t.messages,...ce]:t.messages;let o=new Set(t.messages.map(e=>e.id)),c=xf(ce,i?s.pendingInteractions:t.pendingInteractions,E).filter(e=>o.has(e.id));if(fe(c),i)f({messagesCursor:t.page_after??void 0});else{t.thread.role===`viewer`&&A();let n=s.thread?.agentId!==t.thread.agent_id;f({thread:vf(t.thread,t.messages.length>0),messagesCursor:t.page_after??void 0,pendingInteractions:t.pendingInteractions}),n&&we(),c.length===0&&e.setMessagesManually([])}return{messages:c,activeRun:null,interrupts:null,page:t.page_after?{truncated:!0,cursor:t.page_after}:{truncated:!1}}})();return i||(ae=o.then(()=>`idle`,()=>`failed`).then(t=>new Promise(n=>queueMicrotask(()=>{j===e&&a===C&&(Be&&M(),f({history:t})),n()}))).then(()=>o),ae.catch(()=>void 0)),o}},threadId:ze??pe,persistence:!0,history:{pageSize:100},queue:`drop`,tools:Ne(),forwardedProps:Pe(),onInterruptStateChange:t=>{j===e&&r?.(`tool`,`interrupt state changed`,t)},onCustomEvent:(t,n)=>{if(j!==e)return;if(t===`astralbeam_thread`){let e=n;if(s.thread?.id===e.threadId){if(e.acceptedMessage&&c?.phase===`submitting`&&me(e.acceptedMessage),e.acceptedMessageId&&T(),e.saved)for(let t of e.executableToolCallIds??[])he.has(t)||D.delete(ve(t)),he.add(t);f({thread:{...s.thread,version:e.version},activeToolCallIds:[...he]})}return}if(t===`astralbeam_mcp_tools`){let e=n,t={};for(let n of e.tools??[])typeof n.name==`string`&&typeof n.title==`string`&&(t[n.name]=n.title);f({serverToolTitles:t,unavailableMcpConnections:e.unavailable??[]});return}let i=n;if(t===`astralbeam.usage_limit.reached`&&typeof i?.name==`string`&&typeof i.resetsAt==`string`){f({usageLimitReached:{name:i.name,resetsAt:i.resetsAt}});return}let a=n?.state;t===`astralbeam.sandbox.status`&&(a===`starting`||a===`ready`||a===`error`)?(r?.(`sandbox`,`sandbox ${a}`),f({sandboxStatus:a})):r?.(`stream`,`custom event "${t}"`,n)},onChunk:t=>{j===e&&(t.type===X.RUN_STARTED&&f({serverToolTitles:{},unavailableMcpConnections:[]}),n.streamCallbacks?.onChunk?.(t))},onResponse:t=>{j===e&&n.streamCallbacks?.onResponse?.(t)},onFinish:t=>{j===e&&n.streamCallbacks?.onFinish?.(t)},onError:t=>{j===e&&(c?.phase!==`submitting`&&t.name!==`AbortError`&&f({error:t}),O(t))}});return e},ze,j=Re(),Be,Ve,He=-1,M=()=>{let e=j.getSnapshot(),t=Ve!==e.messages||He!==ue;if(!t&&u===e.status)return;let n={};u!==e.status&&e.status===`submitted`&&(n.usageLimitReached=void 0),u=e.status,t&&(n.messages=Ae(e.messages),n.sandbox=lp(n.messages),Ve=e.messages,He=ue),f(n),t&&je(s.messages)},Ue=()=>{if(!Be){let e=j,t=S;Be=e.subscribeSnapshot(()=>{j===e&&t===S&&M()}),M(),je(s.messages)}j.attach()},We=e=>{let t=j;d=void 0,Be?.(),Be=void 0,Ve=void 0,j=Re(),e&&j.setMessagesManually(e),u=`ready`,t.stop(),t.detach(),he.clear(),f({activeToolCallIds:[]}),x&&Ue(),t.dispose()},Ge=()=>{ge.clear(),j.setMessagesManually(j.getSnapshot().messages.map(e=>{let t=/* @__PURE__ */ new Map,n=e.parts.map(n=>{if(n.type!==`tool-call`||tp(n).providerExecuted)return n;let r=n,i=r.upstreamToolCallId??n.id;if(E.get(i)===e.id&&!ep(n))return n;let a=yf(e.id,r.applicationPartId??i,r.responseTargetId);return t.set(i,a),{...n,upstreamToolCallId:i,id:a,...n.name===`render_widget`?{widgetRenderId:r.widgetRenderId??le.get(e.id)?.renderIds?.get(yf(e.id,n.id))??n.id}:{}}});return t.size&&ge.set(e.id,t),{...e,parts:n}}))},Ke=e=>{let t=s.thread?.id,n=v(`The conversation changed before this was sent.`);t&&(n?.phase===`failed`?l.set(t,n):l.delete(t),_e.set(t,D)),S++,ze=e,oe.abort(),oe=new AbortController,D=_e.get(e??``)??/* @__PURE__ */ new Map,ge.clear(),E.clear(),ce=[],le.clear(),de=/* @__PURE__ */ new WeakMap,ue++,A(),f({thread:void 0,messages:[],submission:void 0,error:void 0,sandbox:{files:[],commands:[]},sandboxStatus:void 0,usageLimitReached:void 0,pendingInteractions:[],serverToolTitles:{},unavailableMcpConnections:[],history:`idle`,messagesCursor:void 0,olderMessagesLoading:!1}),We()},qe=async(e,t=!1)=>{Ke(e);let r=S;c=l.get(e),c&&f({submission:m(c)});try{if(x||Ue(),await ae,r!==S)return;w&&Cf(w,e)}catch(e){if(r!==S)return;t&&(n.threadId===void 0||n.threadId===`auto`)&&or(e)&&e.status===404?Je():be(e)}},Je=()=>{Ke(),x&&we(),w?Cf(w,null):se=!0},Ye=(e=!1)=>{let t=n.threadId;if(t===void 0||t===`auto`){if(!w)return;t=Cf(w)}t&&t!==`new`?t===s.thread?.id&&w?Cf(w,t):qe(t,e):e||Je()},Xe=async(e,t)=>{if(s.thread)return;let r=await k(),i=await Cr(n.agentId?{agent_id:n.agentId}:{},r);if(!_(e,t))throw new DOMException(`Send cancelled`,`AbortError`);ze=i.id,f({thread:vf(i,!1)}),we(),w&&Cf(w,i.id)},Ze=async(e=!0)=>{if(!s.thread)return;let t=S;try{j.detach(),Ue(),await ae,e&&t===S&&f({error:void 0})}catch(e){if(t!==S)return;or(e)&&e.status===404?Je():be(e)}},Qe=async()=>{if(!j.getHasOlderMessages()||s.olderMessagesLoading||s.history!==`idle`||c?.phase===`submitting`)return;let e=S;f({olderMessagesLoading:!0});try{await j.loadOlderMessages(),e===S&&Be&&M()}catch(t){e===S&&be(t)}finally{e===S&&f({olderMessagesLoading:!1})}},$e=async e=>{let t=s.thread;if(!t||t.role!==`manager`)return!1;let n=S;try{let r=await Dr(t.id,{title:e,expected_version:t.version},await k());if(n!==S)return!1;let i=vf(r,t.hasMessages);return f({thread:i}),!0}catch(e){return n===S&&be(e),!1}},et=async(e=s.thread)=>{if(!e||e.role!==`manager`)return!1;let t=S;try{return await kr(e.id,{expected_version:String(e.version)},await k()),t===S&&s.thread?.id===e.id&&Je(),!0}catch(e){return t===S&&be(e),!1}},N=async e=>{let t=S;if(d||c?.phase===`submitting`||j.getIsLoading()){be(/* @__PURE__ */ Error(`Wait for this client's current request to finish before responding.`));return}let n=Bf(y),r=s.pendingInteractions.find(t=>t.toolCallId===e.toolCallId),i=!(`tool`in e)&&r&&(s.thread?.role===`manager`||n.status===`ready`&&r.targetTenantUserId===n.currentUser.user.id),a=`tool`in e&&e.tool===`ask_questionnaire`&&n.status===`ready`&&r?.targetTenantUserId===n.currentUser.user.id;if(s.thread?.role===`viewer`||!he.has(e.toolCallId)&&!a&&!i&&!D.has(ve(e.toolCallId))){be(/* @__PURE__ */ Error(`This tool call belongs to another session and cannot be executed here.`));return}if(i&&!D.has(ve(e.toolCallId)))D.set(ve(e.toolCallId),{outcome:`unknown`,output:null});else if(!D.has(ve(e.toolCallId))&&`tool`in e){let t=e.output;D.set(ve(e.toolCallId),{outcome:e.state===`output-error`?`failed`:`succeeded`,output:t??null})}let o=d={};try{if(f({}),d!==o)return;if(Ge(),r){if(j.stop(),await Ze(!1),d!==o||t!==S)return;await j.append({role:`tool`,toolCallId:e.toolCallId,content:JSON.stringify(D.get(ve(e.toolCallId)))})}else`tool`in e&&await j.addToolResult(e);d===o&&t===S&&await Ze(!1)}finally{p(o)}},tt=e=>N({toolCallId:e}),nt=async e=>{if(e!==c||e.phase!==`submitting`)return m(e);let t=d={};try{if(await Kf(y),await ae.catch(()=>void 0),!_(e,t))return m(e);if(s.history===`failed`)throw Error(up);if(await Xe(e,t),!_(e,t)||(e.callbacks?.onThreadReady?.(s.thread.id),!_(e,t))||(Ge(),await j.sendMessage(e.content),!ee(e,t)))return m(e);te(e,j.getError()),await Ze(!1)}catch(n){if(!ee(e,t))return m(e);let r=n instanceof Error?n:Error(String(n));r.name===`AbortError`?te(e):te(e,r)&&O(r)}finally{p(t)}return m(e)},P=async(e,t)=>{let n=d||c?.phase===`submitting`||j.getIsLoading()?`Wait for this client's current request to finish before sending.`:s.history===`loading`?`Wait for this conversation to load before sending.`:s.history===`failed`?up:s.thread?.agentId===null?`This conversation’s agent is unavailable. Start a new conversation to continue.`:s.thread?.role===`viewer`?`You have read-only access to this conversation.`:c?.phase===`failed`?`The previous message’s acceptance is unconfirmed. Retry that message before sending different text, or start a new conversation.`:void 0;if(n)return{id:_f(),content:e,phase:`refused`,error:Error(n)};let r={id:_f(),content:e,phase:`submitting`,key:_f(),callbacks:t};c=r,f({submission:m(r),error:void 0,olderMessagesLoading:!1}),j.stop(),he.clear(),Ge(),E.clear(),f({activeToolCallIds:[]});let i=new Promise(e=>r.onRefused=e);return Promise.race([nt(r),i.then(()=>m(r))])},rt=async()=>{let e=c;if(!d&&!j.getIsLoading()&&e&&g(e,`submitting`))return f({error:void 0}),nt(e)},it=()=>{let e=Bf(y),t=s.auth;if(e.status===`ready`){let t=Wf(e.currentUser);b!==void 0&&b!==t&&(v(`The account changed before this was sent.`),l.clear(),_e.clear(),D.clear(),Ke(),w=void 0),b=t;let r=JSON.stringify(Sf(n)),i=`astralbeam:thread:${n.apiUrl??`https://astralbeam.ai/api`}:${t}:session:${r}`;w!==i&&(w!==void 0&&Ke(),w=i,se?(Cf(i,null),se=!1):Ye(!0)),Ce!==t&&(Ce=t,we())}f({auth:e}),e.status===`error`&&(t.status!==`error`||t.error!==e.error)&&n.streamCallbacks?.onError?.(e.error)},at=()=>{if(x)return;x=!0;let e=oe.signal.aborted&&j.getIsHydrating();j.updateOptions({tools:Ne()}),oe.signal.aborted&&(oe=new AbortController),re=Vf(y,it),it(),ne=Zf(y),e?We(j.getSnapshot().messages):Ue()};return t||at(),{start:at,getState:()=>s,getOptions:()=>n,attachView:e=>{if(a)throw Error(`This chat session already has a view attached`);let t={options:e},n=()=>{j.updateOptions({tools:Ne()}),je(s.messages)};return A(),a=t,n(),{update:e=>{if(a!==t)return;let r=t.options;t.options=e,(r.widgets!==e.widgets||r.onRenderWidget!==e.onRenderWidget)&&n()},dispose:()=>{a===t&&(A(),a=void 0,n())}}},subscribe:e=>(i.add(e),()=>i.delete(e)),updateOptions:e=>{let t=n.agentId,i=n.apiUrl,a=n.threadId,o=Sf(n),{widgets:c,onRenderWidget:u}=n;n={...n,...e};let d=Sf(n)!==o;r=gf(n.debug),Uf(y,{apiUrl:n.apiUrl,fetchAstralBeamToken:n.fetchAstralBeamToken??{url:`/api/astralbeam/token`}}),y.debug=r,j.updateOptions({tools:Ne(),forwardedProps:Pe()}),n.apiUrl===i?d?(se=!1,(!s.thread||n.threadId!==s.thread.id)&&Ke(),w=void 0,it()):n.threadId!==a&&Ye():(v(`The chat service changed before this was sent.`),l.clear(),_e.clear(),D.clear(),Ke(),w=void 0,it()),(c!==n.widgets||u!==n.onRenderWidget)&&je(s.messages),x&&(n.agentId!==t||n.apiUrl!==i||d)&&we()},sendMessage:P,retry:rt,addToolResult:N,stop:()=>{ie++;let e=c,t=d;e?.phase===`submitting`&&te(e),j.stop(),t&&p(t),e?.phase===`refused`&&e.onRefused?.()},retryAuthentication:()=>{Kf({...y,force:!0}).catch(()=>void 0)},reload:async()=>{let e=S;if(await Ze(),e!==S||s.error)return;let t=/* @__PURE__ */ new Set;for(;e===S;){let e=s.pendingInteractions.find(e=>!t.has(e.sourceMessageId)&&D.has(ve(e.toolCallId)));if(!e||(t.add(e.sourceMessageId),await N({toolCallId:e.toolCallId}),s.error))return}},searchThreads:async(e=``,t,n)=>{let r=await k(),i=await Tr({q:e,page_size:50,...t?{page_after:t}:{}},{...r,signal:AbortSignal.any([r.signal,...n?[n]:[]])});return{items:i.items.map(e=>vf(e)),page_after:i.page_after}},openThread:qe,renameThread:$e,deleteThread:et,refreshThread:()=>Ze(),loadOlderMessages:Qe,uploadAttachment:async({data:e,filename:t,mimeType:r})=>{let i=s.thread?s.thread.agentId:n.agentId,[a,o]=await Promise.all([e,k(!1)]);return gr({...i?{agentId:i}:{},type:r.startsWith(`image/`)?`image`:`document`,source:{type:`data`,value:a,mimeType:r},metadata:{filename:t}},o)},getThreadAttachment:async(e,t)=>{if(!e.threadId&&!t?.preview)throw Error(`A conversation ID is required to download files.`);return(await vr({...e,delivery:`direct`},{...await k(!!e.threadId||!t?.preview),headers:t?.preview?{"X-File-Preview":`true`}:{}})).blob()},getMcpCatalog:async()=>Ir(await k(!1)),manageMcpConnection:async e=>{let t=await Qf(e,await k(!1));return`id`in e?xe(e.id):t&&`id`in t&&xe(t.id),t},authorizeMcpConnection:async e=>{let t=await $f(e,()=>k(!1));xe(t)},abandonToolCall:tt,reset:()=>{if(r?.(`status`,`conversation reset`),Je(),s.auth.status===`ready`){let e=JSON.stringify([b,Sf(n)]),t=n.apiUrl??`https://astralbeam.ai/api`;Df(t,e,``,``),Df(t,e,``,``,`sent`),Of({apiUrl:t,identity:e,threadId:``,update:()=>[]}).catch(e=>r?.(`error`,`Draft could not be cleared`,e))}a?.options.onReset()},dispose:()=>{v(`The chat closed before this was sent.`),d=void 0,Be?.(),Be=void 0,j.detach(),A(),j.stop(),oe.abort(),S++,Se++,Ce=void 0,ne?.(),re?.(),Yf(y),x=!1,queueMicrotask(()=>{x||(j.dispose(),w=void 0,le.clear(),de=/* @__PURE__ */ new WeakMap)}),i.clear()}}}const pp=e=>e[Symbol.toStringTag],mp=(e,t,n)=>{let{alg:r}=e;if(t.use!==void 0){let e=n===`sign`||n===`verify`?`sig`:`enc`;if(t.use!==e)throw TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(t.alg!==void 0&&t.alg!==r)throw TypeError(`Invalid key for this operation, its "alg" must be "${r}" when present`);if(Array.isArray(t.key_ops)){let r=n===`encrypt`||n===`decrypt`?e.ops?.[n===`encrypt`?0:1]:n;if(r&&!t.key_ops.includes(r))throw TypeError(`Invalid key for this operation, its "key_ops" must include "${r}" when present`)}};async function hp(e,t,n){let{alg:r,secret:i}=e,a=n===`decrypt`||n===`sign`;if(i&&t instanceof Uint8Array)return t;let o,s;if(Ja(t)){if(o=Op(t),typeof o.kty!=`string`)throw Sp(r,t,i);if(!(i?o.kty===`oct`&&typeof o.k==`string`:o.kty!==`oct`&&(a?o.kty===`AKP`&&typeof o.priv==`string`||typeof o.d==`string`:o.d===void 0&&o.priv===void 0)))throw TypeError(i?`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`:`JSON Web Key for this operation must be a ${a?`private`:`public`} JWK`);if(mp(e,o,n),o.kty===`oct`)return Ka(o.k);if(!Object.isFrozen(t)){let{key_ops:e}=t;Array.isArray(e)&&Object.freeze(e),Object.freeze(t)}}else{if(!bp(t))throw Sp(r,t,i);let e=i?`secret`:a?`private`:`public`;if(t.type!==e&&(i||[`secret`,`public`,`private`].includes(t.type)))throw TypeError(`${pp(t)} instances must be of type "${e}" for the ${r} algorithm`);if(vp(t))return t;if(s=t,s.type===`secret`)return s.export()}gp||=/* @__PURE__ */ new WeakMap;let c=t,l=gp.get(c);if(l?.[r])return l[r];if(l||gp.set(c,l={}),s&&typeof s.toCryptoKey==`function`){let t=s.type===`public`,n=_p[s.asymmetricKeyDetails?.namedCurve],i=e.resolve?.({crv:n,asymmetricKeyType:s.asymmetricKeyType})??e.subtle;return l[r]=s.toCryptoKey(i,t,e.usages[+!t])}return o??=s.export({format:`jwk`}),o.alg=r,l[r]=await kp(e,o)}let gp;const _p={__proto__:null,prime256v1:`P-256`,secp384r1:`P-384`,secp521r1:`P-521`},vp=e=>{if(e?.[Symbol.toStringTag]===`CryptoKey`)return!0;try{return e instanceof CryptoKey}catch{return!1}},yp=e=>e?.[Symbol.toStringTag]===`KeyObject`,bp=e=>vp(e)||yp(e);function xp(e,t,...n){if(n.length>2){let t=n.pop();e+=`one of type ${n.join(`, `)}, or ${t}.`}else n.length===2?e+=`one of type ${n[0]} or ${n[1]}.`:e+=`of type ${n[0]}.`;return t==null?e+=` Received ${t}`:typeof t==`function`&&t.name?e+=` Received function ${t.name}`:typeof t==`object`&&t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}function Sp(e,t,n){let r=[`CryptoKey`,`KeyObject`,`JSON Web Key`];return n&&r.push(`Uint8Array`),TypeError(xp(`Key for the ${e} algorithm must be `,t,...r))}const Cp=(e,t=`algorithm.name`)=>/* @__PURE__ */ TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function wp(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function Tp(e,t){let{modulusLength:n}=t.algorithm;if(typeof n!=`number`||n<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}function Ep(e,t,n){let r=e.algorithm;if(r.name!==t.name)throw Cp(t.name);if(t.hash&&r.hash?.name!==t.hash)throw Cp(t.hash,`algorithm.hash`);if(t.namedCurve&&r.namedCurve!==t.namedCurve)throw Cp(t.namedCurve,`algorithm.namedCurve`);if(t.length!==void 0&&r.length!==t.length)throw Cp(t.length,`algorithm.length`);wp(e,n)}function Dp(e){return{__proto__:null,...e}}function Op(e){let t=Dp(e);if(t.ext!==void 0&&typeof t.ext!=`boolean`)throw TypeError(`"ext" (Extractable) Parameter must be a boolean`);if(t.key_ops!==void 0){let e=t.key_ops,n=Array.isArray(e)?[...e]:void 0;if(!n||n.some(e=>typeof e!=`string`)||new Set(n).size!==n.length)throw TypeError(`"key_ops" (Key Operations) Parameter must be an array of unique strings`);t.key_ops=n}return t}async function kp(e,t,n){if(!e.kty.includes(t.kty))throw new Ua(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`);let r=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,i=!!(t.d||t.priv),a={...t,ext:n??t.ext};return a.kty!==`AKP`&&delete a.alg,delete a.use,crypto.subtle.importKey(`jwk`,a,r,a.ext??!i,t.key_ops??e.usages[+!!i])}async function Ap(e,t,n,r=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey(`raw`,e,t,r,[n])),Ep(e,t,n),e}function jp(e){let t={__proto__:null};for(let n in e)t[n]={...e[n],alg:n};return t}const Mp=[[`verify`],[`sign`]];function Np(e){let t={name:`HMAC`,hash:`SHA-${e}`};return{kty:[`oct`],secret:!0,subtle:t,signing:t,usages:Mp}}function Pp(e,t){let n={name:t?`RSA-PSS`:`RSASSA-PKCS1-v1_5`,hash:`SHA-${e}`};return{kty:[`RSA`],subtle:n,signing:t?{...n,saltLength:t}:n,usages:Mp,minRsaBits:2048}}function Fp(e,t){return{kty:[`EC`],crv:e,subtle:{name:`ECDSA`,namedCurve:e},signing:{name:`ECDSA`,hash:`SHA-${t}`},usages:Mp}}function Ip(){let e={name:`Ed25519`};return{kty:[`OKP`],crv:`Ed25519`,subtle:e,signing:e,usages:Mp}}function Lp(e){let t={name:`ML-DSA-${e}`};return{kty:[`AKP`],subtle:t,signing:t,usages:Mp}}const Rp=jp({HS256:Np(256),HS384:Np(384),HS512:Np(512),RS256:Pp(256),RS384:Pp(384),RS512:Pp(512),PS256:Pp(256,32),PS384:Pp(384,48),PS512:Pp(512,64),ES256:Fp(`P-256`,256),ES384:Fp(`P-384`,384),ES512:Fp(`P-521`,512),EdDSA:Ip(),Ed25519:Ip(),"ML-DSA-44":Lp(44),"ML-DSA-65":Lp(65),"ML-DSA-87":Lp(87)});function zp(e){let t=typeof e==`string`?Rp[e]:void 0;if(!t)throw new Ua(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}const Bp=e=>Math.floor(e.getTime()/1e3),Vp={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},Hp=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function Up(){throw TypeError(`Invalid time period format`)}function Wp(e){typeof e!=`string`&&Up();let t=Hp.exec(e);(!t||t[4]&&t[1])&&Up();let n=parseFloat(t[2]),r=Math.round(n*Vp[t[3][0].toLowerCase()]);return Number.isFinite(r)||Up(),t[1]===`-`||t[4]===`ago`?-r:r}function Gp(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}function Kp(e,t){if(typeof t!=`string`)throw TypeError(`"${e}" claim must be a string`)}function qp(e){if(typeof e!=`string`&&(!Array.isArray(e)||Array.from(e).some(e=>typeof e!=`string`)))throw TypeError(`"aud" claim must be a string or an array of strings`)}function Jp(e,t){return typeof e==`number`?Gp(t,e):e instanceof Date?Gp(t,Bp(e)):Bp(/* @__PURE__ */ new Date)+Wp(e)}let Yp;function Xp(e){return Yp.get(e)}function Zp(e){let t=Xp(e);for(let e of[`iat`,`nbf`,`exp`]){let n=t[e];if(typeof n==`number`&&!Number.isFinite(n))throw TypeError(`"${e}" claim must be a finite number`)}return Pa.encode(JSON.stringify(t))}var Qp=class{constructor(e={}){if(!Ja(e))throw TypeError(`JWT Claims Set MUST be an object`);(Yp||=/* @__PURE__ */ new WeakMap).set(this,structuredClone(e))}setIssuer(e){return Kp(`iss`,e),Xp(this).iss=e,this}setSubject(e){return Kp(`sub`,e),Xp(this).sub=e,this}setAudience(e){return qp(e),Xp(this).aud=e,this}setJti(e){return Kp(`jti`,e),Xp(this).jti=e,this}setNotBefore(e){return Xp(this).nbf=Jp(e,`setNotBefore`),this}setExpirationTime(e){return Xp(this).exp=Jp(e,`setExpirationTime`),this}setIssuedAt(e){let t=Xp(this);return t.iat=e===void 0?Bp(/* @__PURE__ */ new Date):typeof e==`string`?Gp(`setIssuedAt`,Bp(/* @__PURE__ */ new Date)+Wp(e)):Jp(e,`setIssuedAt`),this}};async function $p(e,t,n){let[r,i,a,o]=e,s=``;if(i!==void 0){let e=to(Wa,i);i=e[0],s=qa(e[1])}if(a!==void 0&&(a=to(Wa,a)[0]),!i&&!a)throw new Wa(`either setProtectedHeader or setUnprotectedHeader must be called before #sign()`);if(!Ya(i,a))throw new Wa(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let c={...i,...a};Qa(Wa,i);let l=eo(i,$a(Wa,Za,o,i,c));l||n?.();let{alg:u}=c;if(typeof u!=`string`||!u)throw new Wa(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);let d=zp(u),f=``,p=r,m;if(l){let t=e[4];t?(f=t[0]??=qa(r),p=t[1]??=za(f)):(f=qa(r),m=Pa.encode(`${s}.${f}`))}m??=La(za(s),za(`.`),p);let h=await Ap(await hp(d,t,`sign`),d.subtle,`sign`);d.minRsaBits&&Tp(d.alg,h);let g={signature:qa(new Uint8Array(await crypto.subtle.sign(d.signing,h,m))),payload:f};return i&&(g.protected=s),a&&(g.header=a),[g,l]}async function em(e,t,n,r,i){let[a]=await $p([e,t,void 0,n],r,i);return`${a.protected}.${a.payload}.${a.signature}`}const tm=Qp;var nm=class extends tm{#e;setProtectedHeader(e){return Xa(this.#e,`setProtectedHeader`),this.#e=e,this}async sign(e,t){return em(Zp(this),this.#e,t?.crit,e,()=>{throw new Ga(`JWTs MUST NOT use unencoded payload`)})}};const rm=`astralbeam`,im=16384,am=8192,om=/^key_[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}_[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}_abo_[A-Za-z]{64}$/,sm=/^limit_[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}_[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,cm=[`id`,`name`,`metadata`],lm=[`id`,`name`,`admin`,`metadata`],um=new TextEncoder;function dm(e){if(!om.test(e))throw Error(`apiKey must match key_<organizationId>_<id>_abo_<secret>`);let t=e.lastIndexOf(`_abo_`),n=e.slice(0,t),r=e.slice(t+1);return{keyId:n,organizationId:n.slice(4,n.indexOf(`_`,4)),keySecret:r}}function fm(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function pm(e){return e===null||typeof e==`string`||typeof e==`boolean`?!0:typeof e==`number`?Number.isFinite(e):Array.isArray(e)?e.every(pm):fm(e)&&Object.values(e).every(pm)}function mm(e,t,n){if(!fm(t))throw Error(`${e} must be an object`);let r=n?lm:cm;for(let n of Object.keys(t))if(!r.includes(n))throw Error(`${e} has an unknown field "${n}"`);let{id:i,name:a,admin:o,metadata:s}=t;if(typeof i!=`string`||i.length<1||i.length>255)throw Error(`${e}.id must be a 1-255 character string`);if(a!==void 0&&typeof a!=`string`)throw Error(`${e}.name must be a string`);if(n&&o!==void 0&&typeof o!=`boolean`)throw Error(`${e}.admin must be a boolean`);if(s!==void 0&&!(fm(s)&&pm(s)))throw Error(`${e}.metadata must be a JSON object`)}function hm(e,t){mm(`user`,e,!0),mm(`tenant`,t,!1);let n=JSON.stringify({user:e,tenant:t});if(um.encode(n).byteLength>am)throw Error(`user and tenant must not exceed ${am} bytes`);return JSON.parse(n)}async function gm(e){let t=await crypto.subtle.digest(`SHA-256`,um.encode(e));return um.encode(qa(new Uint8Array(t)))}async function _m({apiKey:e,email:t,organizationId:n,expiresInSeconds:r=300}){if(typeof t!=`string`||t.length>320||t.includes(`\0`)||!/^[^\s@]+@[^\s@]+$/.test(t))throw Error(`email must be an email address of at most 320 characters`);if(!Number.isInteger(r)||r<60||r>600)throw Error(`organization auth tokens must live for 60-600 seconds`);let{keyId:i,organizationId:a,keySecret:o}=dm(e);if(n!==a)throw Error(`organizationId must match the API key organization`);let s=Math.floor(Date.now()/1e3);return await new nm({ver:1,email:t,organization_id:n}).setProtectedHeader({alg:`HS256`,typ:`astralbeam-organization+jwt`,kid:i}).setIssuer(n).setAudience(rm).setIssuedAt(s).setExpirationTime(s+r).sign(await gm(o))}async function vm({apiKey:e,user:t,tenant:n,usageLimits:r,expiresInSeconds:i=300}){if(!Number.isInteger(i)||i<60||i>600)throw Error(`chat auth tokens must live for 60-600 seconds`);let{keyId:a,organizationId:o,keySecret:s}=dm(e),c=hm(t,n);if(r!==void 0&&(!Array.isArray(r)||r.length>20||!r.every(e=>typeof e==`string`&&sm.test(e))))throw Error(`usageLimits must list at most 20 IDs of the form limit_<organizationId>_<id>`);let l=Math.floor(Date.now()/1e3),u=await new nm({ver:4,user:c.user,tenant:c.tenant,...r?.length?{usage_limits:[...new Set(r)]}:{}}).setProtectedHeader({alg:`HS256`,typ:`astralbeam+jwt`,kid:a}).setIssuer(o).setAudience(rm).setIssuedAt(l).setExpirationTime(l+i).sign(await gm(s));if(um.encode(u).byteLength>im)throw Error(`chat auth tokens must not exceed ${im} bytes`);return u}function ym(e){return e.string([`tenant`,`user`,`tenant-name`,`user-name`]).demandOption([`tenant`,`user`]).boolean(`admin`).number(`expires-in`).coerce(`expires-in`,tr).describe({tenant:`Tenant external ID, signed as tenant.id`,user:`TenantUser external ID, signed as user.id`,"tenant-name":`Tenant display name`,"user-name":`TenantUser display name`,admin:`sign user.admin: true, granting Tenant admin API access`,"expires-in":`token lifetime, 60-600 (default 300)`})}function bm(e){return{tenant:{id:e.tenant,...e.tenantName===void 0?{}:{name:e.tenantName}},user:{id:e.user,...e.userName===void 0?{}:{name:e.userName},...e.admin?{admin:!0}:{}}}}function xm(e,t,n){let r=new Date(Date.now()+t*1e3).toISOString();n?Qr({token:e,expires_at:r}):s.write(`${e}\n`)}function Sm(e){return e.command(`chat`,`Mint a chat JWT for a Tenant's user, as a token endpoint would`,ym,async e=>{let{apiKey:t}=await xi(),n=e.expiresIn??300;xm(await vm({apiKey:t,expiresInSeconds:n,...bm(e)}),n,K.json)}),e.command(`organization`,`Mint an organization-management JWT delegating a member's current role`,e=>e.string(`email`).demandOption(`email`).number(`expires-in`).coerce(`expires-in`,tr).describe({email:`email of an existing member of the organization`,"expires-in":`token lifetime, 60-600 (default 300)`}),async e=>{let{apiKey:t}=await xi(),n=e.expiresIn??300;xm(await _m({apiKey:t,email:e.email,organizationId:li(t),expiresInSeconds:n}),n,K.json)}),e.demandCommand(1)}function Cm(e){return e.filter(e=>e.role===`assistant`).map(e=>e.parts.map(e=>e.type===`text`?e.content:``).join(``)).filter(Boolean).join(`
|
|
147
|
+
`),inputSchema:{type:`object`,properties:{widget:{type:`string`,enum:Object.keys(e),description:`Name of the widget to render.`},props:{type:`object`,description:`Props for the widget, matching its props schema.`}},required:[`widget`]}}).client((e,n)=>t(e,n?.toolCallId??``))}function Pf(){return dl({name:`ask_questionnaire`,description:`Ask the user a short structured questionnaire rendered inline in the chat. Use it when the next step genuinely depends on their choices instead of asking in prose. The call stays pending until the user submits; their answers arrive as the tool output. Skipped optional questions come back with an empty answers array. An output with skipped: true means the user dismissed the questionnaire by continuing the conversation instead — do not re-ask; address their next message.`,inputSchema:{type:`object`,properties:{items:{type:`array`,minItems:1,description:`Questions shown one at a time, in order.`,items:{type:`object`,properties:{name:{type:`string`,description:`Unique key identifying the question.`},title:{type:`string`,description:`The question itself.`},description:{type:`string`,description:`Optional helper text.`},required:{type:`boolean`,description:`Whether an answer is mandatory.`},multiple:{type:`boolean`,description:`Whether several choices may be selected.`},choices:{type:`array`,minItems:1,items:{type:`object`,properties:{value:{type:`string`},label:{type:`string`},description:{type:`string`}},required:[`value`,`label`]}},input:{type:`object`,description:`Optional free-form alternative to the fixed choices.`,properties:{label:{type:`string`},placeholder:{type:`string`}},required:[`label`,`placeholder`]}},required:[`name`,`title`,`choices`]}}},required:[`items`]}}).client()}function Ff(e,t,n){return Object.entries(e).map(([e,r])=>dl({name:e,description:r.description,inputSchema:kf(r.parameters),...r.metadata?{metadata:r.metadata}:{}}).client(async(i,a)=>{let o=!1;try{let s=n?.(e,r,a?.toolCallId);t?.(`tool`,`executing host tool "${e}"`,{input:i});let c=await Af(r.parameters,i??{});if(c==null)throw t?.(`error`,`input for host tool "${e}" failed schema validation`,{input:i}),Error(`Input for tool "${e}" failed schema validation`);a?.abortSignal?.throwIfAborted();let l=s?.()??r;o=!0;let u=await l.execute(c);try{u=Z(u)}catch{throw Error(`Tool "${e}" ran, but its result is not JSON-compatible. Its changes may already be applied. Read current state before retrying. Return plain JSON values and omit undefined fields.`)}return t?.(`tool`,`host tool "${e}" returned`,{output:u}),u}catch(n){t?.(`error`,`host tool "${e}" threw`,{error:n});let r=n instanceof Error?n:Error(String(n));throw o||Object.assign(r,{[jf]:!0}),r}}))}function If(e){if(e.length>16384)throw Error(`The chat auth token is too large`);let{exp:t,iat:n,user:r}=ao(e);if(!Number.isInteger(t)||Number(t)<=0)throw Error(`The chat auth token has no valid expiry`);let i=Number(t)*1e3,a=n===void 0?3e5:i-n*1e3,o=Math.min(6e4,a*.2),s=r?.admin===!0;return{expiresAt:i,refreshAt:i-o,tenantAdmin:s}}async function Lf(e,t){let{fetchAstralBeamToken:n,fetchClient:r}=e;if(typeof n==`function`)return(await n())?.token;if(!n)throw Error(`Provide fetchAstralBeamToken.`);let{url:i,...a}=n,o=new Headers(a.headers);o.has(`accept`)||o.set(`accept`,`application/json`);let s=await r(i,{method:`POST`,credentials:`include`,cache:`no-store`,...a,headers:o,signal:a.signal?AbortSignal.any([t,a.signal]):t});if(!s.ok)throw Object.assign(/* @__PURE__ */ Error(`Authentication endpoint returned HTTP ${s.status}`),{status:s.status,headers:s.headers});return(await s.json())?.token}const Rf={status:`loading`};function zf(e){return{...e,fetchAstralBeamToken:e.fetchAstralBeamToken,session:{cached:void 0,refreshPromise:void 0,abortController:new AbortController,state:Rf,listeners:/* @__PURE__ */ new Set},fetchClient:globalThis.fetch.bind(globalThis),debug:void 0}}function Bf(e){return e.session.state}function Vf(e,t){let{listeners:n}=e.session;return n.add(t),()=>{n.delete(t)}}function Hf(e,t){e.session.state=t;for(let t of e.session.listeners)t()}function Uf(e,t){e.apiUrl!==t.apiUrl&&(Yf(e),e.session.abortController=new AbortController,Hf(e,{status:`loading`})),e.apiUrl=t.apiUrl,e.fetchAstralBeamToken=t.fetchAstralBeamToken}function Wf(e,t){return JSON.stringify([e.scope,e.organization.id,e.scope===`tenant`?e.tenant.id:null,e.user.id,t===void 0?null:e.scope===`tenant`?t:e.user.role])}async function Gf(e){let{session:t,debug:n,apiUrl:r}=e,{signal:i}=t.abortController,a=typeof e.fetchAstralBeamToken==`function`?`fetchAstralBeamToken`:`Authentication endpoint`;try{for(let o=0;o<2;o++){let s=await Lf(e,i);if(i.throwIfAborted(),typeof s!=`string`||!s)throw Error(`${a} did not return a token`);let{expiresAt:c,refreshAt:l,tenantAdmin:u}=If(s);if(c<=Date.now())throw Error(`${a} returned an expired token`);if(!Number.isFinite(l)||l<=Date.now()||c-Date.now()<5e3)throw Error(`${a} returned a token too close to expiry`);let d;try{d=await Pr({apiUrl:r,astralBeamToken:s,fetchClient:e.fetchClient,signal:i,cache:`no-store`,credentials:`omit`})}catch(t){if(!o&&e.retryUnauthorized!==!1&&or(t)&&t.status===401)continue;throw t}if(i.throwIfAborted(),e.scope&&e.scope!==d.scope)throw Error(`Expected ${e.scope} authentication`);return t.cached={value:s,expiresAt:c,refreshAt:l,synchronizedAt:Date.now(),tenantAdmin:u},Hf(e,{status:`ready`,currentUser:d}),n?.(`auth`,`authentication ready`,{expiresAt:new Date(c)}),s}throw Error(`Authentication failed`)}catch(n){i.throwIfAborted();let r=n instanceof Error?n:/* @__PURE__ */ Error(`Authentication failed`);throw or(r)&&r.status===401&&(r.message=`AstralBeam rejected the chat token after renewal. Check that apiUrl matches the deployment that issued your API key. If the key was revoked or expired, create a replacement in API Keys and update your server's secret.`),t.cached=void 0,Hf(e,{status:`error`,error:r}),r}}async function Kf(e){let{session:t,force:n=!1}=e;if(t.abortController.signal.throwIfAborted(),t.refreshPromise)return await t.refreshPromise;if(!n&&t.cached&&t.cached.refreshAt>Date.now())return t.cached.value;(!t.cached||t.cached.expiresAt<=Date.now())&&Hf(e,{status:`loading`});let r=Gf(e);t.refreshPromise=r;try{return await r}finally{t.refreshPromise===r&&(t.refreshPromise=void 0)}}function qf(e,t){let n=!t||e.session.cached?.value===t;return n&&(e.session.cached=void 0),Kf({...e,force:n,retryUnauthorized:!1})}async function Jf(e){e.session.abortController.signal.aborted&&(e.session.abortController=new AbortController),await Kf(e)}function Yf({session:e}){e.abortController.abort(),e.refreshPromise=void 0,e.cached=void 0,e.state=Rf}async function Xf(e){let{input:t,init:n,session:r,fetchClient:i,debug:a}=e,o=Bf(e),s=await i(t,n);if(s.status!==401||r.abortController.signal.aborted)return s;let c=new Headers(n?.headers),l=c.get(`authorization`),u=l?.startsWith(`Bearer `)?l.slice(7):void 0;a?.(`auth`,`chat auth token was rejected; refreshing once`),await s.body?.cancel();let d=await qf(e,u),f=Bf(e);if(o.status!==`ready`||f.status!==`ready`||Wf(o.currentUser)!==Wf(f.currentUser))throw new DOMException(`Identity changed`,`AbortError`);return n?.signal?.throwIfAborted(),c.set(`authorization`,`Bearer ${d}`),await i(t,{...n,headers:c})}function Zf(e){let t,n=new AbortController,r=0,i=()=>typeof document>`u`||document.visibilityState!==`hidden`&&globalThis.navigator?.onLine!==!1,a=()=>{!n.signal.aborted&&i()&&Kf({...e,force:!0}).catch(()=>{})},o=()=>{if(clearTimeout(t),n.signal.aborted||typeof document>`u`||!i())return;let o=Bf(e);if(o.status===`ready`)r=0,t=setTimeout(a,Math.max(1e3,e.session.cached.refreshAt-Date.now()));else if(o.status===`error`&&r<3){let e=o.error;if(e.status!==void 0&&e.status!==429&&e.status<500||e.status===void 0&&!(e instanceof TypeError))return;let n=e.headers?.get(`retry-after`),i=n?/^\d+$/.test(n)?Number(n)*1e3:Date.parse(n)-Date.now():0;t=setTimeout(a,Math.max(1e3*2**r++,Number.isFinite(i)?i:0))}},s=()=>{if(!i()){clearTimeout(t);return}let n=e.session.cached;!n||Date.now()-n.synchronizedAt>=6e4||n.refreshAt<=Date.now()?a():o()},c=Vf(e,o);if(typeof document<`u`){for(let e of[`focus`,`online`,`offline`])globalThis.addEventListener(e,s,{signal:n.signal});document.addEventListener(`visibilitychange`,s,{signal:n.signal})}return Jf(e).catch(()=>{}),o(),()=>{n.abort(),clearTimeout(t),c()}}async function Qf(e,t){switch(e.action){case`connect`:case`headers`:{let n=await Rr({mcp_server_id:e.mcpServerId},t);return e.action===`connect`?n:(await Br(n.id,{lock_version:n.lock_version,headers:e.headers},t),{id:n.id})}case`disconnect`:return Hr(e.id,t);case`test`:return Wr(e.id,t)}}async function $f(e,t){let n=window.open(`about:blank`,`_blank`,`popup,width=600,height=720`);if(!n)throw Error(`Allow popups to authorize this connection.`);try{let r=e.id??(await Rr({mcp_server_id:e.mcpServerId},await t())).id,i=await Kr(r,await t()),a={organizationId:i.attempt.organization_id,tenantId:i.attempt.tenant_id,connectionId:i.attempt.connection_id,id:i.attempt.id},o=new URL(i.popup_url);o.searchParams.set(`origin`,window.location.origin);let{promise:s,resolve:c,reject:l}=Promise.withResolvers(),u={state:`waiting`},d=new AbortController,f=!1,p=e=>l(e instanceof Error?e:/* @__PURE__ */ Error(`Authorization failed.`)),m=async()=>{let e=await t();return d.signal.throwIfAborted(),{...e,signal:AbortSignal.any([d.signal,...e.signal?[e.signal]:[]])}},h=async()=>{if(!(f||d.signal.aborted)){f=!0;try{if(u.state===`binding`&&(await Jr(r,{attempt_id:a.id,challenge:u.challenge},await m()),d.signal.throwIfAborted(),u={state:`completing`}),u.state===`completing`){let e=await Xr(r,{attempt_id:a.id},await m());if(d.signal.throwIfAborted(),e){c();return}}n.closed&&p(/* @__PURE__ */ Error(`Authorization window closed.`))}catch(e){let t=e instanceof Error?e.status:void 0;!(e instanceof TypeError)&&t!==429&&(t??0)<500&&p(e)}finally{f=!1}}},g=e=>{if(e.source!==n||e.origin!==o.origin)return;let t=e.data;t?.attempt&&t.attempt.id===a.id&&t.attempt.organizationId===a.organizationId&&t.attempt.tenantId===a.tenantId&&t.attempt.connectionId===a.connectionId&&t.type===`mcp-browser-challenge`&&u.state===`waiting`&&typeof t.challenge==`string`&&(u={state:`binding`,challenge:t.challenge},h())},_=setInterval(()=>void h(),5e3),v=setTimeout(()=>p(/* @__PURE__ */ Error(`Authorization expired. Try connecting again.`)),6e5);try{window.addEventListener(`message`,g),n.location.replace(o.href),await s}finally{d.abort(),window.removeEventListener(`message`,g),clearInterval(_),clearTimeout(v)}return r}finally{n.close()}}function ep(e){return e.state===`complete`||e.state===`error`||e.output!==void 0}function tp(e){return e.metadata??{}}function np(e,t){return typeof e==`object`&&e&&t in e?e[t]:void 0}function rp(e,t){let n=np(e,t);return typeof n==`string`?n:void 0}function ip(e,t){let n=np(e,t);return typeof n==`number`?n:void 0}function ap(e){return rp(e.output,`refusal`)}function op(e){if(e.name!==`sandbox_write_file`)return;let t=rp(e.output,`path`)??rp(e.input,`path`);if(t===void 0)return;let n=rp(e.input,`content`)??``;return{toolCallId:e.id,path:t,label:sp(e)??t,content:n,lines:n.length===0?0:n.split(`
|
|
148
|
+
`).length,written:e.output!=null&&ap(e)===void 0}}function sp(e){let t=rp(e.output,`relativePath`);return t!==void 0&&t!==`.`?t:rp(e.output,`path`)??rp(e.input,`path`)}function cp(e){if(e.name!==`sandbox_run_command`)return;let t=rp(e.input,`command`);if(t===void 0)return;let n=e.output;return{toolCallId:e.id,command:t,cwd:rp(e.input,`cwd`),exitCode:ip(n,`exitCode`),stdout:rp(n,`stdout`)??``,stderr:rp(n,`stderr`)??``,durationMs:ip(n,`durationMs`),timedOut:np(n,`timedOut`)===!0,truncated:np(n,`truncated`)===!0,finished:n!=null}}function lp(e){let t=/* @__PURE__ */ new Map,n=[];for(let r of e)for(let e of r.parts){if(e.type!==`tool-call`)continue;let r=op(e);r?.written&&t.set(r.path,r);let i=cp(e);i&&ap(e)===void 0&&n.push(i)}return{files:[...t.values()],commands:n}}const up=`Reopen this conversation or start a new one before sending.`;function dp(e,t){return e.length===t.length&&e.every((e,n)=>e.name===t[n]?.name&&e.title===t[n]?.title)}function fp(e,t=!1){let n={...e},r=gf(n.debug),i=/* @__PURE__ */ new Set,a,o=()=>a?.options??n,s={messages:[],status:`ready`,error:void 0,auth:{status:`loading`},capabilities:{attachments:!0},agentTools:[],sandboxStatus:void 0,usageLimitReached:void 0,sandbox:{files:[],commands:[]},thread:void 0,history:`idle`,messagesCursor:void 0,olderMessagesLoading:!1,submission:void 0,activeToolCallIds:[],pendingInteractions:[]},c,l=/* @__PURE__ */ new Map,u,d=`ready`,f,p=e=>{let t=f||c?.phase===`submitting`?d===`streaming`||s.status===`streaming`?`streaming`:`submitted`:d;s={...s,...e,status:t,history:u?.phase??`idle`};for(let e of i)e()},m=e=>e.client===N&&e.selection===w,h=e=>f===e&&m(e),g=e=>{h(e)&&(f=void 0,p({}))},_=({id:e,content:t,phase:n,error:r})=>({id:e,content:t,phase:n,...r?{error:r}:{}}),v={submitting:[`accepted`,`failed`,`refused`],failed:[`submitting`],accepted:[],refused:[]},ee=(e,t,n)=>v[e.phase].includes(t)?(e.phase=t,e.error=n,e===c&&p({submission:_(e)}),!0):!1,y=e=>e.submission===c&&h(e),te=e=>y(e)&&e.submission.phase===`submitting`,ne=(e,t)=>e.delivery.state===`undispatched`?ee(e,`refused`,t):ee(e,`failed`,t??/* @__PURE__ */ Error(`This message may not have been sent. Retry to send it.`)),re=e=>{let t=c;return t?.phase===`submitting`&&ne(t,t.delivery.state===`uncertain`?void 0:Error(e)),t?.phase===`refused`&&t.onRefused?.(),c=void 0,t},b=zf({apiUrl:n.apiUrl,scope:`tenant`,fetchAstralBeamToken:n.fetchAstralBeamToken??{url:`/api/astralbeam/token`}}),x,ie,S,C=!1,w=0,ae=0,oe=async e=>{for(;m(e);){let e=u;try{await e?.completion}catch(t){if(e===u)throw t}if(e===u)return}},se=async e=>{if(await oe(e).catch(()=>void 0),!te(e))return!1;if(s.history===`failed`)throw Error(up);return!0},ce=new AbortController,T,le=!1,ue=[],E=/* @__PURE__ */ new Map,de=0,D=/* @__PURE__ */ new WeakMap,fe=e=>{for(let t of e){if(t.role!==`user`||E.get(t.id)?.attachmentParts||!t.parts.some(e=>`fileId`in e))continue;let e=t.parts.map(e=>Object.freeze({...e}));Object.freeze(e),E.set(t.id,{...E.get(t.id),attachmentParts:e}),de++}},pe=_f(),me=()=>{c&&ee(c,`accepted`)&&(s.thread&&p({thread:{...s.thread,hasMessages:!0}}),c.callbacks?.onAccepted?.())},he=e=>{let t=[...N.getSnapshot().messages],n=t.findLastIndex(e=>e.role===`user`);n!==-1&&(t[n]=xf([e])[0],fe([t[n]]),N.setMessagesManually(t),P&&Ue())},ge=/* @__PURE__ */ new Set,O=/* @__PURE__ */ new Map,_e=/* @__PURE__ */ new Map,k=/* @__PURE__ */ new Map,A=/* @__PURE__ */ new Map,ve=e=>{let t=O.get(e);return t?`live:${t}:${e}`:e},ye=e=>{let t=/* @__PURE__ */ new Map;for(let n of e.pending_interactions){let e=`live:${n.source_message_id}:${n.tool_call_id}`,r=yf(n.source_message_id,n.source_part_id,n.response_target_id),i=k.get(e)??k.get(r);i&&(t.set(r,i),O.get(n.tool_call_id)===n.source_message_id&&t.set(e,i))}k.clear();for(let[e,n]of t)k.set(e,n)},be=e=>{(s.auth.status!==`error`||s.auth.error!==e)&&n.streamCallbacks?.onError?.(e)},xe=e=>{if(e instanceof Error&&e.name===`AbortError`)return;let t=e instanceof Error?e:Error(String(e));p({error:t}),be(t)},Se=e=>{p({unavailableMcpConnections:s.unavailableMcpConnections?.filter(t=>t!==e)??[]})},j=async(e=!0)=>{let t=w,n=b.session.abortController.signal,r=await Kf(b);if(n.throwIfAborted(),e&&t!==w)throw new DOMException(`Conversation changed`,`AbortError`);return{apiUrl:b.apiUrl,astralBeamToken:r,cache:`no-store`,signal:e?AbortSignal.any([ce.signal,n]):n,fetchClient:(e,t)=>Xf({...b,input:e,init:t})}},Ce=0,we,Te=async()=>{let e=++Ce,t=w;if(s.thread?.agentId===null){p({capabilities:{attachments:!1}});return}let i=s.thread?s.thread.agentId:n.agentId;try{let n=await j();if(e!==Ce||t!==w)return;let a=await xr(i?{agentId:i}:{},n);if(e!==Ce||t!==w)return;let o=a.capabilities?.attachments!==!1;p({capabilities:{attachments:o}}),r?.(`mount`,`agent capabilities resolved`,{attachments:o})}catch(e){r?.(`error`,`agent capabilities could not be resolved; keeping the defaults`,e)}},Ee=/* @__PURE__ */ new Map,M=/* @__PURE__ */ new Set,De=/* @__PURE__ */ new Set,Oe=0,ke=()=>{Oe++;for(let e of Ee.values())e();Ee.clear(),M.clear(),De.clear()},Ae=async(e,t)=>{if(!o().onRenderWidget)return{widget:e.widget,rendered:!1};let n=w,r=Oe,i=o().widgets??{};if(!Object.hasOwn(i,e.widget))throw Error(`Unknown widget "${e.widget}"`);let a=i[e.widget],c=await Af(a?.parameters,e.props??{});if(n!==w||r!==Oe||s.thread?.role===`viewer`)return{widget:e.widget,rendered:!1};if(a!==o().widgets?.[e.widget])return Ae(e,t);if(c==null)throw Error(`Props for widget "${e.widget}" failed validation`);let l=o().onRenderWidget;if(!l)return{widget:e.widget,rendered:!1};Ee.get(t)?.(),Ee.delete(t);let u,d=l({widget:e.widget,props:c,toolCallId:t,release:()=>{Ee.get(t)===u&&Ee.delete(t)}});return d&&(u=d,Ee.set(t,d)),M.add(t),{widget:e.widget,rendered:!0}},je=e=>Object.freeze(e.map(e=>{let t=E.get(e.id),n=D.get(e);if(n&&n.presentation===t)return n.message;let r=t?.attachmentParts??e.parts,i=t?.renderIds,a=r.map(t=>{if(t.type!==`tool-call`||t.name!==`render_widget`||t.state!==`complete`||!t.input)return t;let n=t,r=yf(e.id,t.id),a=n.applicationPartId?yf(e.id,n.applicationPartId,n.responseTargetId):r,o=n.upstreamToolCallId,s=n.widgetRenderId??i?.get(r)??i?.get(a)??(o&&O.get(o)===e.id&&M.has(o)?o:t.id);return(i?.get(r)!==s||i.get(a)!==s)&&(i=new Map(i).set(r,s).set(a,s)),n.widgetRenderId===s?t:Object.freeze({...t,widgetRenderId:s})});a.some((e,t)=>e!==r[t])&&(Object.freeze(a),r=a),i&&i!==t?.renderIds&&(t={...t,renderIds:i},E.set(e.id,t),de++);let o=r===e.parts?e:Object.freeze({...e,parts:r});return D.set(e,{presentation:t,message:o}),o})),Me=e=>{if(s.thread?.role!==`viewer`)for(let t of e)for(let e of t.parts){if(e.type!==`tool-call`||e.name!==`render_widget`||e.state!==`complete`||!e.input)continue;let t=e.widgetRenderId??e.id;if(M.has(t)||De.has(t))continue;De.add(t);let n=w,i=Oe,{widgets:a,onRenderWidget:c}=o();Ae(e.input,t).catch(e=>r?.(`error`,`Saved widget could not be rendered`,e)).finally(()=>{n===w&&i===Oe&&(De.delete(t),(a!==o().widgets||c!==o().onRenderWidget)&&Me(s.messages))})}},Ne=()=>{let e=w;return Mf(o().widgets??{},n.tools??{},Ae,r,(t,r,i)=>{let a=ae,o=N,c=S,l=b.apiUrl;return()=>{let u=n.tools&&Object.hasOwn(n.tools,t)?n.tools[t]:void 0;if(e!==w||a!==ae||o!==N||c!==S||l!==b.apiUrl||s.thread?.role===`viewer`||!i||!ge.has(i)||!u||u.parameters!==r.parameters)throw new DOMException(`Host tool authority changed`,`AbortError`);return u}}).map(e=>{if(!e.execute)return e;let t=e.execute;return{...e,execute:async(e,n)=>{let r=n?.toolCallId;if(!r||!ge.has(r))throw Error(`A saved tool call cannot execute again. Send a new message to request it.`);let i=k,a=ve(r),o=S,s=b.apiUrl;try{let r=await t(e,n);return S===o&&b.apiUrl===s&&i.set(a,{outcome:`succeeded`,output:r??null}),r}catch(e){throw!(e instanceof Error&&jf in e)&&S===o&&b.apiUrl===s&&i.set(a,{outcome:`unknown`,output:{error:e instanceof Error?e.message:String(e)}}),e}}}})},Pe=()=>{let e=Ne(),t=e.map(e=>{let t=e.metadata?.title;return{name:e.name,title:typeof t==`string`&&t.length>0?t:void 0}});return dp(s.agentTools,t)||p({agentTools:t}),e},Fe=()=>n.debug?{debug:!0}:{},Ie=async(e,t,n)=>{if(!h(n))throw new DOMException(`Request cancelled`,`AbortError`);let r=s.thread;if(!r||typeof e.body!=`string`)throw Error(`Open a conversation before sending.`);let i=JSON.parse(e.body),a=yr(),o,c=i.messages.at(-1)?.role===`user`&&n.kind===`submission`&&te(n)?n.submission:void 0,l=c?.delivery;if(c)o={...i,threadId:r.id,resume:void 0,parentRunId:void 0,messages:[i.messages.at(-1)],tools:l?.state===`uncertain`?l.tools:i.tools,forwardedProps:{...i.forwardedProps,clientId:pe}};else{Ke();let e=await bf(r.id,t,void 0,O);if(!h(n))throw new DOMException(`Request cancelled`,`AbortError`);p({thread:vf(e.thread,e.messages.length>0)}),ye(e);let s=e.pendingInteractions.filter(e=>k.has(ve(e.toolCallId))),c=s.find(e=>e.toolCallId===i.messages.at(-1)?.toolCallId)??s[0],l=e.pendingInteractions.flatMap(e=>{let t=k.get(ve(e.toolCallId));return t&&e.sourceMessageId===c?.sourceMessageId?[{source_message_id:e.sourceMessageId,source_part_id:e.sourcePartId,response_target_id:e.responseTargetId,...t}]:[]});if(l.length===0)return new Response(``,{headers:{"Content-Type":`text/event-stream`}});a=Mr(r.id),o={client_id:pe,run_id:i.runId,...i.parentRunId?{parent_run_id:i.parentRunId}:{},results:l}}ge.clear(),p({activeToolCallIds:[]});let u=new Headers(e.headers);if(c&&u.set(`Idempotency-Key`,c.key),!h(n))throw new DOMException(`Request cancelled`,`AbortError`);c&&c.delivery.state===`undispatched`&&(c.delivery={state:`uncertain`,tools:i.tools});let d=await fr(a,{...t,...e,headers:u,body:JSON.stringify(o)}).catch(e=>{if(!h(n))throw e;c&&l?.state===`undispatched`&&or(e)&&(e.status===400||e.status===413||e.status===429)&&(c.delivery={state:`undispatched`});let t=or(e)?e.body?.usage_limit:void 0;throw t&&p({usageLimitReached:{name:t.name,resetsAt:t.resets_at}}),e});if(!h(n))throw new DOMException(`Request cancelled`,`AbortError`);if(d.headers.get(`Content-Type`)?.includes(`application/json`)){let e=await d.json();if(!h(n))throw new DOMException(`Request cancelled`,`AbortError`);if(p({thread:{...s.thread,version:e.thread_version},...e.usage_limit?{usageLimitReached:{name:e.usage_limit.name,resetsAt:e.usage_limit.resets_at}}:{}}),c){let i=await bf(r.id,t,void 0,O);if(!h(n))throw new DOMException(`Request cancelled`,`AbortError`);let a=i.messages.find(t=>t.id===e.accepted_message_id);a&&he(a),me()}return new Response(``,{headers:{"Content-Type":`text/event-stream`}})}return d},Le=rd(()=>sr(yr(),b.apiUrl),async()=>{let e=f;if(!e||!h(e))throw new DOMException(`Request cancelled`,`AbortError`);let t=await j();if(!h(e))throw new DOMException(`Request cancelled`,`AbortError`);return{fetchClient:(n,r)=>Ie(r??{},{...t,signal:r?.signal??t.signal},e)}}),Re=Le.connect;Le.connect=async function*(...e){try{for await(let t of Re(...e)){if(t.type===X.TOOL_CALL_START&&t.parentMessageId&&O.set(t.toolCallId,t.parentMessageId),t.type!==X.MESSAGES_SNAPSHOT){yield t;continue}let e;yield{...t,messages:t.messages.map(t=>t.role===`assistant`?(e=_e.get(t.id),e&&t.toolCalls?{...t,toolCalls:t.toolCalls.map(t=>({...t,id:e?.get(t.id)??t.id}))}:t):t.role===`tool`?{...t,toolCallId:e?.get(t.toolCallId)??t.toolCallId}:(e=void 0,t))}}}catch(e){throw e instanceof Error&&or(e.cause)?e.cause:e}};let ze=()=>{let e=new ff({connection:{...Le,hydrate:(t,n)=>{let r=Be;if(!r)return Promise.resolve({messages:[],activeRun:null,interrupts:null,page:{truncated:!1}});let i=n?.before!==void 0,a=i?u?.owner:{client:e,selection:w},o=()=>a!==void 0&&u?.owner===a&&m(a),c=(async()=>{let t=await bf(r,await j(),n?.before,O);for(;n?.before&&t.messages.every(e=>e.role===`tool`)&&t.page_after;){let e=await bf(r,await j(),t.page_after,O);t={...e,messages:[...e.messages,...t.messages]}}if(!o())throw new DOMException(`Conversation changed`,`AbortError`);i||ye(t),ue=i?[...t.messages,...ue]:t.messages;let a=new Set(t.messages.map(e=>e.id)),c=xf(ue,i?s.pendingInteractions:t.pendingInteractions,O).filter(e=>a.has(e.id));if(fe(c),i)p({messagesCursor:t.page_after??void 0});else{t.thread.role===`viewer`&&ke();let n=s.thread?.agentId!==t.thread.agent_id;p({thread:vf(t.thread,t.messages.length>0),messagesCursor:t.page_after??void 0,pendingInteractions:t.pendingInteractions}),n&&Te(),c.length===0&&e.setMessagesManually([])}return{messages:c,activeRun:null,interrupts:null,page:t.page_after?{truncated:!0,cursor:t.page_after}:{truncated:!1}}})();if(!i&&a){let e=c.then(()=>`idle`,()=>`failed`).then(e=>(u&&o()&&(u.phase=e,P&&Ue(),p({})),c));u={owner:a,phase:s.messages.length>0||s.thread?.hasMessages===!1?`refreshing`:`loading`,completion:e},e.catch(()=>void 0),p({olderMessagesLoading:!1})}return c}},threadId:Be??pe,persistence:!0,history:{pageSize:100},queue:`drop`,tools:Pe(),forwardedProps:Fe(),onInterruptStateChange:t=>{N===e&&r?.(`tool`,`interrupt state changed`,t)},onCustomEvent:(t,n)=>{if(N!==e)return;if(t===`astralbeam_thread`){let e=n;if(s.thread?.id===e.threadId){if(e.acceptedMessage&&c?.phase===`submitting`&&he(e.acceptedMessage),e.acceptedMessageId&&me(),e.saved)for(let t of e.executableToolCallIds??[])ge.has(t)||k.delete(ve(t)),ge.add(t);p({thread:{...s.thread,version:e.version},activeToolCallIds:[...ge]})}return}if(t===`astralbeam_mcp_tools`){let e=n,t={};for(let n of e.tools??[])typeof n.name==`string`&&typeof n.title==`string`&&(t[n.name]=n.title);p({serverToolTitles:t,unavailableMcpConnections:e.unavailable??[]});return}let i=n;if(t===`astralbeam.usage_limit.reached`&&typeof i?.name==`string`&&typeof i.resetsAt==`string`){p({usageLimitReached:{name:i.name,resetsAt:i.resetsAt}});return}let a=n?.state;t===`astralbeam.sandbox.status`&&(a===`starting`||a===`ready`||a===`error`)?(r?.(`sandbox`,`sandbox ${a}`),p({sandboxStatus:a})):r?.(`stream`,`custom event "${t}"`,n)},onChunk:t=>{N===e&&(t.type===X.RUN_STARTED&&p({serverToolTitles:{},unavailableMcpConnections:[]}),n.streamCallbacks?.onChunk?.(t))},onResponse:t=>{N===e&&n.streamCallbacks?.onResponse?.(t)},onFinish:t=>{N===e&&n.streamCallbacks?.onFinish?.(t)},onError:t=>{N===e&&(c?.phase!==`submitting`&&t.name!==`AbortError`&&p({error:t}),be(t))}});return e},Be,N=ze(),P,Ve,He=-1,Ue=()=>{let e=N.getSnapshot(),t=Ve!==e.messages||He!==de;if(!t&&d===e.status)return;let n={};d!==e.status&&e.status===`submitted`&&(n.usageLimitReached=void 0),d=e.status,t&&(n.messages=je(e.messages),n.sandbox=lp(n.messages),Ve=e.messages,He=de),p(n),t&&Me(s.messages)},We=()=>{if(!P){let e=N,t=w;P=e.subscribeSnapshot(()=>{N===e&&t===w&&Ue()}),Ue(),Me(s.messages)}N.attach()},Ge=e=>{let t=N;f=void 0,u=void 0,P?.(),P=void 0,Ve=void 0,N=ze(),e&&N.setMessagesManually(e),d=`ready`,t.stop(),t.detach(),ge.clear(),p({activeToolCallIds:[]}),C&&We(),t.dispose()},Ke=()=>{_e.clear(),N.setMessagesManually(N.getSnapshot().messages.map(e=>{let t=/* @__PURE__ */ new Map,n=e.parts.map(n=>{if(n.type!==`tool-call`||tp(n).providerExecuted)return n;let r=n,i=r.upstreamToolCallId??n.id;if(O.get(i)===e.id&&!ep(n))return n;let a=yf(e.id,r.applicationPartId??i,r.responseTargetId);return t.set(i,a),{...n,upstreamToolCallId:i,id:a,...n.name===`render_widget`?{widgetRenderId:r.widgetRenderId??E.get(e.id)?.renderIds?.get(yf(e.id,n.id))??n.id}:{}}});return t.size&&_e.set(e.id,t),{...e,parts:n}}))},qe=e=>{let t=s.thread?.id,n=re(`The conversation changed before this was sent.`);t&&(n?.phase===`failed`?l.set(t,n):l.delete(t),A.set(t,k)),w++,u=void 0,Be=e,ce.abort(),ce=new AbortController,k=A.get(e??``)??/* @__PURE__ */ new Map,_e.clear(),O.clear(),ue=[],E.clear(),D=/* @__PURE__ */ new WeakMap,de++,ke(),p({thread:void 0,messages:[],submission:void 0,error:void 0,sandbox:{files:[],commands:[]},sandboxStatus:void 0,usageLimitReached:void 0,pendingInteractions:[],serverToolTitles:{},unavailableMcpConnections:[],messagesCursor:void 0,olderMessagesLoading:!1}),Ge()},Je=async(e,t=!1)=>{qe(e);let r=w;c=l.get(e),c&&p({submission:_(c)});try{if(C||We(),await oe({client:N,selection:r}),r!==w)return;T&&Cf(T,e)}catch(e){if(r!==w)return;t&&(n.threadId===void 0||n.threadId===`auto`)&&or(e)&&e.status===404?Ye():xe(e)}},Ye=()=>{qe(),C&&Te(),T?Cf(T,null):le=!0},Xe=(e=!1)=>{let t=n.threadId;if(t===void 0||t===`auto`){if(!T)return;t=Cf(T)}t&&t!==`new`?t===s.thread?.id&&T?Cf(T,t):Je(t,e):e||Ye()},Ze=async e=>{if(s.thread)return;let t=await j();if(!te(e))throw new DOMException(`Send cancelled`,`AbortError`);let r=await Cr(n.agentId?{agent_id:n.agentId}:{},t);if(!te(e))throw new DOMException(`Send cancelled`,`AbortError`);Be=r.id,p({thread:vf(r,!1)}),Te(),T&&Cf(T,r.id)},Qe=async(e=!0)=>{if(!s.thread)return;let t=w;try{N.detach(),We(),await oe({client:N,selection:t}),e&&t===w&&p({error:void 0})}catch(e){if(t!==w)return;or(e)&&e.status===404?Ye():xe(e)}},F=async()=>{if(!N.getHasOlderMessages()||s.olderMessagesLoading||s.history!==`idle`||c?.phase===`submitting`)return;let e=w;p({olderMessagesLoading:!0});try{await N.loadOlderMessages(),e===w&&P&&Ue()}catch(t){e===w&&xe(t)}finally{e===w&&p({olderMessagesLoading:!1})}},$e=async e=>{let t=s.thread;if(!t||t.role!==`manager`)return!1;let n=w;try{let r=await Dr(t.id,{title:e,expected_version:t.version},await j());if(n!==w)return!1;let i=vf(r,t.hasMessages);return p({thread:i}),!0}catch(e){return n===w&&xe(e),!1}},et=async(e=s.thread)=>{if(!e||e.role!==`manager`)return!1;let t=w;try{return await kr(e.id,{expected_version:String(e.version)},await j()),t===w&&s.thread?.id===e.id&&Ye(),!0}catch(e){return t===w&&xe(e),!1}},I=async e=>{let t=w;if(f||c?.phase===`submitting`||N.getIsLoading()){xe(/* @__PURE__ */ Error(`Wait for this client's current request to finish before responding.`));return}let n=Bf(b),r=ve(e.toolCallId),i=s.pendingInteractions.find(t=>t.toolCallId===e.toolCallId),a=!(`tool`in e)&&i&&(s.thread?.role===`manager`||n.status===`ready`&&i.targetTenantUserId===n.currentUser.user.id),o=`tool`in e&&e.tool===`ask_questionnaire`&&n.status===`ready`&&i?.targetTenantUserId===n.currentUser.user.id;if(s.thread?.role===`viewer`||!ge.has(e.toolCallId)&&!o&&!a&&!k.has(r)){xe(/* @__PURE__ */ Error(`This tool call belongs to another session and cannot be executed here.`));return}if(!k.has(r)){if(a)k.set(r,{outcome:`unknown`,output:null});else if(`tool`in e){let t=e.output;k.set(r,{outcome:e.state===`output-error`?`failed`:`succeeded`,output:t??null})}}let l={kind:`tool-result`,client:N,selection:t};f=l;try{if(p({}),!h(l)||(Ke(),!h(l)))return;if(i){if(l.client.stop(),await Qe(!1),!h(l))return;await l.client.append({role:`tool`,toolCallId:e.toolCallId,content:JSON.stringify(k.get(ve(e.toolCallId)))})}else`tool`in e&&await l.client.addToolResult(e);h(l)&&await Qe(!1)}finally{g(l)}},tt=e=>I({toolCallId:e}),nt=async e=>{if(e!==c||e.phase!==`submitting`)return _(e);let t={kind:`submission`,submission:e,client:N,selection:w};f=t;try{if(await Kf(b),!await se(t)||(await Ze(t),!te(t))||(e.callbacks?.onThreadReady?.(s.thread.id),!te(t))||(Ke(),!await se(t))||(await t.client.sendMessage(e.content),!y(t)))return _(e);ne(e,t.client.getError()),y(t)&&await Qe(!1)}catch(n){if(!y(t))return _(e);let r=n instanceof Error?n:Error(String(n));r.name===`AbortError`?ne(e):ne(e,r)&&be(r)}finally{g(t)}return _(e)},rt=async(e,t)=>{let n=f||c?.phase===`submitting`||N.getIsLoading()?`Wait for this client's current request to finish before sending.`:s.history===`loading`?`Wait for this conversation to load before sending.`:s.history===`failed`?up:s.thread?.agentId===null?`This conversation’s agent is unavailable. Start a new conversation to continue.`:s.thread?.role===`viewer`?`You have read-only access to this conversation.`:c?.phase===`failed`?`The previous message’s acceptance is unconfirmed. Retry that message before sending different text, or start a new conversation.`:void 0;if(n)return{id:_f(),content:e,phase:`refused`,error:Error(n)};let r={id:_f(),content:e,phase:`submitting`,key:_f(),delivery:{state:`undispatched`},callbacks:t};c=r,p({submission:_(r),error:void 0,olderMessagesLoading:!1}),N.stop(),ge.clear(),Ke(),O.clear(),p({activeToolCallIds:[]});let i=new Promise(e=>r.onRefused=e);return Promise.race([nt(r),i.then(()=>_(r))])},it=async()=>{let e=c;if(!f&&!N.getIsLoading()&&e&&ee(e,`submitting`))return p({error:void 0}),nt(e)},at=()=>{let e=Bf(b),t=s.auth;if(e.status===`ready`){let t=Wf(e.currentUser);S!==void 0&&S!==t&&(re(`The account changed before this was sent.`),l.clear(),A.clear(),k.clear(),qe(),T=void 0),S=t;let r=JSON.stringify(Sf(n)),i=`astralbeam:thread:${n.apiUrl??`https://astralbeam.ai/api`}:${t}:session:${r}`;T!==i&&(T!==void 0&&qe(),T=i,le?(Cf(i,null),le=!1):Xe(!0)),we!==t&&(we=t,Te())}p({auth:e}),e.status===`error`&&(t.status!==`error`||t.error!==e.error)&&n.streamCallbacks?.onError?.(e.error)},ot=()=>{if(C)return;C=!0;let e=ce.signal.aborted&&N.getIsHydrating();N.updateOptions({tools:Pe()}),ce.signal.aborted&&(ce=new AbortController),ie=Vf(b,at),at(),x=Zf(b),e?Ge(N.getSnapshot().messages):We()};return t||ot(),{start:ot,getState:()=>s,getOptions:()=>n,attachView:e=>{if(a)throw Error(`This chat session already has a view attached`);let t={options:e},n=()=>{N.updateOptions({tools:Pe()}),Me(s.messages)};return ke(),a=t,n(),{update:e=>{if(a!==t)return;let r=t.options;t.options=e,(r.widgets!==e.widgets||r.onRenderWidget!==e.onRenderWidget)&&n()},dispose:()=>{a===t&&(ke(),a=void 0,n())}}},subscribe:e=>(i.add(e),()=>i.delete(e)),updateOptions:e=>{let t=n.agentId,i=n.apiUrl,a=n.threadId,o=Sf(n),{widgets:c,onRenderWidget:u}=n;n={...n,...e};let d=Sf(n)!==o;r=gf(n.debug),Uf(b,{apiUrl:n.apiUrl,fetchAstralBeamToken:n.fetchAstralBeamToken??{url:`/api/astralbeam/token`}}),b.debug=r,N.updateOptions({tools:Pe(),forwardedProps:Fe()}),n.apiUrl===i?d?(le=!1,(!s.thread||n.threadId!==s.thread.id)&&qe(),T=void 0,at()):n.threadId!==a&&Xe():(re(`The chat service changed before this was sent.`),l.clear(),A.clear(),k.clear(),qe(),T=void 0,at()),(c!==n.widgets||u!==n.onRenderWidget)&&Me(s.messages),C&&(n.agentId!==t||n.apiUrl!==i||d)&&Te()},sendMessage:rt,retry:it,addToolResult:I,stop:()=>{ae++;let e=c,t=f;e?.phase===`submitting`&&ne(e),N.stop(),t&&g(t),e?.phase===`refused`&&e.onRefused?.()},retryAuthentication:()=>{Kf({...b,force:!0}).catch(()=>void 0)},reload:async()=>{let e=w;if(await Qe(),e!==w||s.error)return;let t=/* @__PURE__ */ new Set;for(;e===w;){let e=s.pendingInteractions.find(e=>!t.has(e.sourceMessageId)&&k.has(ve(e.toolCallId)));if(!e||(t.add(e.sourceMessageId),await I({toolCallId:e.toolCallId}),s.error))return}},searchThreads:async(e=``,t,n)=>{let r=await j(),i=await Tr({q:e,page_size:50,...t?{page_after:t}:{}},{...r,signal:AbortSignal.any([r.signal,...n?[n]:[]])});return{items:i.items.map(e=>vf(e)),page_after:i.page_after}},openThread:Je,renameThread:$e,deleteThread:et,refreshThread:()=>Qe(),loadOlderMessages:F,uploadAttachment:async({data:e,filename:t,mimeType:r})=>{let i=s.thread?s.thread.agentId:n.agentId,[a,o]=await Promise.all([e,j(!1)]);return gr({...i?{agentId:i}:{},type:r.startsWith(`image/`)?`image`:`document`,source:{type:`data`,value:a,mimeType:r},metadata:{filename:t}},o)},getThreadAttachment:async(e,t)=>{if(!e.threadId&&!t?.preview)throw Error(`A conversation ID is required to download files.`);return(await vr({...e,delivery:`direct`},{...await j(!!e.threadId||!t?.preview),headers:t?.preview?{"X-File-Preview":`true`}:{}})).blob()},getMcpCatalog:async()=>Ir(await j(!1)),manageMcpConnection:async e=>{let t=await Qf(e,await j(!1));return`id`in e?Se(e.id):t&&`id`in t&&Se(t.id),t},authorizeMcpConnection:async e=>{let t=await $f(e,()=>j(!1));Se(t)},abandonToolCall:tt,reset:()=>{if(r?.(`status`,`conversation reset`),Ye(),s.auth.status===`ready`){let e=JSON.stringify([S,Sf(n)]),t=n.apiUrl??`https://astralbeam.ai/api`;Df(t,e,``,``),Df(t,e,``,``,`sent`),Of({apiUrl:t,identity:e,threadId:``,update:()=>[]}).catch(e=>r?.(`error`,`Draft could not be cleared`,e))}a?.options.onReset()},dispose:()=>{re(`The chat closed before this was sent.`),f=void 0,u=void 0,P?.(),P=void 0,N.detach(),ke(),N.stop(),ce.abort(),w++,Ce++,we=void 0,x?.(),ie?.(),Yf(b),C=!1,queueMicrotask(()=>{C||(N.dispose(),T=void 0,E.clear(),D=/* @__PURE__ */ new WeakMap)}),i.clear()}}}const pp=e=>e[Symbol.toStringTag],mp=(e,t,n)=>{let{alg:r}=e;if(t.use!==void 0){let e=n===`sign`||n===`verify`?`sig`:`enc`;if(t.use!==e)throw TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(t.alg!==void 0&&t.alg!==r)throw TypeError(`Invalid key for this operation, its "alg" must be "${r}" when present`);if(Array.isArray(t.key_ops)){let r=n===`encrypt`||n===`decrypt`?e.ops?.[n===`encrypt`?0:1]:n;if(r&&!t.key_ops.includes(r))throw TypeError(`Invalid key for this operation, its "key_ops" must include "${r}" when present`)}};async function hp(e,t,n){let{alg:r,secret:i}=e,a=n===`decrypt`||n===`sign`;if(i&&t instanceof Uint8Array)return t;let o,s;if(Ja(t)){if(o=Op(t),typeof o.kty!=`string`)throw Sp(r,t,i);if(!(i?o.kty===`oct`&&typeof o.k==`string`:o.kty!==`oct`&&(a?o.kty===`AKP`&&typeof o.priv==`string`||typeof o.d==`string`:o.d===void 0&&o.priv===void 0)))throw TypeError(i?`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`:`JSON Web Key for this operation must be a ${a?`private`:`public`} JWK`);if(mp(e,o,n),o.kty===`oct`)return Ka(o.k);if(!Object.isFrozen(t)){let{key_ops:e}=t;Array.isArray(e)&&Object.freeze(e),Object.freeze(t)}}else{if(!bp(t))throw Sp(r,t,i);let e=i?`secret`:a?`private`:`public`;if(t.type!==e&&(i||[`secret`,`public`,`private`].includes(t.type)))throw TypeError(`${pp(t)} instances must be of type "${e}" for the ${r} algorithm`);if(vp(t))return t;if(s=t,s.type===`secret`)return s.export()}gp||=/* @__PURE__ */ new WeakMap;let c=t,l=gp.get(c);if(l?.[r])return l[r];if(l||gp.set(c,l={}),s&&typeof s.toCryptoKey==`function`){let t=s.type===`public`,n=_p[s.asymmetricKeyDetails?.namedCurve],i=e.resolve?.({crv:n,asymmetricKeyType:s.asymmetricKeyType})??e.subtle;return l[r]=s.toCryptoKey(i,t,e.usages[+!t])}return o??=s.export({format:`jwk`}),o.alg=r,l[r]=await kp(e,o)}let gp;const _p={__proto__:null,prime256v1:`P-256`,secp384r1:`P-384`,secp521r1:`P-521`},vp=e=>{if(e?.[Symbol.toStringTag]===`CryptoKey`)return!0;try{return e instanceof CryptoKey}catch{return!1}},yp=e=>e?.[Symbol.toStringTag]===`KeyObject`,bp=e=>vp(e)||yp(e);function xp(e,t,...n){if(n.length>2){let t=n.pop();e+=`one of type ${n.join(`, `)}, or ${t}.`}else n.length===2?e+=`one of type ${n[0]} or ${n[1]}.`:e+=`of type ${n[0]}.`;return t==null?e+=` Received ${t}`:typeof t==`function`&&t.name?e+=` Received function ${t.name}`:typeof t==`object`&&t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}function Sp(e,t,n){let r=[`CryptoKey`,`KeyObject`,`JSON Web Key`];return n&&r.push(`Uint8Array`),TypeError(xp(`Key for the ${e} algorithm must be `,t,...r))}const Cp=(e,t=`algorithm.name`)=>/* @__PURE__ */ TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function wp(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function Tp(e,t){let{modulusLength:n}=t.algorithm;if(typeof n!=`number`||n<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}function Ep(e,t,n){let r=e.algorithm;if(r.name!==t.name)throw Cp(t.name);if(t.hash&&r.hash?.name!==t.hash)throw Cp(t.hash,`algorithm.hash`);if(t.namedCurve&&r.namedCurve!==t.namedCurve)throw Cp(t.namedCurve,`algorithm.namedCurve`);if(t.length!==void 0&&r.length!==t.length)throw Cp(t.length,`algorithm.length`);wp(e,n)}function Dp(e){return{__proto__:null,...e}}function Op(e){let t=Dp(e);if(t.ext!==void 0&&typeof t.ext!=`boolean`)throw TypeError(`"ext" (Extractable) Parameter must be a boolean`);if(t.key_ops!==void 0){let e=t.key_ops,n=Array.isArray(e)?[...e]:void 0;if(!n||n.some(e=>typeof e!=`string`)||new Set(n).size!==n.length)throw TypeError(`"key_ops" (Key Operations) Parameter must be an array of unique strings`);t.key_ops=n}return t}async function kp(e,t,n){if(!e.kty.includes(t.kty))throw new Ua(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`);let r=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,i=!!(t.d||t.priv),a={...t,ext:n??t.ext};return a.kty!==`AKP`&&delete a.alg,delete a.use,crypto.subtle.importKey(`jwk`,a,r,a.ext??!i,t.key_ops??e.usages[+!!i])}async function Ap(e,t,n,r=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey(`raw`,e,t,r,[n])),Ep(e,t,n),e}function jp(e){let t={__proto__:null};for(let n in e)t[n]={...e[n],alg:n};return t}const Mp=[[`verify`],[`sign`]];function Np(e){let t={name:`HMAC`,hash:`SHA-${e}`};return{kty:[`oct`],secret:!0,subtle:t,signing:t,usages:Mp}}function Pp(e,t){let n={name:t?`RSA-PSS`:`RSASSA-PKCS1-v1_5`,hash:`SHA-${e}`};return{kty:[`RSA`],subtle:n,signing:t?{...n,saltLength:t}:n,usages:Mp,minRsaBits:2048}}function Fp(e,t){return{kty:[`EC`],crv:e,subtle:{name:`ECDSA`,namedCurve:e},signing:{name:`ECDSA`,hash:`SHA-${t}`},usages:Mp}}function Ip(){let e={name:`Ed25519`};return{kty:[`OKP`],crv:`Ed25519`,subtle:e,signing:e,usages:Mp}}function Lp(e){let t={name:`ML-DSA-${e}`};return{kty:[`AKP`],subtle:t,signing:t,usages:Mp}}const Rp=jp({HS256:Np(256),HS384:Np(384),HS512:Np(512),RS256:Pp(256),RS384:Pp(384),RS512:Pp(512),PS256:Pp(256,32),PS384:Pp(384,48),PS512:Pp(512,64),ES256:Fp(`P-256`,256),ES384:Fp(`P-384`,384),ES512:Fp(`P-521`,512),EdDSA:Ip(),Ed25519:Ip(),"ML-DSA-44":Lp(44),"ML-DSA-65":Lp(65),"ML-DSA-87":Lp(87)});function zp(e){let t=typeof e==`string`?Rp[e]:void 0;if(!t)throw new Ua(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}const Bp=e=>Math.floor(e.getTime()/1e3),Vp={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},Hp=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function Up(){throw TypeError(`Invalid time period format`)}function Wp(e){typeof e!=`string`&&Up();let t=Hp.exec(e);(!t||t[4]&&t[1])&&Up();let n=parseFloat(t[2]),r=Math.round(n*Vp[t[3][0].toLowerCase()]);return Number.isFinite(r)||Up(),t[1]===`-`||t[4]===`ago`?-r:r}function Gp(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}function Kp(e,t){if(typeof t!=`string`)throw TypeError(`"${e}" claim must be a string`)}function qp(e){if(typeof e!=`string`&&(!Array.isArray(e)||Array.from(e).some(e=>typeof e!=`string`)))throw TypeError(`"aud" claim must be a string or an array of strings`)}function Jp(e,t){return typeof e==`number`?Gp(t,e):e instanceof Date?Gp(t,Bp(e)):Bp(/* @__PURE__ */ new Date)+Wp(e)}let Yp;function Xp(e){return Yp.get(e)}function Zp(e){let t=Xp(e);for(let e of[`iat`,`nbf`,`exp`]){let n=t[e];if(typeof n==`number`&&!Number.isFinite(n))throw TypeError(`"${e}" claim must be a finite number`)}return Pa.encode(JSON.stringify(t))}var Qp=class{constructor(e={}){if(!Ja(e))throw TypeError(`JWT Claims Set MUST be an object`);(Yp||=/* @__PURE__ */ new WeakMap).set(this,structuredClone(e))}setIssuer(e){return Kp(`iss`,e),Xp(this).iss=e,this}setSubject(e){return Kp(`sub`,e),Xp(this).sub=e,this}setAudience(e){return qp(e),Xp(this).aud=e,this}setJti(e){return Kp(`jti`,e),Xp(this).jti=e,this}setNotBefore(e){return Xp(this).nbf=Jp(e,`setNotBefore`),this}setExpirationTime(e){return Xp(this).exp=Jp(e,`setExpirationTime`),this}setIssuedAt(e){let t=Xp(this);return t.iat=e===void 0?Bp(/* @__PURE__ */ new Date):typeof e==`string`?Gp(`setIssuedAt`,Bp(/* @__PURE__ */ new Date)+Wp(e)):Jp(e,`setIssuedAt`),this}};async function $p(e,t,n){let[r,i,a,o]=e,s=``;if(i!==void 0){let e=to(Wa,i);i=e[0],s=qa(e[1])}if(a!==void 0&&(a=to(Wa,a)[0]),!i&&!a)throw new Wa(`either setProtectedHeader or setUnprotectedHeader must be called before #sign()`);if(!Ya(i,a))throw new Wa(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let c={...i,...a};Qa(Wa,i);let l=eo(i,$a(Wa,Za,o,i,c));l||n?.();let{alg:u}=c;if(typeof u!=`string`||!u)throw new Wa(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);let d=zp(u),f=``,p=r,m;if(l){let t=e[4];t?(f=t[0]??=qa(r),p=t[1]??=za(f)):(f=qa(r),m=Pa.encode(`${s}.${f}`))}m??=La(za(s),za(`.`),p);let h=await Ap(await hp(d,t,`sign`),d.subtle,`sign`);d.minRsaBits&&Tp(d.alg,h);let g={signature:qa(new Uint8Array(await crypto.subtle.sign(d.signing,h,m))),payload:f};return i&&(g.protected=s),a&&(g.header=a),[g,l]}async function em(e,t,n,r,i){let[a]=await $p([e,t,void 0,n],r,i);return`${a.protected}.${a.payload}.${a.signature}`}const tm=Qp;var nm=class extends tm{#e;setProtectedHeader(e){return Xa(this.#e,`setProtectedHeader`),this.#e=e,this}async sign(e,t){return em(Zp(this),this.#e,t?.crit,e,()=>{throw new Ga(`JWTs MUST NOT use unencoded payload`)})}};const rm=`astralbeam`,im=16384,am=8192,om=/^key_[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}_[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}_abo_[A-Za-z]{64}$/,sm=/^limit_[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}_[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,cm=[`id`,`name`,`metadata`],lm=[`id`,`name`,`admin`,`metadata`],um=new TextEncoder;function dm(e){if(!om.test(e))throw Error(`apiKey must match key_<organizationId>_<id>_abo_<secret>`);let t=e.lastIndexOf(`_abo_`),n=e.slice(0,t),r=e.slice(t+1);return{keyId:n,organizationId:n.slice(4,n.indexOf(`_`,4)),keySecret:r}}function fm(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function pm(e){return e===null||typeof e==`string`||typeof e==`boolean`?!0:typeof e==`number`?Number.isFinite(e):Array.isArray(e)?e.every(pm):fm(e)&&Object.values(e).every(pm)}function mm(e,t,n){if(!fm(t))throw Error(`${e} must be an object`);let r=n?lm:cm;for(let n of Object.keys(t))if(!r.includes(n))throw Error(`${e} has an unknown field "${n}"`);let{id:i,name:a,admin:o,metadata:s}=t;if(typeof i!=`string`||i.length<1||i.length>255)throw Error(`${e}.id must be a 1-255 character string`);if(a!==void 0&&typeof a!=`string`)throw Error(`${e}.name must be a string`);if(n&&o!==void 0&&typeof o!=`boolean`)throw Error(`${e}.admin must be a boolean`);if(s!==void 0&&!(fm(s)&&pm(s)))throw Error(`${e}.metadata must be a JSON object`)}function hm(e,t){mm(`user`,e,!0),mm(`tenant`,t,!1);let n=JSON.stringify({user:e,tenant:t});if(um.encode(n).byteLength>am)throw Error(`user and tenant must not exceed ${am} bytes`);return JSON.parse(n)}async function gm(e){let t=await crypto.subtle.digest(`SHA-256`,um.encode(e));return um.encode(qa(new Uint8Array(t)))}async function _m({apiKey:e,email:t,organizationId:n,expiresInSeconds:r=300}){if(typeof t!=`string`||t.length>320||t.includes(`\0`)||!/^[^\s@]+@[^\s@]+$/.test(t))throw Error(`email must be an email address of at most 320 characters`);if(!Number.isInteger(r)||r<60||r>600)throw Error(`organization auth tokens must live for 60-600 seconds`);let{keyId:i,organizationId:a,keySecret:o}=dm(e);if(n!==a)throw Error(`organizationId must match the API key organization`);let s=Math.floor(Date.now()/1e3);return await new nm({ver:1,email:t,organization_id:n}).setProtectedHeader({alg:`HS256`,typ:`astralbeam-organization+jwt`,kid:i}).setIssuer(n).setAudience(rm).setIssuedAt(s).setExpirationTime(s+r).sign(await gm(o))}async function vm({apiKey:e,user:t,tenant:n,usageLimits:r,expiresInSeconds:i=300}){if(!Number.isInteger(i)||i<60||i>600)throw Error(`chat auth tokens must live for 60-600 seconds`);let{keyId:a,organizationId:o,keySecret:s}=dm(e),c=hm(t,n);if(r!==void 0&&(!Array.isArray(r)||r.length>20||!r.every(e=>typeof e==`string`&&sm.test(e))))throw Error(`usageLimits must list at most 20 IDs of the form limit_<organizationId>_<id>`);let l=Math.floor(Date.now()/1e3),u=await new nm({ver:4,user:c.user,tenant:c.tenant,...r?.length?{usage_limits:[...new Set(r)]}:{}}).setProtectedHeader({alg:`HS256`,typ:`astralbeam+jwt`,kid:a}).setIssuer(o).setAudience(rm).setIssuedAt(l).setExpirationTime(l+i).sign(await gm(s));if(um.encode(u).byteLength>im)throw Error(`chat auth tokens must not exceed ${im} bytes`);return u}function ym(e){return e.string([`tenant`,`user`,`tenant-name`,`user-name`]).demandOption([`tenant`,`user`]).boolean(`admin`).number(`expires-in`).coerce(`expires-in`,tr).describe({tenant:`Tenant external ID, signed as tenant.id`,user:`TenantUser external ID, signed as user.id`,"tenant-name":`Tenant display name`,"user-name":`TenantUser display name`,admin:`sign user.admin: true, granting Tenant admin API access`,"expires-in":`token lifetime, 60-600 (default 300)`})}function bm(e){return{tenant:{id:e.tenant,...e.tenantName===void 0?{}:{name:e.tenantName}},user:{id:e.user,...e.userName===void 0?{}:{name:e.userName},...e.admin?{admin:!0}:{}}}}function xm(e,t,n){let r=new Date(Date.now()+t*1e3).toISOString();n?Qr({token:e,expires_at:r}):s.write(`${e}\n`)}function Sm(e){return e.command(`chat`,`Mint a chat JWT for a Tenant's user, as a token endpoint would`,ym,async e=>{let{apiKey:t}=await xi(),n=e.expiresIn??300;xm(await vm({apiKey:t,expiresInSeconds:n,...bm(e)}),n,K.json)}),e.command(`organization`,`Mint an organization-management JWT delegating a member's current role`,e=>e.string(`email`).demandOption(`email`).number(`expires-in`).coerce(`expires-in`,tr).describe({email:`email of an existing member of the organization`,"expires-in":`token lifetime, 60-600 (default 300)`}),async e=>{let{apiKey:t}=await xi(),n=e.expiresIn??300;xm(await _m({apiKey:t,email:e.email,organizationId:li(t),expiresInSeconds:n}),n,K.json)}),e.demandCommand(1)}function Cm(e){return e.filter(e=>e.role===`assistant`).map(e=>e.parts.map(e=>e.type===`text`?e.content:``).join(``)).filter(Boolean).join(`
|
|
149
149
|
|
|
150
150
|
`)}async function wm(e,t,n){let r=e.getState().messages.length,i=``,o=/* @__PURE__ */ new Set,c=e.subscribe(()=>{if(n)return;let t=e.getState().messages.slice(r),c=Cm(t);c.startsWith(i)&&(s.write($r(c.slice(i.length),`
|
|
151
151
|
`)),i=c);for(let e of t.flatMap(e=>e.parts))e.type!==`tool-call`||o.has(e.id)||(o.add(e.id),a.write(`[tool ${$r(e.name)}]\n`))});try{let n=await e.sendMessage(t);if(n.phase!==`accepted`)throw n.error??/* @__PURE__ */ Error(`The chat message was not accepted.`)}finally{c()}let{error:l,messages:u}=e.getState();if(l)throw l;n?Qr({messages:u.slice(r)}):i.endsWith(`
|
|
152
152
|
`)||s.write(`
|
|
153
|
-
`)}async function Tm(e){let t=
|
|
154
|
-
`);try{for(;;){let n=(await t.question(`> `).catch(()=>`/exit`)).trim();if(n===`/exit`)return;n&&await wm(e,n,!1)}}finally{t.close()}}function Em(e){e.command(`chat [message]`,`Chat with an agent as one of a Tenant's users, like the embedded widget`,e=>ym(e).positional(`message`,{type:`string`,description:`message to send (default: stdin when piped, else an interactive prompt)`}).option(`agent`,{type:`string`,description:`public agent ID (default: the organization's default agent)`}),async e=>{let{json:t,message:n}=e,{apiKey:r,apiUrl:i}=await xi(),a=e.expiresIn??300,s=bm(e),c=fp({apiUrl:i,...e.agent===void 0?{}:{agentId:e.agent},fetchAstralBeamToken:async()=>({token:await vm({apiKey:r,expiresInSeconds:a,...s})})});try{if(n!==void 0)await wm(c,n,t);else if(!o.isTTY)await wm(c,(await
|
|
153
|
+
`)}async function Tm(e){let t=E({input:o,output:s});a.write(`Type a message, or /exit to quit.
|
|
154
|
+
`);try{for(;;){let n=(await t.question(`> `).catch(()=>`/exit`)).trim();if(n===`/exit`)return;n&&await wm(e,n,!1)}}finally{t.close()}}function Em(e){e.command(`chat [message]`,`Chat with an agent as one of a Tenant's users, like the embedded widget`,e=>ym(e).positional(`message`,{type:`string`,description:`message to send (default: stdin when piped, else an interactive prompt)`}).option(`agent`,{type:`string`,description:`public agent ID (default: the organization's default agent)`}),async e=>{let{json:t,message:n}=e,{apiKey:r,apiUrl:i}=await xi(),a=e.expiresIn??300,s=bm(e),c=fp({apiUrl:i,...e.agent===void 0?{}:{agentId:e.agent},fetchAstralBeamToken:async()=>({token:await vm({apiKey:r,expiresInSeconds:a,...s})})});try{if(n!==void 0)await wm(c,n,t);else if(!o.isTTY)await wm(c,(await ue(o)).trim(),t);else if(t)throw new er(`Pass a message or pipe one on stdin with --json.`);else await Tm(c)}finally{c.dispose()}})}const Dm=new URL(`skills/astralbeam/SKILL.md`,import.meta.url);function Om(e){return e.command({command:`$0`,describe:!1,handler:async()=>{let e=await b(Dm,`utf8`);K.json?ni({content:e},!0):s.write(e)}}),e.command(`install`,`Write the skill to <dir>/astralbeam/SKILL.md`,e=>e.option(`dir`,{type:`string`,default:`.agents/skills`,description:`skills directory relative to the current directory, or an absolute path`}),async e=>{let t=ce(e.dir,`astralbeam`);await re(t,{recursive:!0});let n=se(t,`SKILL.md`);await C(n,await b(Dm,`utf8`)),K.json||a.write(`Restart your agent session to load the skill.
|
|
155
155
|
`),ni({path:n},K.json)}),e}const km=`
|
|
156
156
|
Environment:
|
|
157
157
|
ASTRALBEAM_API_KEY organization API key, used instead of directory logins
|