@astralbeam/cli 0.24.0 → 0.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -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 ee,statSync as _,writeFile as te}from"fs";import{format as v,inspect as y}from"util";import{fileURLToPath as ne}from"url";import{mkdir as re,readFile as b,realpath as x,rename as S,rm as ie,writeFile as C}from"node:fs/promises";import{isIPv4 as ae}from"node:net";import{homedir 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 ee,statSync as _,writeFile as te}from"fs";import{format as v,inspect as y}from"util";import{fileURLToPath as ne}from"url";import{mkdir as re,readFile as b,realpath as x,rename as S,rm as ie,writeFile as C}from"node:fs/promises";import{isIPv4 as ae}from"node:net";import{homedir as oe}from"node:os";import{dirname as w,join as se,resolve as ce,sep as le}from"node:path";import{readFileSync as ue}from"node:fs";import{text as de}from"node:stream/consumers";import{createInterface as fe}from"node:readline/promises";var pe=Object.defineProperty,T=(e,t)=>{let n={};for(var r in e)pe(n,r,{get:e[r],enumerable:!0});return t||pe(n,Symbol.toStringTag,{value:`Module`}),n},me=/* @__PURE__ */ e(import.meta.url);const he={right:ve,center:ye};var E=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&&O.stringWidth(e[0])>n&&(n=Math.min(Math.floor(this.width*.5),O.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=O.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>O.stringWidth(n)&&(c+=` `.repeat(s-O.stringWidth(n))),e[a].align&&e[a].align!==`left`&&this.wrap){let t=he[e[a].align];c=t(c,s),O.stringWidth(c)<s&&(c+=` `.repeat((o||0)-O.stringWidth(c)-1))}let l=e[a].padding||[0,0,0,0];l[3]&&(i+=` `.repeat(l[3])),i+=ge(e[a],c,`| `),i+=c,i+=ge(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=O.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?O.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||O.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,D(e[n])):t)}};function ge(e,t,n){return e.border?/[.']-+[.']/.test(t)?``:t.trim().length===0?` `:n:``}function D(e){let t=e.padding||[],n=1+(t[3]||0)+(t[1]||0);return e.border?n+4:n}function _e(){return typeof process==`object`&&process.stdout&&process.stdout.columns?process.stdout.columns:80}function ve(e,t){e=e.trim();let n=O.stringWidth(e);return n<t?` `.repeat(t-n)+e:e}function ye(e,t){e=e.trim();let n=O.stringWidth(e);return n>=t?e:` `.repeat(t-n>>1)+e}let O;function be(e,t){return O=t,new E({width:e?.width||_e(),wrap:e?.wrap})}const xe=/* @__PURE__ */ RegExp(`\x1B(?:\\[(?:\\d+[ABCDEFGJKSTm]|\\d+;\\d+[Hfm]|\\d+;\\d+;\\d+m|6n|s|u|\\?25[lh])|\\w)`,`g`);function k(e){return e.replace(xe,``)}function Se(e,t){let[n,r]=e.match(xe)||[``,``];e=k(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 Ce(e){return be(e,{stringWidth:e=>[...e].length,stripAnsi:k,wrap:Se})}function we(e,t){let n=h(`.`,e),r;for(_(n).isDirectory()||(n=d(n));;){if(r=t(n,ee(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 Te(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 Ee(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 De(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 Oe(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 A;(function(e){e.BOOLEAN=`boolean`,e.STRING=`string`,e.NUMBER=`number`,e.ARRAY=`array`})(A||={});
|
|
25
25
|
/**
|
|
26
26
|
* @license
|
|
27
27
|
* Copyright (c) 2016, Contributors
|
|
28
28
|
* SPDX-License-Identifier: ISC
|
|
29
29
|
*/
|
|
30
|
-
let Oe;var ke=class{constructor(e){Oe=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=De(e),i=typeof e==`string`,a=Ae(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.__||Oe.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)})),fe(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;ye();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)&&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&&(E(c[1],h.arrays)?e=b(e,c[1],r,c[2]):E(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,E(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],E(a,h.arrays)?e=b(e,a,r):E(a,h.nargs)===!1?(l=r[e+1],l!==void 0&&(!l.match(/^-/)||l.match(g))&&!E(a,h.bools)&&!E(a,h.counts)||/^(true|false)$/.test(l)?(x(a,l),e++):x(a,ge(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(/^-/)&&!E(a,h.bools)&&!E(a,h.counts)?(x(a,l),e++):x(a,ge(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],E(a,h.arrays)?e=b(e,a,r,u):E(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)&&E(l,h.bools)===!1||s[n+1]&&s[n+1].match(/\W/)){x(s[n],l),i=!0;break}x(s[n],ge(s[n]))}}a=t.slice(-1)[0],!i&&a!==`-`&&(E(a,h.arrays)?e=b(e,a,r):E(a,h.nargs)===!1?(l=r[e+1],l!==void 0&&(!/^(-|--)[^-]/.test(l)||l.match(g))&&!E(a,h.bools)&&!E(a,h.counts)||/^(true|false)$/.test(l)?(x(a,l),e++):x(a,ge(a))):e=re(e,a,r))}else if(t.match(/^-[0-9]$/)&&t.match(g)&&E(t.slice(1),h.bools))a=t.slice(1),x(a,ge(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)}oe(v,!0),oe(v,!1),ae(v),T(),le(v,h.aliases,s,!0),se(v),o[`set-placeholder-key`]&&ce(v),Object.keys(h.counts).forEach(function(e){ue(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=>we(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=E(t,h.nargs);if(a=typeof a!=`number`||isNaN(a)?1:a,a===0)return k(r)||(_=Error(m(`Argument unexpected for: %s`,t))),x(t,ge(t)),e;let s=+!k(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)||he(n[i]));i++)s++;s<a&&(_=Error(m(`Not enough arguments following: %s`,t)))}let c=Math.min(s,a);for(!k(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=E(t,h.nargs);if(E(t,h.bools)&&!/^(true|false)$/.test(c))a.push(!0);else if(k(c)||k(r)&&/^-/.test(c)&&!g.test(c)&&!he(c)){if(s[t]!==void 0){let e=s[t];a=Array.isArray(e)?e:[e]}}else{k(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)&&!he(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 we(e)}).join(`.`));let r=ie(e,t,n),a=e.split(`.`);de(v,a,r),h.aliases[e]&&h.aliases[e].forEach(function(e){let t=e.split(`.`);de(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(`.`))||de(v,n,r)}),E(e,h.normalize)&&!E(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`?Oe.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=Ne(t)),(E(e,h.bools)||E(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 E(e,h.counts)&&(k(r)||typeof r==`boolean`)&&(r=je()),E(e,h.normalize)&&E(e,h.arrays)&&(r=Array.isArray(t)?t.map(e=>Oe.normalize(e)):Oe.normalize(t)),r}function C(e,t){return!o[`parse-positional-numbers`]&&e===`_`||!E(e,h.strings)&&!E(e,h.bools)&&!Array.isArray(t)&&(Ee(t)&&o[`parse-numbers`]&&Number.isSafeInteger(Math.floor(parseFloat(`${t}`)))||!k(t)&&E(e,h.numbers))&&(t=Number(t)),t}function ae(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=Oe.resolve(Oe.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=Oe.require(t);w(e)}catch(t){t.name===`PermissionDenied`?_=t:e[n]&&(_=Error(m(`Invalid JSON config file: %s`,r)))}})}function w(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`]?w(r,i):(!ue(v,i.split(`.`))||E(i,h.arrays)&&o[`combine-arrays`])&&x(i,r)})}function T(){c!==void 0&&c.forEach(function(e){w(e)})}function oe(e,t){if(l===void 0)return;let n=typeof l==`string`?l:``,r=Oe.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)),we(e)});(t&&h.configs[a.join(`.`)]||!t)&&!ue(e,a)&&x(a.join(`.`),r[i])}})}function se(e){let t,n=/* @__PURE__ */ new Set;Object.keys(e).forEach(function(r){if(!n.has(r)&&(t=E(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 ce(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(`.`))||(de(e,i.split(`.`),n[i]),r&&(p[i]=!0),(t[i]||[]).forEach(function(t){ue(e,t.split(`.`))||de(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 de(e,t,n){let r=e;o[`dot-notation`]||(t=[t.join(`.`)]),t.slice(0,-1).forEach(function(e){e=Me(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=Me(t[t.length-1]),a=E(t.join(`.`),h.arrays),s=Array.isArray(n),c=o[`duplicate-arguments-array`];!c&&E(i,h.nargs)&&(c=!0,(!k(r[i])&&h.nargs[i]===1||Array.isArray(r[i])&&r[i].length===h.nargs[i])&&(r[i]=void 0)),n===je()?r[i]=je(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||E(i,h.counts)||E(i,h.bools))?r[i]=[r[i],n]:r[i]=n}function fe(...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=we(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=Te(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 E(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 pe(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 me(e,...t){return[].concat(...t).some(function(t){let n=e.match(t);return n&&pe(n[1])})}function D(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),!pe(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`]&&O(e)}function O(e){return e=e.replace(/^-{3,}/,`--`),e.match(g)||D(e)?!1:!me(e,/^-+([^=]+?)=[\s\S]*$/,ee,/^-+([^=]+?)$/,/^-+([^=]+?)-$/,/^-+([^=]+?\d+)$/,/^-+([^=]+?)\W+.*$/)}function ge(e){return!E(e,h.bools)&&!E(e,h.counts)&&`${e}`in s?s[e]:_e(ve(e))}function _e(e){return{[j.BOOLEAN]:!0,[j.STRING]:``,[j.NUMBER]:void 0,[j.ARRAY]:[]}[e]}function ve(e){let t=j.BOOLEAN;return E(e,h.strings)?t=j.STRING:E(e,h.numbers)?t=j.NUMBER:E(e,h.bools)?t=j.BOOLEAN:E(e,h.arrays)&&(t=j.ARRAY),t}function k(e){return e===void 0}function ye(){Object.keys(h.counts).find(e=>E(e,h.arrays)?(_=Error(m(`Invalid configuration: %s, opts.count excludes opts.array.`,e)),!0):E(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 Ae(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 je(e){return e===void 0?1:e+1}function Me(e){return e===`__proto__`?`___proto___`:e}function Ne(e){return typeof e==`string`&&(e[0]===`'`||e[0]===`"`)&&e[e.length-1]===e[0]?e.substring(1,e.length-1):e}
|
|
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}
|
|
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 Oe;var ke=class{constructor(e){Oe=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 Pe=process&&process.env&&process.env.YARGS_MIN_NODE_VERSION?Number(process.env.YARGS_MIN_NODE_VERSION):12,Fe=(process==null?void 0:process.versions)?.node??(process==null?void 0:process.version)?.slice(1);if(Fe&&Number(Fe.match(/^([^.]+)/)[1])<Pe)throw Error(`yargs parser supports a minimum Node.js version of ${Pe}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`);const Ie=process?process.env:{},Le=new ke({cwd:process.cwd,env:()=>Ie,format:v,normalize:p,resolve:h,require:e=>{if(pe!==void 0)return pe(e);if(e.match(/\.json$/))return JSON.parse(g(e,`utf8`));throw Error(`only .json config files are supported in ESM`)}}),Re=function(e,t){return Le.parse(e.slice(),t).argv};Re.detailed=function(e,t){return Le.parse(e.slice(),t)},Re.camelCase=we,Re.decamelize=Te,Re.looksLikeNumber=Ee;function M(){return+!ze()}function ze(){return Be()&&!process.defaultApp}function Be(){return!!process.versions.electron}function Ve(){return process.argv[M()]}var N=class e extends Error{constructor(t){super(t||`yargs error`),this.name=`YError`,Error.captureStackTrace&&Error.captureStackTrace(this,e)}},He={fs:{readFileSync:g,writeFile:te},format:v,resolve:h,exists:e=>{try{return _(e).isFile()}catch{return!1}}};let P;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(),P.format.apply(P.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),P.format.apply(P.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);P.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{P.fs.readFileSync&&(e=JSON.parse(P.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=P.resolve(e,`./`,t+`.json`);if(this.fallbackToLanguage&&!this._fileExistsSync(n)&&~t.lastIndexOf(`_`)){let r=P.resolve(e,`./`,t.split(`_`)[0]+`.json`);this._fileExistsSync(r)&&(n=r)}return n}_fileExistsSync(e){return P.exists(e)}};function We(e,t){P=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,He),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:Ce,getEnv:e=>process.env[e],inspect:y,getCallerFile:()=>{throw new N(Ke)},getProcessArgvBin:Ve,mainFilename:Je||process.cwd(),Parser:Re,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 N(`require is not supported by ESM`)},requireDirectory:()=>{throw new N(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 N(`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 N(`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 N(`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(pe===void 0)return null;for(let t=0,n=Object.keys(pe.cache),r;t<n.length;t++)if(r=pe.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 N(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(wt(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]=St(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:wt(i),padding:[0,2,0,2+Ct(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 _(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} ${
|
|
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 _(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} ${Et(e[0])}`:Et(e[0]))+Tt(e[0]),i)}),n&&(i=Math.min(i,parseInt((n*.5).toString(),10))),i}function te(){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 v;r.cacheHelpMessage=function(){v=this.help()},r.clearCachedHelpMessage=function(){v=void 0},r.hasCachedHelpMessage=function(){return!!v};function y(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=yt(p,t=>!e[t]),r};let S=[];return r.freeze=function(){S.push({failMessage:a,failureOutput:c,usages:l,usageDisabled:u,epilogs:m,examples:d,commands:f,descriptions:p})},r.unfreeze=function(e=!1){let t=S.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 Ct(e){return typeof e==`object`}function wt(e,t){return Ct(e)?{text:e.text,indentation:e.indentation+t}:{text:e,indentation:t}}function Tt(e){return Ct(e)?e.indentation:0}function Et(e){return Ct(e)?e.text:e}var Dt=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(gt(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=tt(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(Qe(this.customCompletionFunction,null,this.shim),kt(this.customCompletionFunction)){let e=this.customCompletionFunction(n,t);return N(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 At(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 N(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,77 +84,79 @@ _{{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=>{!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=pe.resolve(e.extends)}catch{return e}Ft(a),Mt.push(a),i=r?JSON.parse(Nt.readFileSync(a,`utf8`)):pe(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 N(`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 N(`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 N(`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 N(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 N(`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`),
|
|
90
|
-
`,`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 N(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 N(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 N)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 N(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.24.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 oe(n.ASTRALBEAM_CONFIG_DIR,`config.json`);let e=i===`win32`?n.APPDATA??w():n.XDG_CONFIG_HOME??oe(w(),`.config`);return oe(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(T(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=T(n)){let t=e.bindings[n];if(t)return{directory:n,binding:t};if(T(n)===n)return}}function vi(e){let t=w();return e===t||e.startsWith(t+ce)?`~${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=se(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=se(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
|
-
`),`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/
|
|
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 Ot(e,t,n,r){return new Dt(e,t,n,r)}function kt(e){return e.length<3}function At(e){return e.length>3}function jt(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 Mt=[`$0`,`--`,`_`];function Nt(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=>{!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`),I(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&&(I(this,V,`f`).defaultDescription[e]=t.defaultDescription),t.skipValidation&&this.skipValidation(e);let i=t.describe||t.description||t.desc,a=I(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){P(`[string|array] [function|boolean|object] [function]`,[e,t,n],arguments.length),this[yn](),e===void 0&&(e=I(this,sn,`f`)),typeof t==`object`&&(F(this,rn,t,`f`),t=n),typeof t==`function`&&(F(this,nn,t,`f`),t=!1),t||F(this,sn,e,`f`),I(this,nn,`f`)&&F(this,qt,!1,`f`);let r=this[qn](e,!!t),i=this.parsed;return I(this,Ht,`f`).setParsed(this.parsed),N(r)?r.then(e=>(I(this,nn,`f`)&&I(this,nn,`f`).call(this,I(this,Wt,`f`),e,I(this,B,`f`)),e)).catch(e=>{throw I(this,nn,`f`)&&I(this,nn,`f`)(e,this.parsed.argv,I(this,B,`f`)),e}).finally(()=>{this[Nn](),this.parsed=i}):(I(this,nn,`f`)&&I(this,nn,`f`).call(this,I(this,Wt,`f`),r,I(this,B,`f`)),this[Nn](),this.parsed=i,r)}parseAsync(e,t,n){let r=this.parse(e,t,n);return N(r)?r:Promise.resolve(r)}parseSync(e,t,n){let r=this.parse(e,t,n);if(N(r))throw new M(`.parseSync() must not be used with asynchronous builders, handlers, or middleware`);return r}parserConfiguration(e){return P(`<object>`,[e],arguments.length),F(this,tn,e,`f`),this}pkgConf(e,t){P(`<string> [string]`,[e,t],arguments.length);let n=null,r=this[En](t||I(this,Bt,`f`));return r[e]&&typeof r[e]==`object`&&(n=It(r[e],t||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(n)),this}positional(e,t){P(`<string> <object>`,[e,t],arguments.length);let n=[`default`,`defaultDescription`,`implies`,`normalize`,`choices`,`conflicts`,`coerce`,`type`,`describe`,`desc`,`description`,`alias`];t=yt(t,(e,t)=>e===`type`&&![`string`,`number`,`boolean`].includes(t)?!1:n.includes(e));let r=I(this,Vt,`f`).fullCommands[I(this,Vt,`f`).fullCommands.length-1],i=r?I(this,L,`f`).cmdToParseOptions(r):{array:[],alias:{},default:{},demand:{}};return et(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,I(this,U,`f`).getPositionalGroupName()),this.option(e,t)}recommendCommands(e=!0){return P(`[boolean]`,[e],arguments.length),F(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 P(`<array|string|object> [number]`,[e],arguments.length),typeof e==`string`&&I(this,V,`f`).narg[e]||this[On](this.requiresArg.bind(this),`narg`,e,NaN),this}showCompletionScript(e,t){return P(`[string] [string]`,[e,t],arguments.length),e||=this.$0,I(this,$t,`f`).log(I(this,Ht,`f`).generateCompletionScript(e,t||I(this,R,`f`)||`completion`)),this}showHelp(e){if(P(`[string|function]`,[e],arguments.length),F(this,z,!0,`f`),!I(this,U,`f`).hasCachedHelpMessage()){if(!this.parsed){let t=this[qn](I(this,sn,`f`),void 0,void 0,0,!0);if(N(t))return t.then(()=>{I(this,U,`f`).showHelp(e)}),this}let t=I(this,L,`f`).runDefaultBuilderOn(this);if(N(t))return t.then(()=>{I(this,U,`f`).showHelp(e)}),this}return I(this,U,`f`).showHelp(e),this}scriptName(e){return this.customScriptName=!0,this.$0=e,this}showHelpOnFail(e,t){return P(`[boolean|string] [string]`,[e,t],arguments.length),I(this,U,`f`).showHelpOnFail(e,t),this}showVersion(e){return P(`[string|function]`,[e],arguments.length),I(this,U,`f`).showVersion(e),this}skipValidation(e){return P(`<array|string>`,[e],arguments.length),this[Dn](`skipValidation`,e),this}strict(e){return P(`[boolean]`,[e],arguments.length),F(this,ln,e!==!1,`f`),this}strictCommands(e){return P(`[boolean]`,[e],arguments.length),F(this,un,e!==!1,`f`),this}strictOptions(e){return P(`[boolean]`,[e],arguments.length),F(this,dn,e!==!1,`f`),this}string(e){return P(`<array|string>`,[e],arguments.length),this[Dn](`string`,e),this[Xn](e),this}terminalWidth(){return P([],0),I(this,H,`f`).process.stdColumns}updateLocale(e){return this.updateStrings(e)}updateStrings(e){return P(`<object>`,[e],arguments.length),F(this,Gt,!1,`f`),I(this,H,`f`).y18n.updateLocale(e),this}usage(e,t,n,r){if(P(`<string|null|undefined> [string|boolean] [function|object] [function]`,[e,t,n,r],arguments.length),t!==void 0){if(Qe(e,null,I(this,H,`f`)),(e||``).match(/^\$0( |$)/))return this.command(e,t,n,r);throw new M(`.usage() description must start with $0 if being used as alias for .command()`)}return I(this,U,`f`).usage(e),this}usageConfiguration(e){return P(`<object>`,[e],arguments.length),F(this,fn,e,`f`),this}version(e,t,n){let r=`version`;if(P(`[boolean|string] [string] [string]`,[e,t,n],arguments.length),I(this,pn,`f`)&&(this[_n](I(this,pn,`f`)),I(this,U,`f`).version(void 0),F(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 F(this,pn,typeof e==`string`?e:r,`f`),t||=I(this,U,`f`).deferY18nLookup(`Show version number`),I(this,U,`f`).version(n||void 0),this.boolean(I(this,pn,`f`)),this.describe(I(this,pn,`f`),t),this}wrap(e){return P(`<number|null|undefined>`,[e],arguments.length),I(this,U,`f`).wrap(e),this}[(L=/* @__PURE__ */ new WeakMap,Bt=/* @__PURE__ */ new WeakMap,Vt=/* @__PURE__ */ new WeakMap,Ht=/* @__PURE__ */ new WeakMap,R=/* @__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,z=/* @__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),F(this,z,!0,`f`),I(this,B,`f`).length&&F(this,B,I(this,B,`f`)+`
|
|
90
|
+
`,`f`),F(this,B,I(this,B,`f`)+e.join(` `),`f`)},error:(...e)=>{this[Hn]()||console.error(...e),F(this,z,!0,`f`),I(this,B,`f`).length&&F(this,B,I(this,B,`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.25.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.
|
|
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
|
|
95
95
|
|
|
96
|
-
|
|
96
|
+
Return the id, name, and slug of the Organization that owns the credential. Accepts an organization API key or organization-management JWT, including a viewer's. Tenant JWTs are forbidden.`).option(`dry-run`,{type:`boolean`,description:`Validate and show what would happen without executing`,default:!1})}const Bi={command:`get`,describe:`Get the current Organization`,builder:zi,handler:async e=>ji({command:`organization get`,classification:{safeFlags:[`dry-run`]}},e,async()=>{if(e.dryRun){Mi({command:`cf organization get`,method:`GET`,url:`https://api.cloudflare.com/client/v4/api/v1/organization`,pathParams:{},bodyKind:`none`});return}let t=await ki(e);q(await J(`Loading`,async()=>t.send(Ri)),{successLabel:`Loaded`})})},Vi={command:`organization`,describe:`organization`,builder:e=>e.command(Bi).demandCommand(1,`Please specify a subcommand`),handler:()=>{}};function Hi(e,...t){let n=e[0]??``;for(let[r,i]of t.entries())n+=encodeURIComponent(String(i))+(e[r+1]??``);return n}var Ui={method:`POST`,path:e=>Hi`/api/v1/tenants/${e.tenant_id}/tenant_users`,body:`json`,errors:{400:`BadRequestError`,401:`UnauthorizedError`,403:`ForbiddenError`,404:`NotFoundError`,409:`ConflictError`,413:`ContentTooLargeError`,415:`UnsupportedMediaTypeError`,422:`UnprocessableEntityError`,429:`TooManyRequestsError`,500:`InternalServerError`,503:`ServiceUnavailableError`}};function Wi(e){return e.usage(`$0 tenant-users create <tenant-id>
|
|
97
97
|
|
|
98
|
-
|
|
98
|
+
Create a TenantUser under the internal tenant_id path identifier, with a customer-provided tenant-local external_id. An external_id already used in this Tenant returns 409; the same external_id in another Tenant is allowed. Stored admin does not change signed JWT authority.`).positional(`tenant-id`,{type:`string`,description:`Tenant ID`,demandOption:!0}).option(`external-id`,{type:`string`,description:`Your stable external identity. Exact and case-sensitive; whitespace is preserved. Immutable after creation.`}).option(`name`,{type:`string`,description:`Defaults to null on creation. Send null to clear the name.`}).option(`metadata`,{type:`string`,description:`Customer-defined JSON object; keys are preserved. Defaults to {} on creation. Updates replace the entire object. Provide as a JSON object or @path/to/file.json.`}).option(`admin`,{type:`boolean`,description:`Defaults to false on creation. Stored admin does not change signed JWT authority.`}).option(`dry-run`,{type:`boolean`,description:`Validate and show what would happen without executing`,default:!1}).option(`body`,{type:`string`,description:`Raw JSON request body (bypasses individual flags)`})}const Gi={command:`create <tenant-id>`,describe:`Create a TenantUser`,builder:Wi,handler:async e=>ji({command:`tenant-users create`,classification:{safeFlags:[`admin`,`dry-run`]}},e,async()=>{if(e.dryRun){Mi({command:`cf tenant-users create`,method:`POST`,url:`https://api.cloudflare.com/client/v4/api/v1/tenants/${e[`tenant-id`]==null?`<tenant-id>`:encodeURIComponent(String(e[`tenant-id`]))}/tenant_users`,pathParams:{"tenant-id":String(e[`tenant-id`]??``)},bodyKind:`json`,body:e.body===void 0?Si({external_id:Di(e[`external-id`],`external-id`,`text`),name:Di(e.name,`name`,`text`),metadata:Ei(e.metadata,`metadata`),admin:e.admin},[[`metadata`]]):wi(e.body)});return}let t=await ki(e);if(e.body){let n=wi(e.body);q(await J(`Creating`,async()=>t.send(Ui,{body:n,tenant_id:e[`tenant-id`]})),{successLabel:`Created`});return}e[`external-id`]===void 0&&(e[`external-id`]=await Ni(`external-id`,`Your stable external identity. Exact and case-sensitive; whitespace is preserved. Immutable after creation.`));let n=Si({external_id:Di(e[`external-id`],`external-id`,`text`),name:Di(e.name,`name`,`text`),metadata:Ei(e.metadata,`metadata`),admin:e.admin},[[`metadata`]]);q(await J(`Creating`,async()=>t.send(Ui,{body:n,tenant_id:e[`tenant-id`]})),{successLabel:`Created`})})};var Ki={method:`GET`,path:e=>Hi`/api/v1/tenants/${e.tenant_id}/tenant_users/${e.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 qi(e){return e.usage(`$0 tenant-users get <id>
|
|
99
99
|
|
|
100
|
-
|
|
100
|
+
Get a TenantUser by the internal tenant_id and id pair within the authorized scope. No identity upsert.`).positional(`id`,{type:`string`,description:`ID`,demandOption:!0}).option(`tenant-id`,{type:`string`,description:`Tenant ID`,demandOption:!0}).option(`dry-run`,{type:`boolean`,description:`Validate and show what would happen without executing`,default:!1})}const Ji={command:`get <id>`,describe:`Get a TenantUser`,builder:qi,handler:async e=>ji({command:`tenant-users get`,classification:{safeFlags:[`dry-run`]}},e,async()=>{if(e.dryRun){Mi({command:`cf tenant-users get`,method:`GET`,url:`https://api.cloudflare.com/client/v4/api/v1/tenants/${e[`tenant-id`]==null?`<tenant-id>`:encodeURIComponent(String(e[`tenant-id`]))}/tenant_users/${e.id==null?`<id>`:encodeURIComponent(String(e.id))}`,pathParams:{"tenant-id":String(e[`tenant-id`]??``),id:String(e.id??``)},bodyKind:`none`});return}let t=await ki(e);q(await J(`Loading`,async()=>t.send(Ki,{tenant_id:e[`tenant-id`],id:e.id})),{successLabel:`Loaded`})})};var Yi={method:`GET`,path:e=>Hi`/api/v1/tenants/${e.tenant_id}/tenant_users`,query:[`q`,`filter_external_id`,`page_size`,`page_after`,`page_before`,`filter_admin`],errors:{400:`BadRequestError`,401:`UnauthorizedError`,403:`ForbiddenError`,404:`NotFoundError`,409:`ConflictError`,413:`ContentTooLargeError`,415:`UnsupportedMediaTypeError`,422:`UnprocessableEntityError`,429:`TooManyRequestsError`,500:`InternalServerError`,503:`ServiceUnavailableError`}};function Xi(e){return e.usage(`$0 tenant-users list
|
|
101
101
|
|
|
102
|
-
|
|
102
|
+
List users of one Tenant in internal ID order. q searches name or external ID as a case-insensitive literal substring. Exact filter[external_id] and filter[admin] combine with AND. No matching user returns an empty page; missing and out-of-scope Tenants return 404. Cursors cannot be reused for another Tenant or filter. Live listing, not a snapshot.`).option(`tenant-id`,{type:`string`,description:`Tenant ID`,demandOption:!0}).option(`q`,{type:`string`,description:`Case-insensitive literal substring of name or external_id. Trimmed, blank means no search.`}).option(`external-id`,{type:`string`,description:`Exact, case-sensitive external ID; whitespace is preserved. Returns zero or one item.`}).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(`admin`,{type:`string`,description:`Filter admin`,choices:[`true`,`false`]}).option(`dry-run`,{type:`boolean`,description:`Validate and show what would happen without executing`,default:!1})}const Zi={command:`list`,describe:`List TenantUsers`,builder:Xi,handler:async e=>ji({command:`tenant-users list`,classification:{safeFlags:[`admin`,`dry-run`]}},e,async()=>{let t={q:e.q,filter_external_id:e[`external-id`],page_size:e[`page-size`],page_after:e[`page-after`],page_before:e[`page-before`],filter_admin:e.admin};if(e.dryRun){Mi({command:`cf tenant-users list`,method:`GET`,url:`https://api.cloudflare.com/client/v4/api/v1/tenants/${e[`tenant-id`]==null?`<tenant-id>`:encodeURIComponent(String(e[`tenant-id`]))}/tenant_users`,pathParams:{"tenant-id":String(e[`tenant-id`]??``)},query:t,bodyKind:`none`});return}let n=await ki(e);q(await J(`Loading`,async()=>n.send(Yi,{tenant_id:e[`tenant-id`],...t})),{successLabel:`Loaded`})})};var Qi={method:`PATCH`,path:e=>Hi`/api/v1/tenants/${e.tenant_id}/tenant_users/${e.id}`,body:`json`,errors:{400:`BadRequestError`,401:`UnauthorizedError`,403:`ForbiddenError`,404:`NotFoundError`,409:`ConflictError`,413:`ContentTooLargeError`,415:`UnsupportedMediaTypeError`,422:`UnprocessableEntityError`,429:`TooManyRequestsError`,500:`InternalServerError`,503:`ServiceUnavailableError`}};function $i(e){return e.usage(`$0 tenant-users update <id>
|
|
103
103
|
|
|
104
|
-
|
|
104
|
+
Update supplied name/metadata/admin fields only. Stored admin does not grant or revoke JWT authority. name:null clears the name; metadata replaces the object.`).positional(`id`,{type:`string`,description:`ID`,demandOption:!0}).option(`tenant-id`,{type:`string`,description:`Tenant ID`,demandOption:!0}).option(`name`,{type:`string`,description:`Defaults to null on creation. Send null to clear the name.`}).option(`metadata`,{type:`string`,description:`Customer-defined JSON object; keys are preserved. Defaults to {} on creation. Updates replace the entire object. Provide as a JSON object or @path/to/file.json.`}).option(`admin`,{type:`boolean`,description:`Defaults to false on creation. Stored admin does not change signed JWT authority.`}).option(`dry-run`,{type:`boolean`,description:`Validate and show what would happen without executing`,default:!1}).option(`body`,{type:`string`,description:`Raw JSON request body (bypasses individual flags)`})}const ea={command:`update <id>`,describe:`Update a TenantUser`,builder:$i,handler:async e=>ji({command:`tenant-users update`,classification:{safeFlags:[`admin`,`dry-run`]}},e,async()=>{if(e.dryRun){Mi({command:`cf tenant-users update`,method:`PATCH`,url:`https://api.cloudflare.com/client/v4/api/v1/tenants/${e[`tenant-id`]==null?`<tenant-id>`:encodeURIComponent(String(e[`tenant-id`]))}/tenant_users/${e.id==null?`<id>`:encodeURIComponent(String(e.id))}`,pathParams:{"tenant-id":String(e[`tenant-id`]??``),id:String(e.id??``)},bodyKind:`json`,body:e.body===void 0?Si({name:Di(e.name,`name`,`text`),metadata:Ei(e.metadata,`metadata`),admin:e.admin},[[`metadata`]]):wi(e.body)});return}let t=await ki(e);if(e.body){let n=wi(e.body);q(await J(`Updating`,async()=>t.send(Qi,{body:n,tenant_id:e[`tenant-id`],id:e.id})),{successLabel:`Updated`});return}let n=Si({name:Di(e.name,`name`,`text`),metadata:Ei(e.metadata,`metadata`),admin:e.admin},[[`metadata`]]);q(await J(`Updating`,async()=>t.send(Qi,{body:n,tenant_id:e[`tenant-id`],id:e.id})),{successLabel:`Updated`})})};var ta={method:`GET`,path:e=>Hi`/api/v1/tenants/${e.tenant_id}/tenant_users/usage`,query:[`user_ids`,`start`,`end`],errors:{400:`BadRequestError`,401:`UnauthorizedError`,403:`ForbiddenError`,404:`NotFoundError`,409:`ConflictError`,413:`ContentTooLargeError`,415:`UnsupportedMediaTypeError`,422:`UnprocessableEntityError`,429:`TooManyRequestsError`,500:`InternalServerError`,503:`ServiceUnavailableError`}};function na(e){return e.usage(`$0 tenant-users usage get <tenant-id>
|
|
105
105
|
|
|
106
|
-
|
|
106
|
+
Read usage in USD for up to 100 users within one Tenant over a positive time range no longer than 93 days. start is inclusive and end is exclusive. Supply ISO 8601 timestamps with an explicit timezone and at most millisecond precision. Only Organization API keys and organization owners or developers may read usage. Missing and out-of-scope user IDs are omitted. Existing users with no settled replies in the range return zero. Results are computed at request time from retained settled replies. Drafts and deleted conversations are excluded, and older replies without saved costs use current rates.`).positional(`tenant-id`,{type:`string`,description:`Tenant ID`,demandOption:!0}).option(`user-ids`,{type:`string`,description:`Comma-separated internal user UUIDs, 1 to 100 unique IDs.`,demandOption:!0}).option(`start`,{type:`string`,description:`Inclusive start timestamp, with Z or a numeric timezone offset.`,demandOption:!0}).option(`end`,{type:`string`,description:`Exclusive end timestamp, with Z or a numeric timezone offset.`,demandOption:!0}).option(`dry-run`,{type:`boolean`,description:`Validate and show what would happen without executing`,default:!1})}const ra={command:`get <tenant-id>`,describe:`Get TenantUser usage`,builder:na,handler:async e=>ji({command:`tenant-users usage get`,classification:{safeFlags:[`dry-run`]}},e,async()=>{let t={user_ids:e[`user-ids`],start:e.start,end:e.end};if(e.dryRun){Mi({command:`cf tenant-users usage get`,method:`GET`,url:`https://api.cloudflare.com/client/v4/api/v1/tenants/${e[`tenant-id`]==null?`<tenant-id>`:encodeURIComponent(String(e[`tenant-id`]))}/tenant_users/usage`,pathParams:{"tenant-id":String(e[`tenant-id`]??``)},query:t,bodyKind:`none`});return}let n=await ki(e);q(await J(`Loading`,async()=>n.send(ta,{tenant_id:e[`tenant-id`],...t})),{successLabel:`Loaded`})})},ia={command:`usage`,describe:`Operations for usage`,builder:e=>e.command(ra).demandCommand(1,`Please specify a subcommand`),handler:()=>{}},aa={command:`tenant-users`,describe:`tenant-users`,builder:e=>e.command(Gi).command(Ji).command(Zi).command(ea).command(ia).demandCommand(1,`Please specify a subcommand`),handler:()=>{}};var oa={method:`POST`,path:()=>`/api/v1/tenants`,body:`json`,errors:{400:`BadRequestError`,401:`UnauthorizedError`,403:`ForbiddenError`,404:`NotFoundError`,409:`ConflictError`,413:`ContentTooLargeError`,415:`UnsupportedMediaTypeError`,422:`UnprocessableEntityError`,429:`TooManyRequestsError`,500:`InternalServerError`,503:`ServiceUnavailableError`}};function sa(e){return e.usage(`$0 tenants create
|
|
107
107
|
|
|
108
|
-
|
|
108
|
+
Create a Tenant with an exact customer-provided external_id. Requires an organization API key or organization-management JWT with a current owner/developer role. An external_id already used in this organization returns 409; creation never upserts.`).option(`external-id`,{type:`string`,description:`Your stable external identity. Exact and case-sensitive; whitespace is preserved. Immutable after creation.`}).option(`name`,{type:`string`,description:`Defaults to null on creation. Send null to clear the name.`}).option(`metadata`,{type:`string`,description:`Customer-defined JSON object; keys are preserved. Defaults to {} on creation. Updates replace the entire object. Provide as a JSON object or @path/to/file.json.`}).option(`dry-run`,{type:`boolean`,description:`Validate and show what would happen without executing`,default:!1}).option(`body`,{type:`string`,description:`Raw JSON request body (bypasses individual flags)`})}const ca={command:`create`,describe:`Create a Tenant`,builder:sa,handler:async e=>ji({command:`tenants create`,classification:{safeFlags:[`dry-run`]}},e,async()=>{if(e.dryRun){Mi({command:`cf tenants create`,method:`POST`,url:`https://api.cloudflare.com/client/v4/api/v1/tenants`,pathParams:{},bodyKind:`json`,body:e.body===void 0?Si({external_id:Di(e[`external-id`],`external-id`,`text`),name:Di(e.name,`name`,`text`),metadata:Ei(e.metadata,`metadata`)},[[`metadata`]]):wi(e.body)});return}let t=await ki(e);if(e.body){let n=wi(e.body);q(await J(`Creating`,async()=>t.send(oa,{body:n})),{successLabel:`Created`});return}e[`external-id`]===void 0&&(e[`external-id`]=await Ni(`external-id`,`Your stable external identity. Exact and case-sensitive; whitespace is preserved. Immutable after creation.`));let n=Si({external_id:Di(e[`external-id`],`external-id`,`text`),name:Di(e.name,`name`,`text`),metadata:Ei(e.metadata,`metadata`)},[[`metadata`]]);q(await J(`Creating`,async()=>t.send(oa,{body:n})),{successLabel:`Created`})})};var la={method:`GET`,path:e=>Hi`/api/v1/tenants/${e.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 ua(e){return e.usage(`$0 tenants get <id>
|
|
109
109
|
|
|
110
|
-
|
|
110
|
+
Get a Tenant by internal UUID, not external_id.`).positional(`id`,{type:`string`,description:`ID`,demandOption:!0}).option(`dry-run`,{type:`boolean`,description:`Validate and show what would happen without executing`,default:!1})}const da={command:`get <id>`,describe:`Get a Tenant`,builder:ua,handler:async e=>ji({command:`tenants get`,classification:{safeFlags:[`dry-run`]}},e,async()=>{if(e.dryRun){Mi({command:`cf tenants get`,method:`GET`,url:`https://api.cloudflare.com/client/v4/api/v1/tenants/${e.id==null?`<id>`:encodeURIComponent(String(e.id))}`,pathParams:{id:String(e.id??``)},bodyKind:`none`});return}let t=await ki(e);q(await J(`Loading`,async()=>t.send(la,{id:e.id})),{successLabel:`Loaded`})})};var fa={method:`GET`,path:()=>`/api/v1/tenants`,query:[`q`,`filter_external_id`,`page_size`,`page_after`,`page_before`],errors:{400:`BadRequestError`,401:`UnauthorizedError`,403:`ForbiddenError`,404:`NotFoundError`,409:`ConflictError`,413:`ContentTooLargeError`,415:`UnsupportedMediaTypeError`,422:`UnprocessableEntityError`,429:`TooManyRequestsError`,500:`InternalServerError`,503:`ServiceUnavailableError`}};function pa(e){return e.usage(`$0 tenants list
|
|
111
111
|
|
|
112
|
-
|
|
112
|
+
List Tenants in internal ID order. q searches name or external ID as a case-insensitive literal substring. filter[external_id] adds an exact match. Organization keys and organization-management JWTs see their organization; admin tenant JWTs see only their signed Tenant. Keep filters unchanged when reusing cursors. Live listing, not a snapshot.`).option(`q`,{type:`string`,description:`Case-insensitive literal substring of name or external_id. Trimmed, blank means no search.`}).option(`external-id`,{type:`string`,description:`Exact, case-sensitive external ID; whitespace is preserved. Returns zero or one item.`}).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 ma={command:`list`,describe:`List Tenants`,builder:pa,handler:async e=>ji({command:`tenants list`,classification:{safeFlags:[`dry-run`]}},e,async()=>{let t={q:e.q,filter_external_id:e[`external-id`],page_size:e[`page-size`],page_after:e[`page-after`],page_before:e[`page-before`]};if(e.dryRun){Mi({command:`cf tenants list`,method:`GET`,url:`https://api.cloudflare.com/client/v4/api/v1/tenants`,pathParams:{},query:t,bodyKind:`none`});return}let n=await ki(e);q(await J(`Loading`,async()=>n.send(fa,t)),{successLabel:`Loaded`})})};var ha={method:`PATCH`,path:e=>Hi`/api/v1/tenants/${e.id}`,body:`json`,errors:{400:`BadRequestError`,401:`UnauthorizedError`,403:`ForbiddenError`,404:`NotFoundError`,409:`ConflictError`,413:`ContentTooLargeError`,415:`UnsupportedMediaTypeError`,422:`UnprocessableEntityError`,429:`TooManyRequestsError`,500:`InternalServerError`,503:`ServiceUnavailableError`}};function ga(e){return e.usage(`$0 tenants update <id>
|
|
113
113
|
|
|
114
|
-
|
|
114
|
+
Update supplied name/metadata fields only. Requires an organization API key or organization-management JWT with a current owner/developer role. name:null clears the name; metadata replaces the object. Last-write-wins; no upsert.`).positional(`id`,{type:`string`,description:`ID`,demandOption:!0}).option(`name`,{type:`string`,description:`Defaults to null on creation. Send null to clear the name.`}).option(`metadata`,{type:`string`,description:`Customer-defined JSON object; keys are preserved. Defaults to {} on creation. Updates replace the entire object. Provide as a JSON object or @path/to/file.json.`}).option(`dry-run`,{type:`boolean`,description:`Validate and show what would happen without executing`,default:!1}).option(`body`,{type:`string`,description:`Raw JSON request body (bypasses individual flags)`})}const _a={command:`update <id>`,describe:`Update a Tenant`,builder:ga,handler:async e=>ji({command:`tenants update`,classification:{safeFlags:[`dry-run`]}},e,async()=>{if(e.dryRun){Mi({command:`cf tenants update`,method:`PATCH`,url:`https://api.cloudflare.com/client/v4/api/v1/tenants/${e.id==null?`<id>`:encodeURIComponent(String(e.id))}`,pathParams:{id:String(e.id??``)},bodyKind:`json`,body:e.body===void 0?Si({name:Di(e.name,`name`,`text`),metadata:Ei(e.metadata,`metadata`)},[[`metadata`]]):wi(e.body)});return}let t=await ki(e);if(e.body){let n=wi(e.body);q(await J(`Updating`,async()=>t.send(ha,{body:n,id:e.id})),{successLabel:`Updated`});return}let n=Si({name:Di(e.name,`name`,`text`),metadata:Ei(e.metadata,`metadata`)},[[`metadata`]]);q(await J(`Updating`,async()=>t.send(ha,{body:n,id:e.id})),{successLabel:`Updated`})})};var va={method:`GET`,path:e=>Hi`/api/v1/tenants/${e.tenantId}/threads/${e.id}/messages`,query:[`page_size`,`page_after`,`page_before`],errors:{400:`BadRequestError`,401:`UnauthorizedError`,403:`ForbiddenError`,404:`NotFoundError`,409:`ConflictError`,413:`ContentTooLargeError`,415:`UnsupportedMediaTypeError`,422:`UnprocessableEntityError`,429:`TooManyRequestsError`,500:`InternalServerError`,503:`ServiceUnavailableError`}};function ya(e){return e.usage(`$0 tenants threads messages list
|
|
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
|
+
|
|
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__ */ T({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(`
|
|
117
119
|
`)},i=i=>{for(let a of i){if(a===`\r`||a===`
|
|
118
|
-
`)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
|
|
119
|
-
`);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
|
|
120
|
-
function
|
|
121
|
-
`;)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 Go(e,t,n,r){if(n&&Uo(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)=>Go(e,t,n?.items?.[i],r)??`null`).join(`,`)+`]`;let i=[];for(let a of Object.keys(e)){let o=Go(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 Ko(e,t){if(t===void 0)return e??``;if(e===void 0)return Go(t,``,void 0,/* @__PURE__ */ new Set)??``;let n;try{n=JSON.parse(e)}catch{return e.trim()===``?Go(t,``,void 0,/* @__PURE__ */ new Set)??e:e}return Uo(n,t)?e:Go(t,e,Wo(e,n),/* @__PURE__ */ new Set)??e}function qo(e){if(e.trim()===``)return{};try{return JSON.parse(e)??void 0}catch{return}}function Jo(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=Ko(s,o)}catch{c=s??e}return{args:c,input:qo(c)}}var Yo=`redacted_thinking-`;function Xo(e){return typeof e==`string`&&e.startsWith(`redacted_thinking-`)}var Zo=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 Qo(e,t){return e>>>t|e<<32-t}function $o(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=Qo(t,7)^Qo(t,18)^t>>>3,i=Qo(n,17)^Qo(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=Qo(a,6)^Qo(a,11)^Qo(a,25),s=a&g^~a&ee,c=_+o+s+(Zo[e]??0)+(h[e]??0)>>>0,l=(Qo(t,2)^Qo(t,13)^Qo(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 es(e){return`sha256:${$o(e)}`}function ts(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(ts(e[n],t));n=`[${r.join(`,`)}]`}else{let r=e;n=`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${ts(r[e],t)}`).join(`,`)}}`}return t.delete(e),n}function ns(e){return ts(e,/* @__PURE__ */ new WeakSet)}function rs(e,t=es){if(typeof e!=`string`)throw TypeError(`Interrupt digests require canonical JSON text.`);return t(e)}function is(e){typeof e==`object`&&e&&!Object.isFrozen(e)&&(Object.values(e).forEach(is),Object.freeze(e))}function Z(e){let t=JSON.parse(ns(e));return is(t),t}function as(e){let t=Z([...e].sort((e,t)=>e.interruptId.localeCompare(t.interruptId))),n=ns(t);return Object.freeze({resolutions:t,canonicalResolutions:n,fingerprint:rs(n)})}function os(e){let t={};for(let[n,r]of Object.entries(e))n!==`$schema`&&(t[n]=r);return t}function ss(e){return(typeof e==`object`||typeof e==`function`)&&e!==null}function cs(e){if(!ss(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 ls(e){return ss(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 us(e){return Object.keys(e).length>0?e:void 0}function ds(e){if(Array.isArray(e)){let t=e.map(e=>fs(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=fs(e,e.required||[]);return{schema:t.schema,itemMap:t.nullWidening}}function fs(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=fs(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=ds(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=ds(n.items);n.items=e.schema,e.itemMap&&(r.items=e.itemMap)}return{schema:n,nullWidening:us(r)}}function ps(e,t=`input`){if(cs(e)){let n=os(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(ls(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`?os(e):e}function ms(e,t={}){if(!e)return;let{forStructuredOutput:n=!1,io:r}=t;if(!n&&!cs(e)&&!ls(e))return e;let i=ps(e,r);return!i||typeof i!=`object`||!n?i:fs(i,i.required||[]).schema}async function hs(e,t){if(!ls(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 gs=/* @__PURE__ */ new Set([`$schema`,`$id`,`$ref`,`$defs`,`type`,`properties`,`required`,`additionalProperties`,`items`,`oneOf`,`anyOf`,`allOf`,`enum`,`const`,`format`,`minimum`,`maximum`,`minLength`,`maxLength`,`pattern`]);function _s(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null)}function vs(e){return _s(e)&&Object.keys(e).some(e=>gs.has(e))}function ys(e){return ls(e)||cs(e)||vs(e)}function bs(e){if(!_s(e))return!1;let t=Object.keys(e);return t.length>0&&t.every(e=>e===`approve`||e===`reject`)&&t.every(t=>ys(e[t]))}function xs(e){let t={};for(let[n,r]of Object.entries(e))t[n]=r;return t}function Ss(e){if(ls(e)){let t=cs(e)?xs(e[`~standard`].jsonSchema.input({target:`draft-2020-12`})):void 0;return{source:e,validator:e,...t!==void 0&&{jsonSchema:t}}}if(vs(e))return{source:e,jsonSchema:e};throw TypeError(`Expected a supported SchemaInput.`)}function Cs(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 ws(e,t){let n=t===void 0?null:Ss(t),r=null,i=null;if(e!==void 0){if(ls(e)||vs(e))r=Ss(e),i=r;else if(bs(e))r=e.approve===void 0?null:Ss(e.approve),i=e.reject===void 0?null:Ss(e.reject);else throw TypeError(`approvalSchema must be a SchemaInput or a nonempty map containing approve or reject.`)}let a={oneOf:[Cs({approved:!0,payload:r,inputSchema:n}),Cs({approved:!1,payload:i,inputSchema:null})]},o=ns(a),s=ns({approve:r?.jsonSchema??null,reject:i?.jsonSchema??null});return{branches:{approve:r,reject:i},responseSchema:a,responseSchemaHash:rs(o),approvalSchemaHash:rs(s)}}function Ts(e){return rs(e===void 0?`undefined`:ns(Ss(e).jsonSchema??{standardValidator:`unserialized`}))}var Es=`tanstack:interruptBinding`,Ds=Es;function Os(e){return e&&typeof e==`object`?e:null}function Q(e,t){return typeof e[t]==`string`?e[t]:void 0}function ks(e){let t=e.v;return t===void 0||t===1}function As(e){let t=Os(e.metadata),n=t?Os(t[Ds]):null;if(!n||Q(n,`interruptId`)!==e.id||!ks(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 js(e){let t=As(e);if(!t)return;let n=Os(e.metadata),r=n?Os(n[Ds]):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 Ms=`tanstack:interruptPayload`;function Ns(e,t){if(!cs(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:ns(n)}}catch(e){throw TypeError(`${t} could not export compatible JSON Schema: ${e instanceof Error?e.message:String(e)}`)}}function Ps(e){return rs(Ns(e,`Interrupt schema`).canonicalJson)}var Fs=`tanstack:interruptContinuation`;function Is(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ls(e){return{[Fs]:e}}function Rs(e){let t=As(e);if(t?.kind!==`generic`||t.definitionId===void 0||t.key===void 0||t.batchIndex===void 0)return;let n=Is(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[Ms]}:{}}}function zs(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Bs=`subagentInput`;function Vs(e){if(zs(e)&&zs(e.tanstack))return e.tanstack[Bs]}function Hs(e){if(!zs(e)||`parts`in e)return;let t=e.subagentRunId;return typeof t==`string`&&t!==``?t:void 0}function Us(e){if(!zs(e)||!zs(e.metadata))return;let t=e.metadata.tanstack;if(!zs(t)||!zs(t.subagent))return;let{name:n,status:r,error:i,interruptIds:a}=t.subagent;if(typeof n!=`string`||!Ws(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},...zs(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},...zs(l)&&{metadata:l},...u===!0&&{placeholder:!0}}}function Ws(e){return e===`running`||e===`finished`||e===`error`||e===`suspended`}function Gs(e){if(!zs(e))return e;let{subagentRunId:t,...n}=e,r=zs(n.metadata)?n.metadata:void 0,i=zs(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 Ks(e){let t=/* @__PURE__ */ new Map;for(let n of e){let e=Hs(n);e!==void 0&&!t.has(e)&&t.set(e,Us(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=Hs(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=Us(t);s&&(o.info=s),s?.placeholder||o.messages.push(Gs(t))}return{top:r,groups:[...i.values()]}}function qs(e){let t=e?.metadata;return typeof t==`object`&&t&&t.providerExecuted===!0?t:null}function Js(e){return qs(e)!==null}function Ys(e,t){return e?.startsWith(`${t}-segment-`)===!0}var Xs=/* @__PURE__ */ new Set([`text`,`image`,`audio`,`video`,`document`]);function Zs(e){return e===`cancelled`||e===`denied`}function Qs(e){if(typeof e!=`object`||!e)return!1;let t=e;if(typeof t.type!=`string`||!Xs.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 $s(e){return Array.isArray(e)&&e.length>0&&e.every(Qs)}function ec(e){return e&&typeof e==`object`&&`error`in e&&typeof e.error==`string`?e.error:typeof e==`string`?e:`Tool execution failed`}function tc(e){return typeof e==`string`||$s(e)?e:JSON.stringify(e)}function nc(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 rc(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 ic(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ac(e){return e.type===`text`||e.type===`image`||e.type===`audio`||e.type===`video`||e.type===`document`}function oc(e){try{return JSON.stringify(e)??``}catch{return``}}function sc(e){return typeof e==`string`&&e!==``?e:void 0}function cc(e){if(`encryptedValue`in e){let t=sc(e.encryptedValue);if(t!==void 0)return t}return sc(Y(e)?.signature)}function lc(e){return`id`in e&&Xo(e.id)?{redacted:!0}:{}}function uc(e){return e.length===0?null:e.every(e=>e.type===`text`)?e.map(e=>e.content).join(``)||null:e}function dc(e){return e==null?``:typeof e==`string`?e:e.filter(e=>e.type===`text`).map(e=>e.content).join(``)}function fc(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=pc(n);e!==``&&t.push(e)}return t.join(`
|
|
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 de(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
|
+
`);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{throw new Ga(`Failed to base64url decode the payload`)}let i;try{i=JSON.parse(Ia.decode(r))}catch{throw new Ga(`Failed to parse the decoded payload as JSON`)}if(!Ja(i))throw new Ga(`Invalid JWT Claims Set`);return i}/* @__NO_SIDE_EFFECTS__ */
|
|
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(`
|
|
122
124
|
|
|
123
|
-
`)}function
|
|
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(`
|
|
124
126
|
|
|
125
|
-
`)}`}function
|
|
127
|
+
`)}`}function vc(e){return Array.isArray(e)?e:hc(e)}function yc(e){if(!(`role`in e)||e.role!==`tool`)return e;let t=e,n=Y(t)?.toolResult;if(!cc(n)||`content`in n&&!rc(n.content))return e;let r={...e};if(`id`in n||Reflect.deleteProperty(r,`id`),`createdAt`in n||Reflect.deleteProperty(r,`createdAt`),typeof n.id==`string`&&Reflect.set(r,`id`,n.id),typeof n.createdAt==`string`){let e=bc(n.createdAt);e&&Reflect.set(r,`createdAt`,e)}rc(n.content)&&Reflect.set(r,`content`,n.content);let i=Reflect.get(t,`metadata`);if(cc(i)){let e=i.tanstack;if(cc(e)){let{toolResult:t,...n}=e,a={...i};Object.keys(n).length?a.tanstack=n:delete a.tanstack,Object.keys(a).length?Reflect.set(r,`metadata`,a):Reflect.deleteProperty(r,`metadata`)}}return r}function bc(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 xc(e){if(e.type!==`tool-result`)return e;let t=bc(e.createdAt),{createdAt:n,...r}=e;return t===void 0?r:{...r,createdAt:t}}function Sc(e){return bc(Y(e)?.createdAt)}function Cc(e){let t=bc(e.createdAt);return t===void 0?{}:{createdAt:t}}function wc(e){return e.name===void 0?{}:{name:e.name}}function Tc(e){if(typeof e!=`object`||!e||Array.isArray(e)||!(`type`in e)||e.type!==`ui-resource`||!(`toolCallId`in e)||typeof e.toolCallId!=`string`||!(`toolName`in e)||typeof e.toolName!=`string`||!(`resource`in e)||e.resource==null||typeof e.resource!=`object`||Array.isArray(e.resource))return!1;let t=e.resource;return`uri`in t&&typeof t.uri==`string`&&`mimeType`in t&&typeof t.mimeType==`string`}function Ec(e){return`${e.toolCallId}\0${e.toolName}\0${e.resource.uri}`}function Dc(e,t){if(t.length===0)return e;let n=new Set(e.parts.filter(Tc).map(e=>Ec(e))),r=t.filter(e=>!n.has(Ec(e)));return r.length===0?e:{...e,parts:[...e.parts,...r]}}function Oc(e){let t=e.parts.filter(Tc),n=e.metadata??{},r={...Y(e)};r.run&&(r.run={...r.run},delete r.run.startedAt,delete r.run.finishedAt),delete r.createdAt,delete r.continues,delete r.structuredOutput,delete r.toolCallMetadata,delete r.toolResult,delete r.toolResultOutcome,delete r.uiResources,t.length>0&&(r.uiResources=t);let i={...n};return Object.keys(r).length>0?i.tanstack=r:delete i.tanstack,Object.keys(i).length>0?i:void 0}function kc(e){return e.role===`system`||e.role===`activity`?[]:e.role===`assistant`?Nc(e):[Ac(e)]}function Ac(e){let t=[];for(let n of e.parts)lc(n)&&t.push(n);return{id:e.id,role:e.role,content:mc(t),...wc(e),...Cc(e),...e.metadata!==void 0&&{metadata:e.metadata}}}function jc(){return{contentParts:[],toolCalls:[],order:[]}}function Mc(e){return e.state===`input-complete`||e.state===`complete`||e.state===`approval-requested`||e.state===`approval-responded`||e.state===`error`||e.output!==void 0}function Nc(e){let t=[],n=jc(),r=[],i=/* @__PURE__ */ new Set,a={id:e.id,...wc(e),...Cc(e)},o=Oc(e),s={...a,...o!==void 0&&{metadata:o}};function c(e=!1){let i=mc(n.contentParts),a=i!==null,o=n.toolCalls.length>0,c=r.length>0,l=Array.isArray(i)?void 0:oc(n.order);(e||a||o||c)&&(t.push({...s,role:`assistant`,content:i,...o&&{toolCalls:n.toolCalls},...c&&{thinking:r},...n.structuredOutput&&{structuredOutput:n.structuredOutput},...l&&{blockOrder:l}}),r=[]),n=jc()}for(let a of e.parts)switch(a.type){case`text`:n.contentParts.push(a),n.order.push({type:`text`,text:a.content});break;case`image`:case`audio`:case`video`:case`document`:n.contentParts.push(a);break;case`tool-call`:Mc(a)&&(n.toolCalls.push({id:a.id,type:`function`,function:{name:a.name,arguments:a.arguments},...a.metadata!==void 0&&{metadata:a.metadata}}),n.order.push({type:`tool-call`,id:a.id}));break;case`tool-result`:if(c(t.length===0),(a.state===`complete`||a.state===`error`)&&!i.has(a.toolCallId)){let e=a.outcome===void 0?a.metadata:Ko(a,{toolResultOutcome:a.outcome}).metadata;t.push({...a.id!==void 0&&{id:a.id},...Cc(a),role:`tool`,content:a.content,toolCallId:a.toolCallId,...a.name!==void 0&&{name:a.name},...e!==void 0&&{metadata:e},...a.error!==void 0&&{error:a.error}}),i.add(a.toolCallId)}break;case`thinking`:(a.content||a.signature)&&(n.toolCalls.some(Qs)&&c(),r.push({content:a.content,...a.signature&&{signature:a.signature},...a.redacted&&{redacted:!0}}),n.order.push({type:`thinking`}));break;case`structured-output`:if(a.status===`complete`){let e=a.raw===``?a.data===void 0?``:uc(a.data):a.raw;e!==``&&(n.contentParts.push({type:`text`,content:e}),n.order.push({type:`text`,text:e}),n.structuredOutput=a)}break;case`ui-resource`:break;case`activity`:break;case`subagent`:{let e=a.subagent.parentToolCallId===void 0?_c(a):``;if(e!==``){let t=`${n.contentParts.length>0?`
|
|
126
128
|
|
|
127
|
-
`:``}${e}`;n.contentParts.push({type:`text`,content:t}),n.order.push({type:`text`,text:t})}break}}c();for(let n of e.parts)if(n.type===`tool-call`&&(n.output!==void 0&&!i.has(n.id)&&(t.push({role:`tool`,content:tc(n.output),toolCallId:n.id}),i.add(n.id)),n.output===void 0&&n.state===`approval-responded`&&n.approval?.approved!==void 0&&!i.has(n.id))){let e=n.approval.approved;t.push({role:`tool`,content:JSON.stringify({approved:e,...e&&{pendingExecution:!0},message:e?`User approved this action`:`User denied this action`}),toolCallId:n.id,...e===!1&&{metadata:{tanstack:{toolResultOutcome:`denied`}}}}),i.add(n.id)}return t.length===0&&t.push({...s,role:`assistant`,content:null}),t}function Ac(e){return{type:`thinking`,content:e.content,...e.signature&&{signature:e.signature},...e.redacted&&{redacted:!0}}}function jc(e){let t;try{t=JSON.parse(e.function.arguments)}catch{t=void 0}return{type:`tool-call`,id:e.id,name:e.function.name,arguments:e.function.arguments,state:`input-complete`,...t!==void 0&&{input:t},...e.metadata!==void 0&&{metadata:e.metadata}}}function Mc(e,t){let n=[],r=gc(e.createdAt);if(e.role===`assistant`&&e.thinking?.length)for(let t of e.thinking)(t.content||t.signature)&&n.push(Ac(t));let i=e.structuredOutput??Fc(Y(e)?.structuredOutput);if(e.role===`assistant`&&i){if(typeof e.content==`string`&&e.content&&e.content!==i.raw){let t=i.raw,r=t!==``&&e.content.endsWith(t)?e.content.slice(0,-t.length):e.content;r&&n.push({type:`text`,content:r})}n.push(i)}else if(e.role===`tool`&&e.toolCallId){let t=Y(e)?.toolResultOutcome,i=Zs(t)?t:void 0,a=e.error===void 0&&i===void 0?`complete`:`error`;n.push({type:`tool-result`,toolCallId:e.toolCallId,content:mc(e.content),state:a,...i!==void 0&&{outcome:i},...e.id!==void 0&&{id:e.id},...e.name!==void 0&&{name:e.name},...e.metadata!==void 0&&{metadata:e.metadata},...r!==void 0&&{createdAt:r},...e.error!==void 0&&{error:e.error}})}else if(Array.isArray(e.content))for(let t of e.content)n.push(t);else{let t=dc(e.content);t&&n.push({type:`text`,content:t})}if(e.toolCalls&&e.toolCalls.length>0)for(let t of e.toolCalls)n.push(jc(t));let a=e.role===`assistant`&&i===void 0?rc(e):void 0;a&&n.splice(0,n.length,...a.flatMap(e=>e.type===`text`?[{type:`text`,content:e.text}]:e.type===`tool-call`?[jc(e.toolCall)]:e.thinking.content||e.thinking.signature?[Ac(e.thinking)]:[]));let o={id:t||zc(),role:e.role===`tool`?`assistant`:e.role,parts:n,...bc(e),...r!==void 0&&{createdAt:r},...e.metadata!==void 0&&{metadata:e.metadata}},s=Y(e)?.uiResources;return Cc(o,Array.isArray(s)?s.filter(xc):[])}function Nc(e){if(`parts`in e)return Pc(e,{...e,id:e.id||zc()});let t=e.id||zc();switch(e.role){case`user`:return Pc(e,{id:t,role:`user`,parts:Ic(e.content)});case`assistant`:{let n=Y(e),r=n?.toolCallMetadata,i=Fc(n?.structuredOutput),a=e.toolCalls?.map(e=>{let t=typeof r==`object`&&r?r[e.id]:void 0;return t===void 0?e:{...e,metadata:t}});return Pc(e,Mc({role:`assistant`,content:e.content??null,...bc(e),...a&&{toolCalls:a},...i&&{structuredOutput:i}},t))}case`tool`:{e=hc(e);let n=gc(`createdAt`in e?e.createdAt:void 0)??vc(e);return Pc(e,Mc({role:`tool`,content:$s(e.content)?e.content:Lc(e.content),toolCallId:e.toolCallId,...`name`in e&&typeof e.name==`string`?{name:e.name}:{},...`id`in e&&typeof e.id==`string`?{id:e.id}:{},...`metadata`in e&&e.metadata!=null?{metadata:e.metadata}:{},...n===void 0?{}:{createdAt:n},...e.error!==void 0&&{error:e.error}},t))}case`system`:case`developer`:return Pc(e,{id:t,role:`system`,parts:e.content?[{type:`text`,content:e.content}]:[]});case`reasoning`:{let n=cc(e),r=typeof e.content==`string`?e.content:``;return Pc(e,{id:t,role:`assistant`,parts:r||n!==void 0?[{type:`thinking`,content:r,...n===void 0?{}:{signature:n},...lc(e)}]:[]})}case`activity`:return Pc(e,{id:t,role:`activity`,parts:[{type:`activity`,activityType:e.activityType,content:structuredClone(e.content)}]});default:return Pc(e,{id:t,role:`assistant`,parts:[]})}}function Pc(e,t){let n=t.parts.map(e=>_c(e));n!==t.parts&&(t={...t,parts:n});let r=`name`in e&&typeof e.name==`string`?e.name:void 0,i=r===void 0?t:{...t,name:r},a;if(`metadata`in e){let t=e.metadata;typeof t==`object`&&t&&!Array.isArray(t)&&(a=t,i={...i,metadata:a})}let o=gc(i.createdAt)??(a===void 0?void 0:vc(a));if(o!==void 0&&!Object.is(o,i.createdAt))i={...i,createdAt:o};else if(o===void 0&&i.createdAt!==void 0){let{createdAt:e,...t}=i;i=t}let s=Y(a)?.uiResources,c=Array.isArray(s)?s.filter(xc):[];return Cc(i,c)}function Fc(e){if(e==null||e.status!==`streaming`&&e.status!==`complete`&&e.status!==`error`||typeof e.raw!=`string`)return;let t={type:`structured-output`,raw:e.raw,...e.partial===void 0?{}:{partial:e.partial},...e.reasoning?{reasoning:e.reasoning}:{},...e.errorMessage===void 0?{}:{errorMessage:e.errorMessage}};if(e.status!==`complete`)return{...t,status:e.status};if(e.data!==void 0)return{...t,status:`complete`,data:e.data}}function Ic(e){let t=Lc(e);return typeof t==`string`?t?[{type:`text`,content:t}]:[]:t}function Lc(e){return typeof e==`string`?e:e.map(e=>{if(e.type!==`text`)return e;let{text:t,...n}=e;return{...n,content:t}})}function Rc(e,t){if(`parts`in e){let n=e.parts.map(e=>_c(e));return{...e,parts:n,id:e.id||t(),createdAt:gc(e.createdAt)??/* @__PURE__ */ new Date}}return{...Mc(e,t()),createdAt:gc(e.createdAt)??/* @__PURE__ */ new Date}}function zc(){return`msg-${Date.now()}-${Math.random().toString(36).substring(7)}`}function Bc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Vc(e,t,n,r,i=!1,a){let o=Bc(e)?e:{},s=Bc(o.tanstack)?{...o.tanstack}:{};i&&delete s.uiResources;let c=gc(t),l={...n===void 0?{}:{id:n},...c&&{createdAt:c.toISOString()},...Array.isArray(r)&&{content:r}},u={...o,tanstack:{...s,...a!==void 0&&{toolResultOutcome:a},toolResult:l}};return Object.keys(u).length?u:void 0}function Hc(e,t){let n=[],r=new Set(e.flatMap(e=>`id`in e&&e.id&&e.role!==`tool`?[e.id]:[])),i=t?.includeSnapshotStructuredOutput??!1,a=t?.includeActivity??!1,o=/* @__PURE__ */ new Set;for(let t of e)t.role===`assistant`&&t.id!==void 0&&o.add(t.id);for(let s of e){if(s.role===`activity`){if(a&&`parts`in s){let e=s.parts.find(e=>e.type===`activity`);if(e){let t={id:s.id,role:`activity`,activityType:e.activityType,content:structuredClone(e.content),...s.metadata!=null&&{metadata:s.metadata},...e.subagentRunId!==void 0&&{subagentRunId:e.subagentRunId}};n.push(t)}}continue}if(!(`parts`in s)&&s.role===`tool`&&s.toolCallId){let e=tl(rl(s.id,s.toolCallId,o),r),t=Vc(s.metadata,s.createdAt,s.id,s.content);n.push({role:`tool`,id:e,...s.name!==void 0&&{name:s.name},toolCallId:s.toolCallId,content:typeof s.content==`string`?s.content:JSON.stringify(s.content),...s.error!==void 0&&{error:s.error},...t!==void 0&&{metadata:t}});continue}let e=`parts`in s?s:Mc(s,s.id),c=e.parts;if(r.add(e.id),s.role===`system`){n.push(Uc(e,`system`,{content:c.length>0?qc(c):s.content??``},c,i));continue}if(s.role===`user`){n.push(Uc(e,`user`,{content:c.length>0?Xc(c):s.content??``},c,i));continue}let l=e=>({thinking:[],parts:[],continues:e,closed:!1}),u=l(!1),d=[u];for(let e of c){u.closed&&(e.type===`thinking`||e.type===`text`||e.type===`tool-call`)&&(u=l(!1),d.push(u));let t=u.parts.some(e=>e.type===`tool-call`);e.type===`thinking`?(u.parts.some(e=>e.type===`tool-call`&&Js(e))?(u=l(!1),d.push(u)):(t||u.parts.some(e=>e.type===`text`))&&(u=l(!0),d.push(u)),u.thinking.push(e)):e.type===`text`&&t?(u=l(!0),d.push(u),u.parts.push(e)):(u.parts.push(e),e.type===`tool-result`&&(u.closed=!0))}let f=new Set(c.flatMap(e=>e.type===`tool-result`?[e.toolCallId]:[])),p=e=>{for(let t of e)if(t.type===`tool-result`){let e=tl(t.id??el(t.toolCallId),r),i=Vc(t.metadata,t.createdAt,t.id,t.content,!0,t.outcome);n.push({role:`tool`,id:e,toolCallId:t.toolCallId,...t.name!==void 0&&{name:t.name},content:typeof t.content==`string`?t.content:JSON.stringify(t.content),...t.error!==void 0&&{error:t.error},...i!==void 0&&{metadata:i}})}else if(t.type===`tool-call`){let e=t.approval?.approved;if(f.has(t.id)||t.output===void 0&&(t.state!==`approval-responded`||e===void 0))continue;let i=t.output===void 0?JSON.stringify({approved:e,...e&&{pendingExecution:!0},message:e?`User approved this action`:`User denied this action`}):tc(t.output),a=typeof i==`string`?i:JSON.stringify(i);n.push({role:`tool`,id:tl(el(t.id),r),toolCallId:t.id,content:a,metadata:Vc(void 0,void 0,void 0,i,!1,t.approval?.approved===!1?`denied`:void 0)})}},m=e.id,h=[];d.forEach((t,a)=>{for(let i of t.thinking){let t={role:`reasoning`,id:nl($c(e.id,i),r),content:i.content};i.signature&&(t.encryptedValue=i.signature),n.push(t)}let o=qc(t.parts),s=Qc(t.parts),c=Uc(a===0?e:{...e,id:nl(`${e.id}-segment-${a}`,r)},`assistant`,{...o!==``&&{content:o},...s&&{toolCalls:s}},t.parts,i);if(t.continues){let e=c.metadata??{};c.metadata={...e,tanstack:{...Bc(e.tanstack)?e.tanstack:{},continues:m}}}n.push(c),m=c.id,h.push(...t.parts),(t.closed||a===d.length-1)&&(p(h),h=[])});for(let e of c)e.type===`subagent`&&n.push(...Jc(e,t))}return n}function Uc(e,t,n,r,i){let a=Wc(e,r,i),o={id:e.id,...e.name!==void 0&&{name:e.name},...a!==void 0&&{metadata:a}};return t===`system`?{...o,role:t,content:String(n.content??``)}:t===`user`?{...o,role:t,content:n.content??``}:{...o,role:t,...typeof n.content==`string`&&{content:n.content},...n.toolCalls!==void 0&&{toolCalls:n.toolCalls}}}function Wc(e,t,n){let r={...e.metadata??{}},i={...Y(e)};i.run&&(i.run={...i.run},delete i.run.startedAt,delete i.run.finishedAt),delete i.createdAt,delete i.continues,delete i.structuredOutput,delete i.toolCallMetadata,delete i.toolResult,delete i.toolResultOutcome,delete i.uiResources;let a=gc(e.createdAt);a!==void 0&&(i.createdAt=a.toISOString());let o=Gc(t,n);o&&(i.structuredOutput=o);let s={};for(let e of t)e.type===`tool-call`&&e.metadata!==void 0&&(s[e.id]=e.metadata);Object.keys(s).length>0&&(i.toolCallMetadata=s);let c=t.filter(e=>e.type===`ui-resource`);return c.length>0&&(i.uiResources=c),Object.keys(i).length>0?r.tanstack=i:delete r.tanstack,Object.keys(r).length>0?r:void 0}function Gc(e,t){for(let n of e)if(n.type===`structured-output`&&(t||n.status!==`complete`))return Kc(n,t)}function Kc(e,t){return{status:e.status,raw:e.raw,...t&&e.partial!==void 0?{partial:e.partial}:{},...t&&e.data!==void 0?{data:e.data}:{},...t&&e.reasoning?{reasoning:e.reasoning}:{},...e.errorMessage!==void 0&&{errorMessage:e.errorMessage}}}function qc(e){let t=[];for(let n of e)n.type===`text`?t.push(n.content):n.type===`structured-output`&&n.status===`complete`&&n.raw!==``&&t.push(n.raw);return t.join(``)}function Jc(e,t){let{subagent:n}=e,r={name:n.name,status:n.status,...n.description!==void 0&&{description:n.description},...n.error!==void 0&&{error:n.error},...n.interruptIds!==void 0&&{interruptIds:n.interruptIds},...n.parentSubagentRunId!==void 0&&{parentSubagentRunId:n.parentSubagentRunId},...n.parentToolCallId!==void 0&&{parentToolCallId:n.parentToolCallId},...n.metadata!==void 0&&{metadata:n.metadata}},i=Hc(n.messages,t),a=i.some(e=>Hs(e)===void 0);return(a?i:[{id:`subagent:${n.id}`,role:`assistant`},...i]).map((e,t)=>{let i=Hs(e);if(i!==void 0){let t=Us(e);return!t||t.parentSubagentRunId!==void 0?e:Yc(e,i,{...t,parentSubagentRunId:n.id})}return Yc(e,n.id,!a&&t===0?{...r,placeholder:!0}:r)})}function Yc(e,t,n){let r=Bc(e.metadata)?e.metadata:{},i=Bc(r.tanstack)?r.tanstack:{};return{...e,subagentRunId:t,metadata:{...r,tanstack:{...i,subagent:n}}}}function Xc(e){if(!e.some(e=>e.type===`image`||e.type===`audio`||e.type===`video`||e.type===`document`))return qc(e);let t=[];for(let n of e)n.type===`text`?t.push({type:`text`,text:n.content}):(n.type===`image`||n.type===`audio`||n.type===`video`||n.type===`document`)&&t.push(n);return t}function Zc(e){if(typeof e!=`object`||!e||Array.isArray(e)||!(`thoughtSignature`in e))return;let t=e.thoughtSignature;return typeof t==`string`&&t!==``?t:void 0}function Qc(e){let t=[];for(let n of e)if(n.type===`tool-call`){let e=Zc(n.metadata);t.push({id:n.id,type:`function`,function:{name:n.name,arguments:n.arguments},...e===void 0?{}:{encryptedValue:e}})}return t.length>0?t:void 0}function $c(e,t){let n=`${e}-reasoning-${t.id??il(t.content)}`;return t.type===`thinking`&&t.redacted?`${Yo}${n}`:n}function el(e){return`tool-${e}`}function tl(e,t){return nl(e,t)}function nl(e,t){if(!t.has(e))return t.add(e),e;let n=2;for(;t.has(`${e}-${n}`);)n++;let r=`${e}-${n}`;return t.add(r),r}function rl(e,t,n){let r=el(t);return e===void 0||n.has(e)?r:e}function il(e){let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)|0;return Math.abs(t).toString(36)}function al(e){if((e.type===X.RUN_FINISHED||e.type===X.RUN_ERROR)&&(Array.isArray(e.usage)||Lo(e.usage))){let t=Ro(e.usage,Y(e)?.usage);t!==void 0&&(e.usage=t)}if(e.type===X.TOOL_CALL_END&&e.input===void 0){let t=Y(e),n=t?.input??(typeof t?.args==`string`?qo(t.args):void 0);n!==void 0&&(e.input=n)}return e}function ol(e){al(e);let t=Y(e),n=e;if(t==null)return n;for(let[e,r]of Object.entries(t))e!==`usage`&&e!==`interruptErrors`&&n[e]===void 0&&r!==void 0&&(n[e]=r);return t.interruptErrors!==void 0&&(n[`tanstack:interruptErrors`]=t.interruptErrors),n}function sl(e){if(e.approvalSchema!==void 0&&e.needsApproval!==!0)throw TypeError(`approvalSchema requires needsApproval: true.`);let t=e.inputSchema,n=e.outputSchema,r=e.approvalSchema,i=e.needsApproval,a=e.execution;return{__toolSide:`definition`,...e,inputSchema:t,outputSchema:n,approvalSchema:r,needsApproval:i,execution:a,server(o){return{__toolSide:`server`,...e,inputSchema:t,outputSchema:n,approvalSchema:r,needsApproval:i,execution:a,execute:o}},client(o){return{__toolSide:`client`,...e,inputSchema:t,outputSchema:n,approvalSchema:r,needsApproval:i,execution:a,...o!==void 0&&{execute:o}}}}}function cl(e){return typeof e==`string`&&e!==``?e:void 0}function ll(e){if(`runId`in e){let t=cl(e.runId);if(t!==void 0)return t}return cl(Y(e)?.runId)}var ul=/* @__PURE__ */ $a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.ALL=e.COLLECTION=e.ATOM=e.SPECIAL=e.INF=e._INFINITY=e.INFINITY=e.NAN=e.BOOL=e.NULL=e.OBJ=e.ARR=e.NUM=e.STR=void 0,e.STR=1,e.NUM=2,e.ARR=4,e.OBJ=8,e.NULL=16,e.BOOL=32,e.NAN=64,e.INFINITY=128,e._INFINITY=256,e.INF=e.INFINITY|e._INFINITY,e.SPECIAL=e.NULL|e.BOOL|e.INF|e.NAN,e.ATOM=e.STR|e.NUM|e.SPECIAL,e.COLLECTION=e.ARR|e.OBJ,e.ALL=e.ATOM|e.COLLECTION,e.Allow={STR:e.STR,NUM:e.NUM,ARR:e.ARR,OBJ:e.OBJ,NULL:e.NULL,BOOL:e.BOOL,NAN:e.NAN,INFINITY:e.INFINITY,_INFINITY:e._INFINITY,INF:e.INF,SPECIAL:e.SPECIAL,ATOM:e.ATOM,COLLECTION:e.COLLECTION,ALL:e.ALL},e.default=e.Allow})),dl=(/* @__PURE__ */ $a(((e,t,n)=>{var r=n&&n.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),i=n&&n.__exportStar||function(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&r(t,e,n)};Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.MalformedJSON=e.PartialJSON=e.parseJSON=e.parse=void 0;let a=ul();Object.defineProperty(e,"Allow",{enumerable:!0,get:function(){return a.Allow}}),i(ul(),e);var o=class extends Error{};e.PartialJSON=o;var s=class extends Error{};e.MalformedJSON=s;function c(e,t=a.Allow.ALL){if(typeof e!=`string`)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return l(e.trim(),t)}e.parseJSON=c;let l=(e,t)=>{let n=e.length,r=0,i=e=>{throw new o(`${e} at position ${r}`)},c=e=>{throw new s(`${e} at position ${r}`)},l=()=>(m(),r>=n&&i(`Unexpected end of input`),e[r]===`"`?u():e[r]===`{`?d():e[r]===`[`?f():e.substring(r,r+4)===`null`||a.Allow.NULL&t&&n-r<4&&`null`.startsWith(e.substring(r))?(r+=4,null):e.substring(r,r+4)===`true`||a.Allow.BOOL&t&&n-r<4&&`true`.startsWith(e.substring(r))?(r+=4,!0):e.substring(r,r+5)===`false`||a.Allow.BOOL&t&&n-r<5&&`false`.startsWith(e.substring(r))?(r+=5,!1):e.substring(r,r+8)===`Infinity`||a.Allow.INFINITY&t&&n-r<8&&`Infinity`.startsWith(e.substring(r))?(r+=8,1/0):e.substring(r,r+9)===`-Infinity`||a.Allow._INFINITY&t&&1<n-r&&n-r<9&&`-Infinity`.startsWith(e.substring(r))?(r+=9,-1/0):e.substring(r,r+3)===`NaN`||a.Allow.NAN&t&&n-r<3&&`NaN`.startsWith(e.substring(r))?(r+=3,NaN):p()),u=()=>{let o=r,s=!1;for(r++;r<n&&(e[r]!==`"`||s&&e[r-1]===`\\`);)s=e[r]===`\\`&&!s,r++;if(e.charAt(r)==`"`)try{return JSON.parse(e.substring(o,++r-Number(s)))}catch(e){c(String(e))}else if(a.Allow.STR&t)try{return JSON.parse(e.substring(o,r-Number(s))+`"`)}catch{return JSON.parse(e.substring(o,e.lastIndexOf(`\\`))+`"`)}i(`Unterminated string literal`)},d=()=>{r++,m();let o={};try{for(;e[r]!==`}`;){if(m(),r>=n&&a.Allow.OBJ&t)return o;let i=u();m(),r++;try{o[i]=l()}catch(e){if(a.Allow.OBJ&t)return o;throw e}m(),e[r]===`,`&&r++}}catch{if(a.Allow.OBJ&t)return o;i(`Expected '}' at end of object`)}return r++,o},f=()=>{r++;let n=[];try{for(;e[r]!==`]`;)n.push(l()),m(),e[r]===`,`&&r++}catch{if(a.Allow.ARR&t)return n;i(`Expected ']' at end of array`)}return r++,n},p=()=>{if(r===0){e===`-`&&c(`Not sure what '-' is`);try{return JSON.parse(e)}catch(n){if(a.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf(`e`)))}catch{}c(String(n))}}let o=r;for(e[r]===`-`&&r++;e[r]&&`,]}`.indexOf(e[r])===-1;)r++;r==n&&!(a.Allow.NUM&t)&&i(`Unterminated number literal`);try{return JSON.parse(e.substring(o,r))}catch{e.substring(o,r)===`-`&&i(`Not sure what '-' is`);try{return JSON.parse(e.substring(o,e.lastIndexOf(`e`)))}catch(e){c(String(e))}}},m=()=>{for(;r<n&&`
|
|
128
|
-
\r `.includes(e[r]);)r++};return l()};e.parse=c})))(),
|
|
129
|
+
`:``}${e}`;n.contentParts.push({type:`text`,content:t}),n.order.push({type:`text`,text:t})}break}}c();for(let n of e.parts)if(n.type===`tool-call`&&(n.output!==void 0&&!i.has(n.id)&&(t.push({role:`tool`,content:ac(n.output),toolCallId:n.id}),i.add(n.id)),n.output===void 0&&n.state===`approval-responded`&&n.approval?.approved!==void 0&&!i.has(n.id))){let e=n.approval.approved;t.push({role:`tool`,content:JSON.stringify({approved:e,...e&&{pendingExecution:!0},message:e?`User approved this action`:`User denied this action`}),toolCallId:n.id,...e===!1&&{metadata:{tanstack:{toolResultOutcome:`denied`}}}}),i.add(n.id)}return t.length===0&&t.push({...s,role:`assistant`,content:null}),t}function Pc(e){return{type:`thinking`,content:e.content,...e.signature&&{signature:e.signature},...e.redacted&&{redacted:!0}}}function Fc(e){let t;try{t=JSON.parse(e.function.arguments)}catch{t=void 0}return{type:`tool-call`,id:e.id,name:e.function.name,arguments:e.function.arguments,state:`input-complete`,...t!==void 0&&{input:t},...e.metadata!==void 0&&{metadata:e.metadata}}}function Ic(e,t){let n=[],r=bc(e.createdAt);if(e.role===`assistant`&&e.thinking?.length)for(let t of e.thinking)(t.content||t.signature)&&n.push(Pc(t));let i=e.structuredOutput??zc(Y(e)?.structuredOutput);if(e.role===`assistant`&&i){if(typeof e.content==`string`&&e.content&&e.content!==i.raw){let t=i.raw,r=t!==``&&e.content.endsWith(t)?e.content.slice(0,-t.length):e.content;r&&n.push({type:`text`,content:r})}n.push(i)}else if(e.role===`tool`&&e.toolCallId){let t=Y(e)?.toolResultOutcome,i=tc(t)?t:void 0,a=e.error===void 0&&i===void 0?`complete`:`error`;n.push({type:`tool-result`,toolCallId:e.toolCallId,content:vc(e.content),state:a,...i!==void 0&&{outcome:i},...e.id!==void 0&&{id:e.id},...e.name!==void 0&&{name:e.name},...e.metadata!==void 0&&{metadata:e.metadata},...r!==void 0&&{createdAt:r},...e.error!==void 0&&{error:e.error}})}else if(Array.isArray(e.content))for(let t of e.content)n.push(t);else{let t=hc(e.content);t&&n.push({type:`text`,content:t})}if(e.toolCalls&&e.toolCalls.length>0)for(let t of e.toolCalls)n.push(Fc(t));let a=e.role===`assistant`&&i===void 0?sc(e):void 0;a&&n.splice(0,n.length,...a.flatMap(e=>e.type===`text`?[{type:`text`,content:e.text}]:e.type===`tool-call`?[Fc(e.toolCall)]:e.thinking.content||e.thinking.signature?[Pc(e.thinking)]:[]));let o={id:t||Uc(),role:e.role===`tool`?`assistant`:e.role,parts:n,...wc(e),...r!==void 0&&{createdAt:r},...e.metadata!==void 0&&{metadata:e.metadata}},s=Y(e)?.uiResources;return Dc(o,Array.isArray(s)?s.filter(Tc):[])}function Lc(e){if(`parts`in e)return Rc(e,{...e,id:e.id||Uc()});let t=e.id||Uc();switch(e.role){case`user`:return Rc(e,{id:t,role:`user`,parts:Bc(e.content)});case`assistant`:{let n=Y(e),r=n?.toolCallMetadata,i=zc(n?.structuredOutput),a=e.toolCalls?.map(e=>{let t=typeof r==`object`&&r?r[e.id]:void 0;return t===void 0?e:{...e,metadata:t}});return Rc(e,Ic({role:`assistant`,content:e.content??null,...wc(e),...a&&{toolCalls:a},...i&&{structuredOutput:i}},t))}case`tool`:{e=yc(e);let n=bc(`createdAt`in e?e.createdAt:void 0)??Sc(e);return Rc(e,Ic({role:`tool`,content:rc(e.content)?e.content:Vc(e.content),toolCallId:e.toolCallId,...`name`in e&&typeof e.name==`string`?{name:e.name}:{},...`id`in e&&typeof e.id==`string`?{id:e.id}:{},...`metadata`in e&&e.metadata!=null?{metadata:e.metadata}:{},...n===void 0?{}:{createdAt:n},...e.error!==void 0&&{error:e.error}},t))}case`system`:case`developer`:return Rc(e,{id:t,role:`system`,parts:e.content?[{type:`text`,content:e.content}]:[]});case`reasoning`:{let n=fc(e),r=typeof e.content==`string`?e.content:``;return Rc(e,{id:t,role:`assistant`,parts:r||n!==void 0?[{type:`thinking`,content:r,...n===void 0?{}:{signature:n},...pc(e)}]:[]})}case`activity`:return Rc(e,{id:t,role:`activity`,parts:[{type:`activity`,activityType:e.activityType,content:structuredClone(e.content)}]});default:return Rc(e,{id:t,role:`assistant`,parts:[]})}}function Rc(e,t){let n=t.parts.map(e=>xc(e));n!==t.parts&&(t={...t,parts:n});let r=`name`in e&&typeof e.name==`string`?e.name:void 0,i=r===void 0?t:{...t,name:r},a;if(`metadata`in e){let t=e.metadata;typeof t==`object`&&t&&!Array.isArray(t)&&(a=t,i={...i,metadata:a})}let o=bc(i.createdAt)??(a===void 0?void 0:Sc(a));if(o!==void 0&&!Object.is(o,i.createdAt))i={...i,createdAt:o};else if(o===void 0&&i.createdAt!==void 0){let{createdAt:e,...t}=i;i=t}let s=Y(a)?.uiResources,c=Array.isArray(s)?s.filter(Tc):[];return Dc(i,c)}function zc(e){if(e==null||e.status!==`streaming`&&e.status!==`complete`&&e.status!==`error`||typeof e.raw!=`string`)return;let t={type:`structured-output`,raw:e.raw,...e.partial===void 0?{}:{partial:e.partial},...e.reasoning?{reasoning:e.reasoning}:{},...e.errorMessage===void 0?{}:{errorMessage:e.errorMessage}};if(e.status!==`complete`)return{...t,status:e.status};if(e.data!==void 0)return{...t,status:`complete`,data:e.data}}function Bc(e){let t=Vc(e);return typeof t==`string`?t?[{type:`text`,content:t}]:[]:t}function Vc(e){return typeof e==`string`?e:e.map(e=>{if(e.type!==`text`)return e;let{text:t,...n}=e;return{...n,content:t}})}function Hc(e,t){if(`parts`in e){let n=e.parts.map(e=>xc(e));return{...e,parts:n,id:e.id||t(),createdAt:bc(e.createdAt)??/* @__PURE__ */ new Date}}return{...Ic(e,t()),createdAt:bc(e.createdAt)??/* @__PURE__ */ new Date}}function Uc(){return`msg-${Date.now()}-${Math.random().toString(36).substring(7)}`}function Wc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Gc(e,t,n,r,i=!1,a){let o=Wc(e)?e:{},s=Wc(o.tanstack)?{...o.tanstack}:{};i&&delete s.uiResources;let c=bc(t),l={...n===void 0?{}:{id:n},...c&&{createdAt:c.toISOString()},...Array.isArray(r)&&{content:r}},u={...o,tanstack:{...s,...a!==void 0&&{toolResultOutcome:a},toolResult:l}};return Object.keys(u).length?u:void 0}function Kc(e,t){let n=[],r=new Set(e.flatMap(e=>`id`in e&&e.id&&e.role!==`tool`?[e.id]:[])),i=t?.includeSnapshotStructuredOutput??!1,a=t?.includeActivity??!1,o=/* @__PURE__ */ new Set;for(let t of e)t.role===`assistant`&&t.id!==void 0&&o.add(t.id);for(let s of e){if(s.role===`activity`){if(a&&`parts`in s){let e=s.parts.find(e=>e.type===`activity`);if(e){let t={id:s.id,role:`activity`,activityType:e.activityType,content:structuredClone(e.content),...s.metadata!=null&&{metadata:s.metadata},...e.subagentRunId!==void 0&&{subagentRunId:e.subagentRunId}};n.push(t)}}continue}if(!(`parts`in s)&&s.role===`tool`&&s.toolCallId){let e=al(sl(s.id,s.toolCallId,o),r),t=Gc(s.metadata,s.createdAt,s.id,s.content);n.push({role:`tool`,id:e,...s.name!==void 0&&{name:s.name},toolCallId:s.toolCallId,content:typeof s.content==`string`?s.content:JSON.stringify(s.content),...s.error!==void 0&&{error:s.error},...t!==void 0&&{metadata:t}});continue}let e=`parts`in s?s:Ic(s,s.id),c=e.parts;if(r.add(e.id),s.role===`system`){n.push(qc(e,`system`,{content:c.length>0?Zc(c):s.content??``},c,i));continue}if(s.role===`user`){n.push(qc(e,`user`,{content:c.length>0?el(c):s.content??``},c,i));continue}let l=e=>({thinking:[],parts:[],continues:e,closed:!1}),u=l(!1),d=[u];for(let e of c){u.closed&&(e.type===`thinking`||e.type===`text`||e.type===`tool-call`)&&(u=l(!1),d.push(u));let t=u.parts.some(e=>e.type===`tool-call`);e.type===`thinking`?(u.parts.some(e=>e.type===`tool-call`&&Qs(e))?(u=l(!1),d.push(u)):(t||u.parts.some(e=>e.type===`text`))&&(u=l(!0),d.push(u)),u.thinking.push(e)):e.type===`text`&&t?(u=l(!0),d.push(u),u.parts.push(e)):(u.parts.push(e),e.type===`tool-result`&&(u.closed=!0))}let f=new Set(c.flatMap(e=>e.type===`tool-result`?[e.toolCallId]:[])),p=e=>{for(let t of e)if(t.type===`tool-result`){let e=al(t.id??il(t.toolCallId),r),i=Gc(t.metadata,t.createdAt,t.id,t.content,!0,t.outcome);n.push({role:`tool`,id:e,toolCallId:t.toolCallId,...t.name!==void 0&&{name:t.name},content:typeof t.content==`string`?t.content:JSON.stringify(t.content),...t.error!==void 0&&{error:t.error},...i!==void 0&&{metadata:i}})}else if(t.type===`tool-call`){let e=t.approval?.approved;if(f.has(t.id)||t.output===void 0&&(t.state!==`approval-responded`||e===void 0))continue;let i=t.output===void 0?JSON.stringify({approved:e,...e&&{pendingExecution:!0},message:e?`User approved this action`:`User denied this action`}):ac(t.output),a=typeof i==`string`?i:JSON.stringify(i);n.push({role:`tool`,id:al(il(t.id),r),toolCallId:t.id,content:a,metadata:Gc(void 0,void 0,void 0,i,!1,t.approval?.approved===!1?`denied`:void 0)})}},m=e.id,h=[];d.forEach((t,a)=>{for(let i of t.thinking){let t={role:`reasoning`,id:ol(rl(e.id,i),r),content:i.content};i.signature&&(t.encryptedValue=i.signature),n.push(t)}let o=Zc(t.parts),s=nl(t.parts),c=qc(a===0?e:{...e,id:ol(`${e.id}-segment-${a}`,r)},`assistant`,{...o!==``&&{content:o},...s&&{toolCalls:s}},t.parts,i);if(t.continues){let e=c.metadata??{};c.metadata={...e,tanstack:{...Wc(e.tanstack)?e.tanstack:{},continues:m}}}n.push(c),m=c.id,h.push(...t.parts),(t.closed||a===d.length-1)&&(p(h),h=[])});for(let e of c)e.type===`subagent`&&n.push(...Qc(e,t))}return n}function qc(e,t,n,r,i){let a=Jc(e,r,i),o={id:e.id,...e.name!==void 0&&{name:e.name},...a!==void 0&&{metadata:a}};return t===`system`?{...o,role:t,content:String(n.content??``)}:t===`user`?{...o,role:t,content:n.content??``}:{...o,role:t,...typeof n.content==`string`&&{content:n.content},...n.toolCalls!==void 0&&{toolCalls:n.toolCalls}}}function Jc(e,t,n){let r={...e.metadata??{}},i={...Y(e)};i.run&&(i.run={...i.run},delete i.run.startedAt,delete i.run.finishedAt),delete i.createdAt,delete i.continues,delete i.structuredOutput,delete i.toolCallMetadata,delete i.toolResult,delete i.toolResultOutcome,delete i.uiResources;let a=bc(e.createdAt);a!==void 0&&(i.createdAt=a.toISOString());let o=Yc(t,n);o&&(i.structuredOutput=o);let s={};for(let e of t)e.type===`tool-call`&&e.metadata!==void 0&&(s[e.id]=e.metadata);Object.keys(s).length>0&&(i.toolCallMetadata=s);let c=t.filter(e=>e.type===`ui-resource`);return c.length>0&&(i.uiResources=c),Object.keys(i).length>0?r.tanstack=i:delete r.tanstack,Object.keys(r).length>0?r:void 0}function Yc(e,t){for(let n of e)if(n.type===`structured-output`&&(t||n.status!==`complete`))return Xc(n,t)}function Xc(e,t){return{status:e.status,raw:e.raw,...t&&e.partial!==void 0?{partial:e.partial}:{},...t&&e.data!==void 0?{data:e.data}:{},...t&&e.reasoning?{reasoning:e.reasoning}:{},...e.errorMessage!==void 0&&{errorMessage:e.errorMessage}}}function Zc(e){let t=[];for(let n of e)n.type===`text`?t.push(n.content):n.type===`structured-output`&&n.status===`complete`&&n.raw!==``&&t.push(n.raw);return t.join(``)}function Qc(e,t){let{subagent:n}=e,r={name:n.name,status:n.status,...n.description!==void 0&&{description:n.description},...n.error!==void 0&&{error:n.error},...n.interruptIds!==void 0&&{interruptIds:n.interruptIds},...n.parentSubagentRunId!==void 0&&{parentSubagentRunId:n.parentSubagentRunId},...n.parentToolCallId!==void 0&&{parentToolCallId:n.parentToolCallId},...n.metadata!==void 0&&{metadata:n.metadata}},i=Kc(n.messages,t),a=i.some(e=>Ks(e)===void 0);return(a?i:[{id:`subagent:${n.id}`,role:`assistant`},...i]).map((e,t)=>{let i=Ks(e);if(i!==void 0){let t=qs(e);return!t||t.parentSubagentRunId!==void 0?e:$c(e,i,{...t,parentSubagentRunId:n.id})}return $c(e,n.id,!a&&t===0?{...r,placeholder:!0}:r)})}function $c(e,t,n){let r=Wc(e.metadata)?e.metadata:{},i=Wc(r.tanstack)?r.tanstack:{};return{...e,subagentRunId:t,metadata:{...r,tanstack:{...i,subagent:n}}}}function el(e){if(!e.some(e=>e.type===`image`||e.type===`audio`||e.type===`video`||e.type===`document`))return Zc(e);let t=[];for(let n of e)n.type===`text`?t.push({type:`text`,text:n.content}):(n.type===`image`||n.type===`audio`||n.type===`video`||n.type===`document`)&&t.push(n);return t}function tl(e){if(typeof e!=`object`||!e||Array.isArray(e)||!(`thoughtSignature`in e))return;let t=e.thoughtSignature;return typeof t==`string`&&t!==``?t:void 0}function nl(e){let t=[];for(let n of e)if(n.type===`tool-call`){let e=tl(n.metadata);t.push({id:n.id,type:`function`,function:{name:n.name,arguments:n.arguments},...e===void 0?{}:{encryptedValue:e}})}return t.length>0?t:void 0}function rl(e,t){let n=`${e}-reasoning-${t.id??cl(t.content)}`;return t.type===`thinking`&&t.redacted?`${$o}${n}`:n}function il(e){return`tool-${e}`}function al(e,t){return ol(e,t)}function ol(e,t){if(!t.has(e))return t.add(e),e;let n=2;for(;t.has(`${e}-${n}`);)n++;let r=`${e}-${n}`;return t.add(r),r}function sl(e,t,n){let r=il(t);return e===void 0||n.has(e)?r:e}function cl(e){let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)|0;return Math.abs(t).toString(36)}function ll(e){if((e.type===X.RUN_FINISHED||e.type===X.RUN_ERROR)&&(Array.isArray(e.usage)||Vo(e.usage))){let t=Ho(e.usage,Y(e)?.usage);t!==void 0&&(e.usage=t)}if(e.type===X.TOOL_CALL_END&&e.input===void 0){let t=Y(e),n=t?.input??(typeof t?.args==`string`?Zo(t.args):void 0);n!==void 0&&(e.input=n)}return e}function ul(e){ll(e);let t=Y(e),n=e;if(t==null)return n;for(let[e,r]of Object.entries(t))e!==`usage`&&e!==`interruptErrors`&&n[e]===void 0&&r!==void 0&&(n[e]=r);return t.interruptErrors!==void 0&&(n[`tanstack:interruptErrors`]=t.interruptErrors),n}function dl(e){if(e.approvalSchema!==void 0&&e.needsApproval!==!0)throw TypeError(`approvalSchema requires needsApproval: true.`);let t=e.inputSchema,n=e.outputSchema,r=e.approvalSchema,i=e.needsApproval,a=e.execution;return{__toolSide:`definition`,...e,inputSchema:t,outputSchema:n,approvalSchema:r,needsApproval:i,execution:a,server(o){return{__toolSide:`server`,...e,inputSchema:t,outputSchema:n,approvalSchema:r,needsApproval:i,execution:a,execute:o}},client(o){return{__toolSide:`client`,...e,inputSchema:t,outputSchema:n,approvalSchema:r,needsApproval:i,execution:a,...o!==void 0&&{execute:o}}}}}function fl(e){return typeof e==`string`&&e!==``?e:void 0}function pl(e){if(`runId`in e){let t=fl(e.runId);if(t!==void 0)return t}return fl(Y(e)?.runId)}var ml=/* @__PURE__ */ ro((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.ALL=e.COLLECTION=e.ATOM=e.SPECIAL=e.INF=e._INFINITY=e.INFINITY=e.NAN=e.BOOL=e.NULL=e.OBJ=e.ARR=e.NUM=e.STR=void 0,e.STR=1,e.NUM=2,e.ARR=4,e.OBJ=8,e.NULL=16,e.BOOL=32,e.NAN=64,e.INFINITY=128,e._INFINITY=256,e.INF=e.INFINITY|e._INFINITY,e.SPECIAL=e.NULL|e.BOOL|e.INF|e.NAN,e.ATOM=e.STR|e.NUM|e.SPECIAL,e.COLLECTION=e.ARR|e.OBJ,e.ALL=e.ATOM|e.COLLECTION,e.Allow={STR:e.STR,NUM:e.NUM,ARR:e.ARR,OBJ:e.OBJ,NULL:e.NULL,BOOL:e.BOOL,NAN:e.NAN,INFINITY:e.INFINITY,_INFINITY:e._INFINITY,INF:e.INF,SPECIAL:e.SPECIAL,ATOM:e.ATOM,COLLECTION:e.COLLECTION,ALL:e.ALL},e.default=e.Allow})),hl=(/* @__PURE__ */ ro(((e,t,n)=>{var r=n&&n.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),i=n&&n.__exportStar||function(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&r(t,e,n)};Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.MalformedJSON=e.PartialJSON=e.parseJSON=e.parse=void 0;let a=ml();Object.defineProperty(e,"Allow",{enumerable:!0,get:function(){return a.Allow}}),i(ml(),e);var o=class extends Error{};e.PartialJSON=o;var s=class extends Error{};e.MalformedJSON=s;function c(e,t=a.Allow.ALL){if(typeof e!=`string`)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return l(e.trim(),t)}e.parseJSON=c;let l=(e,t)=>{let n=e.length,r=0,i=e=>{throw new o(`${e} at position ${r}`)},c=e=>{throw new s(`${e} at position ${r}`)},l=()=>(m(),r>=n&&i(`Unexpected end of input`),e[r]===`"`?u():e[r]===`{`?d():e[r]===`[`?f():e.substring(r,r+4)===`null`||a.Allow.NULL&t&&n-r<4&&`null`.startsWith(e.substring(r))?(r+=4,null):e.substring(r,r+4)===`true`||a.Allow.BOOL&t&&n-r<4&&`true`.startsWith(e.substring(r))?(r+=4,!0):e.substring(r,r+5)===`false`||a.Allow.BOOL&t&&n-r<5&&`false`.startsWith(e.substring(r))?(r+=5,!1):e.substring(r,r+8)===`Infinity`||a.Allow.INFINITY&t&&n-r<8&&`Infinity`.startsWith(e.substring(r))?(r+=8,1/0):e.substring(r,r+9)===`-Infinity`||a.Allow._INFINITY&t&&1<n-r&&n-r<9&&`-Infinity`.startsWith(e.substring(r))?(r+=9,-1/0):e.substring(r,r+3)===`NaN`||a.Allow.NAN&t&&n-r<3&&`NaN`.startsWith(e.substring(r))?(r+=3,NaN):p()),u=()=>{let o=r,s=!1;for(r++;r<n&&(e[r]!==`"`||s&&e[r-1]===`\\`);)s=e[r]===`\\`&&!s,r++;if(e.charAt(r)==`"`)try{return JSON.parse(e.substring(o,++r-Number(s)))}catch(e){c(String(e))}else if(a.Allow.STR&t)try{return JSON.parse(e.substring(o,r-Number(s))+`"`)}catch{return JSON.parse(e.substring(o,e.lastIndexOf(`\\`))+`"`)}i(`Unterminated string literal`)},d=()=>{r++,m();let o={};try{for(;e[r]!==`}`;){if(m(),r>=n&&a.Allow.OBJ&t)return o;let i=u();m(),r++;try{o[i]=l()}catch(e){if(a.Allow.OBJ&t)return o;throw e}m(),e[r]===`,`&&r++}}catch{if(a.Allow.OBJ&t)return o;i(`Expected '}' at end of object`)}return r++,o},f=()=>{r++;let n=[];try{for(;e[r]!==`]`;)n.push(l()),m(),e[r]===`,`&&r++}catch{if(a.Allow.ARR&t)return n;i(`Expected ']' at end of array`)}return r++,n},p=()=>{if(r===0){e===`-`&&c(`Not sure what '-' is`);try{return JSON.parse(e)}catch(n){if(a.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf(`e`)))}catch{}c(String(n))}}let o=r;for(e[r]===`-`&&r++;e[r]&&`,]}`.indexOf(e[r])===-1;)r++;r==n&&!(a.Allow.NUM&t)&&i(`Unterminated number literal`);try{return JSON.parse(e.substring(o,r))}catch{e.substring(o,r)===`-`&&i(`Not sure what '-' is`);try{return JSON.parse(e.substring(o,e.lastIndexOf(`e`)))}catch(e){c(String(e))}}},m=()=>{for(;r<n&&`
|
|
130
|
+
\r `.includes(e[r]);)r++};return l()};e.parse=c})))(),gl=new class{parse(e){if(e&&e.trim()!==``)try{return(0,hl.parse)(e)}catch{return}}};function _l(e){return gl.parse(e)}var vl=class{shouldEmit(e,t){return!0}};function yl(e){let t=Error(e.message||`An error occurred`);return e.code!==void 0&&Object.assign(t,{code:e.code}),e.rawEvent!==void 0&&Object.assign(t,{rawEvent:e.rawEvent}),t}
|
|
129
131
|
/*!
|
|
130
132
|
* https://github.com/Starcounter-Jack/JSON-Patch
|
|
131
133
|
* (c) 2017-2022 Joachim Wester
|
|
132
134
|
* MIT licensed
|
|
133
135
|
*/
|
|
134
|
-
var
|
|
135
|
-
`)}var
|
|
136
|
+
var bl=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)};return function(t,n){e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),xl=Object.prototype.hasOwnProperty;function Sl(e,t){return xl.call(e,t)}function Cl(e){if(Array.isArray(e)){for(var t=Array(e.length),n=0;n<t.length;n++)t[n]=``+n;return t}if(Object.keys)return Object.keys(e);var r=[];for(var i in e)Sl(e,i)&&r.push(i);return r}function wl(e){switch(typeof e){case`object`:return JSON.parse(JSON.stringify(e));case`undefined`:return null;default:return e}}function Tl(e){for(var t=0,n=e.length,r;t<n;)if(r=e.charCodeAt(t),r>=48&&r<=57)t++;else return!1;return!0}function El(e){return e.indexOf(`/`)===-1&&e.indexOf(`~`)===-1?e:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function Dl(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}function Ol(e){if(e===void 0)return!0;if(e){if(Array.isArray(e)){for(var t=0,n=e.length;t<n;t++)if(Ol(e[t]))return!0}else if(typeof e==`object`){for(var r=Cl(e),i=r.length,a=0;a<i;a++)if(Ol(e[r[a]]))return!0}}return!1}function kl(e,t){var n=[e];for(var r in t){var i=typeof t[r]==`object`?JSON.stringify(t[r],null,2):t[r];i!==void 0&&n.push(r+`: `+i)}return n.join(`
|
|
137
|
+
`)}var Al=function(e){bl(t,e);function t(t,n,r,i,a){var o=this.constructor,s=e.call(this,kl(t,{name:n,index:r,operation:i,tree:a}))||this;return s.name=n,s.index=r,s.operation=i,s.tree=a,Object.setPrototypeOf(s,o.prototype),s.message=kl(t,{name:n,index:r,operation:i,tree:a}),s}return t}(Error),jl=/* @__PURE__ */ io({JsonPatchError:()=>$,_areEquals:()=>Vl,applyOperation:()=>Il,applyPatch:()=>Ll,applyReducer:()=>Rl,deepClone:()=>Ml,getValueByPointer:()=>Fl,validate:()=>Bl,validator:()=>zl}),$=Al,Ml=wl,Nl={add:function(e,t,n){return e[t]=this.value,{newDocument:n}},remove:function(e,t,n){var r=e[t];return delete e[t],{newDocument:n,removed:r}},replace:function(e,t,n){var r=e[t];return e[t]=this.value,{newDocument:n,removed:r}},move:function(e,t,n){var r=Fl(n,this.path);r&&=wl(r);var i=Il(n,{op:`remove`,path:this.from}).removed;return Il(n,{op:`add`,path:this.path,value:i}),{newDocument:n,removed:r}},copy:function(e,t,n){var r=Fl(n,this.from);return Il(n,{op:`add`,path:this.path,value:wl(r)}),{newDocument:n}},test:function(e,t,n){return{newDocument:n,test:Vl(e[t],this.value)}},_get:function(e,t,n){return this.value=e[t],{newDocument:n}}},Pl={add:function(e,t,n){return Tl(t)?e.splice(t,0,this.value):e[t]=this.value,{newDocument:n,index:t}},remove:function(e,t,n){return{newDocument:n,removed:e.splice(t,1)[0]}},replace:function(e,t,n){var r=e[t];return e[t]=this.value,{newDocument:n,removed:r}},move:Nl.move,copy:Nl.copy,test:Nl.test,_get:Nl._get};function Fl(e,t){if(t==``)return e;var n={op:`_get`,path:t};return Il(e,n),n.value}function Il(e,t,n,r,i,a){if(n===void 0&&(n=!1),r===void 0&&(r=!0),i===void 0&&(i=!0),a===void 0&&(a=0),n&&(typeof n==`function`?n(t,0,e,t.path):zl(t,0)),t.path===``){var o={newDocument:e};if(t.op===`add`)return o.newDocument=t.value,o;if(t.op===`replace`)return o.newDocument=t.value,o.removed=e,o;if(t.op===`move`||t.op===`copy`)return o.newDocument=Fl(e,t.from),t.op===`move`&&(o.removed=e),o;if(t.op===`test`){if(o.test=Vl(e,t.value),o.test===!1)throw new $(`Test operation failed`,`TEST_OPERATION_FAILED`,a,t,e);return o.newDocument=e,o}if(t.op===`remove`)return o.removed=e,o.newDocument=null,o;if(t.op===`_get`)return t.value=e,o;if(n)throw new $("Operation `op` property is not one of operations defined in RFC-6902",`OPERATION_OP_INVALID`,a,t,e);return o}r||(e=wl(e));var s=(t.path||``).split(`/`),c=e,l=1,u=s.length,d=void 0,f=void 0,p=void 0;for(p=typeof n==`function`?n:zl;;){if(f=s[l],f&&f.indexOf(`~`)!=-1&&(f=Dl(f)),i&&(f==`__proto__`||f==`prototype`&&l>0&&s[l-1]==`constructor`))throw TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(n&&d===void 0&&(c[f]===void 0?d=s.slice(0,l).join(`/`):l==u-1&&(d=t.path),d!==void 0&&p(t,0,e,d)),l++,Array.isArray(c)){if(f===`-`)f=c.length;else if(n&&!Tl(f))throw new $(`Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index`,`OPERATION_PATH_ILLEGAL_ARRAY_INDEX`,a,t,e);else Tl(f)&&(f=~~f);if(l>=u){if(n&&t.op===`add`&&f>c.length)throw new $(`The specified index MUST NOT be greater than the number of elements in the array`,`OPERATION_VALUE_OUT_OF_BOUNDS`,a,t,e);var o=Pl[t.op].call(t,c,f,e);if(o.test===!1)throw new $(`Test operation failed`,`TEST_OPERATION_FAILED`,a,t,e);return o}}else if(l>=u){var o=Nl[t.op].call(t,c,f,e);if(o.test===!1)throw new $(`Test operation failed`,`TEST_OPERATION_FAILED`,a,t,e);return o}if(c=c[f],n&&l<u&&(!c||typeof c!=`object`))throw new $(`Cannot perform operation at the desired path`,`OPERATION_PATH_UNRESOLVABLE`,a,t,e)}}function Ll(e,t,n,r,i){if(r===void 0&&(r=!0),i===void 0&&(i=!0),n&&!Array.isArray(t))throw new $(`Patch sequence must be an array`,`SEQUENCE_NOT_AN_ARRAY`);r||(e=wl(e));for(var a=Array(t.length),o=0,s=t.length;o<s;o++)a[o]=Il(e,t[o],n,!0,i,o),e=a[o].newDocument;return a.newDocument=e,a}function Rl(e,t,n){var r=Il(e,t);if(r.test===!1)throw new $(`Test operation failed`,`TEST_OPERATION_FAILED`,n,t,e);return r.newDocument}function zl(e,t,n,r){if(typeof e!=`object`||!e||Array.isArray(e))throw new $(`Operation is not an object`,`OPERATION_NOT_AN_OBJECT`,t,e,n);if(!Nl[e.op])throw new $("Operation `op` property is not one of operations defined in RFC-6902",`OPERATION_OP_INVALID`,t,e,n);if(typeof e.path!=`string`)throw new $("Operation `path` property is not a string",`OPERATION_PATH_INVALID`,t,e,n);if(e.path.indexOf(`/`)!==0&&e.path.length>0)throw new $('Operation `path` property must start with "/"',`OPERATION_PATH_INVALID`,t,e,n);if((e.op===`move`||e.op===`copy`)&&typeof e.from!=`string`)throw new $("Operation `from` property is not present (applicable in `move` and `copy` operations)",`OPERATION_FROM_REQUIRED`,t,e,n);if((e.op===`add`||e.op===`replace`||e.op===`test`)&&e.value===void 0)throw new $("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)",`OPERATION_VALUE_REQUIRED`,t,e,n);if((e.op===`add`||e.op===`replace`||e.op===`test`)&&Ol(e.value))throw new $("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)",`OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED`,t,e,n);if(n){if(e.op==`add`){var i=e.path.split(`/`).length,a=r.split(`/`).length;if(i!==a+1&&i!==a)throw new $("Cannot perform an `add` operation at the desired path",`OPERATION_PATH_CANNOT_ADD`,t,e,n)}else if(e.op===`replace`||e.op===`remove`||e.op===`_get`){if(e.path!==r)throw new $(`Cannot perform the operation at a path that does not exist`,`OPERATION_PATH_UNRESOLVABLE`,t,e,n)}else if(e.op===`move`||e.op===`copy`){var o=Bl([{op:`_get`,path:e.from,value:void 0}],n);if(o&&o.name===`OPERATION_PATH_UNRESOLVABLE`)throw new $(`Cannot perform the operation from a path that does not exist`,`OPERATION_FROM_UNRESOLVABLE`,t,e,n)}}}function Bl(e,t,n){try{if(!Array.isArray(e))throw new $(`Patch sequence must be an array`,`SEQUENCE_NOT_AN_ARRAY`);if(t)Ll(wl(t),wl(e),n||!0);else{n||=zl;for(var r=0;r<e.length;r++)n(e[r],r,t,void 0)}}catch(e){if(e instanceof $)return e;throw e}}function Vl(e,t){if(e===t)return!0;if(e&&t&&typeof e==`object`&&typeof t==`object`){var n=Array.isArray(e),r=Array.isArray(t),i,a,o;if(n&&r){if(a=e.length,a!=t.length)return!1;for(i=a;i--!==0;)if(!Vl(e[i],t[i]))return!1;return!0}if(n!=r)return!1;var s=Object.keys(e);if(a=s.length,a!==Object.keys(t).length)return!1;for(i=a;i--!==0;)if(!t.hasOwnProperty(s[i]))return!1;for(i=a;i--!==0;)if(o=s[i],!Vl(e[o],t[o]))return!1;return!0}return e!==e&&t!==t}
|
|
136
138
|
/*!
|
|
137
139
|
* https://github.com/Starcounter-Jack/JSON-Patch
|
|
138
140
|
* (c) 2017-2021 Joachim Wester
|
|
139
141
|
* MIT license
|
|
140
142
|
*/
|
|
141
|
-
var Rl=/* @__PURE__ */ eo({compare:()=>Yl,generate:()=>ql,observe:()=>Kl,unobserve:()=>Gl}),zl=/* @__PURE__ */ new WeakMap,Bl=function(){function e(e){this.observers=/* @__PURE__ */ new Map,this.obj=e}return e}(),Vl=function(){function e(e,t){this.callback=e,this.observer=t}return e}();function Hl(e){return zl.get(e)}function Ul(e,t){return e.observers.get(t)}function Wl(e,t){e.observers.delete(t.callback)}function Gl(e,t){t.unobserve()}function Kl(e,t){var n=[],r,i=Hl(e);if(!i)i=new Bl(e),zl.set(e,i);else{var a=Ul(i,t);r=a&&a.observer}if(r)return r;if(r={},i.value=bl(e),t){r.callback=t,r.next=null;var o=function(){ql(r)},s=function(){clearTimeout(r.next),r.next=setTimeout(o)};typeof window<`u`&&(window.addEventListener(`mouseup`,s),window.addEventListener(`keyup`,s),window.addEventListener(`mousedown`,s),window.addEventListener(`keydown`,s),window.addEventListener(`change`,s))}return r.patches=n,r.object=e,r.unobserve=function(){ql(r),clearTimeout(r.next),Wl(i,r),typeof window<`u`&&(window.removeEventListener(`mouseup`,s),window.removeEventListener(`keyup`,s),window.removeEventListener(`mousedown`,s),window.removeEventListener(`keydown`,s),window.removeEventListener(`change`,s))},i.observers.set(t,new Vl(t,r)),r}function ql(e,t){t===void 0&&(t=!1);var n=zl.get(e.object);Jl(n.value,e.object,e.patches,``,t),e.patches.length&&Nl(n.value,e.patches);var r=e.patches;return r.length>0&&(e.patches=[],e.callback&&e.callback(r)),r}function Jl(e,t,n,r,i){if(t!==e){typeof t.toJSON==`function`&&(t=t.toJSON());for(var a=yl(t),o=yl(e),s=!1,c=o.length-1;c>=0;c--){var l=o[c],u=e[l];if(vl(t,l)&&(t[l]!==void 0||u===void 0||Array.isArray(t)!==!1)){var d=t[l];typeof u==`object`&&u&&typeof d==`object`&&d&&Array.isArray(u)===Array.isArray(d)?Jl(u,d,n,r+`/`+Sl(l),i):u!==d&&(i&&n.push({op:`test`,path:r+`/`+Sl(l),value:bl(u)}),n.push({op:`replace`,path:r+`/`+Sl(l),value:bl(d)}))}else Array.isArray(e)===Array.isArray(t)?(i&&n.push({op:`test`,path:r+`/`+Sl(l),value:bl(u)}),n.push({op:`remove`,path:r+`/`+Sl(l)}),s=!0):(i&&n.push({op:`test`,path:r,value:e}),n.push({op:`replace`,path:r,value:t}))}if(s||a.length!=o.length)for(var c=0;c<a.length;c++){var l=a[c];!vl(e,l)&&t[l]!==void 0&&n.push({op:`add`,path:r+`/`+Sl(l),value:bl(t[l])})}}}function Yl(e,t,n){n===void 0&&(n=!1);var r=[];return Jl(e,t,r,``,n),r}var Xl=Object.assign({},Dl,Rl,{JsonPatchError:El,deepClone:bl,escapePathComponent:Sl,unescapePathComponent:Cl});function Zl(e){return e.type===`activity`}function Ql(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function $l(e,t){let{messageId:n,activityType:r,content:i}=t,a=t.replace??!0,o=e.findIndex(e=>e.id===n),s=o>=0?e[o]:void 0;if(s&&s.role!==`activity`)return console.warn(`ACTIVITY_SNAPSHOT: Message '${n}' is not an activity message`),e;if(s&&!a)return e;let c=Vo(s?.role===`activity`?s.metadata:void 0,t.metadata),l={id:n,role:`activity`,parts:[{type:`activity`,activityType:r,content:structuredClone(i??{})}],...c==null?{}:{metadata:c},...s?.role===`activity`&&s.createdAt!=null?{createdAt:s.createdAt}:{},...s?.role===`activity`&&s.name!=null?{name:s.name}:{}};return o===-1?[...e,l]:e.map((e,t)=>t===o?l:e)}function eu(e,t){let{messageId:n,activityType:r,patch:i}=t,a=e.findIndex(e=>e.id===n);if(a===-1)return console.warn(`ACTIVITY_DELTA: No activity message '${n}'`),e;let o=e[a];if(o==null||o.role!==`activity`)return console.warn(`ACTIVITY_DELTA: Message '${n}' is not an activity message`),e;let s=o.parts.find(Zl);if(s&&s.activityType!==r)return console.warn(`ACTIVITY_DELTA: activityType '${r}' does not match '${s.activityType}' for '${n}'`),e;let c=structuredClone(s?.content??{});try{let l=Xl.applyPatch(c,i??[],!0,!1);if(!Ql(l.newDocument))return console.warn(`ACTIVITY_DELTA: patched content for '${n}' is not an object`),e;let u={type:`activity`,activityType:r,content:structuredClone(l.newDocument)},d=s?o.parts.map(e=>e.type===`activity`?u:e):[u],f=Vo(o.metadata,t.metadata);return e.map((e,t)=>t===a?{...e,parts:d,...f==null?{}:{metadata:f}}:e)}catch(t){let r=t instanceof Error?t.message:String(t);return console.warn(`Failed to apply activity patch for '${n}': ${r}`),e}}function tu(e,t,n){return e.map(e=>{if(e.id!==t)return e;let r=[...e.parts],i=r.length>0?r[r.length-1]:null;return i&&i.type===`text`?r[r.length-1]={type:`text`,content:n}:r.push({type:`text`,content:n}),{...e,parts:r}})}function nu(e,t,n){return e.map(e=>{if(e.id!==t)return e;let r=[...e.parts],i=r.find(e=>e.type===`tool-call`&&e.id===n.id),a=n.metadata??i?.metadata,o=n.input??i?.input,s={type:`tool-call`,id:n.id,name:n.name,arguments:n.arguments,state:n.state,...i?.approval&&{approval:{...i.approval}},...i?.output!==void 0&&{output:i.output},...o!==void 0&&{input:o},...a!==void 0&&{metadata:a}};return i?r[r.indexOf(i)]=s:r.push(s),{...e,parts:r}})}function ru(e,t,n,r,i,a,o){return e.map(e=>{if(e.id!==t)return e;let s=[...e.parts],c=s.findIndex(e=>e.type===`tool-result`&&e.toolCallId===n),l={type:`tool-result`,toolCallId:n,content:r,state:i,...o!==void 0&&{outcome:o},...a&&{error:a}};return c>=0?s[c]=l:s.push(l),{...e,parts:s}})}function iu(e,t,n,r){return e.map(e=>{if(e.id!==t)return e;let i=[...e.parts],a=i.find(e=>e.type===`tool-call`&&e.id===n);if(a){let e=i.indexOf(a);i[e]={...a,state:`approval-requested`,approval:{id:r,needsApproval:!0}}}return{...e,parts:i}})}function au(e,t,n,r,i){return e.map(e=>{let a=[...e.parts],o=a.find(e=>e.type===`tool-call`&&e.id===t);if(o){let e=a.indexOf(o);a[e]={...o,output:i?{error:i}:n,state:r??(i?`error`:`complete`)}}return{...e,parts:a}})}function ou(e,t,n){return e.map(e=>{let r=[...e.parts],i=r.find(e=>e.type===`tool-call`&&e.approval?.id===t);if(i&&i.approval){let e=r.indexOf(i);r[e]={...i,approval:{...i.approval,approved:n},state:`approval-responded`}}return{...e,parts:r}})}function su(e,t,n){return e.map(e=>{if(e.id!==t)return e;let r=[...e.parts],i=r.findIndex(e=>e.type===`structured-output`),a=i>=0?r[i]:null,o=(a?.raw??``)+n,s=pl(o)??a?.partial,c={type:`structured-output`,status:`streaming`,raw:o,...s===void 0?{}:{partial:s},...a?.reasoning===void 0?{}:{reasoning:a.reasoning}};return i>=0?r[i]=c:r.push(c),{...e,parts:r}})}function cu(e,t,n,r,i){return e.map(e=>{if(e.id!==t)return e;let a=[...e.parts],o=a.findIndex(e=>e.type===`structured-output`),s=o>=0?a[o].raw:``,c=r||s;if(c===``&&n!==void 0)try{c=JSON.stringify(n)}catch{}let l={type:`structured-output`,status:`complete`,data:n,partial:n,raw:c,...i===void 0?{}:{reasoning:i}};return o>=0?a[o]=l:a.push(l),{...e,parts:a}})}function lu(e,t,n){return e.map(e=>{if(e.id!==t)return e;let r=[...e.parts],i=r.findIndex(e=>e.type===`structured-output`);if(i<0)return r.push({type:`structured-output`,status:`error`,raw:``,errorMessage:n}),{...e,parts:r};let a=r[i];return a.status===`complete`?e:(r[i]={...a,status:`error`,errorMessage:n},{...e,parts:r})})}function uu(e,t,n,r,i){return e.map(e=>{if(e.id!==t)return e;let a=[...e.parts],o=a.findIndex(e=>e.type===`thinking`&&e.stepId===n),s;if(o<0){o=a.findIndex(e=>e.type===`thinking`&&e.stepId===void 0);let e=a[o];e?.type===`thinking`&&(s=e)}let c=i??s?.signature,l=Xo(n)||s?.redacted===!0,u={type:`thinking`,content:r,stepId:n,...c&&{signature:c},...l&&{redacted:!0}};return o>=0?a[o]=u:a.push(u),{...e,parts:a}})}var du=12,fu=/* @__PURE__ */ new Set([`RAW`,`ACTIVITY_SNAPSHOT`,`ACTIVITY_DELTA`,`REASONING_ENCRYPTED_VALUE`,`SUBAGENT_STARTED`,`SUBAGENT_FINISHED`,`SUBAGENT_ERROR`]),pu=/* @__PURE__ */ new Set([`RUN_STARTED`,`RUN_FINISHED`,`RUN_ERROR`,`MESSAGES_SNAPSHOT`]);function mu(e){return e.some(e=>{let t=e.metadata;if(!t||typeof t!=`object`||Array.isArray(t))return!1;let n=t[Es];return typeof n==`object`&&!!n&&!Array.isArray(n)&&n.kind===`generic`})}var hu=class e{chunkStrategy;events;jsonParser;recordingEnabled;messages=[];messageStates=/* @__PURE__ */ new Map;activeMessageIds=/* @__PURE__ */ new Set;toolCallToMessage=/* @__PURE__ */ new Map;pendingManualMessageId=null;openChunk=null;structuredMessageIds=/* @__PURE__ */ new Set;structuredOutputUpdateBatches=/* @__PURE__ */ new Map;activeRuns=/* @__PURE__ */ new Set;callMessageIds=/* @__PURE__ */ new Map;unassignedCallMessageIds=/* @__PURE__ */ new Set;sealedMessageIds=/* @__PURE__ */ new Set;thinkingOwners=/* @__PURE__ */ new Map;runToolCallIds=[];toolCallsSentToClient=/* @__PURE__ */ new Set;childProcessors=/* @__PURE__ */ new Map;childToolCalls=/* @__PURE__ */ new Map;finishReason=null;hasError=!1;isDone=!1;streamEndEmitted=!1;recording=null;recordingStartTime=0;subagentRunId;constructor(e={}){this.subagentRunId=e.subagentRunId,this.chunkStrategy=e.chunkStrategy||new ml,this.events=e.events||{},this.jsonParser=e.jsonParser||fl,this.recordingEnabled=e.recording??!1,e.initialMessages&&(this.messages=[...e.initialMessages])}setMessages(e){this.messages=[...e],this.emitMessagesChange()}prependMessages(e){let t=new Set(this.messages.map(e=>e.id)),n=[];for(let r of e)t.has(r.id)||(t.add(r.id),n.push(r));this.messages=[...n,...this.messages],this.emitMessagesChange()}addUserMessage(e,t,n){let r=typeof e==`string`?[{type:`text`,content:e}]:e.map(e=>e),i={id:t??zc(),role:`user`,parts:r,createdAt:/* @__PURE__ */ new Date,...n==null?{}:{metadata:n}};return this.messages=[...this.messages,i],this.emitMessagesChange(),i}prepareAssistantMessage(){this.resetStreamState()}getCurrentAssistantMessageId(){let e=null;for(let[t,n]of this.messageStates)n.role===`assistant`&&(e=t);return e}addToolResult(e,t,n){let r=this.messages.find(t=>t.parts.some(t=>t.type===`tool-call`&&t.id===e));if(!r){let r=this.childOwningToolCall(t=>t.id===e);if(r!==void 0){this.updateChild(r,r=>r.addToolResult(e,t,n));return}console.warn(`[StreamProcessor] Could not find message with tool call ${e}`);return}let i=au(this.messages,e,t,n?`error`:void 0,n),a=tc(t),o=n?`error`:`complete`;i=ru(i,r.id,e,a,o,n),this.messages=i,this.emitMessagesChange()}addToolApprovalResponse(e,t){let n=this.childOwningToolCall(t=>t.approval?.id===e);n===void 0?(this.messages=ou(this.messages,e,t),this.emitMessagesChange()):this.updateChild(n,n=>n.addToolApprovalResponse(e,t))}toModelMessages(){let e=[];for(let t of this.messages)e.push(...Tc(t));return e}getMessages(){return this.messages}areAllToolsComplete(){let e=this.messages.findLast(e=>e.role===`assistant`);if(!e)return!0;let t=e.parts.filter(e=>e.type===`tool-call`);if(t.length===0)return!0;let n=new Set(e.parts.filter(e=>e.type===`tool-result`).map(e=>e.toolCallId));return t.every(e=>e.state===`complete`||e.state===`approval-responded`||e.output!==void 0&&!e.approval||n.has(e.id)||Js(e))}removeMessagesAfter(e){let t=new Set(this.messages.slice(0,e+1).map(e=>e.id));for(let e of this.structuredMessageIds)t.has(e)||this.structuredMessageIds.delete(e);for(let e of this.structuredOutputUpdateBatches.keys())t.has(e)||this.structuredOutputUpdateBatches.delete(e);for(let e of this.messageStates.keys())t.has(e)||this.messageStates.delete(e);for(let[e,n]of this.toolCallToMessage)t.has(n)||this.toolCallToMessage.delete(e);for(let e of this.activeMessageIds)t.has(e)||this.activeMessageIds.delete(e);this.pendingManualMessageId&&!t.has(this.pendingManualMessageId)&&(this.pendingManualMessageId=null);for(let e of this.callMessageIds.values())for(let n of e)t.has(n)||e.delete(n);for(let e of this.unassignedCallMessageIds)t.has(e)||this.unassignedCallMessageIds.delete(e);for(let e of this.sealedMessageIds)t.has(e)||this.sealedMessageIds.delete(e);for(let[e,n]of this.thinkingOwners)t.has(n.messageId)||this.thinkingOwners.delete(e);this.messages=this.messages.slice(0,e+1),this.emitMessagesChange()}clearMessages(){for(let e of this.callMessageIds.values())e.clear();this.unassignedCallMessageIds.clear(),this.messages=[],this.messageStates.clear(),this.activeMessageIds.clear(),this.toolCallToMessage.clear(),this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.pendingManualMessageId=null,this.sealedMessageIds.clear(),this.thinkingOwners.clear(),this.openChunk=null,this.childProcessors.clear(),this.childToolCalls.clear(),this.emitMessagesChange()}async process(e){this.resetStreamState(),this.recordingEnabled&&this.startRecording();for await(let t of e)this.processChunk(t);return this.finalizeStream(),this.recording&&(this.recording.result=this.getResult()),this.getResult()}processChunk(e){if(this.recording&&this.recording.chunks.push({chunk:e,timestamp:Date.now(),index:this.recording.chunks.length}),!this.routeToChild(e))for(let t of this.expandChunk(e))this.dispatchChunk(t)}dispatchChunk(e){switch(e.type){case`SUBAGENT_STARTED`:this.handleSubagentStartedEvent(e);break;case`SUBAGENT_FINISHED`:this.handleSubagentFinishedEvent(e);break;case`SUBAGENT_ERROR`:this.handleSubagentErrorEvent(e);break;case`TEXT_MESSAGE_START`:this.handleTextMessageStartEvent(e);break;case`TEXT_MESSAGE_CONTENT`:this.handleTextMessageContentEvent(e);break;case`TEXT_MESSAGE_END`:this.handleTextMessageEndEvent(e);break;case`TOOL_CALL_START`:this.handleToolCallStartEvent(e);break;case`TOOL_CALL_ARGS`:this.handleToolCallArgsEvent(e);break;case`TOOL_CALL_END`:this.handleToolCallEndEvent(e);break;case`RUN_FINISHED`:this.handleRunFinishedEvent(e);break;case`RUN_ERROR`:this.handleRunErrorEvent(e);break;case`MESSAGES_SNAPSHOT`:this.handleMessagesSnapshotEvent(e);break;case`CUSTOM`:this.handleCustomEvent(e);break;case`RUN_STARTED`:this.handleRunStartedEvent(e);break;case`REASONING_START`:case`REASONING_MESSAGE_END`:case`REASONING_END`:break;case`REASONING_MESSAGE_START`:{let t=e,n=this.unscopedAssistant(t),r=n.id?this.getMessageState(n.id):void 0;if(r&&(r.currentThinkingStepId=null),t.metadata==null)break;let{messageId:i}=this.ensureAssistantMessage(n.id??void 0,!n.create);this.mergeMessageMetadata(i,t.metadata);break}case`REASONING_MESSAGE_CONTENT`:this.handleReasoningMessageContentEvent(e);break;case`REASONING_ENCRYPTED_VALUE`:this.handleReasoningEncryptedValueEvent(e);break;case`TOOL_CALL_RESULT`:this.handleToolCallResultEvent(e);break;case`ACTIVITY_SNAPSHOT`:this.handleActivitySnapshotEvent(e);break;case`ACTIVITY_DELTA`:this.handleActivityDeltaEvent(e)}}expandChunk(e){let t=this.openChunk,n=e.timestamp;switch(e.type){case`TEXT_MESSAGE_CHUNK`:{let r=this.chunkStreamId(`TEXT_MESSAGE`,e.messageId,e.type);if(r===void 0)return this.closeChunk();let i=[];return(t?.family!==`TEXT_MESSAGE`||t.id!==r)&&(i.push(...this.closeChunk(),{type:X.TEXT_MESSAGE_START,messageId:r,role:e.role??`assistant`,...e.name===void 0?{}:{name:e.name},timestamp:n}),this.openChunk={family:`TEXT_MESSAGE`,id:r}),(e.delta!==void 0||e.metadata!==void 0)&&i.push({type:X.TEXT_MESSAGE_CONTENT,messageId:r,delta:e.delta??``,metadata:e.metadata,timestamp:n}),i}case`TOOL_CALL_CHUNK`:{let r=this.chunkStreamId(`TOOL_CALL`,e.toolCallId,e.type);if(r===void 0)return this.closeChunk();let i=[];if(t?.family!==`TOOL_CALL`||t.id!==r){if(e.toolCallName===void 0)return console.warn(`[StreamProcessor] Dropped TOOL_CALL_CHUNK ${r}: the first chunk of a tool call needs a toolCallName`),this.closeChunk();i.push(...this.closeChunk(),{type:X.TOOL_CALL_START,toolCallId:r,toolCallName:e.toolCallName,parentMessageId:e.parentMessageId,metadata:e.metadata,timestamp:n}),this.openChunk={family:`TOOL_CALL`,id:r}}return(e.delta!==void 0||e.metadata!==void 0)&&i.push({type:X.TOOL_CALL_ARGS,toolCallId:r,delta:e.delta??``,...e.metadata===void 0?{}:{metadata:e.metadata},timestamp:n}),i}case`REASONING_MESSAGE_CHUNK`:{let r=this.chunkStreamId(`REASONING_MESSAGE`,e.messageId,e.type);if(r===void 0)return this.closeChunk();let i=[];return(t?.family!==`REASONING_MESSAGE`||t.id!==r)&&(i.push(...this.closeChunk(),{type:X.REASONING_MESSAGE_START,messageId:r,role:`reasoning`,timestamp:n}),this.openChunk={family:`REASONING_MESSAGE`,id:r}),(e.delta!==void 0||e.metadata!==void 0)&&i.push({type:X.REASONING_MESSAGE_CONTENT,messageId:r,delta:e.delta??``,...e.metadata===void 0?{}:{metadata:e.metadata},timestamp:n}),i}default:{let n=t&&!fu.has(e.type)?this.closeChunk():[];return pu.has(e.type)&&this.closeChildChunkLanes(),[...n,e]}}}closeChildChunkLanes(){for(let e of this.childProcessors.values()){for(let t of e.closeChunk())e.dispatchChunk(t);e.closeChildChunkLanes()}}childContinuing(e){let t;if(e.type===`TEXT_MESSAGE_CHUNK`&&e.messageId===void 0)t=`TEXT_MESSAGE`;else if(e.type===`REASONING_MESSAGE_CHUNK`&&e.messageId===void 0)t=`REASONING_MESSAGE`;else if(e.type===`TOOL_CALL_CHUNK`&&e.toolCallId===void 0)t=`TOOL_CALL`;else return;if(this.openChunkCount(t)===1){for(let[e,n]of this.childProcessors)if(n.openChunkCount(t)===1)return e}}openChunkCount(e){let t=+(this.openChunk?.family===e);for(let n of this.childProcessors.values())t+=n.openChunkCount(e);return t}chunkStreamId(e,t,n){if(t!==void 0)return t;if(this.openChunk?.family===e)return this.openChunk.id;console.warn(`[StreamProcessor] Dropped ${n}: it has no id and continues nothing`)}closeChunk(){let e=this.openChunk;if(!e)return[];this.openChunk=null;let t=Date.now();switch(e.family){case`TEXT_MESSAGE`:return[{type:X.TEXT_MESSAGE_END,messageId:e.id,timestamp:t}];case`TOOL_CALL`:return[{type:X.TOOL_CALL_END,toolCallId:e.id,timestamp:t}];case`REASONING_MESSAGE`:return[{type:X.REASONING_MESSAGE_END,messageId:e.id,timestamp:t}]}}createMessageState(e,t){let n={id:e,role:t,totalTextContent:``,currentSegmentText:``,lastEmittedText:``,thinkingSteps:/* @__PURE__ */ new Map,thinkingStepSignatures:/* @__PURE__ */ new Map,thinkingStepOrder:[],currentThinkingStepId:null,toolCalls:/* @__PURE__ */ new Map,toolCallOrder:[],hasToolCallsSinceTextStart:!1,isComplete:!1};return this.messageStates.set(e,n),n}getMessageState(e){return this.messageStates.get(e)}getActiveAssistantMessageId(){let e=e=>this.activeRuns.size===0||[...this.activeRuns].some(t=>this.callMessageIds.get(t)?.has(e))||this.pendingManualMessageId===e&&!this.messageStates.get(e)?.isComplete&&!this.isDone,t=Array.from(this.activeMessageIds).reverse();for(let n of t){if(this.sealedMessageIds.has(n))continue;let t=this.messageStates.get(n);if(t&&t.role===`assistant`&&e(n))return n}for(let[t,n]of[...this.messageStates].reverse())if(!this.sealedMessageIds.has(t)&&n.role===`assistant`&&e(t))return t;return null}runOfMessage(e){for(let[t,n]of this.callMessageIds)if(n.has(e))return t}openMessageOfRun(e){let t=this.callMessageIds.get(e);if(!t)return null;for(let e of[...t].reverse())if(!this.sealedMessageIds.has(e)&&this.messageStates.get(e)?.role===`assistant`)return e;return null}unscopedAssistant(e){let t=ll(e),n=this.activeRuns.size===1?[...this.activeRuns][0]:void 0,r=t??n;if(r!==void 0){let e=this.openMessageOfRun(r);if(e)return{id:e,create:!1};if(t!==void 0||this.activeRuns.has(r))return{id:null,create:!0}}let i=this.getActiveAssistantMessageId();return i?{id:i,create:!1}:{id:null,create:!0}}rememberThinking(e,t,n){let r={messageId:e,stepId:t};this.thinkingOwners.set(t,r),n!==void 0&&n!==t&&this.thinkingOwners.set(n,r)}applyKnownSignature(e,t){if(!e)return!1;let n=this.thinkingOwners.get(e);if(!n)return!1;let r=this.getMessageState(n.messageId);if(!r)return!1;r.thinkingStepSignatures.set(n.stepId,t);let i=r.thinkingSteps.get(n.stepId)??``;return r.thinkingSteps.has(n.stepId)||(r.thinkingSteps.set(n.stepId,i),r.thinkingStepOrder.push(n.stepId)),this.messages=uu(this.messages,n.messageId,n.stepId,i,t),this.emitMessagesChange(),!0}resumeAssistantState(e,t){this.activeMessageIds.add(e),(t.isComplete||this.isDone)&&(t.isComplete=!1,this.isDone=!1)}ensureAssistantMessage(e,t=!0){if(e){let t=this.pendingManualMessageId;t&&t!==e&&this.messageStates.get(t)?.isComplete===!1&&!this.messages.some(t=>t.id===e)&&(this.renameMessage(t,e),this.pendingManualMessageId=e);let n=this.getMessageState(e);if(n)return this.resumeAssistantState(e,n),{messageId:e,state:n}}let n=t&&e===void 0?this.getActiveAssistantMessageId():null;if(n){let e=this.getMessageState(n);if(e)return this.resumeAssistantState(n,e),{messageId:n,state:e}}if(e){let t=this.messages.find(t=>t.id===e);if(t?.role===`activity`)e=void 0;else if(t){let n=this.createMessageState(e,t.role);this.activeMessageIds.add(e);let r=t.parts.length>0?t.parts[t.parts.length-1]:null;return r&&r.type===`text`&&(n.currentSegmentText=r.content,n.lastEmittedText=r.content,n.totalTextContent=r.content),{messageId:e,state:n}}}let r=e||zc(),i={id:r,role:`assistant`,parts:[],createdAt:/* @__PURE__ */ new Date};this.messages=[...this.messages,i];let a=this.createMessageState(r,`assistant`);return this.activeMessageIds.add(r),e||(this.pendingManualMessageId=r),this.events.onStreamStart?.(),this.emitMessagesChange(),{messageId:r,state:a}}mergeMessageMetadata(e,t){let n=Y({metadata:typeof t==`object`&&t?{...t}:void 0})?.runId??(this.activeRuns.size===1?[...this.activeRuns][0]:void 0);if(n!==void 0){let t=this.callMessageIds.get(n)??/* @__PURE__ */ new Set;t.add(e),this.callMessageIds.set(n,t)}else this.unassignedCallMessageIds.add(e);if(typeof t!=`object`||!t||Array.isArray(t))return;let r=this.messages.find(t=>t.id===e);if(!r)return;let i=t,a=Y(i),o=a!=null&&(`content`in a||`args`in a)?{...i,tanstack:Object.fromEntries(Object.entries(a).filter(([e])=>e!==`content`&&e!==`args`))}:i,s=Vo(r.metadata,o),c=gc(Y(i)?.createdAt),l=c!==void 0;this.messages=this.messages.map(t=>t.id===e?{...t,...s===void 0?{}:{metadata:s},...l?{createdAt:c}:{}}:t),this.emitMessagesChange()}findSubagentPart(e){for(let t of this.messages)for(let n of t.parts)if(n.type===`subagent`&&n.subagent.id===e)return{message:t,part:n}}childOwning(e){let t=n=>n.some(n=>n.parts.some(n=>n.type===`subagent`&&(n.subagent.id===e||t(n.subagent.messages))));for(let n of this.messages)for(let r of n.parts)if(r.type===`subagent`&&(r.subagent.id===e||t(r.subagent.messages)))return r.subagent.id}childOwningToolCall(e){let t=n=>n.some(n=>n.parts.some(n=>n.type===`tool-call`&&e(n)||n.type===`subagent`&&t(n.subagent.messages)));for(let e of this.messages)for(let n of e.parts)if(n.type===`subagent`&&t(n.subagent.messages))return n.subagent.id}childProcessor(t){let n=this.findSubagentPart(t);if(!n)return;let r=n.part.subagent.messages,i=this.childProcessors.get(t);if(i)return i.getMessages()!==r&&(i.messages=r),i;let a=new e({subagentRunId:t,initialMessages:r,events:{onToolCall:e=>this.events.onToolCall?.(e),onApprovalRequest:e=>this.events.onApprovalRequest?.(e),onCustomEvent:(e,t,n)=>this.events.onCustomEvent?.(e,t,n)}});return this.childProcessors.set(t,a),a}updateChild(e,t){let n=this.childProcessor(e);if(!n)return;t(n);let r=n.getMessages();this.patchSubagent(e,e=>{e.messages=r})}handleSubagentStartedEvent(e){if(e.type!==`SUBAGENT_STARTED`)return;if(this.findSubagentPart(e.subagentRunId)){this.childProcessors.delete(e.subagentRunId),this.patchSubagent(e.subagentRunId,t=>{t.status=`running`,delete t.interruptIds,delete t.error,e.metadata!==void 0&&(t.metadata=e.metadata)});return}let{messageId:t}=this.ensureAssistantMessage(),n={type:`subagent`,subagent:{id:e.subagentRunId,name:e.name,...e.description!==void 0&&{description:e.description},status:`running`,...e.parentSubagentRunId!==void 0&&{parentSubagentRunId:e.parentSubagentRunId},...e.parentToolCallId!==void 0&&{parentToolCallId:e.parentToolCallId},...e.metadata!==void 0&&{metadata:e.metadata},messages:[]}};this.messages=this.messages.map(e=>e.id===t?{...e,parts:[...e.parts,n]}:e),this.emitMessagesChange()}handleSubagentFinishedEvent(e){e.type===`SUBAGENT_FINISHED`&&(this.updateChild(e.subagentRunId,e=>e.finalizeStream()),this.patchSubagent(e.subagentRunId,t=>{t.status!==`error`&&(e.outcome?.type===`suspended`?(t.status=`suspended`,t.interruptIds=e.outcome.interruptIds??[]):t.status=`finished`)}))}handleSubagentErrorEvent(e){e.type===`SUBAGENT_ERROR`&&(this.updateChild(e.subagentRunId,e=>e.finalizeStream()),this.patchSubagent(e.subagentRunId,t=>{t.status=`error`,t.error={message:e.message,...e.code!==void 0&&{code:e.code}}}))}patchSubagent(e,t){this.messages=this.messages.map(n=>{let r=n.parts.findIndex(t=>t.type===`subagent`&&t.subagent.id===e);if(r===-1)return n;let i=n.parts[r];if(!i||i.type!==`subagent`)return n;let a={type:`subagent`,subagent:{...i.subagent}};t(a.subagent);let o=[...n.parts];return o[r]=a,{...n,parts:o}}),this.emitMessagesChange()}routeToChild(e){let t;if(e.type===`SUBAGENT_STARTED`)t=e.parentSubagentRunId;else if(e.type===`SUBAGENT_FINISHED`||e.type===`SUBAGENT_ERROR`){if(this.findSubagentPart(e.subagentRunId))return!1;t=e.subagentRunId}else t=`subagentRunId`in e&&e.subagentRunId?e.subagentRunId:`toolCallId`in e&&typeof e.toolCallId==`string`?this.childToolCalls.get(e.toolCallId):this.childContinuing(e);if(t===void 0)return!1;let n=this.childOwning(t);return n===void 0?t!==this.subagentRunId&&(console.warn(`[StreamProcessor] Dropped a chunk for unknown subagent ${t}`),!0):(this.findSubagentPart(n)?.part.subagent.status===`error`||((e.type===`TOOL_CALL_START`||e.type===`TOOL_CALL_CHUNK`)&&e.toolCallId!==void 0&&this.childToolCalls.set(e.toolCallId,n),this.updateChild(n,t=>t.processChunk(e))),!0)}renameMessage(e,t){this.messages=this.messages.map(n=>n.id===e?{...n,id:t}:n);let n=this.messageStates.get(e);n&&(n.id=t,this.messageStates.delete(e),this.messageStates.set(t,n)),this.activeMessageIds.delete(e),this.activeMessageIds.add(t);for(let[n,r]of this.toolCallToMessage)r===e&&this.toolCallToMessage.set(n,t);this.structuredMessageIds.delete(e)&&this.structuredMessageIds.add(t);let r=this.structuredOutputUpdateBatches.get(e);r&&(this.structuredOutputUpdateBatches.delete(e),this.structuredOutputUpdateBatches.set(t,r));for(let n of this.callMessageIds.values())n.delete(e)&&n.add(t);this.unassignedCallMessageIds.delete(e)&&this.unassignedCallMessageIds.add(t),this.sealedMessageIds.delete(e)&&this.sealedMessageIds.add(t);for(let[n,r]of this.thinkingOwners)r.messageId===e&&this.thinkingOwners.set(n,{messageId:t,stepId:r.stepId})}handleTextMessageStartEvent(e){let{messageId:t,role:n}=e;if(this.messages.some(e=>e.id===t&&e.role===`activity`)){console.warn(`TEXT_MESSAGE_START: Dropped text for '${t}', the id of an activity message`);return}let r=n===`user`||n===`system`?n:`assistant`,i=this.pendingManualMessageId,a=i?this.runOfMessage(i):void 0,o=this.runOfMessage(t);if(i&&(a===void 0||o===void 0||a===o)){this.pendingManualMessageId=null,i!==t&&this.renameMessage(i,t);let n=this.messageStates.get(t);n?n.hasToolCallsSinceTextStart&&(n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(t),n.currentSegmentText=``,n.lastEmittedText=``,n.hasToolCallsSinceTextStart=!1):(n=this.createMessageState(t,r),this.activeMessageIds.add(t)),this.applySenderName(t,e.name),this.mergeMessageMetadata(t,e.metadata),this.emitMessagesChange();return}if(this.messages.find(e=>e.id===t)){this.activeMessageIds.add(t);let n=this.messageStates.get(t);n?n.hasToolCallsSinceTextStart&&=(n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(t),n.currentSegmentText=``,n.lastEmittedText=``,!1):this.createMessageState(t,r),this.applySenderName(t,e.name),this.mergeMessageMetadata(t,e.metadata);return}let s={id:t,role:r,parts:[],createdAt:/* @__PURE__ */ new Date};this.messages=[...this.messages,s],this.createMessageState(t,r),this.activeMessageIds.add(t),this.applySenderName(t,e.name),this.mergeMessageMetadata(t,e.metadata),this.events.onStreamStart?.(),this.emitMessagesChange()}applySenderName(e,t){t!==void 0&&(this.messages=this.messages.map(n=>n.id===e?{...n,name:t}:n))}handleTextMessageEndEvent(e){let{messageId:t}=e;this.mergeMessageMetadata(t,e.metadata);let n=this.getMessageState(t);n&&(n.isComplete||n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(t))}handleMessagesSnapshotEvent(e){this.resetStreamState();let t=this.messages,n=new Map(t.map(e=>[e.id,e])),{top:r,groups:i}=Ks(e.messages),a=this.mergeReasoningFanOut(r.map(Nc)),o=this.reconcileSnapshotToolCalls(a,t).map(e=>{if(e.metadata!=null)return e;let t=n.get(e.id);return t?.metadata==null?e:{...e,metadata:t.metadata}});this.messages=this.mergeOmittedActivity(t,this.attachSnapshotSubagents(o,r,i,t)),this.emitMessagesChange()}mergeOmittedActivity(e,t){let n=new Set(t.map(e=>e.id)),r=e.filter(e=>e.role===`activity`&&!n.has(e.id));if(r.length===0)return t;let i=[...t];for(let t of r){let n=e.findIndex(e=>e.id===t.id);i.splice(Math.min(Math.max(n,0),i.length),0,t)}return i}attachSnapshotSubagents(t,n,r,i){let a=[],o=/* @__PURE__ */ new Map;for(let t of r){let r=new e({subagentRunId:t.id});r.processChunk({type:X.MESSAGES_SNAPSHOT,messages:t.messages,timestamp:Date.now()}),o.set(t.id,r);let{placeholder:i,...s}=t.info;a.push({hostId:n.slice(0,t.hostIndex+1).findLast(e=>e.role===`assistant`)?.id,part:{type:`subagent`,subagent:{...s,id:t.id,messages:r.getMessages()}},carried:!1})}let s=new Set(r.map(e=>e.id));for(let e of i)for(let t of e.parts){if(t.type!==`subagent`||s.has(t.subagent.id))continue;a.push({hostId:e.id,...t.subagent.parentToolCallId!==void 0&&{toolCallId:t.subagent.parentToolCallId},part:t,carried:!0});let n=this.childProcessors.get(t.subagent.id);n&&o.set(t.subagent.id,n)}this.childProcessors.clear();for(let[e,t]of o)this.childProcessors.set(e,t);let c=t;for(let e of a){let t=c.findIndex(t=>t.id===e.hostId);t===-1&&e.toolCallId!==void 0&&(t=c.findIndex(t=>t.parts.some(t=>t.type===`tool-call`&&t.id===e.toolCallId))),t===-1&&!e.carried&&(t=c.findLastIndex(e=>e.role===`assistant`)),t===-1?e.carried||(c=[...c,{id:zc(),role:`assistant`,parts:[e.part]}]):c=c.map((n,r)=>r!==t||n.parts.some(t=>t.type===`subagent`&&t.subagent.id===e.part.subagent.id)?n:{...n,parts:[...n.parts,e.part]})}return c}mergeReasoningFanOut(e){let t=[],n=[],r=e=>e.parts.filter(e=>e.type===`thinking`),i=e=>e.role===`assistant`&&e.parts.length>0&&e.parts.every(e=>e.type===`thinking`),a=e=>e.role===`assistant`&&e.parts.some(e=>e.type===`tool-result`)&&e.parts.every(e=>e.type===`tool-result`||e.type===`ui-resource`),o=()=>{t.push(...n),n=[]};for(let s of e){if(i(s)){n.push(s);continue}let e=s;s.role===`assistant`&&n.length>0&&!a(s)?(e={...s,parts:[...n.flatMap(r),...s.parts]},n=[]):o();let c=t.length-1;for(;c>=0;){let e=t[c];if(!e||!a(e))break;c--}let l=t[c];if(l?.role===`assistant`&&e.role===`assistant`&&Ys(e.id,l.id)){let n=t.slice(c).flatMap(e=>e.parts);t.splice(c,t.length-c,{...l,parts:[...n,...e.parts]})}else t.push(e)}return o(),t}reconcileSnapshotToolCalls(e,t){let n=/* @__PURE__ */ new Map;for(let e of t)for(let t of e.parts)t.type===`tool-call`&&n.set(t.id,t);let r=/* @__PURE__ */ new Set;for(let t of e)for(let e of t.parts)e.type===`tool-call`&&r.add(e.id);let i=[];for(let t of e){let e=t.parts.filter(e=>e.type===`tool-result`),a=t.role===`assistant`&&e.length===1&&t.parts.every(e=>e.type===`tool-result`||e.type===`ui-resource`)?e[0]:void 0;if(!a){i.push(t);continue}let o=i.findLast(e=>e.parts.some(e=>e.type===`tool-call`&&e.id===a.toolCallId))??i.findLast(e=>e.role===`assistant`&&(e.parts.length!==1||e.parts[0]?.type!==`tool-result`));if(!o){r.has(a.toolCallId)||console.warn(`[StreamProcessor] MESSAGES_SNAPSHOT contains a tool-result for "${a.toolCallId}" but no matching tool-call exists in the snapshot, and there is no assistant message to anchor into; addToolResult("${a.toolCallId}") will not be able to locate this call`),i.push(t);continue}let s=[...o.parts];if(!r.has(a.toolCallId)&&!s.some(e=>e.type===`tool-call`&&e.id===a.toolCallId)){let e=n.get(a.toolCallId);e?(s.push({...e}),r.add(e.id)):console.warn(`[StreamProcessor] MESSAGES_SNAPSHOT contains a tool-result for "${a.toolCallId}" but no matching tool-call exists in the snapshot or the pre-snapshot state; addToolResult("${a.toolCallId}") will not be able to locate this call`)}s.push(...t.parts),o.parts=s}return this.enrichSnapshotToolCallsFromResults(i,n)}enrichSnapshotToolCallsFromResults(e,t){let n=/* @__PURE__ */ new Map;for(let t of e)for(let e of t.parts)e.type===`tool-result`&&n.set(e.toolCallId,e);return e.map(e=>{let r=e.parts.map(e=>{if(e.type!==`tool-call`)return e;let r=t.get(e.id),i=n.get(e.id),a=e;if(r&&(r.output!==void 0||r.state===`complete`||r.state===`error`)&&(e.output===void 0||e.state===`input-complete`||e.state===`input-streaming`||e.state===`awaiting-input`)&&(a={...e,...r.output===void 0?{}:{output:r.output},state:r.state,...r.approval===void 0?{}:{approval:r.approval},...r.metadata===void 0?{}:{metadata:r.metadata}}),i&&a.output===void 0){let e;if(Array.isArray(i.content))e=i.content;else try{e=JSON.parse(i.content)}catch{e=i.content}let t=i.state===`error`?ec(e):void 0;a={...a,output:t?{error:t}:e,state:i.state===`error`?`error`:`complete`}}return a});return r.some((t,n)=>t!==e.parts[n])?{...e,parts:r}:e})}handleTextMessageContentEvent(e){if(this.messages.some(t=>t.id===e.messageId&&t.role===`activity`)){console.warn(`TEXT_MESSAGE_CONTENT: Dropped text for '${e.messageId}', the id of an activity message`);return}let{messageId:t,state:n}=this.ensureAssistantMessage(e.messageId);if(this.mergeMessageMetadata(t,e.metadata),this.structuredMessageIds.has(t)){let r=e.delta||``;r!==``&&(this.messages=su(this.messages,t,r),n.totalTextContent+=r,this.queueStructuredOutputUpdate(t,r),this.emitMessagesChange());return}let r=n.currentSegmentText;n.hasToolCallsSinceTextStart&&r.length>0&&this.isNewTextSegment(e,r)&&(r!==n.lastEmittedText&&this.emitTextUpdateForMessage(t),n.currentSegmentText=``,n.lastEmittedText=``,n.hasToolCallsSinceTextStart=!1),n.hasToolCallsSinceTextStart=!1;let i=n.currentSegmentText,a=e.delta||``,o=a===``?i:i+a,s=o.slice(i.length);n.currentSegmentText=o,n.totalTextContent+=s;let c=e.delta||``;this.chunkStrategy.shouldEmit(c,n.currentSegmentText)&&n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(t)}handleToolCallStartEvent(e){let t=this.pendingManualMessageId,n=e.parentMessageId;if(t&&n&&n!==t){let e=this.messages.find(e=>e.id===n),r=this.messages.find(e=>e.id===t),i=this.runOfMessage(t),a=e?this.runOfMessage(e.id):void 0;e?(i===void 0||a===void 0||i===a)&&e.role===`assistant`&&r&&(this.pendingManualMessageId=null,this.messages=this.messages.filter(e=>e.id!==t).map(e=>e.id===n?{...e,parts:[...e.parts,...r.parts]}:e),this.renameMessage(t,n)):(this.pendingManualMessageId=null,this.renameMessage(t,n))}let r=e.parentMessageId??this.getActiveAssistantMessageId(),{messageId:i,state:a}=this.ensureAssistantMessage(r??void 0,e.parentMessageId===void 0),o=Y(e);this.mergeMessageMetadata(i,o===void 0?void 0:{tanstack:o}),a.hasToolCallsSinceTextStart=!0;let s=e.toolCallId;if(!a.toolCalls.get(s)){let t=`awaiting-input`,n=e.toolCallName,r=e.metadata,o={id:e.toolCallId,name:n,arguments:``,state:t,parsedArguments:void 0,index:a.toolCalls.size,...r!==void 0&&{metadata:r}};a.toolCalls.set(s,o),a.toolCallOrder.push(s),this.runToolCallIds.push(s),this.toolCallToMessage.set(s,i),this.messages=nu(this.messages,i,{id:e.toolCallId,name:n,arguments:``,state:t,...r!==void 0&&{metadata:r}}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(i,e.toolCallId,t,``)}}handleToolCallArgsEvent(e){let t=e.toolCallId,n=this.toolCallToMessage.get(t);if(!n)return;let r=this.getMessageState(n);if(!r)return;let i=r.toolCalls.get(t);if(!i)return;let a=i.state===`awaiting-input`;e.metadata!==void 0&&(i.metadata=Vo(i.metadata,e.metadata)),i.arguments+=e.delta||``,a&&e.delta&&(i.state=`input-streaming`),i.parsedArguments=this.jsonParser.parse(i.arguments),this.messages=nu(this.messages,n,{id:i.id,name:i.name,arguments:i.arguments,state:i.state,...i.metadata!==void 0&&{metadata:i.metadata}}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(n,i.id,i.state,i.arguments)}handleToolCallEndEvent(e){let t=this.toolCallToMessage.get(e.toolCallId);if(!t)return;let n=this.getMessageState(t);if(!n)return;let r=n.toolCalls.get(e.toolCallId);if(r&&r.state!==`input-complete`){r.arguments=Jo(r.arguments,e).args;let i=n.toolCallOrder.indexOf(e.toolCallId);this.completeToolCall(t,i,r)}}handleToolCallResultEvent(e){let t=this.toolCallToMessage.get(e.toolCallId)??this.messages.find(t=>t.parts.some(t=>t.type===`tool-call`&&t.id===e.toolCallId))?.id;if(!t)return;let n=e,r=Y(e)?.toolResultOutcome,i=Zs(r)?r:void 0,a=n.state===`output-error`||Y(e)?.state===`output-error`||i!==void 0,o;try{o=typeof e.content==`string`?JSON.parse(e.content):e.content}catch{o=e.content}this.messages=au(this.messages,e.toolCallId,o,a?`error`:void 0);let s=a?`error`:`complete`;this.messages=ru(this.messages,t,e.toolCallId,$s(o)?o:Lc(e.content),s,s===`error`?ec(o):void 0,i),this.emitMessagesChange()}handleRunStartedEvent(e){this.activeRuns.size===0&&(this.runToolCallIds=[],this.toolCallsSentToClient.clear(),this.streamEndEmitted=!1),this.activeRuns.add(e.runId)}handleRunFinishedEvent(e){let t=e,n=Y(e),r=e.model??n?.model,i=e.responseId??n?.responseId,a=this.callMessageIds.get(e.runId)??(this.activeRuns.has(e.runId)?/* @__PURE__ */ new Set:new Set(this.unassignedCallMessageIds));for(let t of a)this.mergeMessageMetadata(t,Ho(e,{...r===void 0?{}:{model:r},...i===void 0?{}:{responseId:i}}).metadata);this.pendingManualMessageId&&a.has(this.pendingManualMessageId)&&(this.pendingManualMessageId=null),this.callMessageIds.delete(e.runId);for(let e of a)this.unassignedCallMessageIds.delete(e);if(this.finishReason=t.finishReason===void 0?Y(e)?.finishReason??null:t.finishReason,this.activeRuns.delete(e.runId),e.outcome?.type===`interrupt`&&this.handleInterrupts(e.outcome.interrupts),this.activeRuns.size===0){if(this.completeAllToolCalls(),this.finishReason===`tool_calls`&&e.outcome?.type!==`interrupt`){for(let e of a)this.sealedMessageIds.add(e);return}(!e.outcome||e.outcome.type===`success`)&&this.handlePendingToolCalls(e.outcome?.pendingToolCallIds),this.isDone=!0,this.finalizeStream()}}handlePendingToolCalls(e){let t=e?.length?e.filter(e=>this.runToolCallIds.includes(e)):this.runToolCallIds,n=this.messages.flatMap(e=>e.parts??[]);for(let e of t){if(this.toolCallsSentToClient.has(e))continue;let t=n.find(t=>t.type===`tool-call`&&t.id===e);if(!t||Js(t)||t.output!==void 0||n.some(t=>t.type===`tool-result`&&t.toolCallId===e)||this.isToolCallPartTerminal(e)||this.isToolCallPartAwaitingUserAction(e)||this.finishReason===`length`)continue;let r=t.input??qo(t.arguments);r===void 0?console.warn(`[StreamProcessor] Did not run tool call ${e}: the arguments of ${t.name} are not complete JSON`):(this.toolCallsSentToClient.add(e),this.events.onToolCall?.({toolCallId:e,toolName:t.name,input:r}))}}handleInterrupts(e,t=!0){let n=mu(e);for(let r of e){let e=r.metadata&&typeof r.metadata==`object`?r.metadata:{},i=typeof e.kind==`string`?e.kind:void 0,a=r.toolCallId;if(!a)continue;let o=r.subagentRunId===void 0?this.childOwningToolCall(e=>e.id===a):this.childOwning(r.subagentRunId);o!==void 0&&this.updateChild(o,e=>e.handleInterrupts([r],!1));let s=typeof e.toolName==`string`?e.toolName:this.findToolCallName(a),c=Object.hasOwn(e,`input`)?e.input:{};if(i===`approval`){if(o!==void 0){t&&this.events.onApprovalRequest?.({toolCallId:a,toolName:s,input:c,approvalId:r.id});continue}let e=this.getActiveAssistantMessageId()??this.toolCallToMessage.get(a)??this.messages.find(e=>e.role===`assistant`&&e.parts.some(e=>e.type===`tool-call`&&e.id===a))?.id;if(e&&(this.messages=iu(this.messages,e,a,r.id),this.emitMessagesChange()),!t)continue;this.events.onApprovalRequest?.({toolCallId:a,toolName:s,input:c,approvalId:r.id})}else if(i===`client_tool`){if(n||!t)continue;this.toolCallsSentToClient.add(a),this.events.onToolCall?.({toolCallId:a,toolName:s,input:c})}}}findToolCallName(e){for(let t of this.messageStates.values()){let n=t.toolCalls.get(e);if(n)return n.name}return``}handleRunErrorEvent(e){this.hasError=!0;let t=ll(e)??(this.activeRuns.size===1?[...this.activeRuns][0]:void 0),n=t===void 0?this.unassignedCallMessageIds:this.callMessageIds.get(t)??this.unassignedCallMessageIds;t?this.activeRuns.delete(t):this.activeRuns.clear();let r=t!==void 0&&this.callMessageIds.has(t)&&n.size===0?void 0:this.ensureAssistantMessage([...n].at(-1)??zc(),!1).messageId,i=new Set(n);r!==void 0&&i.add(r);for(let t of i)this.mergeMessageMetadata(t,Ho(e,{stopReason:Y(e)?.stopReason??`error`}).metadata);this.pendingManualMessageId&&i.has(this.pendingManualMessageId)&&(this.pendingManualMessageId=null),t!==void 0&&this.callMessageIds.delete(t);for(let e of i)this.unassignedCallMessageIds.delete(e);let a=e.message||`An error occurred`;e.message||console.error(`[StreamProcessor] RUN_ERROR with no message; original chunk:`,e),r!==void 0&&this.structuredMessageIds.has(r)&&(this.flushStructuredOutputUpdate(r),this.messages=lu(this.messages,r,a),this.structuredMessageIds.delete(r),this.emitStructuredOutputChange(r,`error`),this.emitMessagesChange()),this.events.onError?.(hl(e))}handleActivitySnapshotEvent(e){this.messages=$l(this.messages,e),this.emitMessagesChange()}handleActivityDeltaEvent(e){this.messages=eu(this.messages,e),this.emitMessagesChange()}handleReasoningMessageContentEvent(e){let t=this.unscopedAssistant(e),{messageId:n,state:r}=this.ensureAssistantMessage(t.id??void 0,!t.create);this.mergeMessageMetadata(n,e.metadata);let i=e.delta||``,a=r.currentThinkingStepId??e.messageId;r.thinkingSteps.has(a)||(r.thinkingSteps.set(a,``),r.thinkingStepOrder.push(a),r.currentThinkingStepId=a),this.rememberThinking(n,a,e.messageId);let o=(r.thinkingSteps.get(a)??``)+i;r.thinkingSteps.set(a,o),this.messages=uu(this.messages,n,a,o,r.thinkingStepSignatures.get(a)),this.emitMessagesChange(),this.events.onThinkingUpdate?.(n,a,o)}handleReasoningEncryptedValueEvent(e){let t=e.encryptedValue;if(typeof t!=`string`||t===``)return;if(e.subtype===`tool-call`){this.attachToolCallSignature(e.entityId,t);return}if(this.applyKnownSignature(e.entityId,t))return;let n=this.unscopedAssistant(e),{messageId:r,state:i}=this.ensureAssistantMessage(n.id??void 0,!n.create),a=i.currentThinkingStepId??e.entityId;this.rememberThinking(r,a,e.entityId),this.mergeMessageMetadata(r,e.metadata),i.thinkingStepSignatures.set(a,t);let o=i.thinkingSteps.get(a)??``;i.thinkingSteps.has(a)||(i.thinkingSteps.set(a,o),i.thinkingStepOrder.push(a)),this.messages=uu(this.messages,r,a,o,t),this.emitMessagesChange()}attachToolCallSignature(e,t){this.messages=this.messages.map(n=>{let r=!1,i=n.parts.map(n=>n.type!==`tool-call`||n.id!==e?n:(r=!0,{...n,metadata:{...n.metadata!=null&&typeof n.metadata==`object`?n.metadata:{},thoughtSignature:t}}));return r?{...n,parts:i}:n});for(let n of this.messageStates.values()){let r=n.toolCalls.get(e);r&&(r.metadata={...r.metadata??{},thoughtSignature:t})}this.emitMessagesChange()}handleCustomEvent(e){let t=this.getActiveAssistantMessageId();if(e.name===`structured-output.start`&&e.value){let n=e.value,{messageId:r}=this.ensureAssistantMessage(n.messageId&&this.getMessageState(n.messageId)?n.messageId:t??n.messageId);r&&(this.structuredMessageIds.add(r),this.structuredOutputUpdateBatches.delete(r),this.events.onStructuredOutputChange?.({phase:`start`,messageId:r,status:`streaming`,raw:``}))}else{if(e.name===`structured-output.complete`&&e.value){let n=e.value,{messageId:r}=this.ensureAssistantMessage(n.messageId&&this.getMessageState(n.messageId)?n.messageId:t??n.messageId);r&&(this.flushStructuredOutputUpdate(r),this.messages=cu(this.messages,r,n.object,n.raw??``,n.reasoning),this.structuredMessageIds.delete(r),this.emitStructuredOutputChange(r,`complete`),this.emitMessagesChange())}if(e.name===`ui-resource`&&e.value){let n=e.value,r=this.toolCallToMessage.get(n.toolCallId)??t;if(r){let e={type:`ui-resource`,resource:n.resource,toolCallId:n.toolCallId,toolName:n.toolName,...n.serverId!==void 0&&{serverId:n.serverId},...n.meta!==void 0&&{meta:n.meta}};this.messages=this.messages.map(t=>t.id===r?{...t,parts:[...t.parts,e]}:t),this.emitMessagesChange()}else console.warn(`[mcp-apps] dropped ui-resource: no target message for toolCallId "${n.toolCallId}" (toolName "${n.toolName}")`)}else if(this.events.onCustomEvent){let t=e.value&&typeof e.value==`object`?e.value.toolCallId:void 0;this.events.onCustomEvent(e.name,e.value,{toolCallId:t})}}}isNewTextSegment(e,t){return!0}completeAllToolCalls(){for(let e of this.activeMessageIds)this.completeAllToolCallsForMessage(e)}completeAllToolCallsForMessage(e){let t=this.getMessageState(e);t&&t.toolCalls.forEach((n,r)=>{if(n.state!==`input-complete`){let i=t.toolCallOrder.indexOf(r);this.completeToolCall(e,i,n)}})}completeToolCall(e,t,n){n.state=`input-complete`;let r=!1;try{n.parsedArguments=JSON.parse(n.arguments),r=!0}catch{n.parsedArguments=void 0}this.isToolCallPartTerminal(n.id)||this.isToolCallPartAwaitingUserAction(n.id)||(this.messages=nu(this.messages,e,{id:n.id,name:n.name,arguments:n.arguments,state:`input-complete`,...r&&{input:n.parsedArguments},...n.metadata!==void 0&&{metadata:n.metadata}}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(e,n.id,`input-complete`,n.arguments))}isToolCallPartAwaitingUserAction(e){return this.messages.some(t=>t.parts?.some(t=>t.type===`tool-call`&&t.id===e&&(t.state===`approval-requested`||t.state===`approval-responded`)))}isToolCallPartTerminal(e){return this.messages.some(t=>t.parts?.some(t=>t.type===`tool-call`&&t.id===e&&(t.state===`error`||t.state===`complete`)))}emitTextUpdateForMessage(e){let t=this.getMessageState(e);t&&(t.lastEmittedText=t.currentSegmentText,this.messages=tu(this.messages,e,t.currentSegmentText),this.emitMessagesChange(),this.events.onTextUpdate?.(e,t.currentSegmentText))}queueStructuredOutputUpdate(e,t){let n=this.structuredOutputUpdateBatches.get(e),r={delta:`${n?.delta??``}${t}`,chunkCount:(n?.chunkCount??0)+1};this.structuredOutputUpdateBatches.set(e,r),r.chunkCount>=du&&this.flushStructuredOutputUpdate(e)}flushStructuredOutputUpdate(e){let t=this.structuredOutputUpdateBatches.get(e);t&&t.chunkCount!==0&&(this.structuredOutputUpdateBatches.delete(e),this.emitStructuredOutputChange(e,`update`,t.delta))}emitStructuredOutputChange(e,t,n){let r=this.messages.find(t=>t.id===e)?.parts.find(e=>e.type===`structured-output`);r&&this.events.onStructuredOutputChange?.({phase:t,messageId:e,status:r.status,raw:r.raw,...r.partial===void 0?{}:{partial:r.partial},...r.data===void 0?{}:{data:r.data},...r.reasoning===void 0?{}:{reasoning:r.reasoning},...r.errorMessage===void 0?{}:{errorMessage:r.errorMessage},...n===void 0?{}:{delta:n}})}emitMessagesChange(){this.events.onMessagesChange?.([...this.messages])}finalizeStream(){this.isDone=!0;for(let e of this.closeChunk())this.dispatchChunk(e);this.closeChildChunkLanes();let e;for(let t of this.activeMessageIds){let n=this.getMessageState(t);if(!n)continue;this.completeAllToolCallsForMessage(t),n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(t),n.isComplete=!0;let r=this.messages.find(e=>e.id===t);r&&r.role===`assistant`&&(e=r)}for(let e of this.structuredMessageIds)this.flushStructuredOutputUpdate(e),this.messages=lu(this.messages,e,`Stream ended without structured-output.complete`),this.emitStructuredOutputChange(e,`error`);this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.activeMessageIds.clear(),e&&!this.hasError&&this.isWhitespaceOnlyMessage(e)?(this.messages=this.messages.filter(t=>t.id!==e.id),this.emitMessagesChange()):e&&!this.streamEndEmitted&&(this.streamEndEmitted=!0,this.events.onStreamEnd?.(e))}getCompletedToolCalls(){let e=[];for(let t of this.messageStates.values())for(let n of t.toolCalls.values())n.state===`input-complete`&&e.push({id:n.id,type:`function`,function:{name:n.name,arguments:n.arguments},...n.metadata!==void 0&&{metadata:n.metadata}});return e}getResult(){let e=this.getCompletedToolCalls(),t=``,n=``;for(let e of this.messageStates.values()){t+=e.totalTextContent;for(let t of e.thinkingStepOrder)n+=e.thinkingSteps.get(t)??``}return{content:t,thinking:n||void 0,toolCalls:e.length>0?e:void 0,finishReason:this.finishReason}}getState(){let e=``,t=``,n=/* @__PURE__ */ new Map,r=[];for(let i of this.messageStates.values()){e+=i.totalTextContent;for(let e of i.thinkingStepOrder)t+=i.thinkingSteps.get(e)??``;for(let[e,t]of i.toolCalls)n.set(e,t);r.push(...i.toolCallOrder)}return{content:e,thinking:t,toolCalls:n,toolCallOrder:r,finishReason:this.finishReason,done:this.isDone}}startRecording(){this.recordingEnabled=!0,this.recordingStartTime=Date.now(),this.recording={version:`1.0`,timestamp:this.recordingStartTime,chunks:[]}}getRecording(){return this.recording}resetStreamState(){this.messageStates.clear(),this.callMessageIds.clear(),this.unassignedCallMessageIds.clear(),this.activeMessageIds.clear(),this.activeRuns.clear(),this.toolCallToMessage.clear(),this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.pendingManualMessageId=null,this.sealedMessageIds.clear(),this.thinkingOwners.clear(),this.openChunk=null,this.finishReason=null,this.hasError=!1,this.isDone=!1,this.streamEndEmitted=!1,this.chunkStrategy.reset?.()}reset(){this.resetStreamState(),this.messages=[],this.childProcessors.clear(),this.childToolCalls.clear()}isWhitespaceOnlyMessage(e){return e.parts.length!==0&&e.parts.every(e=>e.type===`text`&&e.content.trim()===``)}static async replay(t,n){return new e(n).process(gu(t))}};function gu(e){return{async*[Symbol.asyncIterator](){for(let{chunk:t}of e.chunks)yield t}}}var _u=class extends Error{provider;constructor(e){super(`Missing ${e} API key`),this.name=`ByokMissingError`,this.provider=e}},vu=class extends Error{provider;reason;constructor(e,t){super(t===`locked`?`${e} key is locked`:`Missing ${e} API key`),this.name=`ByokBlockedError`,this.provider=e,this.reason=t}},yu=class extends Error{constructor(){super(`BYOK is enabled but no provider slug was resolved. Pass byokProvider or forwardedProps.provider.`),this.name=`ByokUnresolvedProviderError`}},bu=/^[a-z][a-z0-9-]{0,63}$/;function xu(e){return typeof e==`string`&&bu.test(e)}function Su(e){if(typeof e!=`object`||!e||!(`error`in e))return!1;let t=e.error;return!(typeof t!=`object`||!t||!(`type`in t)||t.type!==`byok_missing`||!(`provider`in t)||typeof t.provider!=`string`||!xu(t.provider)||!(`message`in t)||typeof t.message!=`string`)}var Cu=/* @__PURE__ */ new WeakMap;function wu(e){return Cu.get(e)??ll(e)}var Tu=class extends Error{constructor(){super(`Stream ended with unterminated trailing data — connection was likely cut short.`),this.name=`StreamTruncatedError`}},Eu=class extends Error{constructor(e){super(`Stream response body read failed`,{cause:e}),this.name=`StreamReadError`}},Du=class extends Error{constructor(){super(`Durable run ended without a terminal event and could not resume — the run did not complete.`),this.name=`DurableStreamIncompleteError`}},Ou=class extends Error{constructor(e,t){super(t===void 0?`Durable run exceeded its reconnect ceiling of ${e} attempts — giving up.`:`Durable run did not reconnect within its budget of ${t} ms (${e} attempts) — giving up.`),this.name=`StreamReconnectLimitError`}},ku=/* @__PURE__ */ new Set([408,429,502,503,504]),Au=class extends Error{status;retryAfterMs;constructor(e,t,n){super(e),this.status=t,this.name=`StreamHttpError`,this.retryAfterMs=ju(n)}};function ju(e){if(!e)return;let t=Number(e);if(Number.isFinite(t))return t>=0?t*1e3:void 0;let n=Date.parse(e);return Number.isNaN(n)?void 0:Math.max(0,n-Date.now())}function Mu(e){return e instanceof Au&&ku.has(e.status)}function Nu(e){let t=e?.budgetMs,n=e?.maxAttempts??(t===void 0?5:1/0),r=e?.initialDelayMs??e?.delayMs??250,i=e?.maxDelayMs??Math.max(5e3,r);if(e?.maxAttempts!==void 0&&(!Number.isInteger(n)||n<0))throw Error(`Invalid reconnect.maxAttempts: ${n}. Must be a non-negative integer.`);for(let[e,t]of[[`initialDelayMs`,r],[`maxDelayMs`,i]])if(!Number.isFinite(t)||t<0)throw Error(`Invalid reconnect.${e}: ${t}. Must be a non-negative finite number.`);if(t!==void 0&&(!Number.isFinite(t)||t<=0))throw Error(`Invalid reconnect.budgetMs: ${t}. Must be a positive finite number.`);return{maxAttempts:n,initialDelayMs:r,maxDelayMs:i,budgetMs:t}}function Pu(e){let t=Nu(e),n=/* @__PURE__ */ new Set,r,i=0,a;return{get lastEventId(){return r},note(e){return e===void 0?`new`:e===``?(r=void 0,n.clear(),`reset`):n.has(e)?`duplicate`:(n.add(e),r=e,`new`)},async waitBeforeReconnect(e,n,r){if(e)i=0,a=void 0;else if(i+=1,a??=Date.now(),i>t.maxAttempts)throw new Ou(t.maxAttempts);let o=t.initialDelayMs===0?0:Math.min(t.maxDelayMs,t.initialDelayMs*2**Math.max(0,i-1)),s=r===void 0?o*(.5+Math.random()/2):Math.min(r,t.maxDelayMs);if(t.budgetMs!==void 0&&a!==void 0&&Date.now()-a+s>t.budgetMs)throw new Ou(i-1,t.budgetMs);await Fu(s,n)}}}function Fu(e,t){return e<=0||t?.aborted?Promise.resolve():new Promise(n=>{let r=()=>{clearTimeout(i),n()},i=setTimeout(()=>{t?.removeEventListener(`abort`,r),n()},e);t?.addEventListener(`abort`,r,{once:!0})})}function Iu(e){if(!e)return{};if(e instanceof Headers){let t={};return e.forEach((e,n)=>{t[n]=e}),t}return e}var Lu=`X-Run-Id`;function Ru(e){return{[Lu]:e}}function zu(e,t){let n=e.indexOf(`#`),r=n===-1?``:e.slice(n),i=n===-1?e:e.slice(0,n),a=i.indexOf(`?`),o=a===-1?i:i.slice(0,a),s=new URLSearchParams(a===-1?``:i.slice(a+1));for(let[e,n]of Object.entries(t))s.set(e,n);let c=s.toString();return`${o}${c.length===0?``:`?${c}`}${r}`}async function*Bu(e,t){try{let n=jo(),r=``;for(;!t?.aborted;){let i;try{i=await e.read()}catch(e){if(t?.aborted)return;throw new Eu(e)}let{done:a,value:o}=i;if(a)break;r+=n.decode(o,{stream:!0});let s=r.split(`
|
|
142
|
-
`);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 Tu}finally{try{e.cancel().catch(()=>{})}catch{}e.releaseLock()}}async function*Vu(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=Mo(n),r=ol(JSON.parse(e)),i=t;t=void 0,yield{chunk:r,...i===void 0?{}:{id:i}}}}async function Hu(e){if(!e.ok){if(e.status===401){let t=await e.clone().json().catch(()=>null);if(Su(t))throw new _u(t.error.provider)}throw new Au(`HTTP error! status: ${e.status} ${e.statusText}`,e.status,e.headers.get(`retry-after`))}}function Uu(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 Wu(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 Gu(e,t,n,r,i,a){let o=await e(zu(t,Uu(i,a)),{method:`GET`,headers:{Accept:`application/json`,...n},credentials:r});await Hu(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)?Fo(s.messages):[],activeRun:c,interrupts:l,page:Wu(s.page)}}async function Ku(e,t,n,r,i){let a=await e(zu(t,{threadId:i}),{method:`GET`,headers:{Accept:`application/json`,...n},credentials:r});await Hu(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*qu(e,t){await Hu(e),yield*Vu(Bu(Ao(e),t))}async function*Ju(e,t){for await(let{chunk:n}of qu(e,t))yield n}function Yu(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 Eu(e)}yield*r(o,a)}}async function*Xu(e,t,n){let r=Pu(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 Tu||e instanceof Eu||Mu(e))&&r.lastEventId!==void 0){await r.waitBeforeReconnect(a,t,Mu(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 Du}return}}function Zu(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&&Cu.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(Ho({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 Qu(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=Hc(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 $u(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`,...Iu(s.headers),...Iu(a.headers),...Ru(a.runId)},l=Qu(n,r,a,s),u=s.fetchClient??fetch,d=i||s.signal;yield*Xu(Yu(u,o,{method:`POST`,headers:c,body:JSON.stringify(l),credentials:s.credentials||`same-origin`},qu),d,s.reconnect)},async*joinRun(n,r){let i=typeof e==`function`?e():e,a=typeof t==`function`?await t():t,o=zu(i,{offset:`-1`,runId:n}),s={...Iu(a.headers)},c=a.fetchClient??fetch,l=r||a.signal;yield*Xu(Yu(c,o,{method:`GET`,headers:s,credentials:a.credentials||`same-origin`},qu),l,a.reconnect)},async hydrate(n,r){let i=typeof e==`function`?e():e,a=typeof t==`function`?await t():t;return Gu(a.fetchClient??fetch,i,Iu(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 Ku(i.fetchClient??fetch,r,Iu(i.headers),i.credentials||`same-origin`,n)}}}function ed(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*Ju(a,r):yield*td(a,r)}}}async function*td(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 nd(e){return e.resumable}function rd(e,t){let n=Rs(e.descriptor);return n?{...t,metadata:Ls(n)}:t}function id(e){return`cancel`in e&&`clearResolution`in e}var ad=/* @__PURE__ */ new Set([`invalid-payload`,`invalid-edited-args`,`invalid-tool-output`,`invalid-response-schema`,`unknown-interrupt`,`expired`,`stale`,`conflict`]),od=/* @__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 sd(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function cd(e){return js(e)}function ld(e){if(!sd(e.metadata))return!1;let t=e.metadata[Es];return!sd(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 ud(e){if(!sd(e.metadata))return!1;let t=e.metadata[Es];return!sd(t)||t.kind!==`generic`?!1:`definitionId`in t||`key`in t||`batchIndex`in t||`payloadSchemaHash`in t}function dd(e){return e.metadata?.[`tanstack:interruptPayload`]}function fd(e){if(e.responseSchema!==void 0)try{return rs(ns(e.responseSchema))}catch{return}}function pd(e){if(e!==void 0)try{return Ps(e)}catch{return}}function md(e){return e!==null&&(typeof e==`object`||typeof e==`function`)&&`then`in e&&typeof e.then==`function`}function hd(e,t,n){if(e===void 0)return{valid:!0,payload:t};if(ls(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 md(r)?Promise.resolve(r).then(i):i(r)}return{valid:!0,payload:t}}function gd(e){for(let t of ad)if(t===e)return!0;return!1}function _d(e){for(let t of od)if(t===e)return!0;return!1}function vd(e){if(!sd(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`?gd(n)&&typeof e.interruptId==`string`&&(e.source===`client`||e.source===`server`):t===`batch`&&_d(n)&&Array.isArray(e.interruptIds)&&e.interruptIds.every(e=>typeof e==`string`)&&(e.source===`client`||e.source===`server`||e.source===`transport`)}function yd(e){return vd(e)?[e]:!sd(e)||!Array.isArray(e.errors)?[]:e.errors.every(vd)?e.errors:[]}function bd(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 xd(e,t){return e.threadId===t.threadId&&e.interruptedRunId===t.interruptedRunId&&e.generation===t.generation&&bd(e.interruptIds,t.interruptIds)}function Sd(e,t,n){let r=n.filter(e=>e.source!==`transport`),i=e=>t.includes(e)&&r.some(t=>xd(e,t)),a=e.filter(e=>!i(e)),o=t.filter(e=>!r.some(t=>xd(e,t)));return Object.freeze({rootErrors:Object.freeze([...a,...n]),submissionRootErrors:Object.freeze([...o,...r])})}function Cd(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):bd(e.interruptIds,n)}function wd(e,t,n){let r=fd(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 Td(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 Ed=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=cd(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)nd(e)&&(e.validationGeneration++,e.resolution=Object.freeze(rd(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(Ho(rd(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=cd(r);if(i===void 0)return ld(r)?{descriptor:r,binding:wd(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&&fd(r)===i.responseSchemaHash,o=i.interruptId===r.id&&i.interruptedRunId===t.interruptedRunId&&i.generation===t.generation&&i.responseSchemaHash===(fd(r)??i.responseSchemaHash);if(ud(r)&&(!o||i.kind!==`generic`||i.definitionId===void 0||i.key===void 0||i.batchIndex===void 0))return{descriptor:r,binding:wd(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=ws(e.approvalSchema,e.inputSchema);if(Ts(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(Ts(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&&pd(e.responseSchema)===i.responseSchemaHash&&(e.payloadSchema===void 0?i.payloadSchemaHash===void 0:i.payloadSchemaHash===pd(e.payloadSchema))){let t=dd(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`||fd(r)===void 0||i.responseSchemaHash===fd(r));return{descriptor:r,binding:wd(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=Td(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=sd(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);md(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(rd(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=>nd(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=as(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(rd(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=hd(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 md(n)?Promise.resolve(n).then(r):r(n)}if(e.kind===`client-tool-execution`){let n=hd(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 md(n)?Promise.resolve(n).then(r):r(n)}return this.validateApprovalCandidate(e,t)}validateApprovalCandidate(e,t){if(!sd(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=hd(e.tool?.inputSchema,r,`invalid-edited-args`);return md(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=hd(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 md(o)?Promise.resolve(o).then(s):s(o)}approvalBranchSchema(e,t){let n=e?.approvalSchema;return!sd(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=>nd(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(id),i;try{for(let t of r){let n=e(t);if(n!==void 0){i={code:md(n)?`async-resolver`:`inactive-transaction`,message:md(n)?`Interrupt transaction resolvers must be synchronous.`:`Interrupt transaction resolvers must return literal undefined.`};break}}i===void 0&&this.items.some(e=>nd(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)nd(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=yd(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)nd(e)&&(e.status=`error`);return}let r=n.filter(e=>Cd(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=>nd(t)&&t.descriptor.id===e.interruptId);t&&(t.status=`error`,t.error=Z(e))}else o.push(Z(e));let s=Sd(this.rootErrors,this.submissionRootErrors,o);this.rootErrors=s.rootErrors,this.submissionRootErrors=s.submissionRootErrors;for(let e of this.items)nd(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(nd).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})}},Dd=/* @__PURE__ */ new WeakMap;function Od(e){let t=Object.entries(e.keys()).filter(e=>!!e[1]).map(e=>e[0]).filter(xu);if(t.length===1)return t[0];let n=Dd.get(e)??[];if(n.length===1)return n[0]}function kd(e,...t){let n=e?.();if(xu(n))return n;for(let e of t)if(xu(e))return e}async function Ad(e,t){if(!t)throw new yu;return await e.prepare(t),e.headers(t)}var jd=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})}},Md=class extends jd{emitEvent(){}},Nd=class{events;constructor(e){this.events=new Md(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){}},Pd=e=>new Nd(e);function Fd(e){return`toolCallId`in e&&typeof e.toolCallId==`string`?e.toolCallId:void 0}function Id(e){return`messageId`in e&&typeof e.messageId==`string`?e.messageId:void 0}function Ld(e){return`parentMessageId`in e&&typeof e.parentMessageId==`string`?e.parentMessageId:void 0}var Rd=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=wu(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=Fd(e);if(n&&this.clearedToolCallIds.has(n))return!0;let r=Ld(e);if(r&&this.clearedMessageIds.has(r))return n&&this.clearedToolCallIds.add(n),!0;let i=Id(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=Id(e);t&&this.clearedMessageIds.add(t);let n=Fd(e);n&&this.clearedToolCallIds.add(n)}isRunlessChunkFromIgnoredRun(e){return wu(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 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{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=wu(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))}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=Bd(e);t&&this.clearedMessageIds.add(t);let n=zd(e);n&&this.clearedToolCallIds.add(n)}isRunlessChunkFromIgnoredRun(e){return wu(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`}},Ud=8;function Wd(){let{scheduler:e}=globalThis;return e?.yield?e.yield():new Promise(e=>setTimeout(e,0))}function Gd(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 Kd(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 ed(n);throw Error("ChatClient: either `connection` or `fetcher` is required.")}function qd(e){return`connect`in e}function Jd(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 Yd(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 Xd(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(`
|
|
143
|
-
`),...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=Vo(i,t.content.metadata));return{content:{content:r,...i===void 0?{}:{metadata:i}},...t===void 0?{}:{body:t}}}function Zd(e){if(typeof e==`object`&&e&&!Array.isArray(e)&&`approved`in e&&typeof e.approved==`boolean`)return e.approved}function Qd(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 $d=2e3,ef=/* @__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 tf(e){return e.type===`REASONING_ENCRYPTED_VALUE`?e.subtype===`message`&&typeof e.encryptedValue==`string`&&e.encryptedValue.length>0:ef.has(e.type)}function nf(e){return e.map(e=>({...e,parts:e.parts.map(e=>Object.isFrozen(e)?e.type===`subagent`?{...e,subagent:{...e.subagent,messages:nf(e.subagent.messages)}}:{...e}:e)}))}function rf(e){let t=[];for(let n of e)for(let e of n.parts)e.type===`subagent`&&(t.push(e),t.push(...rf(e.subagent.messages)));return t}function af(e){if(`subagentRunId`in e&&typeof e.subagentRunId==`string`)return e.subagentRunId}var of=64;function sf(e){if(Array.isArray(e))return e.map(sf);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]=sf(r));return t}var cf=class{processor;subagentHandles=/* @__PURE__ */ new Map;stoppedSubagentIds=/* @__PURE__ */ new Set;connection;threadId;persistor;clearedStreamTracker=new Hd;snapshotAtom=_o({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(Gd(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 Rd(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=Yd(e.queue);let n=Kd(e);if(this.connectionDrainsOnSend=qd(n),this.connection=Zu(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??Pd)(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 Ed({...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&&nf(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 hu({...e.streamProcessor?.chunkStrategy?{chunkStrategy:e.streamProcessor.chunkStrategy}:{},...a?{initialMessages:a}:{},events:{onMessagesChange:e=>{this.syncSubagentHandles(),this.persistor?.notifyMessagesChanged(e),To(this.snapshotAtom,{messages:wo(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=Qd(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=Fo(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 _u&&this.byok?.request(t.provider,`missing`),t instanceof vu&&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=wu(e)??this.clearedStreamTracker.takeRunlessRunId();t&&(this.activeRunIds.delete(t),this.setSessionGenerating(this.activeRunIds.size>0),wu(e)||this.resolveProcessing())}updateRunLifecycle(e,t){if(e.type===`RUN_STARTED`){let t=wu(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=wu(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`&&Jd(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=wu(e),n=`threadId`in e&&typeof e.threadId==`string`?e.threadId:this.activeResumeThreadId;if(t&&!Jd(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<of;){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&&(To(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=Zd(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=>So(e))):e.content.content;return Object.freeze({...e,content:Object.freeze({...e.content,content:t})})}))}readSnapshot(e){return Object.freeze({...this.snapshotAtom.get(),messages:wo(this.frozenMessages,this.processor.getMessages()),queue:this.freezeSnapshotQueue(this.getQueue()),isHydrating:e,interruptState:this.interruptManager.getState()})}subscribeSnapshot=e=>Do(this.snapshotAtom,e);getSnapshot=()=>this.snapshotAtom.get();setIsLoading(e){To(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){To(this.snapshotAtom,{status:e}),this.callbacksRef.current.onStatusChange(e),this.devtoolsBridge.emitSnapshot()}setIsSubscribed(e){To(this.snapshotAtom,{isSubscribed:e}),this.callbacksRef.current.onSubscriptionChange(e),this.devtoolsBridge.emitSnapshot()}setConnectionStatus(e){To(this.snapshotAtom,{connectionStatus:e}),this.callbacksRef.current.onConnectionStatusChange(e),this.devtoolsBridge.emitSnapshot()}syncIsHydrating(){let e=this.hydrationInFlight!==void 0||this.storeHydrating;this.isHydrating!==e&&(To(this.snapshotAtom,{isHydrating:e}),this.callbacksRef.current.onHydratingChange(e))}setSessionGenerating(e){this.sessionGenerating!==e&&(To(this.snapshotAtom,{sessionGenerating:e}),this.callbacksRef.current.onSessionGeneratingChange(e),this.devtoolsBridge.emitSnapshot())}notifyResumeStateChange(e){let t=this.getResumeState(),n=this.interruptManager.getState();To(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){To(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:sf(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<Ud)&&(n=0,!(typeof document<`u`&&document.hidden)&&await Wd())}}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()},$d);try{for await(let a of t(e,n.signal)){if(n.signal.aborted)break;i||(i=!0,clearTimeout(o)),!r&&tf(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=ol(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`)&&(wu(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=af(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=wu(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=wu(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=Rc(e,zc);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=kd(this.byokProvider,f.provider,Od(this.byok));m=await Ad(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?ms(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 _u&&this.byok?.request(n.provider,`missing`),n instanceof vu&&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 _u||n instanceof vu||n instanceof yu))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&&ls(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 hs(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=Vs(n.metadata);return r===void 0?n:{...n,input:r}},t=rf(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=Fo(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){To(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=Xd(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();To(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(nf(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=Kd({connection:e.connection,fetcher:e.fetcher});this.connectionDrainsOnSend=qd(n),this.connection=Zu(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=Yd(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 lf=e=>`background:${e};color:#fff;border-radius:3px;padding:1px 5px`,uf=`${lf(`#7c3aed`)};font-weight:600`,df={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 ff(e){if(e)return(e,t,n)=>{console.log(`%cAstralBeam%c ${(/* @__PURE__ */ new Date()).toISOString().slice(11,19)} %c${e}%c ${t}`,uf,`color:#94a3b8;font-weight:400`,lf(df[e]),``,...n===void 0?[]:[n])}}function pf(){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 mf(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 hf(e,t,n){return`saved:${e}:${t}${n?`:${n}`:``}`}async function gf(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:hf(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 _f(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(hf(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=hf(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 vf(e){return e.placementKey??e.agentId??`default`}function yf(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 bf;function xf(e,t,n){if(!n){if(!bf)try{let e=`astralbeam:draft-session`;bf=globalThis.sessionStorage?.getItem(e)??pf(),globalThis.sessionStorage?.setItem(e,bf)}catch{bf??=pf()}n=`new:${bf}`}return JSON.stringify([e.replace(/\/+$/,``),t,n])}function Sf(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 Cf(e,t,n,r,i=`draft`){if(!t)return``;let a=`astralbeam:${i}:${xf(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 wf({apiUrl:e,identity:t,threadId:n,update:r,moveTo:i}){let a=()=>{if(!t)return[];let a=`astralbeam:attachments:${xf(e,t,n)}`,o=e=>{let t=JSON.parse(globalThis.localStorage?.getItem(e)??`[]`);if(!Array.isArray(t)||!t.every(Sf))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:${xf(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 Tf(e){return e?`~standard`in e?`jsonSchema`in e[`~standard`]?ms(e):{type:`object`}:e:{type:`object`,properties:{}}}async function Ef(e,t){let n=await hs(e,t);return n.success?n.data??{}:null}const Df=Symbol(`Host tool was not executed`);function Of(e,t,n,r,i){return[...Object.keys(e).length>0?[kf(e,n)]:[],Af(),...jf(t,r,i)]}function kf(e,t){return sl({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:
|
|
144
|
-
`+Object.entries(e).map(([e,{description:t,parameters:n}])=>`- ${e}: ${t} Props schema: ${JSON.stringify(
|
|
145
|
-
`),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 Af(){return sl({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 jf(e,t,n){return Object.entries(e).map(([e,r])=>sl({name:e,description:r.description,inputSchema:Tf(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 Ef(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{ns(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,{[Df]:!0}),n}}))}function Mf(e){if(e.length>16384)throw Error(`The chat auth token is too large`);let{exp:t,iat:n,user:r}=to(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 Nf(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 Pf={status:`loading`};function Ff(e){return{...e,fetchAstralBeamToken:e.fetchAstralBeamToken,session:{cached:void 0,refreshPromise:void 0,abortController:new AbortController,state:Pf,listeners:/* @__PURE__ */ new Set},fetchClient:globalThis.fetch.bind(globalThis),debug:void 0}}function If(e){return e.session.state}function Lf(e,t){let{listeners:n}=e.session;return n.add(t),()=>{n.delete(t)}}function Rf(e,t){e.session.state=t;for(let t of e.session.listeners)t()}function zf(e,t){e.apiUrl!==t.apiUrl&&(Gf(e),e.session.abortController=new AbortController,Rf(e,{status:`loading`})),e.apiUrl=t.apiUrl,e.fetchAstralBeamToken=t.fetchAstralBeamToken}function Bf(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 Vf(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 Nf(e,i);if(i.throwIfAborted(),typeof s!=`string`||!s)throw Error(`${a} did not return a token`);let{expiresAt:c,refreshAt:l,tenantAdmin:u}=Mf(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},Rf(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,Rf(e,{status:`error`,error:r}),r}}async function Hf(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())&&Rf(e,{status:`loading`});let r=Vf(e);t.refreshPromise=r;try{return await r}finally{t.refreshPromise===r&&(t.refreshPromise=void 0)}}function Uf(e,t){let n=!t||e.session.cached?.value===t;return n&&(e.session.cached=void 0),Hf({...e,force:n,retryUnauthorized:!1})}async function Wf(e){e.session.abortController.signal.aborted&&(e.session.abortController=new AbortController),await Hf(e)}function Gf({session:e}){e.abortController.abort(),e.refreshPromise=void 0,e.cached=void 0,e.state=Pf}async function Kf(e){let{input:t,init:n,session:r,fetchClient:i,debug:a}=e,o=If(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 Uf(e,u),f=If(e);if(o.status!==`ready`||f.status!==`ready`||Bf(o.currentUser)!==Bf(f.currentUser))throw new DOMException(`Identity changed`,`AbortError`);return n?.signal?.throwIfAborted(),c.set(`authorization`,`Bearer ${d}`),await i(t,{...n,headers:c})}function qf(e){let t,n=new AbortController,r=0,i=()=>typeof document>`u`||document.visibilityState!==`hidden`&&globalThis.navigator?.onLine!==!1,a=()=>{!n.signal.aborted&&i()&&Hf({...e,force:!0}).catch(()=>{})},o=()=>{if(clearTimeout(t),n.signal.aborted||typeof document>`u`||!i())return;let o=If(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=Lf(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 Wf(e).catch(()=>{}),o(),()=>{n.abort(),clearTimeout(t),c()}}async function Jf(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 Yf(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 Xf(e){return e.state===`complete`||e.state===`error`||e.output!==void 0}function Zf(e){return e.metadata??{}}function Qf(e,t){return typeof e==`object`&&e&&t in e?e[t]:void 0}function $f(e,t){let n=Qf(e,t);return typeof n==`string`?n:void 0}function ep(e,t){let n=Qf(e,t);return typeof n==`number`?n:void 0}function tp(e){return $f(e.output,`refusal`)}function np(e){if(e.name!==`sandbox_write_file`)return;let t=$f(e.output,`path`)??$f(e.input,`path`);if(t===void 0)return;let n=$f(e.input,`content`)??``;return{toolCallId:e.id,path:t,label:rp(e)??t,content:n,lines:n.length===0?0:n.split(`
|
|
146
|
-
`).length,written:e.output!=null&&tp(e)===void 0}}function rp(e){let t=$f(e.output,`relativePath`);return t!==void 0&&t!==`.`?t:$f(e.output,`path`)??$f(e.input,`path`)}function ip(e){if(e.name!==`sandbox_run_command`)return;let t=$f(e.input,`command`);if(t===void 0)return;let n=e.output;return{toolCallId:e.id,command:t,cwd:$f(e.input,`cwd`),exitCode:ep(n,`exitCode`),stdout:$f(n,`stdout`)??``,stderr:$f(n,`stderr`)??``,durationMs:ep(n,`durationMs`),timedOut:Qf(n,`timedOut`)===!0,truncated:Qf(n,`truncated`)===!0,finished:n!=null}}function ap(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=np(e);r?.written&&t.set(r.path,r);let i=ip(e);i&&tp(e)===void 0&&n.push(i)}return{files:[...t.values()],commands:n}}const op=`Reopen this conversation or start a new one before sending.`;function sp(e,t){return e.length===t.length&&e.every((e,n)=>e.name===t[n]?.name&&e.title===t[n]?.title)}function cp(e,t=!1){let n={...e},r=ff(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=Ff({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(),w=new AbortController,T,oe=!1,se=[],ce=/* @__PURE__ */ new Map,le=0,ue=/* @__PURE__ */ new WeakMap,de=e=>{for(let t of e){if(t.role!==`user`||ce.get(t.id)?.attachmentParts||!t.parts.some(e=>`fileId`in e))continue;let e=t.parts.map(e=>Object.freeze({...e}));Object.freeze(e),ce.set(t.id,{...ce.get(t.id),attachmentParts:e}),le++}},fe=pf(),E=()=>{c&&g(c,`accepted`)&&(s.thread&&f({thread:{...s.thread,hasMessages:!0}}),c.callbacks?.onAccepted?.())},pe=e=>{let t=[...M.getSnapshot().messages],n=t.findLastIndex(e=>e.role===`user`);n!==-1&&(t[n]=_f([e])[0],de([t[n]]),M.setMessagesManually(t),ze&&N())},me=/* @__PURE__ */ new Set,D=/* @__PURE__ */ new Map,he=/* @__PURE__ */ new Map,O=/* @__PURE__ */ new Map,ge=/* @__PURE__ */ new Map,_e=e=>{let t=D.get(e);return t?`live:${t}:${e}`:e},ve=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=hf(n.source_message_id,n.source_part_id,n.response_target_id),i=O.get(e)??O.get(r);i&&(t.set(r,i),D.get(n.tool_call_id)===n.source_message_id&&t.set(e,i))}O.clear();for(let[e,n]of t)O.set(e,n)},k=e=>{(s.auth.status!==`error`||s.auth.error!==e)&&n.streamCallbacks?.onError?.(e)},ye=e=>{if(e instanceof Error&&e.name===`AbortError`)return;let t=e instanceof Error?e:Error(String(e));f({error:t}),k(t)},be=e=>{f({unavailableMcpConnections:s.unavailableMcpConnections?.filter(t=>t!==e)??[]})},A=async(e=!0)=>{let t=S,n=y.session.abortController.signal,r=await Hf(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([w.signal,n]):n,fetchClient:(e,t)=>Kf({...y,input:e,init:t})}},xe=0,Se,Ce=async()=>{let e=++xe,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 A();if(e!==xe||t!==S)return;let a=await xr(i?{agentId:i}:{},n);if(e!==xe||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)}},we=/* @__PURE__ */ new Map,Te=/* @__PURE__ */ new Set,Ee=/* @__PURE__ */ new Set,De=0,j=()=>{De++;for(let e of we.values())e();we.clear(),Te.clear(),Ee.clear()},Oe=async(e,t)=>{if(!o().onRenderWidget)return{widget:e.widget,rendered:!1};let n=S,r=De,i=o().widgets??{};if(!Object.hasOwn(i,e.widget))throw Error(`Unknown widget "${e.widget}"`);let a=i[e.widget],c=await Ef(a?.parameters,e.props??{});if(n!==S||r!==De||s.thread?.role===`viewer`)return{widget:e.widget,rendered:!1};if(a!==o().widgets?.[e.widget])return Oe(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};we.get(t)?.(),we.delete(t);let u,d=l({widget:e.widget,props:c,toolCallId:t,release:()=>{we.get(t)===u&&we.delete(t)}});return d&&(u=d,we.set(t,d)),Te.add(t),{widget:e.widget,rendered:!0}},ke=e=>Object.freeze(e.map(e=>{let t=ce.get(e.id),n=ue.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=hf(e.id,t.id),a=n.applicationPartId?hf(e.id,n.applicationPartId,n.responseTargetId):r,o=n.upstreamToolCallId,s=n.widgetRenderId??i?.get(r)??i?.get(a)??(o&&D.get(o)===e.id&&Te.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},ce.set(e.id,t),le++);let o=r===e.parts?e:Object.freeze({...e,parts:r});return ue.set(e,{presentation:t,message:o}),o})),Ae=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(Te.has(t)||Ee.has(t))continue;Ee.add(t);let n=S,i=De,{widgets:a,onRenderWidget:c}=o();Oe(e.input,t).catch(e=>r?.(`error`,`Saved widget could not be rendered`,e)).finally(()=>{n===S&&i===De&&(Ee.delete(t),(a!==o().widgets||c!==o().onRenderWidget)&&Ae(s.messages))})}},je=()=>{let e=S;return Of(o().widgets??{},n.tools??{},Oe,r,(t,r,i)=>{let a=ie,o=M,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!==M||c!==b||l!==y.apiUrl||s.thread?.role===`viewer`||!i||!me.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||!me.has(r))throw Error(`A saved tool call cannot execute again. Send a new message to request it.`);let i=O,a=_e(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&&Df in e)&&b===o&&y.apiUrl===s&&i.set(a,{outcome:`unknown`,output:{error:e instanceof Error?e.message:String(e)}}),e}}}})},Me=()=>{let e=je(),t=e.map(e=>{let t=e.metadata?.title;return{name:e.name,title:typeof t==`string`&&t.length>0?t:void 0}});return sp(s.agentTools,t)||f({agentTools:t}),e},Ne=()=>n.debug?{debug:!0}:{},Pe=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:fe}};else{Ue();let e=await gf(n.id,t,void 0,D);if(r!==S)throw new DOMException(`Conversation changed`,`AbortError`);f({thread:mf(e.thread,e.messages.length>0)}),ve(e);let s=e.pendingInteractions.filter(e=>O.has(_e(e.toolCallId))),c=s.find(e=>e.toolCallId===i.messages.at(-1)?.toolCallId)??s[0],l=e.pendingInteractions.flatMap(e=>{let t=O.get(_e(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:fe,run_id:i.runId,...i.parentRunId?{parent_run_id:i.parentRunId}:{},results:l}}me.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 gf(n.id,t,void 0,D);if(r!==S)throw new DOMException(`Conversation changed`,`AbortError`);let a=i.messages.find(t=>t.id===e.accepted_message_id);a&&pe(a),E()}return new Response(``,{headers:{"Content-Type":`text/event-stream`}})}return p},Fe=$u(()=>sr(yr(),y.apiUrl),async()=>{let e=b,t=await Hf(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)=>Kf({...y,input:e,init:t})};return Pe(n??{},r)}}}),Ie=Fe.connect;Fe.connect=async function*(...e){try{for await(let t of Ie(...e)){if(t.type===X.TOOL_CALL_START&&t.parentMessageId&&D.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=he.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 Le=()=>{let e=new cf({connection:{...Fe,hydrate:(t,n)=>{let r=Re;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 gf(r,await A(),n?.before,D);for(;n?.before&&t.messages.every(e=>e.role===`tool`)&&t.page_after;){let e=await gf(r,await A(),t.page_after,D);t={...e,messages:[...e.messages,...t.messages]}}if(M!==e||a!==C)throw new DOMException(`Conversation changed`,`AbortError`);i||ve(t),se=i?[...t.messages,...se]:t.messages;let o=new Set(t.messages.map(e=>e.id)),c=_f(se,i?s.pendingInteractions:t.pendingInteractions,D).filter(e=>o.has(e.id));if(de(c),i)f({messagesCursor:t.page_after??void 0});else{t.thread.role===`viewer`&&j();let n=s.thread?.agentId!==t.thread.agent_id;f({thread:mf(t.thread,t.messages.length>0),messagesCursor:t.page_after??void 0,pendingInteractions:t.pendingInteractions}),n&&Ce(),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(()=>{M===e&&a===C&&(ze&&N(),f({history:t})),n()}))).then(()=>o),ae.catch(()=>void 0)),o}},threadId:Re??fe,persistence:!0,history:{pageSize:100},queue:`drop`,tools:Me(),forwardedProps:Ne(),onInterruptStateChange:t=>{M===e&&r?.(`tool`,`interrupt state changed`,t)},onCustomEvent:(t,n)=>{if(M!==e)return;if(t===`astralbeam_thread`){let e=n;if(s.thread?.id===e.threadId){if(e.acceptedMessage&&c?.phase===`submitting`&&pe(e.acceptedMessage),e.acceptedMessageId&&E(),e.saved)for(let t of e.executableToolCallIds??[])me.has(t)||O.delete(_e(t)),me.add(t);f({thread:{...s.thread,version:e.version},activeToolCallIds:[...me]})}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=>{M===e&&(t.type===X.RUN_STARTED&&f({serverToolTitles:{},unavailableMcpConnections:[]}),n.streamCallbacks?.onChunk?.(t))},onResponse:t=>{M===e&&n.streamCallbacks?.onResponse?.(t)},onFinish:t=>{M===e&&n.streamCallbacks?.onFinish?.(t)},onError:t=>{M===e&&(c?.phase!==`submitting`&&t.name!==`AbortError`&&f({error:t}),k(t))}});return e},Re,M=Le(),ze,Be,Ve=-1,N=()=>{let e=M.getSnapshot(),t=Be!==e.messages||Ve!==le;if(!t&&u===e.status)return;let n={};u!==e.status&&e.status===`submitted`&&(n.usageLimitReached=void 0),u=e.status,t&&(n.messages=ke(e.messages),n.sandbox=ap(n.messages),Be=e.messages,Ve=le),f(n),t&&Ae(s.messages)},He=()=>{if(!ze){let e=M,t=S;ze=e.subscribeSnapshot(()=>{M===e&&t===S&&N()}),N(),Ae(s.messages)}M.attach()},P=e=>{let t=M;d=void 0,ze?.(),ze=void 0,Be=void 0,M=Le(),e&&M.setMessagesManually(e),u=`ready`,t.stop(),t.detach(),me.clear(),f({activeToolCallIds:[]}),x&&He(),t.dispose()},Ue=()=>{he.clear(),M.setMessagesManually(M.getSnapshot().messages.map(e=>{let t=/* @__PURE__ */ new Map,n=e.parts.map(n=>{if(n.type!==`tool-call`||Zf(n).providerExecuted)return n;let r=n,i=r.upstreamToolCallId??n.id;if(D.get(i)===e.id&&!Xf(n))return n;let a=hf(e.id,r.applicationPartId??i,r.responseTargetId);return t.set(i,a),{...n,upstreamToolCallId:i,id:a,...n.name===`render_widget`?{widgetRenderId:r.widgetRenderId??ce.get(e.id)?.renderIds?.get(hf(e.id,n.id))??n.id}:{}}});return t.size&&he.set(e.id,t),{...e,parts:n}}))},We=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),ge.set(t,O)),S++,Re=e,w.abort(),w=new AbortController,O=ge.get(e??``)??/* @__PURE__ */ new Map,he.clear(),D.clear(),se=[],ce.clear(),ue=/* @__PURE__ */ new WeakMap,le++,j(),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}),P()},Ge=async(e,t=!1)=>{We(e);let r=S;c=l.get(e),c&&f({submission:m(c)});try{if(x||He(),await ae,r!==S)return;T&&yf(T,e)}catch(e){if(r!==S)return;t&&(n.threadId===void 0||n.threadId===`auto`)&&or(e)&&e.status===404?Ke():ye(e)}},Ke=()=>{We(),x&&Ce(),T?yf(T,null):oe=!0},qe=(e=!1)=>{let t=n.threadId;if(t===void 0||t===`auto`){if(!T)return;t=yf(T)}t&&t!==`new`?t===s.thread?.id&&T?yf(T,t):Ge(t,e):e||Ke()},Je=async(e,t)=>{if(s.thread)return;let r=await A(),i=await Cr(n.agentId?{agent_id:n.agentId}:{},r);if(!_(e,t))throw new DOMException(`Send cancelled`,`AbortError`);Re=i.id,f({thread:mf(i,!1)}),Ce(),T&&yf(T,i.id)},Ye=async(e=!0)=>{if(!s.thread)return;let t=S;try{M.detach(),He(),await ae,e&&t===S&&f({error:void 0})}catch(e){if(t!==S)return;or(e)&&e.status===404?Ke():ye(e)}},Xe=async()=>{if(!M.getHasOlderMessages()||s.olderMessagesLoading||s.history!==`idle`||c?.phase===`submitting`)return;let e=S;f({olderMessagesLoading:!0});try{await M.loadOlderMessages(),e===S&&ze&&N()}catch(t){e===S&&ye(t)}finally{e===S&&f({olderMessagesLoading:!1})}},Ze=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 A());if(n!==S)return!1;let i=mf(r,t.hasMessages);return f({thread:i}),!0}catch(e){return n===S&&ye(e),!1}},Qe=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 A()),t===S&&s.thread?.id===e.id&&Ke(),!0}catch(e){return t===S&&ye(e),!1}},F=async e=>{let t=S;if(d||c?.phase===`submitting`||M.getIsLoading()){ye(/* @__PURE__ */ Error(`Wait for this client's current request to finish before responding.`));return}let n=If(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`||!me.has(e.toolCallId)&&!a&&!i&&!O.has(_e(e.toolCallId))){ye(/* @__PURE__ */ Error(`This tool call belongs to another session and cannot be executed here.`));return}if(i&&!O.has(_e(e.toolCallId)))O.set(_e(e.toolCallId),{outcome:`unknown`,output:null});else if(!O.has(_e(e.toolCallId))&&`tool`in e){let t=e.output;O.set(_e(e.toolCallId),{outcome:e.state===`output-error`?`failed`:`succeeded`,output:t??null})}let o=d={};try{if(f({}),d!==o)return;if(Ue(),r){if(M.stop(),await Ye(!1),d!==o||t!==S)return;await M.append({role:`tool`,toolCallId:e.toolCallId,content:JSON.stringify(O.get(_e(e.toolCallId)))})}else`tool`in e&&await M.addToolResult(e);d===o&&t===S&&await Ye(!1)}finally{p(o)}},$e=e=>F({toolCallId:e}),et=async e=>{if(e!==c||e.phase!==`submitting`)return m(e);let t=d={};try{if(await Hf(y),await ae.catch(()=>void 0),!_(e,t))return m(e);if(s.history===`failed`)throw Error(op);if(await Je(e,t),!_(e,t)||(e.callbacks?.onThreadReady?.(s.thread.id),!_(e,t))||(Ue(),await M.sendMessage(e.content),!ee(e,t)))return m(e);te(e,M.getError()),await Ye(!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)&&k(r)}finally{p(t)}return m(e)},I=async(e,t)=>{let n=d||c?.phase===`submitting`||M.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`?op: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:pf(),content:e,phase:`refused`,error:Error(n)};let r={id:pf(),content:e,phase:`submitting`,key:pf(),callbacks:t};c=r,f({submission:m(r),error:void 0,olderMessagesLoading:!1}),M.stop(),me.clear(),Ue(),D.clear(),f({activeToolCallIds:[]});let i=new Promise(e=>r.onRefused=e);return Promise.race([et(r),i.then(()=>m(r))])},tt=async()=>{let e=c;if(!d&&!M.getIsLoading()&&e&&g(e,`submitting`))return f({error:void 0}),et(e)},nt=()=>{let e=If(y),t=s.auth;if(e.status===`ready`){let t=Bf(e.currentUser);b!==void 0&&b!==t&&(v(`The account changed before this was sent.`),l.clear(),ge.clear(),O.clear(),We(),T=void 0),b=t;let r=JSON.stringify(vf(n)),i=`astralbeam:thread:${n.apiUrl??`https://astralbeam.ai/api`}:${t}:session:${r}`;T!==i&&(T!==void 0&&We(),T=i,oe?(yf(i,null),oe=!1):qe(!0)),Se!==t&&(Se=t,Ce())}f({auth:e}),e.status===`error`&&(t.status!==`error`||t.error!==e.error)&&n.streamCallbacks?.onError?.(e.error)},rt=()=>{if(x)return;x=!0;let e=w.signal.aborted&&M.getIsHydrating();M.updateOptions({tools:Me()}),w.signal.aborted&&(w=new AbortController),re=Lf(y,nt),nt(),ne=qf(y),e?P(M.getSnapshot().messages):He()};return t||rt(),{start:rt,getState:()=>s,getOptions:()=>n,attachView:e=>{if(a)throw Error(`This chat session already has a view attached`);let t={options:e},n=()=>{M.updateOptions({tools:Me()}),Ae(s.messages)};return j(),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&&(j(),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=vf(n),{widgets:c,onRenderWidget:u}=n;n={...n,...e};let d=vf(n)!==o;r=ff(n.debug),zf(y,{apiUrl:n.apiUrl,fetchAstralBeamToken:n.fetchAstralBeamToken??{url:`/api/astralbeam/token`}}),y.debug=r,M.updateOptions({tools:Me(),forwardedProps:Ne()}),n.apiUrl===i?d?(oe=!1,(!s.thread||n.threadId!==s.thread.id)&&We(),T=void 0,nt()):n.threadId!==a&&qe():(v(`The chat service changed before this was sent.`),l.clear(),ge.clear(),O.clear(),We(),T=void 0,nt()),(c!==n.widgets||u!==n.onRenderWidget)&&Ae(s.messages),x&&(n.agentId!==t||n.apiUrl!==i||d)&&Ce()},sendMessage:I,retry:tt,addToolResult:F,stop:()=>{ie++;let e=c,t=d;e?.phase===`submitting`&&te(e),M.stop(),t&&p(t),e?.phase===`refused`&&e.onRefused?.()},retryAuthentication:()=>{Hf({...y,force:!0}).catch(()=>void 0)},reload:async()=>{let e=S;if(await Ye(),e!==S||s.error)return;let t=/* @__PURE__ */ new Set;for(;e===S;){let e=s.pendingInteractions.find(e=>!t.has(e.sourceMessageId)&&O.has(_e(e.toolCallId)));if(!e||(t.add(e.sourceMessageId),await F({toolCallId:e.toolCallId}),s.error))return}},searchThreads:async(e=``,t,n)=>{let r=await A(),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=>mf(e)),page_after:i.page_after}},openThread:Ge,renameThread:Ze,deleteThread:Qe,refreshThread:()=>Ye(),loadOlderMessages:Xe,uploadAttachment:async({data:e,filename:t,mimeType:r})=>{let i=s.thread?s.thread.agentId:n.agentId,[a,o]=await Promise.all([e,A(!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 A(!!e.threadId||!t?.preview),headers:t?.preview?{"X-File-Preview":`true`}:{}})).blob()},getMcpCatalog:async()=>Ir(await A(!1)),manageMcpConnection:async e=>{let t=await Jf(e,await A(!1));return`id`in e?be(e.id):t&&`id`in t&&be(t.id),t},authorizeMcpConnection:async e=>{let t=await Yf(e,()=>A(!1));be(t)},abandonToolCall:$e,reset:()=>{if(r?.(`status`,`conversation reset`),Ke(),s.auth.status===`ready`){let e=JSON.stringify([b,vf(n)]),t=n.apiUrl??`https://astralbeam.ai/api`;Cf(t,e,``,``),Cf(t,e,``,``,`sent`),wf({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,ze?.(),ze=void 0,M.detach(),j(),M.stop(),w.abort(),S++,xe++,Se=void 0,ne?.(),re?.(),Gf(y),x=!1,queueMicrotask(()=>{x||(M.dispose(),T=void 0,ce.clear(),ue=/* @__PURE__ */ new WeakMap)}),i.clear()}}}const lp=e=>e[Symbol.toStringTag],up=(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 dp(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(Wa(t)){if(o=wp(t),typeof o.kty!=`string`)throw vp(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(up(e,o,n),o.kty===`oct`)return Ha(o.k);if(!Object.isFrozen(t)){let{key_ops:e}=t;Array.isArray(e)&&Object.freeze(e),Object.freeze(t)}}else{if(!gp(t))throw vp(r,t,i);let e=i?`secret`:a?`private`:`public`;if(t.type!==e&&(i||[`secret`,`public`,`private`].includes(t.type)))throw TypeError(`${lp(t)} instances must be of type "${e}" for the ${r} algorithm`);if(mp(t))return t;if(s=t,s.type===`secret`)return s.export()}fp||=/* @__PURE__ */ new WeakMap;let c=t,l=fp.get(c);if(l?.[r])return l[r];if(l||fp.set(c,l={}),s&&typeof s.toCryptoKey==`function`){let t=s.type===`public`,n=pp[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 Tp(e,o)}let fp;const pp={__proto__:null,prime256v1:`P-256`,secp384r1:`P-384`,secp521r1:`P-521`},mp=e=>{if(e?.[Symbol.toStringTag]===`CryptoKey`)return!0;try{return e instanceof CryptoKey}catch{return!1}},hp=e=>e?.[Symbol.toStringTag]===`KeyObject`,gp=e=>mp(e)||hp(e);function _p(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 vp(e,t,n){let r=[`CryptoKey`,`KeyObject`,`JSON Web Key`];return n&&r.push(`Uint8Array`),TypeError(_p(`Key for the ${e} algorithm must be `,t,...r))}const yp=(e,t=`algorithm.name`)=>/* @__PURE__ */ TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function bp(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function xp(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 Sp(e,t,n){let r=e.algorithm;if(r.name!==t.name)throw yp(t.name);if(t.hash&&r.hash?.name!==t.hash)throw yp(t.hash,`algorithm.hash`);if(t.namedCurve&&r.namedCurve!==t.namedCurve)throw yp(t.namedCurve,`algorithm.namedCurve`);if(t.length!==void 0&&r.length!==t.length)throw yp(t.length,`algorithm.length`);bp(e,n)}function Cp(e){return{__proto__:null,...e}}function wp(e){let t=Cp(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 Tp(e,t,n){if(!e.kty.includes(t.kty))throw new za(`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 Ep(e,t,n,r=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey(`raw`,e,t,r,[n])),Sp(e,t,n),e}function Dp(e){let t={__proto__:null};for(let n in e)t[n]={...e[n],alg:n};return t}const Op=[[`verify`],[`sign`]];function kp(e){let t={name:`HMAC`,hash:`SHA-${e}`};return{kty:[`oct`],secret:!0,subtle:t,signing:t,usages:Op}}function Ap(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:Op,minRsaBits:2048}}function jp(e,t){return{kty:[`EC`],crv:e,subtle:{name:`ECDSA`,namedCurve:e},signing:{name:`ECDSA`,hash:`SHA-${t}`},usages:Op}}function Mp(){let e={name:`Ed25519`};return{kty:[`OKP`],crv:`Ed25519`,subtle:e,signing:e,usages:Op}}function Np(e){let t={name:`ML-DSA-${e}`};return{kty:[`AKP`],subtle:t,signing:t,usages:Op}}const Pp=Dp({HS256:kp(256),HS384:kp(384),HS512:kp(512),RS256:Ap(256),RS384:Ap(384),RS512:Ap(512),PS256:Ap(256,32),PS384:Ap(384,48),PS512:Ap(512,64),ES256:jp(`P-256`,256),ES384:jp(`P-384`,384),ES512:jp(`P-521`,512),EdDSA:Mp(),Ed25519:Mp(),"ML-DSA-44":Np(44),"ML-DSA-65":Np(65),"ML-DSA-87":Np(87)});function Fp(e){let t=typeof e==`string`?Pp[e]:void 0;if(!t)throw new za(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}const Ip=e=>Math.floor(e.getTime()/1e3),Lp={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},Rp=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function zp(){throw TypeError(`Invalid time period format`)}function Bp(e){typeof e!=`string`&&zp();let t=Rp.exec(e);(!t||t[4]&&t[1])&&zp();let n=parseFloat(t[2]),r=Math.round(n*Lp[t[3][0].toLowerCase()]);return Number.isFinite(r)||zp(),t[1]===`-`||t[4]===`ago`?-r:r}function Vp(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}function Hp(e,t){if(typeof t!=`string`)throw TypeError(`"${e}" claim must be a string`)}function Up(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 Wp(e,t){return typeof e==`number`?Vp(t,e):e instanceof Date?Vp(t,Ip(e)):Ip(/* @__PURE__ */ new Date)+Bp(e)}let Gp;function Kp(e){return Gp.get(e)}function qp(e){let t=Kp(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 Aa.encode(JSON.stringify(t))}var Jp=class{constructor(e={}){if(!Wa(e))throw TypeError(`JWT Claims Set MUST be an object`);(Gp||=/* @__PURE__ */ new WeakMap).set(this,structuredClone(e))}setIssuer(e){return Hp(`iss`,e),Kp(this).iss=e,this}setSubject(e){return Hp(`sub`,e),Kp(this).sub=e,this}setAudience(e){return Up(e),Kp(this).aud=e,this}setJti(e){return Hp(`jti`,e),Kp(this).jti=e,this}setNotBefore(e){return Kp(this).nbf=Wp(e,`setNotBefore`),this}setExpirationTime(e){return Kp(this).exp=Wp(e,`setExpirationTime`),this}setIssuedAt(e){let t=Kp(this);return t.iat=e===void 0?Ip(/* @__PURE__ */ new Date):typeof e==`string`?Vp(`setIssuedAt`,Ip(/* @__PURE__ */ new Date)+Bp(e)):Wp(e,`setIssuedAt`),this}};async function Yp(e,t,n){let[r,i,a,o]=e,s=``;if(i!==void 0){let e=Za(Ba,i);i=e[0],s=Ua(e[1])}if(a!==void 0&&(a=Za(Ba,a)[0]),!i&&!a)throw new Ba(`either setProtectedHeader or setUnprotectedHeader must be called before #sign()`);if(!Ga(i,a))throw new Ba(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let c={...i,...a};Ja(Ba,i);let l=Xa(i,Ya(Ba,qa,o,i,c));l||n?.();let{alg:u}=c;if(typeof u!=`string`||!u)throw new Ba(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);let d=Fp(u),f=``,p=r,m;if(l){let t=e[4];t?(f=t[0]??=Ua(r),p=t[1]??=Fa(f)):(f=Ua(r),m=Aa.encode(`${s}.${f}`))}m??=Na(Fa(s),Fa(`.`),p);let h=await Ep(await dp(d,t,`sign`),d.subtle,`sign`);d.minRsaBits&&xp(d.alg,h);let g={signature:Ua(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 Xp(e,t,n,r,i){let[a]=await Yp([e,t,void 0,n],r,i);return`${a.protected}.${a.payload}.${a.signature}`}const Zp=Jp;var Qp=class extends Zp{#e;setProtectedHeader(e){return Ka(this.#e,`setProtectedHeader`),this.#e=e,this}async sign(e,t){return Xp(qp(this),this.#e,t?.crit,e,()=>{throw new Va(`JWTs MUST NOT use unencoded payload`)})}};const $p=`astralbeam`,em=16384,tm=8192,nm=/^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}$/,rm=/^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}$/,im=[`id`,`name`,`metadata`],am=[`id`,`name`,`admin`,`metadata`],om=new TextEncoder;function sm(e){if(!nm.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 cm(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function lm(e){return e===null||typeof e==`string`||typeof e==`boolean`?!0:typeof e==`number`?Number.isFinite(e):Array.isArray(e)?e.every(lm):cm(e)&&Object.values(e).every(lm)}function um(e,t,n){if(!cm(t))throw Error(`${e} must be an object`);let r=n?am:im;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&&!(cm(s)&&lm(s)))throw Error(`${e}.metadata must be a JSON object`)}function dm(e,t){um(`user`,e,!0),um(`tenant`,t,!1);let n=JSON.stringify({user:e,tenant:t});if(om.encode(n).byteLength>tm)throw Error(`user and tenant must not exceed ${tm} bytes`);return JSON.parse(n)}async function fm(e){let t=await crypto.subtle.digest(`SHA-256`,om.encode(e));return om.encode(Ua(new Uint8Array(t)))}async function pm({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}=sm(e);if(n!==a)throw Error(`organizationId must match the API key organization`);let s=Math.floor(Date.now()/1e3);return await new Qp({ver:1,email:t,organization_id:n}).setProtectedHeader({alg:`HS256`,typ:`astralbeam-organization+jwt`,kid:i}).setIssuer(n).setAudience($p).setIssuedAt(s).setExpirationTime(s+r).sign(await fm(o))}async function mm({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}=sm(e),c=dm(t,n);if(r!==void 0&&(!Array.isArray(r)||r.length>20||!r.every(e=>typeof e==`string`&&rm.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 Qp({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($p).setIssuedAt(l).setExpirationTime(l+i).sign(await fm(s));if(om.encode(u).byteLength>em)throw Error(`chat auth tokens must not exceed ${em} bytes`);return u}function hm(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 gm(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 _m(e,t,n){let r=new Date(Date.now()+t*1e3).toISOString();n?Qr({token:e,expires_at:r}):s.write(`${e}\n`)}function vm(e){return e.command(`chat`,`Mint a chat JWT for a Tenant's user, as a token endpoint would`,hm,async e=>{let{apiKey:t}=await xi(),n=e.expiresIn??300;_m(await mm({apiKey:t,expiresInSeconds:n,...gm(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;_m(await pm({apiKey:t,email:e.email,organizationId:li(t),expiresInSeconds:n}),n,K.json)}),e.demandCommand(1)}function ym(e){return e.filter(e=>e.role===`assistant`).map(e=>e.parts.map(e=>e.type===`text`?e.content:``).join(``)).filter(Boolean).join(`
|
|
147
|
-
|
|
148
|
-
`)}async function
|
|
143
|
+
var Hl=/* @__PURE__ */ io({compare:()=>$l,generate:()=>Zl,observe:()=>Xl,unobserve:()=>Yl}),Ul=/* @__PURE__ */ new WeakMap,Wl=function(){function e(e){this.observers=/* @__PURE__ */ new Map,this.obj=e}return e}(),Gl=function(){function e(e,t){this.callback=e,this.observer=t}return e}();function Kl(e){return Ul.get(e)}function ql(e,t){return e.observers.get(t)}function Jl(e,t){e.observers.delete(t.callback)}function Yl(e,t){t.unobserve()}function Xl(e,t){var n=[],r,i=Kl(e);if(!i)i=new Wl(e),Ul.set(e,i);else{var a=ql(i,t);r=a&&a.observer}if(r)return r;if(r={},i.value=wl(e),t){r.callback=t,r.next=null;var o=function(){Zl(r)},s=function(){clearTimeout(r.next),r.next=setTimeout(o)};typeof window<`u`&&(window.addEventListener(`mouseup`,s),window.addEventListener(`keyup`,s),window.addEventListener(`mousedown`,s),window.addEventListener(`keydown`,s),window.addEventListener(`change`,s))}return r.patches=n,r.object=e,r.unobserve=function(){Zl(r),clearTimeout(r.next),Jl(i,r),typeof window<`u`&&(window.removeEventListener(`mouseup`,s),window.removeEventListener(`keyup`,s),window.removeEventListener(`mousedown`,s),window.removeEventListener(`keydown`,s),window.removeEventListener(`change`,s))},i.observers.set(t,new Gl(t,r)),r}function Zl(e,t){t===void 0&&(t=!1);var n=Ul.get(e.object);Ql(n.value,e.object,e.patches,``,t),e.patches.length&&Ll(n.value,e.patches);var r=e.patches;return r.length>0&&(e.patches=[],e.callback&&e.callback(r)),r}function Ql(e,t,n,r,i){if(t!==e){typeof t.toJSON==`function`&&(t=t.toJSON());for(var a=Cl(t),o=Cl(e),s=!1,c=o.length-1;c>=0;c--){var l=o[c],u=e[l];if(Sl(t,l)&&(t[l]!==void 0||u===void 0||Array.isArray(t)!==!1)){var d=t[l];typeof u==`object`&&u&&typeof d==`object`&&d&&Array.isArray(u)===Array.isArray(d)?Ql(u,d,n,r+`/`+El(l),i):u!==d&&(i&&n.push({op:`test`,path:r+`/`+El(l),value:wl(u)}),n.push({op:`replace`,path:r+`/`+El(l),value:wl(d)}))}else Array.isArray(e)===Array.isArray(t)?(i&&n.push({op:`test`,path:r+`/`+El(l),value:wl(u)}),n.push({op:`remove`,path:r+`/`+El(l)}),s=!0):(i&&n.push({op:`test`,path:r,value:e}),n.push({op:`replace`,path:r,value:t}))}if(s||a.length!=o.length)for(var c=0;c<a.length;c++){var l=a[c];!Sl(e,l)&&t[l]!==void 0&&n.push({op:`add`,path:r+`/`+El(l),value:wl(t[l])})}}}function $l(e,t,n){n===void 0&&(n=!1);var r=[];return Ql(e,t,r,``,n),r}var eu=Object.assign({},jl,Hl,{JsonPatchError:Al,deepClone:wl,escapePathComponent:El,unescapePathComponent:Dl});function tu(e){return e.type===`activity`}function nu(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ru(e,t){let{messageId:n,activityType:r,content:i}=t,a=t.replace??!0,o=e.findIndex(e=>e.id===n),s=o>=0?e[o]:void 0;if(s&&s.role!==`activity`)return console.warn(`ACTIVITY_SNAPSHOT: Message '${n}' is not an activity message`),e;if(s&&!a)return e;let c=Go(s?.role===`activity`?s.metadata:void 0,t.metadata),l={id:n,role:`activity`,parts:[{type:`activity`,activityType:r,content:structuredClone(i??{})}],...c==null?{}:{metadata:c},...s?.role===`activity`&&s.createdAt!=null?{createdAt:s.createdAt}:{},...s?.role===`activity`&&s.name!=null?{name:s.name}:{}};return o===-1?[...e,l]:e.map((e,t)=>t===o?l:e)}function iu(e,t){let{messageId:n,activityType:r,patch:i}=t,a=e.findIndex(e=>e.id===n);if(a===-1)return console.warn(`ACTIVITY_DELTA: No activity message '${n}'`),e;let o=e[a];if(o==null||o.role!==`activity`)return console.warn(`ACTIVITY_DELTA: Message '${n}' is not an activity message`),e;let s=o.parts.find(tu);if(s&&s.activityType!==r)return console.warn(`ACTIVITY_DELTA: activityType '${r}' does not match '${s.activityType}' for '${n}'`),e;let c=structuredClone(s?.content??{});try{let l=eu.applyPatch(c,i??[],!0,!1);if(!nu(l.newDocument))return console.warn(`ACTIVITY_DELTA: patched content for '${n}' is not an object`),e;let u={type:`activity`,activityType:r,content:structuredClone(l.newDocument)},d=s?o.parts.map(e=>e.type===`activity`?u:e):[u],f=Go(o.metadata,t.metadata);return e.map((e,t)=>t===a?{...e,parts:d,...f==null?{}:{metadata:f}}:e)}catch(t){let r=t instanceof Error?t.message:String(t);return console.warn(`Failed to apply activity patch for '${n}': ${r}`),e}}function au(e,t,n){return e.map(e=>{if(e.id!==t)return e;let r=[...e.parts],i=r.length>0?r[r.length-1]:null;return i&&i.type===`text`?r[r.length-1]={type:`text`,content:n}:r.push({type:`text`,content:n}),{...e,parts:r}})}function ou(e,t,n){return e.map(e=>{if(e.id!==t)return e;let r=[...e.parts],i=r.find(e=>e.type===`tool-call`&&e.id===n.id),a=n.metadata??i?.metadata,o=n.input??i?.input,s={type:`tool-call`,id:n.id,name:n.name,arguments:n.arguments,state:n.state,...i?.approval&&{approval:{...i.approval}},...i?.output!==void 0&&{output:i.output},...o!==void 0&&{input:o},...a!==void 0&&{metadata:a}};return i?r[r.indexOf(i)]=s:r.push(s),{...e,parts:r}})}function su(e,t,n,r,i,a,o){return e.map(e=>{if(e.id!==t)return e;let s=[...e.parts],c=s.findIndex(e=>e.type===`tool-result`&&e.toolCallId===n),l={type:`tool-result`,toolCallId:n,content:r,state:i,...o!==void 0&&{outcome:o},...a&&{error:a}};return c>=0?s[c]=l:s.push(l),{...e,parts:s}})}function cu(e,t,n,r){return e.map(e=>{if(e.id!==t)return e;let i=[...e.parts],a=i.find(e=>e.type===`tool-call`&&e.id===n);if(a){let e=i.indexOf(a);i[e]={...a,state:`approval-requested`,approval:{id:r,needsApproval:!0}}}return{...e,parts:i}})}function lu(e,t,n,r,i){return e.map(e=>{let a=[...e.parts],o=a.find(e=>e.type===`tool-call`&&e.id===t);if(o){let e=a.indexOf(o);a[e]={...o,output:i?{error:i}:n,state:r??(i?`error`:`complete`)}}return{...e,parts:a}})}function uu(e,t,n){return e.map(e=>{let r=[...e.parts],i=r.find(e=>e.type===`tool-call`&&e.approval?.id===t);if(i&&i.approval){let e=r.indexOf(i);r[e]={...i,approval:{...i.approval,approved:n},state:`approval-responded`}}return{...e,parts:r}})}function du(e,t,n){return e.map(e=>{if(e.id!==t)return e;let r=[...e.parts],i=r.findIndex(e=>e.type===`structured-output`),a=i>=0?r[i]:null,o=(a?.raw??``)+n,s=_l(o)??a?.partial,c={type:`structured-output`,status:`streaming`,raw:o,...s===void 0?{}:{partial:s},...a?.reasoning===void 0?{}:{reasoning:a.reasoning}};return i>=0?r[i]=c:r.push(c),{...e,parts:r}})}function fu(e,t,n,r,i){return e.map(e=>{if(e.id!==t)return e;let a=[...e.parts],o=a.findIndex(e=>e.type===`structured-output`),s=o>=0?a[o].raw:``,c=r||s;if(c===``&&n!==void 0)try{c=JSON.stringify(n)}catch{}let l={type:`structured-output`,status:`complete`,data:n,partial:n,raw:c,...i===void 0?{}:{reasoning:i}};return o>=0?a[o]=l:a.push(l),{...e,parts:a}})}function pu(e,t,n){return e.map(e=>{if(e.id!==t)return e;let r=[...e.parts],i=r.findIndex(e=>e.type===`structured-output`);if(i<0)return r.push({type:`structured-output`,status:`error`,raw:``,errorMessage:n}),{...e,parts:r};let a=r[i];return a.status===`complete`?e:(r[i]={...a,status:`error`,errorMessage:n},{...e,parts:r})})}function mu(e,t,n,r,i){return e.map(e=>{if(e.id!==t)return e;let a=[...e.parts],o=a.findIndex(e=>e.type===`thinking`&&e.stepId===n),s;if(o<0){o=a.findIndex(e=>e.type===`thinking`&&e.stepId===void 0);let e=a[o];e?.type===`thinking`&&(s=e)}let c=i??s?.signature,l=es(n)||s?.redacted===!0,u={type:`thinking`,content:r,stepId:n,...c&&{signature:c},...l&&{redacted:!0}};return o>=0?a[o]=u:a.push(u),{...e,parts:a}})}var hu=12,gu=/* @__PURE__ */ new Set([`RAW`,`ACTIVITY_SNAPSHOT`,`ACTIVITY_DELTA`,`REASONING_ENCRYPTED_VALUE`,`SUBAGENT_STARTED`,`SUBAGENT_FINISHED`,`SUBAGENT_ERROR`]),_u=/* @__PURE__ */ new Set([`RUN_STARTED`,`RUN_FINISHED`,`RUN_ERROR`,`MESSAGES_SNAPSHOT`]);function vu(e){return e.some(e=>{let t=e.metadata;if(!t||typeof t!=`object`||Array.isArray(t))return!1;let n=t[As];return typeof n==`object`&&!!n&&!Array.isArray(n)&&n.kind===`generic`})}var yu=class e{chunkStrategy;events;jsonParser;recordingEnabled;messages=[];messageStates=/* @__PURE__ */ new Map;activeMessageIds=/* @__PURE__ */ new Set;toolCallToMessage=/* @__PURE__ */ new Map;pendingManualMessageId=null;openChunk=null;structuredMessageIds=/* @__PURE__ */ new Set;structuredOutputUpdateBatches=/* @__PURE__ */ new Map;activeRuns=/* @__PURE__ */ new Set;callMessageIds=/* @__PURE__ */ new Map;unassignedCallMessageIds=/* @__PURE__ */ new Set;sealedMessageIds=/* @__PURE__ */ new Set;thinkingOwners=/* @__PURE__ */ new Map;runToolCallIds=[];toolCallsSentToClient=/* @__PURE__ */ new Set;childProcessors=/* @__PURE__ */ new Map;childToolCalls=/* @__PURE__ */ new Map;finishReason=null;hasError=!1;isDone=!1;streamEndEmitted=!1;recording=null;recordingStartTime=0;subagentRunId;constructor(e={}){this.subagentRunId=e.subagentRunId,this.chunkStrategy=e.chunkStrategy||new vl,this.events=e.events||{},this.jsonParser=e.jsonParser||gl,this.recordingEnabled=e.recording??!1,e.initialMessages&&(this.messages=[...e.initialMessages])}setMessages(e){this.messages=[...e],this.emitMessagesChange()}prependMessages(e){let t=new Set(this.messages.map(e=>e.id)),n=[];for(let r of e)t.has(r.id)||(t.add(r.id),n.push(r));this.messages=[...n,...this.messages],this.emitMessagesChange()}addUserMessage(e,t,n){let r=typeof e==`string`?[{type:`text`,content:e}]:e.map(e=>e),i={id:t??Uc(),role:`user`,parts:r,createdAt:/* @__PURE__ */ new Date,...n==null?{}:{metadata:n}};return this.messages=[...this.messages,i],this.emitMessagesChange(),i}prepareAssistantMessage(){this.resetStreamState()}getCurrentAssistantMessageId(){let e=null;for(let[t,n]of this.messageStates)n.role===`assistant`&&(e=t);return e}addToolResult(e,t,n){let r=this.messages.find(t=>t.parts.some(t=>t.type===`tool-call`&&t.id===e));if(!r){let r=this.childOwningToolCall(t=>t.id===e);if(r!==void 0){this.updateChild(r,r=>r.addToolResult(e,t,n));return}console.warn(`[StreamProcessor] Could not find message with tool call ${e}`);return}let i=lu(this.messages,e,t,n?`error`:void 0,n),a=ac(t),o=n?`error`:`complete`;i=su(i,r.id,e,a,o,n),this.messages=i,this.emitMessagesChange()}addToolApprovalResponse(e,t){let n=this.childOwningToolCall(t=>t.approval?.id===e);n===void 0?(this.messages=uu(this.messages,e,t),this.emitMessagesChange()):this.updateChild(n,n=>n.addToolApprovalResponse(e,t))}toModelMessages(){let e=[];for(let t of this.messages)e.push(...kc(t));return e}getMessages(){return this.messages}areAllToolsComplete(){let e=this.messages.findLast(e=>e.role===`assistant`);if(!e)return!0;let t=e.parts.filter(e=>e.type===`tool-call`);if(t.length===0)return!0;let n=new Set(e.parts.filter(e=>e.type===`tool-result`).map(e=>e.toolCallId));return t.every(e=>e.state===`complete`||e.state===`approval-responded`||e.output!==void 0&&!e.approval||n.has(e.id)||Qs(e))}removeMessagesAfter(e){let t=new Set(this.messages.slice(0,e+1).map(e=>e.id));for(let e of this.structuredMessageIds)t.has(e)||this.structuredMessageIds.delete(e);for(let e of this.structuredOutputUpdateBatches.keys())t.has(e)||this.structuredOutputUpdateBatches.delete(e);for(let e of this.messageStates.keys())t.has(e)||this.messageStates.delete(e);for(let[e,n]of this.toolCallToMessage)t.has(n)||this.toolCallToMessage.delete(e);for(let e of this.activeMessageIds)t.has(e)||this.activeMessageIds.delete(e);this.pendingManualMessageId&&!t.has(this.pendingManualMessageId)&&(this.pendingManualMessageId=null);for(let e of this.callMessageIds.values())for(let n of e)t.has(n)||e.delete(n);for(let e of this.unassignedCallMessageIds)t.has(e)||this.unassignedCallMessageIds.delete(e);for(let e of this.sealedMessageIds)t.has(e)||this.sealedMessageIds.delete(e);for(let[e,n]of this.thinkingOwners)t.has(n.messageId)||this.thinkingOwners.delete(e);this.messages=this.messages.slice(0,e+1),this.emitMessagesChange()}clearMessages(){for(let e of this.callMessageIds.values())e.clear();this.unassignedCallMessageIds.clear(),this.messages=[],this.messageStates.clear(),this.activeMessageIds.clear(),this.toolCallToMessage.clear(),this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.pendingManualMessageId=null,this.sealedMessageIds.clear(),this.thinkingOwners.clear(),this.openChunk=null,this.childProcessors.clear(),this.childToolCalls.clear(),this.emitMessagesChange()}async process(e){this.resetStreamState(),this.recordingEnabled&&this.startRecording();for await(let t of e)this.processChunk(t);return this.finalizeStream(),this.recording&&(this.recording.result=this.getResult()),this.getResult()}processChunk(e){if(this.recording&&this.recording.chunks.push({chunk:e,timestamp:Date.now(),index:this.recording.chunks.length}),!this.routeToChild(e))for(let t of this.expandChunk(e))this.dispatchChunk(t)}dispatchChunk(e){switch(e.type){case`SUBAGENT_STARTED`:this.handleSubagentStartedEvent(e);break;case`SUBAGENT_FINISHED`:this.handleSubagentFinishedEvent(e);break;case`SUBAGENT_ERROR`:this.handleSubagentErrorEvent(e);break;case`TEXT_MESSAGE_START`:this.handleTextMessageStartEvent(e);break;case`TEXT_MESSAGE_CONTENT`:this.handleTextMessageContentEvent(e);break;case`TEXT_MESSAGE_END`:this.handleTextMessageEndEvent(e);break;case`TOOL_CALL_START`:this.handleToolCallStartEvent(e);break;case`TOOL_CALL_ARGS`:this.handleToolCallArgsEvent(e);break;case`TOOL_CALL_END`:this.handleToolCallEndEvent(e);break;case`RUN_FINISHED`:this.handleRunFinishedEvent(e);break;case`RUN_ERROR`:this.handleRunErrorEvent(e);break;case`MESSAGES_SNAPSHOT`:this.handleMessagesSnapshotEvent(e);break;case`CUSTOM`:this.handleCustomEvent(e);break;case`RUN_STARTED`:this.handleRunStartedEvent(e);break;case`REASONING_START`:case`REASONING_MESSAGE_END`:case`REASONING_END`:break;case`REASONING_MESSAGE_START`:{let t=e,n=this.unscopedAssistant(t),r=n.id?this.getMessageState(n.id):void 0;if(r&&(r.currentThinkingStepId=null),t.metadata==null)break;let{messageId:i}=this.ensureAssistantMessage(n.id??void 0,!n.create);this.mergeMessageMetadata(i,t.metadata);break}case`REASONING_MESSAGE_CONTENT`:this.handleReasoningMessageContentEvent(e);break;case`REASONING_ENCRYPTED_VALUE`:this.handleReasoningEncryptedValueEvent(e);break;case`TOOL_CALL_RESULT`:this.handleToolCallResultEvent(e);break;case`ACTIVITY_SNAPSHOT`:this.handleActivitySnapshotEvent(e);break;case`ACTIVITY_DELTA`:this.handleActivityDeltaEvent(e)}}expandChunk(e){let t=this.openChunk,n=e.timestamp;switch(e.type){case`TEXT_MESSAGE_CHUNK`:{let r=this.chunkStreamId(`TEXT_MESSAGE`,e.messageId,e.type);if(r===void 0)return this.closeChunk();let i=[];return(t?.family!==`TEXT_MESSAGE`||t.id!==r)&&(i.push(...this.closeChunk(),{type:X.TEXT_MESSAGE_START,messageId:r,role:e.role??`assistant`,...e.name===void 0?{}:{name:e.name},timestamp:n}),this.openChunk={family:`TEXT_MESSAGE`,id:r}),(e.delta!==void 0||e.metadata!==void 0)&&i.push({type:X.TEXT_MESSAGE_CONTENT,messageId:r,delta:e.delta??``,metadata:e.metadata,timestamp:n}),i}case`TOOL_CALL_CHUNK`:{let r=this.chunkStreamId(`TOOL_CALL`,e.toolCallId,e.type);if(r===void 0)return this.closeChunk();let i=[];if(t?.family!==`TOOL_CALL`||t.id!==r){if(e.toolCallName===void 0)return console.warn(`[StreamProcessor] Dropped TOOL_CALL_CHUNK ${r}: the first chunk of a tool call needs a toolCallName`),this.closeChunk();i.push(...this.closeChunk(),{type:X.TOOL_CALL_START,toolCallId:r,toolCallName:e.toolCallName,parentMessageId:e.parentMessageId,metadata:e.metadata,timestamp:n}),this.openChunk={family:`TOOL_CALL`,id:r}}return(e.delta!==void 0||e.metadata!==void 0)&&i.push({type:X.TOOL_CALL_ARGS,toolCallId:r,delta:e.delta??``,...e.metadata===void 0?{}:{metadata:e.metadata},timestamp:n}),i}case`REASONING_MESSAGE_CHUNK`:{let r=this.chunkStreamId(`REASONING_MESSAGE`,e.messageId,e.type);if(r===void 0)return this.closeChunk();let i=[];return(t?.family!==`REASONING_MESSAGE`||t.id!==r)&&(i.push(...this.closeChunk(),{type:X.REASONING_MESSAGE_START,messageId:r,role:`reasoning`,timestamp:n}),this.openChunk={family:`REASONING_MESSAGE`,id:r}),(e.delta!==void 0||e.metadata!==void 0)&&i.push({type:X.REASONING_MESSAGE_CONTENT,messageId:r,delta:e.delta??``,...e.metadata===void 0?{}:{metadata:e.metadata},timestamp:n}),i}default:{let n=t&&!gu.has(e.type)?this.closeChunk():[];return _u.has(e.type)&&this.closeChildChunkLanes(),[...n,e]}}}closeChildChunkLanes(){for(let e of this.childProcessors.values()){for(let t of e.closeChunk())e.dispatchChunk(t);e.closeChildChunkLanes()}}childContinuing(e){let t;if(e.type===`TEXT_MESSAGE_CHUNK`&&e.messageId===void 0)t=`TEXT_MESSAGE`;else if(e.type===`REASONING_MESSAGE_CHUNK`&&e.messageId===void 0)t=`REASONING_MESSAGE`;else if(e.type===`TOOL_CALL_CHUNK`&&e.toolCallId===void 0)t=`TOOL_CALL`;else return;if(this.openChunkCount(t)===1){for(let[e,n]of this.childProcessors)if(n.openChunkCount(t)===1)return e}}openChunkCount(e){let t=+(this.openChunk?.family===e);for(let n of this.childProcessors.values())t+=n.openChunkCount(e);return t}chunkStreamId(e,t,n){if(t!==void 0)return t;if(this.openChunk?.family===e)return this.openChunk.id;console.warn(`[StreamProcessor] Dropped ${n}: it has no id and continues nothing`)}closeChunk(){let e=this.openChunk;if(!e)return[];this.openChunk=null;let t=Date.now();switch(e.family){case`TEXT_MESSAGE`:return[{type:X.TEXT_MESSAGE_END,messageId:e.id,timestamp:t}];case`TOOL_CALL`:return[{type:X.TOOL_CALL_END,toolCallId:e.id,timestamp:t}];case`REASONING_MESSAGE`:return[{type:X.REASONING_MESSAGE_END,messageId:e.id,timestamp:t}]}}createMessageState(e,t){let n={id:e,role:t,totalTextContent:``,currentSegmentText:``,lastEmittedText:``,thinkingSteps:/* @__PURE__ */ new Map,thinkingStepSignatures:/* @__PURE__ */ new Map,thinkingStepOrder:[],currentThinkingStepId:null,toolCalls:/* @__PURE__ */ new Map,toolCallOrder:[],hasToolCallsSinceTextStart:!1,isComplete:!1};return this.messageStates.set(e,n),n}getMessageState(e){return this.messageStates.get(e)}getActiveAssistantMessageId(){let e=e=>this.activeRuns.size===0||[...this.activeRuns].some(t=>this.callMessageIds.get(t)?.has(e))||this.pendingManualMessageId===e&&!this.messageStates.get(e)?.isComplete&&!this.isDone,t=Array.from(this.activeMessageIds).reverse();for(let n of t){if(this.sealedMessageIds.has(n))continue;let t=this.messageStates.get(n);if(t&&t.role===`assistant`&&e(n))return n}for(let[t,n]of[...this.messageStates].reverse())if(!this.sealedMessageIds.has(t)&&n.role===`assistant`&&e(t))return t;return null}runOfMessage(e){for(let[t,n]of this.callMessageIds)if(n.has(e))return t}openMessageOfRun(e){let t=this.callMessageIds.get(e);if(!t)return null;for(let e of[...t].reverse())if(!this.sealedMessageIds.has(e)&&this.messageStates.get(e)?.role===`assistant`)return e;return null}unscopedAssistant(e){let t=pl(e),n=this.activeRuns.size===1?[...this.activeRuns][0]:void 0,r=t??n;if(r!==void 0){let e=this.openMessageOfRun(r);if(e)return{id:e,create:!1};if(t!==void 0||this.activeRuns.has(r))return{id:null,create:!0}}let i=this.getActiveAssistantMessageId();return i?{id:i,create:!1}:{id:null,create:!0}}rememberThinking(e,t,n){let r={messageId:e,stepId:t};this.thinkingOwners.set(t,r),n!==void 0&&n!==t&&this.thinkingOwners.set(n,r)}applyKnownSignature(e,t){if(!e)return!1;let n=this.thinkingOwners.get(e);if(!n)return!1;let r=this.getMessageState(n.messageId);if(!r)return!1;r.thinkingStepSignatures.set(n.stepId,t);let i=r.thinkingSteps.get(n.stepId)??``;return r.thinkingSteps.has(n.stepId)||(r.thinkingSteps.set(n.stepId,i),r.thinkingStepOrder.push(n.stepId)),this.messages=mu(this.messages,n.messageId,n.stepId,i,t),this.emitMessagesChange(),!0}resumeAssistantState(e,t){this.activeMessageIds.add(e),(t.isComplete||this.isDone)&&(t.isComplete=!1,this.isDone=!1)}ensureAssistantMessage(e,t=!0){if(e){let t=this.pendingManualMessageId;t&&t!==e&&this.messageStates.get(t)?.isComplete===!1&&!this.messages.some(t=>t.id===e)&&(this.renameMessage(t,e),this.pendingManualMessageId=e);let n=this.getMessageState(e);if(n)return this.resumeAssistantState(e,n),{messageId:e,state:n}}let n=t&&e===void 0?this.getActiveAssistantMessageId():null;if(n){let e=this.getMessageState(n);if(e)return this.resumeAssistantState(n,e),{messageId:n,state:e}}if(e){let t=this.messages.find(t=>t.id===e);if(t?.role===`activity`)e=void 0;else if(t){let n=this.createMessageState(e,t.role);this.activeMessageIds.add(e);let r=t.parts.length>0?t.parts[t.parts.length-1]:null;return r&&r.type===`text`&&(n.currentSegmentText=r.content,n.lastEmittedText=r.content,n.totalTextContent=r.content),{messageId:e,state:n}}}let r=e||Uc(),i={id:r,role:`assistant`,parts:[],createdAt:/* @__PURE__ */ new Date};this.messages=[...this.messages,i];let a=this.createMessageState(r,`assistant`);return this.activeMessageIds.add(r),e||(this.pendingManualMessageId=r),this.events.onStreamStart?.(),this.emitMessagesChange(),{messageId:r,state:a}}mergeMessageMetadata(e,t){let n=Y({metadata:typeof t==`object`&&t?{...t}:void 0})?.runId??(this.activeRuns.size===1?[...this.activeRuns][0]:void 0);if(n!==void 0){let t=this.callMessageIds.get(n)??/* @__PURE__ */ new Set;t.add(e),this.callMessageIds.set(n,t)}else this.unassignedCallMessageIds.add(e);if(typeof t!=`object`||!t||Array.isArray(t))return;let r=this.messages.find(t=>t.id===e);if(!r)return;let i=t,a=Y(i),o=a!=null&&(`content`in a||`args`in a)?{...i,tanstack:Object.fromEntries(Object.entries(a).filter(([e])=>e!==`content`&&e!==`args`))}:i,s=Go(r.metadata,o),c=bc(Y(i)?.createdAt),l=c!==void 0;this.messages=this.messages.map(t=>t.id===e?{...t,...s===void 0?{}:{metadata:s},...l?{createdAt:c}:{}}:t),this.emitMessagesChange()}findSubagentPart(e){for(let t of this.messages)for(let n of t.parts)if(n.type===`subagent`&&n.subagent.id===e)return{message:t,part:n}}childOwning(e){let t=n=>n.some(n=>n.parts.some(n=>n.type===`subagent`&&(n.subagent.id===e||t(n.subagent.messages))));for(let n of this.messages)for(let r of n.parts)if(r.type===`subagent`&&(r.subagent.id===e||t(r.subagent.messages)))return r.subagent.id}childOwningToolCall(e){let t=n=>n.some(n=>n.parts.some(n=>n.type===`tool-call`&&e(n)||n.type===`subagent`&&t(n.subagent.messages)));for(let e of this.messages)for(let n of e.parts)if(n.type===`subagent`&&t(n.subagent.messages))return n.subagent.id}childProcessor(t){let n=this.findSubagentPart(t);if(!n)return;let r=n.part.subagent.messages,i=this.childProcessors.get(t);if(i)return i.getMessages()!==r&&(i.messages=r),i;let a=new e({subagentRunId:t,initialMessages:r,events:{onToolCall:e=>this.events.onToolCall?.(e),onApprovalRequest:e=>this.events.onApprovalRequest?.(e),onCustomEvent:(e,t,n)=>this.events.onCustomEvent?.(e,t,n)}});return this.childProcessors.set(t,a),a}updateChild(e,t){let n=this.childProcessor(e);if(!n)return;t(n);let r=n.getMessages();this.patchSubagent(e,e=>{e.messages=r})}handleSubagentStartedEvent(e){if(e.type!==`SUBAGENT_STARTED`)return;if(this.findSubagentPart(e.subagentRunId)){this.childProcessors.delete(e.subagentRunId),this.patchSubagent(e.subagentRunId,t=>{t.status=`running`,delete t.interruptIds,delete t.error,e.metadata!==void 0&&(t.metadata=e.metadata)});return}let{messageId:t}=this.ensureAssistantMessage(),n={type:`subagent`,subagent:{id:e.subagentRunId,name:e.name,...e.description!==void 0&&{description:e.description},status:`running`,...e.parentSubagentRunId!==void 0&&{parentSubagentRunId:e.parentSubagentRunId},...e.parentToolCallId!==void 0&&{parentToolCallId:e.parentToolCallId},...e.metadata!==void 0&&{metadata:e.metadata},messages:[]}};this.messages=this.messages.map(e=>e.id===t?{...e,parts:[...e.parts,n]}:e),this.emitMessagesChange()}handleSubagentFinishedEvent(e){e.type===`SUBAGENT_FINISHED`&&(this.updateChild(e.subagentRunId,e=>e.finalizeStream()),this.patchSubagent(e.subagentRunId,t=>{t.status!==`error`&&(e.outcome?.type===`suspended`?(t.status=`suspended`,t.interruptIds=e.outcome.interruptIds??[]):t.status=`finished`)}))}handleSubagentErrorEvent(e){e.type===`SUBAGENT_ERROR`&&(this.updateChild(e.subagentRunId,e=>e.finalizeStream()),this.patchSubagent(e.subagentRunId,t=>{t.status=`error`,t.error={message:e.message,...e.code!==void 0&&{code:e.code}}}))}patchSubagent(e,t){this.messages=this.messages.map(n=>{let r=n.parts.findIndex(t=>t.type===`subagent`&&t.subagent.id===e);if(r===-1)return n;let i=n.parts[r];if(!i||i.type!==`subagent`)return n;let a={type:`subagent`,subagent:{...i.subagent}};t(a.subagent);let o=[...n.parts];return o[r]=a,{...n,parts:o}}),this.emitMessagesChange()}routeToChild(e){let t;if(e.type===`SUBAGENT_STARTED`)t=e.parentSubagentRunId;else if(e.type===`SUBAGENT_FINISHED`||e.type===`SUBAGENT_ERROR`){if(this.findSubagentPart(e.subagentRunId))return!1;t=e.subagentRunId}else t=`subagentRunId`in e&&e.subagentRunId?e.subagentRunId:`toolCallId`in e&&typeof e.toolCallId==`string`?this.childToolCalls.get(e.toolCallId):this.childContinuing(e);if(t===void 0)return!1;let n=this.childOwning(t);return n===void 0?t!==this.subagentRunId&&(console.warn(`[StreamProcessor] Dropped a chunk for unknown subagent ${t}`),!0):(this.findSubagentPart(n)?.part.subagent.status===`error`||((e.type===`TOOL_CALL_START`||e.type===`TOOL_CALL_CHUNK`)&&e.toolCallId!==void 0&&this.childToolCalls.set(e.toolCallId,n),this.updateChild(n,t=>t.processChunk(e))),!0)}renameMessage(e,t){this.messages=this.messages.map(n=>n.id===e?{...n,id:t}:n);let n=this.messageStates.get(e);n&&(n.id=t,this.messageStates.delete(e),this.messageStates.set(t,n)),this.activeMessageIds.delete(e),this.activeMessageIds.add(t);for(let[n,r]of this.toolCallToMessage)r===e&&this.toolCallToMessage.set(n,t);this.structuredMessageIds.delete(e)&&this.structuredMessageIds.add(t);let r=this.structuredOutputUpdateBatches.get(e);r&&(this.structuredOutputUpdateBatches.delete(e),this.structuredOutputUpdateBatches.set(t,r));for(let n of this.callMessageIds.values())n.delete(e)&&n.add(t);this.unassignedCallMessageIds.delete(e)&&this.unassignedCallMessageIds.add(t),this.sealedMessageIds.delete(e)&&this.sealedMessageIds.add(t);for(let[n,r]of this.thinkingOwners)r.messageId===e&&this.thinkingOwners.set(n,{messageId:t,stepId:r.stepId})}handleTextMessageStartEvent(e){let{messageId:t,role:n}=e;if(this.messages.some(e=>e.id===t&&e.role===`activity`)){console.warn(`TEXT_MESSAGE_START: Dropped text for '${t}', the id of an activity message`);return}let r=n===`user`||n===`system`?n:`assistant`,i=this.pendingManualMessageId,a=i?this.runOfMessage(i):void 0,o=this.runOfMessage(t);if(i&&(a===void 0||o===void 0||a===o)){this.pendingManualMessageId=null,i!==t&&this.renameMessage(i,t);let n=this.messageStates.get(t);n?n.hasToolCallsSinceTextStart&&(n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(t),n.currentSegmentText=``,n.lastEmittedText=``,n.hasToolCallsSinceTextStart=!1):(n=this.createMessageState(t,r),this.activeMessageIds.add(t)),this.applySenderName(t,e.name),this.mergeMessageMetadata(t,e.metadata),this.emitMessagesChange();return}if(this.messages.find(e=>e.id===t)){this.activeMessageIds.add(t);let n=this.messageStates.get(t);n?n.hasToolCallsSinceTextStart&&=(n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(t),n.currentSegmentText=``,n.lastEmittedText=``,!1):this.createMessageState(t,r),this.applySenderName(t,e.name),this.mergeMessageMetadata(t,e.metadata);return}let s={id:t,role:r,parts:[],createdAt:/* @__PURE__ */ new Date};this.messages=[...this.messages,s],this.createMessageState(t,r),this.activeMessageIds.add(t),this.applySenderName(t,e.name),this.mergeMessageMetadata(t,e.metadata),this.events.onStreamStart?.(),this.emitMessagesChange()}applySenderName(e,t){t!==void 0&&(this.messages=this.messages.map(n=>n.id===e?{...n,name:t}:n))}handleTextMessageEndEvent(e){let{messageId:t}=e;this.mergeMessageMetadata(t,e.metadata);let n=this.getMessageState(t);n&&(n.isComplete||n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(t))}handleMessagesSnapshotEvent(e){this.resetStreamState();let t=this.messages,n=new Map(t.map(e=>[e.id,e])),{top:r,groups:i}=Xs(e.messages),a=this.mergeReasoningFanOut(r.map(Lc)),o=this.reconcileSnapshotToolCalls(a,t).map(e=>{if(e.metadata!=null)return e;let t=n.get(e.id);return t?.metadata==null?e:{...e,metadata:t.metadata}});this.messages=this.mergeOmittedActivity(t,this.attachSnapshotSubagents(o,r,i,t)),this.emitMessagesChange()}mergeOmittedActivity(e,t){let n=new Set(t.map(e=>e.id)),r=e.filter(e=>e.role===`activity`&&!n.has(e.id));if(r.length===0)return t;let i=[...t];for(let t of r){let n=e.findIndex(e=>e.id===t.id);i.splice(Math.min(Math.max(n,0),i.length),0,t)}return i}attachSnapshotSubagents(t,n,r,i){let a=[],o=/* @__PURE__ */ new Map;for(let t of r){let r=new e({subagentRunId:t.id});r.processChunk({type:X.MESSAGES_SNAPSHOT,messages:t.messages,timestamp:Date.now()}),o.set(t.id,r);let{placeholder:i,...s}=t.info;a.push({hostId:n.slice(0,t.hostIndex+1).findLast(e=>e.role===`assistant`)?.id,part:{type:`subagent`,subagent:{...s,id:t.id,messages:r.getMessages()}},carried:!1})}let s=new Set(r.map(e=>e.id));for(let e of i)for(let t of e.parts){if(t.type!==`subagent`||s.has(t.subagent.id))continue;a.push({hostId:e.id,...t.subagent.parentToolCallId!==void 0&&{toolCallId:t.subagent.parentToolCallId},part:t,carried:!0});let n=this.childProcessors.get(t.subagent.id);n&&o.set(t.subagent.id,n)}this.childProcessors.clear();for(let[e,t]of o)this.childProcessors.set(e,t);let c=t;for(let e of a){let t=c.findIndex(t=>t.id===e.hostId);t===-1&&e.toolCallId!==void 0&&(t=c.findIndex(t=>t.parts.some(t=>t.type===`tool-call`&&t.id===e.toolCallId))),t===-1&&!e.carried&&(t=c.findLastIndex(e=>e.role===`assistant`)),t===-1?e.carried||(c=[...c,{id:Uc(),role:`assistant`,parts:[e.part]}]):c=c.map((n,r)=>r!==t||n.parts.some(t=>t.type===`subagent`&&t.subagent.id===e.part.subagent.id)?n:{...n,parts:[...n.parts,e.part]})}return c}mergeReasoningFanOut(e){let t=[],n=[],r=e=>e.parts.filter(e=>e.type===`thinking`),i=e=>e.role===`assistant`&&e.parts.length>0&&e.parts.every(e=>e.type===`thinking`),a=e=>e.role===`assistant`&&e.parts.some(e=>e.type===`tool-result`)&&e.parts.every(e=>e.type===`tool-result`||e.type===`ui-resource`),o=()=>{t.push(...n),n=[]};for(let s of e){if(i(s)){n.push(s);continue}let e=s;s.role===`assistant`&&n.length>0&&!a(s)?(e={...s,parts:[...n.flatMap(r),...s.parts]},n=[]):o();let c=t.length-1;for(;c>=0;){let e=t[c];if(!e||!a(e))break;c--}let l=t[c];if(l?.role===`assistant`&&e.role===`assistant`&&$s(e.id,l.id)){let n=t.slice(c).flatMap(e=>e.parts);t.splice(c,t.length-c,{...l,parts:[...n,...e.parts]})}else t.push(e)}return o(),t}reconcileSnapshotToolCalls(e,t){let n=/* @__PURE__ */ new Map;for(let e of t)for(let t of e.parts)t.type===`tool-call`&&n.set(t.id,t);let r=/* @__PURE__ */ new Set;for(let t of e)for(let e of t.parts)e.type===`tool-call`&&r.add(e.id);let i=[];for(let t of e){let e=t.parts.filter(e=>e.type===`tool-result`),a=t.role===`assistant`&&e.length===1&&t.parts.every(e=>e.type===`tool-result`||e.type===`ui-resource`)?e[0]:void 0;if(!a){i.push(t);continue}let o=i.findLast(e=>e.parts.some(e=>e.type===`tool-call`&&e.id===a.toolCallId))??i.findLast(e=>e.role===`assistant`&&(e.parts.length!==1||e.parts[0]?.type!==`tool-result`));if(!o){r.has(a.toolCallId)||console.warn(`[StreamProcessor] MESSAGES_SNAPSHOT contains a tool-result for "${a.toolCallId}" but no matching tool-call exists in the snapshot, and there is no assistant message to anchor into; addToolResult("${a.toolCallId}") will not be able to locate this call`),i.push(t);continue}let s=[...o.parts];if(!r.has(a.toolCallId)&&!s.some(e=>e.type===`tool-call`&&e.id===a.toolCallId)){let e=n.get(a.toolCallId);e?(s.push({...e}),r.add(e.id)):console.warn(`[StreamProcessor] MESSAGES_SNAPSHOT contains a tool-result for "${a.toolCallId}" but no matching tool-call exists in the snapshot or the pre-snapshot state; addToolResult("${a.toolCallId}") will not be able to locate this call`)}s.push(...t.parts),o.parts=s}return this.enrichSnapshotToolCallsFromResults(i,n)}enrichSnapshotToolCallsFromResults(e,t){let n=/* @__PURE__ */ new Map;for(let t of e)for(let e of t.parts)e.type===`tool-result`&&n.set(e.toolCallId,e);return e.map(e=>{let r=e.parts.map(e=>{if(e.type!==`tool-call`)return e;let r=t.get(e.id),i=n.get(e.id),a=e;if(r&&(r.output!==void 0||r.state===`complete`||r.state===`error`)&&(e.output===void 0||e.state===`input-complete`||e.state===`input-streaming`||e.state===`awaiting-input`)&&(a={...e,...r.output===void 0?{}:{output:r.output},state:r.state,...r.approval===void 0?{}:{approval:r.approval},...r.metadata===void 0?{}:{metadata:r.metadata}}),i&&a.output===void 0){let e;if(Array.isArray(i.content))e=i.content;else try{e=JSON.parse(i.content)}catch{e=i.content}let t=i.state===`error`?ic(e):void 0;a={...a,output:t?{error:t}:e,state:i.state===`error`?`error`:`complete`}}return a});return r.some((t,n)=>t!==e.parts[n])?{...e,parts:r}:e})}handleTextMessageContentEvent(e){if(this.messages.some(t=>t.id===e.messageId&&t.role===`activity`)){console.warn(`TEXT_MESSAGE_CONTENT: Dropped text for '${e.messageId}', the id of an activity message`);return}let{messageId:t,state:n}=this.ensureAssistantMessage(e.messageId);if(this.mergeMessageMetadata(t,e.metadata),this.structuredMessageIds.has(t)){let r=e.delta||``;r!==``&&(this.messages=du(this.messages,t,r),n.totalTextContent+=r,this.queueStructuredOutputUpdate(t,r),this.emitMessagesChange());return}let r=n.currentSegmentText;n.hasToolCallsSinceTextStart&&r.length>0&&this.isNewTextSegment(e,r)&&(r!==n.lastEmittedText&&this.emitTextUpdateForMessage(t),n.currentSegmentText=``,n.lastEmittedText=``,n.hasToolCallsSinceTextStart=!1),n.hasToolCallsSinceTextStart=!1;let i=n.currentSegmentText,a=e.delta||``,o=a===``?i:i+a,s=o.slice(i.length);n.currentSegmentText=o,n.totalTextContent+=s;let c=e.delta||``;this.chunkStrategy.shouldEmit(c,n.currentSegmentText)&&n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(t)}handleToolCallStartEvent(e){let t=this.pendingManualMessageId,n=e.parentMessageId;if(t&&n&&n!==t){let e=this.messages.find(e=>e.id===n),r=this.messages.find(e=>e.id===t),i=this.runOfMessage(t),a=e?this.runOfMessage(e.id):void 0;e?(i===void 0||a===void 0||i===a)&&e.role===`assistant`&&r&&(this.pendingManualMessageId=null,this.messages=this.messages.filter(e=>e.id!==t).map(e=>e.id===n?{...e,parts:[...e.parts,...r.parts]}:e),this.renameMessage(t,n)):(this.pendingManualMessageId=null,this.renameMessage(t,n))}let r=e.parentMessageId??this.getActiveAssistantMessageId(),{messageId:i,state:a}=this.ensureAssistantMessage(r??void 0,e.parentMessageId===void 0),o=Y(e);this.mergeMessageMetadata(i,o===void 0?void 0:{tanstack:o}),a.hasToolCallsSinceTextStart=!0;let s=e.toolCallId;if(!a.toolCalls.get(s)){let t=`awaiting-input`,n=e.toolCallName,r=e.metadata,o={id:e.toolCallId,name:n,arguments:``,state:t,parsedArguments:void 0,index:a.toolCalls.size,...r!==void 0&&{metadata:r}};a.toolCalls.set(s,o),a.toolCallOrder.push(s),this.runToolCallIds.push(s),this.toolCallToMessage.set(s,i),this.messages=ou(this.messages,i,{id:e.toolCallId,name:n,arguments:``,state:t,...r!==void 0&&{metadata:r}}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(i,e.toolCallId,t,``)}}handleToolCallArgsEvent(e){let t=e.toolCallId,n=this.toolCallToMessage.get(t);if(!n)return;let r=this.getMessageState(n);if(!r)return;let i=r.toolCalls.get(t);if(!i)return;let a=i.state===`awaiting-input`;e.metadata!==void 0&&(i.metadata=Go(i.metadata,e.metadata)),i.arguments+=e.delta||``,a&&e.delta&&(i.state=`input-streaming`),i.parsedArguments=this.jsonParser.parse(i.arguments),this.messages=ou(this.messages,n,{id:i.id,name:i.name,arguments:i.arguments,state:i.state,...i.metadata!==void 0&&{metadata:i.metadata}}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(n,i.id,i.state,i.arguments)}handleToolCallEndEvent(e){let t=this.toolCallToMessage.get(e.toolCallId);if(!t)return;let n=this.getMessageState(t);if(!n)return;let r=n.toolCalls.get(e.toolCallId);if(r&&r.state!==`input-complete`){r.arguments=Qo(r.arguments,e).args;let i=n.toolCallOrder.indexOf(e.toolCallId);this.completeToolCall(t,i,r)}}handleToolCallResultEvent(e){let t=this.toolCallToMessage.get(e.toolCallId)??this.messages.find(t=>t.parts.some(t=>t.type===`tool-call`&&t.id===e.toolCallId))?.id;if(!t)return;let n=e,r=Y(e)?.toolResultOutcome,i=tc(r)?r:void 0,a=n.state===`output-error`||Y(e)?.state===`output-error`||i!==void 0,o;try{o=typeof e.content==`string`?JSON.parse(e.content):e.content}catch{o=e.content}this.messages=lu(this.messages,e.toolCallId,o,a?`error`:void 0);let s=a?`error`:`complete`;this.messages=su(this.messages,t,e.toolCallId,rc(o)?o:Vc(e.content),s,s===`error`?ic(o):void 0,i),this.emitMessagesChange()}handleRunStartedEvent(e){this.activeRuns.size===0&&(this.runToolCallIds=[],this.toolCallsSentToClient.clear(),this.streamEndEmitted=!1),this.activeRuns.add(e.runId)}handleRunFinishedEvent(e){let t=e,n=Y(e),r=e.model??n?.model,i=e.responseId??n?.responseId,a=this.callMessageIds.get(e.runId)??(this.activeRuns.has(e.runId)?/* @__PURE__ */ new Set:new Set(this.unassignedCallMessageIds));for(let t of a)this.mergeMessageMetadata(t,Ko(e,{...r===void 0?{}:{model:r},...i===void 0?{}:{responseId:i}}).metadata);this.pendingManualMessageId&&a.has(this.pendingManualMessageId)&&(this.pendingManualMessageId=null),this.callMessageIds.delete(e.runId);for(let e of a)this.unassignedCallMessageIds.delete(e);if(this.finishReason=t.finishReason===void 0?Y(e)?.finishReason??null:t.finishReason,this.activeRuns.delete(e.runId),e.outcome?.type===`interrupt`&&this.handleInterrupts(e.outcome.interrupts),this.activeRuns.size===0){if(this.completeAllToolCalls(),this.finishReason===`tool_calls`&&e.outcome?.type!==`interrupt`){for(let e of a)this.sealedMessageIds.add(e);return}(!e.outcome||e.outcome.type===`success`)&&this.handlePendingToolCalls(e.outcome?.pendingToolCallIds),this.isDone=!0,this.finalizeStream()}}handlePendingToolCalls(e){let t=e?.length?e.filter(e=>this.runToolCallIds.includes(e)):this.runToolCallIds,n=this.messages.flatMap(e=>e.parts??[]);for(let e of t){if(this.toolCallsSentToClient.has(e))continue;let t=n.find(t=>t.type===`tool-call`&&t.id===e);if(!t||Qs(t)||t.output!==void 0||n.some(t=>t.type===`tool-result`&&t.toolCallId===e)||this.isToolCallPartTerminal(e)||this.isToolCallPartAwaitingUserAction(e)||this.finishReason===`length`)continue;let r=t.input??Zo(t.arguments);r===void 0?console.warn(`[StreamProcessor] Did not run tool call ${e}: the arguments of ${t.name} are not complete JSON`):(this.toolCallsSentToClient.add(e),this.events.onToolCall?.({toolCallId:e,toolName:t.name,input:r}))}}handleInterrupts(e,t=!0){let n=vu(e);for(let r of e){let e=r.metadata&&typeof r.metadata==`object`?r.metadata:{},i=typeof e.kind==`string`?e.kind:void 0,a=r.toolCallId;if(!a)continue;let o=r.subagentRunId===void 0?this.childOwningToolCall(e=>e.id===a):this.childOwning(r.subagentRunId);o!==void 0&&this.updateChild(o,e=>e.handleInterrupts([r],!1));let s=typeof e.toolName==`string`?e.toolName:this.findToolCallName(a),c=Object.hasOwn(e,`input`)?e.input:{};if(i===`approval`){if(o!==void 0){t&&this.events.onApprovalRequest?.({toolCallId:a,toolName:s,input:c,approvalId:r.id});continue}let e=this.getActiveAssistantMessageId()??this.toolCallToMessage.get(a)??this.messages.find(e=>e.role===`assistant`&&e.parts.some(e=>e.type===`tool-call`&&e.id===a))?.id;if(e&&(this.messages=cu(this.messages,e,a,r.id),this.emitMessagesChange()),!t)continue;this.events.onApprovalRequest?.({toolCallId:a,toolName:s,input:c,approvalId:r.id})}else if(i===`client_tool`){if(n||!t)continue;this.toolCallsSentToClient.add(a),this.events.onToolCall?.({toolCallId:a,toolName:s,input:c})}}}findToolCallName(e){for(let t of this.messageStates.values()){let n=t.toolCalls.get(e);if(n)return n.name}return``}handleRunErrorEvent(e){this.hasError=!0;let t=pl(e)??(this.activeRuns.size===1?[...this.activeRuns][0]:void 0),n=t===void 0?this.unassignedCallMessageIds:this.callMessageIds.get(t)??this.unassignedCallMessageIds;t?this.activeRuns.delete(t):this.activeRuns.clear();let r=t!==void 0&&this.callMessageIds.has(t)&&n.size===0?void 0:this.ensureAssistantMessage([...n].at(-1)??Uc(),!1).messageId,i=new Set(n);r!==void 0&&i.add(r);for(let t of i)this.mergeMessageMetadata(t,Ko(e,{stopReason:Y(e)?.stopReason??`error`}).metadata);this.pendingManualMessageId&&i.has(this.pendingManualMessageId)&&(this.pendingManualMessageId=null),t!==void 0&&this.callMessageIds.delete(t);for(let e of i)this.unassignedCallMessageIds.delete(e);let a=e.message||`An error occurred`;e.message||console.error(`[StreamProcessor] RUN_ERROR with no message; original chunk:`,e),r!==void 0&&this.structuredMessageIds.has(r)&&(this.flushStructuredOutputUpdate(r),this.messages=pu(this.messages,r,a),this.structuredMessageIds.delete(r),this.emitStructuredOutputChange(r,`error`),this.emitMessagesChange()),this.events.onError?.(yl(e))}handleActivitySnapshotEvent(e){this.messages=ru(this.messages,e),this.emitMessagesChange()}handleActivityDeltaEvent(e){this.messages=iu(this.messages,e),this.emitMessagesChange()}handleReasoningMessageContentEvent(e){let t=this.unscopedAssistant(e),{messageId:n,state:r}=this.ensureAssistantMessage(t.id??void 0,!t.create);this.mergeMessageMetadata(n,e.metadata);let i=e.delta||``,a=r.currentThinkingStepId??e.messageId;r.thinkingSteps.has(a)||(r.thinkingSteps.set(a,``),r.thinkingStepOrder.push(a),r.currentThinkingStepId=a),this.rememberThinking(n,a,e.messageId);let o=(r.thinkingSteps.get(a)??``)+i;r.thinkingSteps.set(a,o),this.messages=mu(this.messages,n,a,o,r.thinkingStepSignatures.get(a)),this.emitMessagesChange(),this.events.onThinkingUpdate?.(n,a,o)}handleReasoningEncryptedValueEvent(e){let t=e.encryptedValue;if(typeof t!=`string`||t===``)return;if(e.subtype===`tool-call`){this.attachToolCallSignature(e.entityId,t);return}if(this.applyKnownSignature(e.entityId,t))return;let n=this.unscopedAssistant(e),{messageId:r,state:i}=this.ensureAssistantMessage(n.id??void 0,!n.create),a=i.currentThinkingStepId??e.entityId;this.rememberThinking(r,a,e.entityId),this.mergeMessageMetadata(r,e.metadata),i.thinkingStepSignatures.set(a,t);let o=i.thinkingSteps.get(a)??``;i.thinkingSteps.has(a)||(i.thinkingSteps.set(a,o),i.thinkingStepOrder.push(a)),this.messages=mu(this.messages,r,a,o,t),this.emitMessagesChange()}attachToolCallSignature(e,t){this.messages=this.messages.map(n=>{let r=!1,i=n.parts.map(n=>n.type!==`tool-call`||n.id!==e?n:(r=!0,{...n,metadata:{...n.metadata!=null&&typeof n.metadata==`object`?n.metadata:{},thoughtSignature:t}}));return r?{...n,parts:i}:n});for(let n of this.messageStates.values()){let r=n.toolCalls.get(e);r&&(r.metadata={...r.metadata??{},thoughtSignature:t})}this.emitMessagesChange()}handleCustomEvent(e){let t=this.getActiveAssistantMessageId();if(e.name===`structured-output.start`&&e.value){let n=e.value,{messageId:r}=this.ensureAssistantMessage(n.messageId&&this.getMessageState(n.messageId)?n.messageId:t??n.messageId);r&&(this.structuredMessageIds.add(r),this.structuredOutputUpdateBatches.delete(r),this.events.onStructuredOutputChange?.({phase:`start`,messageId:r,status:`streaming`,raw:``}))}else{if(e.name===`structured-output.complete`&&e.value){let n=e.value,{messageId:r}=this.ensureAssistantMessage(n.messageId&&this.getMessageState(n.messageId)?n.messageId:t??n.messageId);r&&(this.flushStructuredOutputUpdate(r),this.messages=fu(this.messages,r,n.object,n.raw??``,n.reasoning),this.structuredMessageIds.delete(r),this.emitStructuredOutputChange(r,`complete`),this.emitMessagesChange())}if(e.name===`ui-resource`&&e.value){let n=e.value,r=this.toolCallToMessage.get(n.toolCallId)??t;if(r){let e={type:`ui-resource`,resource:n.resource,toolCallId:n.toolCallId,toolName:n.toolName,...n.serverId!==void 0&&{serverId:n.serverId},...n.meta!==void 0&&{meta:n.meta}};this.messages=this.messages.map(t=>t.id===r?{...t,parts:[...t.parts,e]}:t),this.emitMessagesChange()}else console.warn(`[mcp-apps] dropped ui-resource: no target message for toolCallId "${n.toolCallId}" (toolName "${n.toolName}")`)}else if(this.events.onCustomEvent){let t=e.value&&typeof e.value==`object`?e.value.toolCallId:void 0;this.events.onCustomEvent(e.name,e.value,{toolCallId:t})}}}isNewTextSegment(e,t){return!0}completeAllToolCalls(){for(let e of this.activeMessageIds)this.completeAllToolCallsForMessage(e)}completeAllToolCallsForMessage(e){let t=this.getMessageState(e);t&&t.toolCalls.forEach((n,r)=>{if(n.state!==`input-complete`){let i=t.toolCallOrder.indexOf(r);this.completeToolCall(e,i,n)}})}completeToolCall(e,t,n){n.state=`input-complete`;let r=!1;try{n.parsedArguments=JSON.parse(n.arguments),r=!0}catch{n.parsedArguments=void 0}this.isToolCallPartTerminal(n.id)||this.isToolCallPartAwaitingUserAction(n.id)||(this.messages=ou(this.messages,e,{id:n.id,name:n.name,arguments:n.arguments,state:`input-complete`,...r&&{input:n.parsedArguments},...n.metadata!==void 0&&{metadata:n.metadata}}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(e,n.id,`input-complete`,n.arguments))}isToolCallPartAwaitingUserAction(e){return this.messages.some(t=>t.parts?.some(t=>t.type===`tool-call`&&t.id===e&&(t.state===`approval-requested`||t.state===`approval-responded`)))}isToolCallPartTerminal(e){return this.messages.some(t=>t.parts?.some(t=>t.type===`tool-call`&&t.id===e&&(t.state===`error`||t.state===`complete`)))}emitTextUpdateForMessage(e){let t=this.getMessageState(e);t&&(t.lastEmittedText=t.currentSegmentText,this.messages=au(this.messages,e,t.currentSegmentText),this.emitMessagesChange(),this.events.onTextUpdate?.(e,t.currentSegmentText))}queueStructuredOutputUpdate(e,t){let n=this.structuredOutputUpdateBatches.get(e),r={delta:`${n?.delta??``}${t}`,chunkCount:(n?.chunkCount??0)+1};this.structuredOutputUpdateBatches.set(e,r),r.chunkCount>=hu&&this.flushStructuredOutputUpdate(e)}flushStructuredOutputUpdate(e){let t=this.structuredOutputUpdateBatches.get(e);t&&t.chunkCount!==0&&(this.structuredOutputUpdateBatches.delete(e),this.emitStructuredOutputChange(e,`update`,t.delta))}emitStructuredOutputChange(e,t,n){let r=this.messages.find(t=>t.id===e)?.parts.find(e=>e.type===`structured-output`);r&&this.events.onStructuredOutputChange?.({phase:t,messageId:e,status:r.status,raw:r.raw,...r.partial===void 0?{}:{partial:r.partial},...r.data===void 0?{}:{data:r.data},...r.reasoning===void 0?{}:{reasoning:r.reasoning},...r.errorMessage===void 0?{}:{errorMessage:r.errorMessage},...n===void 0?{}:{delta:n}})}emitMessagesChange(){this.events.onMessagesChange?.([...this.messages])}finalizeStream(){this.isDone=!0;for(let e of this.closeChunk())this.dispatchChunk(e);this.closeChildChunkLanes();let e;for(let t of this.activeMessageIds){let n=this.getMessageState(t);if(!n)continue;this.completeAllToolCallsForMessage(t),n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(t),n.isComplete=!0;let r=this.messages.find(e=>e.id===t);r&&r.role===`assistant`&&(e=r)}for(let e of this.structuredMessageIds)this.flushStructuredOutputUpdate(e),this.messages=pu(this.messages,e,`Stream ended without structured-output.complete`),this.emitStructuredOutputChange(e,`error`);this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.activeMessageIds.clear(),e&&!this.hasError&&this.isWhitespaceOnlyMessage(e)?(this.messages=this.messages.filter(t=>t.id!==e.id),this.emitMessagesChange()):e&&!this.streamEndEmitted&&(this.streamEndEmitted=!0,this.events.onStreamEnd?.(e))}getCompletedToolCalls(){let e=[];for(let t of this.messageStates.values())for(let n of t.toolCalls.values())n.state===`input-complete`&&e.push({id:n.id,type:`function`,function:{name:n.name,arguments:n.arguments},...n.metadata!==void 0&&{metadata:n.metadata}});return e}getResult(){let e=this.getCompletedToolCalls(),t=``,n=``;for(let e of this.messageStates.values()){t+=e.totalTextContent;for(let t of e.thinkingStepOrder)n+=e.thinkingSteps.get(t)??``}return{content:t,thinking:n||void 0,toolCalls:e.length>0?e:void 0,finishReason:this.finishReason}}getState(){let e=``,t=``,n=/* @__PURE__ */ new Map,r=[];for(let i of this.messageStates.values()){e+=i.totalTextContent;for(let e of i.thinkingStepOrder)t+=i.thinkingSteps.get(e)??``;for(let[e,t]of i.toolCalls)n.set(e,t);r.push(...i.toolCallOrder)}return{content:e,thinking:t,toolCalls:n,toolCallOrder:r,finishReason:this.finishReason,done:this.isDone}}startRecording(){this.recordingEnabled=!0,this.recordingStartTime=Date.now(),this.recording={version:`1.0`,timestamp:this.recordingStartTime,chunks:[]}}getRecording(){return this.recording}resetStreamState(){this.messageStates.clear(),this.callMessageIds.clear(),this.unassignedCallMessageIds.clear(),this.activeMessageIds.clear(),this.activeRuns.clear(),this.toolCallToMessage.clear(),this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.pendingManualMessageId=null,this.sealedMessageIds.clear(),this.thinkingOwners.clear(),this.openChunk=null,this.finishReason=null,this.hasError=!1,this.isDone=!1,this.streamEndEmitted=!1,this.chunkStrategy.reset?.()}reset(){this.resetStreamState(),this.messages=[],this.childProcessors.clear(),this.childToolCalls.clear()}isWhitespaceOnlyMessage(e){return e.parts.length!==0&&e.parts.every(e=>e.type===`text`&&e.content.trim()===``)}static async replay(t,n){return new e(n).process(bu(t))}};function bu(e){return{async*[Symbol.asyncIterator](){for(let{chunk:t}of e.chunks)yield t}}}var xu=class extends Error{provider;constructor(e){super(`Missing ${e} API key`),this.name=`ByokMissingError`,this.provider=e}},Su=class extends Error{provider;reason;constructor(e,t){super(t===`locked`?`${e} key is locked`:`Missing ${e} API key`),this.name=`ByokBlockedError`,this.provider=e,this.reason=t}},Cu=class extends Error{constructor(){super(`BYOK is enabled but no provider slug was resolved. Pass byokProvider or forwardedProps.provider.`),this.name=`ByokUnresolvedProviderError`}},wu=/^[a-z][a-z0-9-]{0,63}$/;function Tu(e){return typeof e==`string`&&wu.test(e)}function Eu(e){if(typeof e!=`object`||!e||!(`error`in e))return!1;let t=e.error;return!(typeof t!=`object`||!t||!(`type`in t)||t.type!==`byok_missing`||!(`provider`in t)||typeof t.provider!=`string`||!Tu(t.provider)||!(`message`in t)||typeof t.message!=`string`)}var Du=/* @__PURE__ */ new WeakMap;function Ou(e){return Du.get(e)??pl(e)}var ku=class extends Error{constructor(){super(`Stream ended with unterminated trailing data — connection was likely cut short.`),this.name=`StreamTruncatedError`}},Au=class extends Error{constructor(e){super(`Stream response body read failed`,{cause:e}),this.name=`StreamReadError`}},ju=class extends Error{constructor(){super(`Durable run ended without a terminal event and could not resume — the run did not complete.`),this.name=`DurableStreamIncompleteError`}},Mu=class extends Error{constructor(e,t){super(t===void 0?`Durable run exceeded its reconnect ceiling of ${e} attempts — giving up.`:`Durable run did not reconnect within its budget of ${t} ms (${e} attempts) — giving up.`),this.name=`StreamReconnectLimitError`}},Nu=/* @__PURE__ */ new Set([408,429,502,503,504]),Pu=class extends Error{status;retryAfterMs;constructor(e,t,n){super(e),this.status=t,this.name=`StreamHttpError`,this.retryAfterMs=Fu(n)}};function Fu(e){if(!e)return;let t=Number(e);if(Number.isFinite(t))return t>=0?t*1e3:void 0;let n=Date.parse(e);return Number.isNaN(n)?void 0:Math.max(0,n-Date.now())}function Iu(e){return e instanceof Pu&&Nu.has(e.status)}function Lu(e){let t=e?.budgetMs,n=e?.maxAttempts??(t===void 0?5:1/0),r=e?.initialDelayMs??e?.delayMs??250,i=e?.maxDelayMs??Math.max(5e3,r);if(e?.maxAttempts!==void 0&&(!Number.isInteger(n)||n<0))throw Error(`Invalid reconnect.maxAttempts: ${n}. Must be a non-negative integer.`);for(let[e,t]of[[`initialDelayMs`,r],[`maxDelayMs`,i]])if(!Number.isFinite(t)||t<0)throw Error(`Invalid reconnect.${e}: ${t}. Must be a non-negative finite number.`);if(t!==void 0&&(!Number.isFinite(t)||t<=0))throw Error(`Invalid reconnect.budgetMs: ${t}. Must be a positive finite number.`);return{maxAttempts:n,initialDelayMs:r,maxDelayMs:i,budgetMs:t}}function Ru(e){let t=Lu(e),n=/* @__PURE__ */ new Set,r,i=0,a;return{get lastEventId(){return r},note(e){return e===void 0?`new`:e===``?(r=void 0,n.clear(),`reset`):n.has(e)?`duplicate`:(n.add(e),r=e,`new`)},async waitBeforeReconnect(e,n,r){if(e)i=0,a=void 0;else if(i+=1,a??=Date.now(),i>t.maxAttempts)throw new Mu(t.maxAttempts);let o=t.initialDelayMs===0?0:Math.min(t.maxDelayMs,t.initialDelayMs*2**Math.max(0,i-1)),s=r===void 0?o*(.5+Math.random()/2):Math.min(r,t.maxDelayMs);if(t.budgetMs!==void 0&&a!==void 0&&Date.now()-a+s>t.budgetMs)throw new Mu(i-1,t.budgetMs);await zu(s,n)}}}function zu(e,t){return e<=0||t?.aborted?Promise.resolve():new Promise(n=>{let r=()=>{clearTimeout(i),n()},i=setTimeout(()=>{t?.removeEventListener(`abort`,r),n()},e);t?.addEventListener(`abort`,r,{once:!0})})}function Bu(e){if(!e)return{};if(e instanceof Headers){let t={};return e.forEach((e,n)=>{t[n]=e}),t}return e}var Vu=`X-Run-Id`;function Hu(e){return{[Vu]:e}}function Uu(e,t){let n=e.indexOf(`#`),r=n===-1?``:e.slice(n),i=n===-1?e:e.slice(0,n),a=i.indexOf(`?`),o=a===-1?i:i.slice(0,a),s=new URLSearchParams(a===-1?``:i.slice(a+1));for(let[e,n]of Object.entries(t))s.set(e,n);let c=s.toString();return`${o}${c.length===0?``:`?${c}`}${r}`}async function*Wu(e,t){try{let n=Fo(),r=``;for(;!t?.aborted;){let i;try{i=await e.read()}catch(e){if(t?.aborted)return;throw new Au(e)}let{done:a,value:o}=i;if(a)break;r+=n.decode(o,{stream:!0});let s=r.split(`
|
|
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
|
+
`),...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
|
+
`+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(`
|
|
149
|
+
|
|
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),`
|
|
149
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(`
|
|
150
152
|
`)||s.write(`
|
|
151
|
-
`)}async function
|
|
152
|
-
`);try{for(;;){let n=(await t.question(`> `).catch(()=>`/exit`)).trim();if(n===`/exit`)return;n&&await
|
|
153
|
-
`),ni({path:n},K.json)}),e}const
|
|
153
|
+
`)}async function Tm(e){let t=fe({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 de(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
|
+
`),ni({path:n},K.json)}),e}const km=`
|
|
154
156
|
Environment:
|
|
155
157
|
ASTRALBEAM_API_KEY organization API key, used instead of directory logins
|
|
156
158
|
ASTRALBEAM_API_URL override the saved API URL (default ${oi})
|
|
157
159
|
ASTRALBEAM_CONFIG_DIR directory holding config.json
|
|
158
160
|
|
|
159
161
|
Exit codes: 0 success, 1 API or runtime failure, 2 parser usage errors.
|
|
160
|
-
Docs: https://astralbeam.ai/docs/cli/getting-started`;async function
|
|
162
|
+
Docs: https://astralbeam.ai/docs/cli/getting-started`;async function Am(e){let t=e.includes(`--json`),n=e.includes(`--debug`),r=$n(e.slice(2)).scriptName(`astralbeam`).version(Zr).option(`json`,{type:`boolean`,default:!1,description:`Print JSON instead of human-readable output`}).option(`debug`,{type:`boolean`,default:!1,description:`Log HTTP requests and errors without headers`}).strict().demandCommand(1).help().exitProcess(!1).fail((e,t)=>{throw new er(e||t?.message||`Invalid command.`)}).epilog(km).alias(`q`,`search`).command(Object.values(Oa)).command(`auth`,`Bind organization API keys to directories, and check them`,Na).command(`token`,`Mint short-lived JWTs offline with the organization API key`,Sm).command(`skill`,`Print or install the AstralBeam integration skill`,Om);Em(r),Object.assign(K,{json:t,context:void 0,failedRequest:void 0});let i=globalThis.fetch;globalThis.fetch=jm(i,n);try{return await r.parseAsync(),t&&a.write(`${JSON.stringify({context:K.context??null})}\n`),0}catch(e){return n&&e instanceof Error&&a.write(`[debug] ${e.stack}\n`),ai(e,t,K.context,K.failedRequest),e instanceof er?2:1}finally{globalThis.fetch=i}}function jm(e,t){return Object.assign(async(...[n,r])=>{let i=r?.method??(n instanceof Request?n.method:`GET`),o=n instanceof Request?n.url:String(n),s=performance.now();t&&a.write(`[debug] → ${i} ${o}\n`);let c;try{c=await e(n,r)}catch(e){if(!(e instanceof TypeError))throw e;let t=e.cause instanceof Error?e.cause.message:e.message;throw Error(`Could not reach ${o}: ${t}`,{cause:e})}let l=Math.round(performance.now()-s);return t&&a.write(`[debug] ← ${c.status} ${c.statusText} (${l} ms)\n`),c.ok||(K.failedRequest=`${i} ${o}`),c},e)}export{Am as run};
|