@astralbeam/cli 0.30.7 → 0.30.8

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 _,statSync as v,writeFile as ee}from"fs";import{format as y,inspect as te}from"util";import{fileURLToPath as ne}from"url";import{mkdir as re,readFile as b,realpath as x,rename as ie,rm as S,writeFile as C}from"node:fs/promises";import{isIPv4 as w}from"node:net";import{homedir as ae}from"node:os";import{dirname as oe,join as se,resolve as ce,sep as T}from"node:path";import{readFileSync as le}from"node:fs";import{text as ue}from"node:stream/consumers";import{createInterface as E}from"node:readline/promises";var de=Object.defineProperty,D=(e,t)=>{let n=Object.setPrototypeOf({},null);for(var r in e)de(n,r,{get:e[r],enumerable:!0});return t&1||de(n,Symbol.toStringTag,{value:`Module`}),t&2?n:Object.preventExtensions(n)},fe=/* @__PURE__ */ e(import.meta.url);const pe={right:_e,center:k};var me=class{constructor(e){this.width=e.width,this.wrap=e.wrap??!0,this.rows=[]}span(...e){let t=this.div(...e);t.span=!0}resetOutput(){this.rows=[]}div(...e){if(e.length===0&&this.div(``),this.wrap&&this.shouldApplyLayoutDSL(...e)&&typeof e[0]==`string`)return this.applyLayoutDSL(e[0]);let t=e.map(e=>typeof e==`string`?this.colFromString(e):e);return this.rows.push(t),t}shouldApplyLayoutDSL(...e){return e.length===1&&typeof e[0]==`string`&&/[\t\n]/.test(e[0])}applyLayoutDSL(e){let t=e.split(`
2
- `).map(e=>e.split(` `)),n=0;return t.forEach(e=>{e.length>1&&A.stringWidth(e[0])>n&&(n=Math.min(Math.floor(this.width*.5),A.stringWidth(e[0])))}),t.forEach(e=>{this.div(...e.map((t,r)=>({text:t.trim(),padding:this.measurePadding(t),width:r===0&&e.length>1?n:void 0})))}),this.rows[this.rows.length-1]}colFromString(e){return{text:e,padding:this.measurePadding(e)}}measurePadding(e){let t=A.stripAnsi(e);return[0,t.match(/\s*$/)[0].length,0,t.match(/^\s*/)[0].length]}toString(){let e=[];return this.rows.forEach(t=>{this.rowToString(t,e)}),e.filter(e=>!e.hidden).map(e=>e.text).join(`
3
- `)}rowToString(e,t){return this.rasterize(e).forEach((n,r)=>{let i=``;n.forEach((n,a)=>{let{width:o}=e[a],s=this.negatePadding(e[a]),c=n;if(s>A.stringWidth(n)&&(c+=` `.repeat(s-A.stringWidth(n))),e[a].align&&e[a].align!==`left`&&this.wrap){let t=pe[e[a].align];c=t(c,s),A.stringWidth(c)<s&&(c+=` `.repeat((o||0)-A.stringWidth(c)-1))}let l=e[a].padding||[0,0,0,0];l[3]&&(i+=` `.repeat(l[3])),i+=he(e[a],c,`| `),i+=c,i+=he(e[a],c,` |`),l[1]&&(i+=` `.repeat(l[1])),r===0&&t.length>0&&(i=this.renderInline(i,t[t.length-1]))}),t.push({text:i.replace(/ +$/,``),span:e.span})}),t}renderInline(e,t){let n=e.match(/^ */),r=n?n[0].length:0,i=t.text,a=A.stringWidth(i.trimRight());return t.span?this.wrap?r<a?e:(t.hidden=!0,i.trimRight()+` `.repeat(r-a)+e.trimLeft()):(t.hidden=!0,i+e):e}rasterize(e){let t=[],n=this.columnWidths(e),r;return e.forEach((e,i)=>{e.width=n[i],r=this.wrap?A.wrap(e.text,this.negatePadding(e),{hard:!0}).split(`
1
+ import{createRequire as e}from"node:module";import{cwd as t,env as n,pid as r,platform as i,stderr as a,stdin as o,stdout as s}from"node:process";import{notStrictEqual as c,strictEqual as l}from"assert";import{basename as u,dirname as d,extname as f,normalize as p,relative as m,resolve as h}from"path";import{readFileSync as g,readdirSync as _,statSync as v,writeFile as ee}from"fs";import{format as y,inspect as te}from"util";import{fileURLToPath as ne}from"url";import{mkdir as re,readFile as b,realpath as x,rename as ie,rm as ae,rmdir as S,writeFile as oe}from"node:fs/promises";import{isIPv4 as se}from"node:net";import{homedir as ce}from"node:os";import{dirname as C,join as le,resolve as ue,sep as de}from"node:path";import{setTimeout as fe}from"node:timers/promises";import{readFileSync as w}from"node:fs";import{text as pe}from"node:stream/consumers";import{createInterface as T}from"node:readline/promises";var me=Object.defineProperty,he=(e,t)=>{let n=Object.setPrototypeOf({},null);for(var r in e)me(n,r,{get:e[r],enumerable:!0});return t&1||me(n,Symbol.toStringTag,{value:`Module`}),t&2?n:Object.preventExtensions(n)},ge=/* @__PURE__ */ e(import.meta.url);const _e={right:E,center:Se};var ve=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&&D.stringWidth(e[0])>n&&(n=Math.min(Math.floor(this.width*.5),D.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=D.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>D.stringWidth(n)&&(c+=` `.repeat(s-D.stringWidth(n))),e[a].align&&e[a].align!==`left`&&this.wrap){let t=_e[e[a].align];c=t(c,s),D.stringWidth(c)<s&&(c+=` `.repeat((o||0)-D.stringWidth(c)-1))}let l=e[a].padding||[0,0,0,0];l[3]&&(i+=` `.repeat(l[3])),i+=ye(e[a],c,`| `),i+=c,i+=ye(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=D.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?D.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||A.stringWidth(e.text));let t=e.length,n=this.width,r=e.map(e=>{if(e.width)return t--,n-=e.width,e.width}),i=t?Math.floor(n/t):0;return r.map((t,n)=>t===void 0?Math.max(i,ge(e[n])):t)}};function he(e,t,n){return e.border?/[.']-+[.']/.test(t)?``:t.trim().length===0?` `:n:``}function ge(e){let t=e.padding||[],n=1+(t[3]||0)+(t[1]||0);return e.border?n+4:n}function O(){return typeof process==`object`&&process.stdout&&process.stdout.columns?process.stdout.columns:80}function _e(e,t){e=e.trim();let n=A.stringWidth(e);return n<t?` `.repeat(t-n)+e:e}function k(e,t){e=e.trim();let n=A.stringWidth(e);return n>=t?e:` `.repeat(t-n>>1)+e}let A;function ve(e,t){return A=t,new me({width:e?.width||O(),wrap:e?.wrap})}const ye=/* @__PURE__ */ RegExp(`\x1B(?:\\[(?:\\d+[ABCDEFGJKSTm]|\\d+;\\d+[Hfm]|\\d+;\\d+;\\d+m|6n|s|u|\\?25[lh])|\\w)`,`g`);function be(e){return e.replace(ye,``)}function xe(e,t){let[n,r]=e.match(ye)||[``,``];e=be(e);let i=``;for(let n=0;n<e.length;n++)n!==0&&n%t===0&&(i+=`
6
- `),i+=e.charAt(n);return n&&r&&(i=`${n}${i}${r}`),i}function Se(e){return ve(e,{stringWidth:e=>[...e].length,stripAnsi:be,wrap:xe})}function j(e,t){let n=h(`.`,e),r;for(v(n).isDirectory()||(n=d(n));;){if(r=t(n,_(n)),r)return h(n,r);if(n=d(r=n),r===n)break}}
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||D.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,be(e[n])):t)}};function ye(e,t,n){return e.border?/[.']-+[.']/.test(t)?``:t.trim().length===0?` `:n:``}function be(e){let t=e.padding||[],n=1+(t[3]||0)+(t[1]||0);return e.border?n+4:n}function xe(){return typeof process==`object`&&process.stdout&&process.stdout.columns?process.stdout.columns:80}function E(e,t){e=e.trim();let n=D.stringWidth(e);return n<t?` `.repeat(t-n)+e:e}function Se(e,t){e=e.trim();let n=D.stringWidth(e);return n>=t?e:` `.repeat(t-n>>1)+e}let D;function O(e,t){return D=t,new ve({width:e?.width||xe(),wrap:e?.wrap})}const Ce=/* @__PURE__ */ RegExp(`\x1B(?:\\[(?:\\d+[ABCDEFGJKSTm]|\\d+;\\d+[Hfm]|\\d+;\\d+;\\d+m|6n|s|u|\\?25[lh])|\\w)`,`g`);function we(e){return e.replace(Ce,``)}function Te(e,t){let[n,r]=e.match(Ce)||[``,``];e=we(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 Ee(e){return O(e,{stringWidth:e=>[...e].length,stripAnsi:we,wrap:Te})}function De(e,t){let n=h(`.`,e),r;for(v(n).isDirectory()||(n=d(n));;){if(r=t(n,_(n)),r)return h(n,r);if(n=d(r=n),r===n)break}}
7
7
  /**
8
8
  * @license
9
9
  * Copyright (c) 2016, Contributors
10
10
  * SPDX-License-Identifier: ISC
11
11
  */
12
- function Ce(e){if((e===e.toLowerCase()||e===e.toUpperCase())&&(e=e.toLowerCase()),e.indexOf(`-`)===-1&&e.indexOf(`_`)===-1)return e;{let t=``,n=!1,r=e.match(/^-+/);for(let i=r?r[0].length:0;i<e.length;i++){let r=e.charAt(i);n&&(n=!1,r=r.toUpperCase()),i!==0&&(r===`-`||r===`_`)?n=!0:r!==`-`&&r!==`_`&&(t+=r)}return t}}function we(e,t){let n=e.toLowerCase();t||=`-`;let r=``;for(let i=0;i<e.length;i++){let a=n.charAt(i),o=e.charAt(i);r+=a!==o&&i>0?`${t}${n.charAt(i)}`:o}return r}function Te(e){return e==null?!1:typeof e==`number`||/^0x[0-9a-f]+$/i.test(e)?!0:!/^0[^.]/.test(e)&&/^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(e)}
12
+ function Oe(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 k(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 ke(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 Ee(e){if(Array.isArray(e))return e.map(e=>typeof e==`string`?e:e+``);e=e.trim();let t=0,n=null,r=null,i=null,a=[];for(let o=0;o<e.length;o++)n=r,r=e.charAt(o),r===` `&&!i?n!==` `&&t++:(r===i?i=null:r!==`'`&&r!==`"`||i||(i=r),a[t]||(a[t]=``),a[t]+=r);return a}
18
+ function Ae(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 M;(function(e){e.BOOLEAN=`boolean`,e.STRING=`string`,e.NUMBER=`number`,e.ARRAY=`array`})(M||={});
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 De;var Oe=class{constructor(e){De=e}parse(e,t){let n=Object.assign({alias:void 0,array:void 0,boolean:void 0,config:void 0,configObjects:void 0,configuration:void 0,coerce:void 0,count:void 0,default:void 0,envPrefix:void 0,narg:void 0,normalize:void 0,string:void 0,number:void 0,__:void 0,key:void 0},t),r=Ee(e),i=typeof e==`string`,a=ke(Object.assign(Object.create(null),n.alias)),o=Object.assign({"boolean-negation":!0,"camel-case-expansion":!0,"combine-arrays":!1,"dot-notation":!0,"duplicate-arguments-array":!0,"flatten-duplicate-arrays":!0,"greedy-arrays":!0,"halt-at-non-option":!1,"nargs-eats-options":!1,"negation-prefix":`no-`,"parse-numbers":!0,"parse-positional-numbers":!0,"populate--":!1,"set-placeholder-key":!1,"short-option-groups":!0,"strip-aliased":!1,"strip-dashed":!1,"unknown-options-as-args":!1},n.configuration),s=Object.assign(Object.create(null),n.default),c=n.configObjects||[],l=n.envPrefix,u=o[`populate--`],d=u?`--`:`_`,f=Object.create(null),p=Object.create(null),m=n.__||De.format,h={aliases:Object.create(null),arrays:Object.create(null),bools:Object.create(null),strings:Object.create(null),numbers:Object.create(null),counts:Object.create(null),normalize:Object.create(null),configs:Object.create(null),nargs:Object.create(null),coercions:Object.create(null),keys:[]},g=/^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/,_=RegExp(`^--`+o[`negation-prefix`]+`(.+)`);[].concat(n.array||[]).filter(Boolean).forEach(function(e){let t=typeof e==`object`?e.key:e,n=Object.keys(e).map(function(e){return{boolean:`bools`,string:`strings`,number:`numbers`}[e]}).filter(Boolean).pop();n&&(h[n][t]=!0),h.arrays[t]=!0,h.keys.push(t)}),[].concat(n.boolean||[]).filter(Boolean).forEach(function(e){h.bools[e]=!0,h.keys.push(e)}),[].concat(n.string||[]).filter(Boolean).forEach(function(e){h.strings[e]=!0,h.keys.push(e)}),[].concat(n.number||[]).filter(Boolean).forEach(function(e){h.numbers[e]=!0,h.keys.push(e)}),[].concat(n.count||[]).filter(Boolean).forEach(function(e){h.counts[e]=!0,h.keys.push(e)}),[].concat(n.normalize||[]).filter(Boolean).forEach(function(e){h.normalize[e]=!0,h.keys.push(e)}),typeof n.narg==`object`&&Object.entries(n.narg).forEach(([e,t])=>{typeof t==`number`&&(h.nargs[e]=t,h.keys.push(e))}),typeof n.coerce==`object`&&Object.entries(n.coerce).forEach(([e,t])=>{typeof t==`function`&&(h.coercions[e]=t,h.keys.push(e))}),n.config!==void 0&&(Array.isArray(n.config)||typeof n.config==`string`?[].concat(n.config).filter(Boolean).forEach(function(e){h.configs[e]=!0}):typeof n.config==`object`&&Object.entries(n.config).forEach(([e,t])=>{(typeof t==`boolean`||typeof t==`function`)&&(h.configs[e]=t)})),de(n.key,a,n.default,h.arrays),Object.keys(s).forEach(function(e){(h.aliases[e]||[]).forEach(function(t){s[t]=s[e]})});let v=null;ve();let ee=[],y=Object.assign(Object.create(null),{_:[]}),te={};for(let e=0;e<r.length;e++){let t=r[e],n=t.replace(/^-{3,}/,`---`),i,a,s,c,l,u;if(t!==`--`&&/^-/.test(t)&&he(t))ne(t);else if(n.match(/^---+(=|$)/)){ne(t);continue}else if(t.match(/^--.+=/)||!o[`short-option-groups`]&&t.match(/^-.+=/))c=t.match(/^--?([^=]+)=([\s\S]*)$/),c!==null&&Array.isArray(c)&&c.length>=3&&(D(c[1],h.arrays)?e=b(e,c[1],r,c[2]):D(c[1],h.nargs)===!1?x(c[1],c[2],!0):e=re(e,c[1],r,c[2]));else if(t.match(_)&&o[`boolean-negation`])c=t.match(_),c!==null&&Array.isArray(c)&&c.length>=2&&(a=c[1],x(a,D(a,h.arrays)?[!1]:!1));else if(t.match(/^--.+/)||!o[`short-option-groups`]&&t.match(/^-[^-]+/))c=t.match(/^--?(.+)/),c!==null&&Array.isArray(c)&&c.length>=2&&(a=c[1],D(a,h.arrays)?e=b(e,a,r):D(a,h.nargs)===!1?(l=r[e+1],l!==void 0&&(!l.match(/^-/)||l.match(g))&&!D(a,h.bools)&&!D(a,h.counts)||/^(true|false)$/.test(l)?(x(a,l),e++):x(a,O(a))):e=re(e,a,r));else if(t.match(/^-.\..+=/))c=t.match(/^-([^=]+)=([\s\S]*)$/),c!==null&&Array.isArray(c)&&c.length>=3&&x(c[1],c[2]);else if(t.match(/^-.\..+/)&&!t.match(g))l=r[e+1],c=t.match(/^-(.\..+)/),c!==null&&Array.isArray(c)&&c.length>=2&&(a=c[1],l!==void 0&&!l.match(/^-/)&&!D(a,h.bools)&&!D(a,h.counts)?(x(a,l),e++):x(a,O(a)));else if(t.match(/^-[^-]+/)&&!t.match(g)){s=t.slice(1,-1).split(``),i=!1;for(let n=0;n<s.length;n++){if(l=t.slice(n+2),s[n+1]&&s[n+1]===`=`){u=t.slice(n+3),a=s[n],D(a,h.arrays)?e=b(e,a,r,u):D(a,h.nargs)===!1?x(a,u):e=re(e,a,r,u),i=!0;break}if(l===`-`)x(s[n],l);else{if(/[A-Za-z]/.test(s[n])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(l)&&D(l,h.bools)===!1||s[n+1]&&s[n+1].match(/\W/)){x(s[n],l),i=!0;break}x(s[n],O(s[n]))}}a=t.slice(-1)[0],!i&&a!==`-`&&(D(a,h.arrays)?e=b(e,a,r):D(a,h.nargs)===!1?(l=r[e+1],l!==void 0&&(!/^(-|--)[^-]/.test(l)||l.match(g))&&!D(a,h.bools)&&!D(a,h.counts)||/^(true|false)$/.test(l)?(x(a,l),e++):x(a,O(a))):e=re(e,a,r))}else if(t.match(/^-[0-9]$/)&&t.match(g)&&D(t.slice(1),h.bools))a=t.slice(1),x(a,O(a));else if(t===`--`){ee=r.slice(e+1);break}else if(o[`halt-at-non-option`]){ee=r.slice(e);break}else ne(t)}se(y,!0),se(y,!1),w(y),oe(),le(y,h.aliases,s,!0),ce(y),o[`set-placeholder-key`]&&T(y),Object.keys(h.counts).forEach(function(e){ue(y,e.split(`.`))||x(e,0)}),u&&ee.length&&(y[d]=[]),ee.forEach(function(e){y[d].push(e)}),o[`camel-case-expansion`]&&o[`strip-dashed`]&&Object.keys(y).filter(e=>e!==`--`&&e.includes(`-`)).forEach(e=>{delete y[e]}),o[`strip-aliased`]&&[].concat(...Object.keys(a).map(e=>a[e])).forEach(e=>{o[`camel-case-expansion`]&&e.includes(`-`)&&delete y[e.split(`.`).map(e=>Ce(e)).join(`.`)],delete y[e]});function ne(e){let t=C(`_`,e);(typeof t==`string`||typeof t==`number`)&&y._.push(t)}function re(e,t,n,r){let i,a=D(t,h.nargs);if(a=typeof a!=`number`||isNaN(a)?1:a,a===0)return A(r)||(v=Error(m(`Argument unexpected for: %s`,t))),x(t,O(t)),e;let s=+!A(r);if(o[`nargs-eats-options`])n.length-(e+1)+s<a&&(v=Error(m(`Not enough arguments following: %s`,t))),s=a;else{for(i=e+1;i<n.length&&(!n[i].match(/^-[^0-9]/)||n[i].match(g)||he(n[i]));i++)s++;s<a&&(v=Error(m(`Not enough arguments following: %s`,t)))}let c=Math.min(s,a);for(!A(r)&&c>0&&(x(t,r),c--),i=e+1;i<c+e+1;i++)x(t,n[i]);return e+c}function b(e,t,n,r){let a=[],c=r||n[e+1],l=D(t,h.nargs);if(D(t,h.bools)&&!/^(true|false)$/.test(c))a.push(!0);else if(A(c)||A(r)&&/^-/.test(c)&&!g.test(c)&&!he(c)){if(s[t]!==void 0){let e=s[t];a=Array.isArray(e)?e:[e]}}else{A(r)||a.push(S(t,r,!0));for(let r=e+1;r<n.length&&!(!o[`greedy-arrays`]&&a.length>0||l&&typeof l==`number`&&a.length>=l||(c=n[r],/^-/.test(c)&&!g.test(c)&&!he(c)));r++)e=r,a.push(S(t,c,i))}return typeof l==`number`&&(l&&a.length<l||isNaN(l)&&a.length===0)&&(v=Error(m(`Not enough arguments following: %s`,t))),x(t,a),e}function x(e,t,n=i){/-/.test(e)&&o[`camel-case-expansion`]&&ie(e,e.split(`.`).map(function(e){return Ce(e)}).join(`.`));let r=S(e,t,n),a=e.split(`.`);E(y,a,r),h.aliases[e]&&h.aliases[e].forEach(function(e){let t=e.split(`.`);E(y,t,r)}),a.length>1&&o[`dot-notation`]&&(h.aliases[a[0]]||[]).forEach(function(t){let n=t.split(`.`),i=[].concat(a);i.shift(),n=n.concat(i),(h.aliases[e]||[]).includes(n.join(`.`))||E(y,n,r)}),D(e,h.normalize)&&!D(e,h.arrays)&&[e].concat(h.aliases[e]||[]).forEach(function(e){Object.defineProperty(te,e,{enumerable:!0,get(){return t},set(e){t=typeof e==`string`?De.normalize(e):e}})})}function ie(e,t){h.aliases[e]&&h.aliases[e].length||(h.aliases[e]=[t],f[t]=!0),h.aliases[t]&&h.aliases[t].length||ie(t,e)}function S(e,t,n){n&&(t=Me(t)),(D(e,h.bools)||D(e,h.counts))&&typeof t==`string`&&(t=t===`true`);let r=Array.isArray(t)?t.map(function(t){return C(e,t)}):C(e,t);return D(e,h.counts)&&(A(r)||typeof r==`boolean`)&&(r=Ae()),D(e,h.normalize)&&D(e,h.arrays)&&(r=Array.isArray(t)?t.map(e=>De.normalize(e)):De.normalize(t)),r}function C(e,t){return!o[`parse-positional-numbers`]&&e===`_`||!D(e,h.strings)&&!D(e,h.bools)&&!Array.isArray(t)&&(Te(t)&&o[`parse-numbers`]&&Number.isSafeInteger(Math.floor(parseFloat(`${t}`)))||!A(t)&&D(e,h.numbers))&&(t=Number(t)),t}function w(e){let t=Object.create(null);le(t,h.aliases,s),Object.keys(h.configs).forEach(function(n){let r=e[n]||t[n];if(r)try{let e=null,t=De.resolve(De.cwd(),r),i=h.configs[n];if(typeof i==`function`){try{e=i(t)}catch(t){e=t}if(e instanceof Error){v=e;return}}else e=De.require(t);ae(e)}catch(t){t.name===`PermissionDenied`?v=t:e[n]&&(v=Error(m(`Invalid JSON config file: %s`,r)))}})}function ae(e,t){Object.keys(e).forEach(function(n){let r=e[n],i=t?t+`.`+n:n;typeof r==`object`&&r&&!Array.isArray(r)&&o[`dot-notation`]?ae(r,i):(!ue(y,i.split(`.`))||D(i,h.arrays)&&o[`combine-arrays`])&&x(i,r)})}function oe(){c!==void 0&&c.forEach(function(e){ae(e)})}function se(e,t){if(l===void 0)return;let n=typeof l==`string`?l:``,r=De.env();Object.keys(r).forEach(function(i){if(n===``||i.lastIndexOf(n,0)===0){let a=i.split(`__`).map(function(e,t){return t===0&&(e=e.substring(n.length)),Ce(e)});(t&&h.configs[a.join(`.`)]||!t)&&!ue(e,a)&&x(a.join(`.`),r[i])}})}function ce(e){let t,n=/* @__PURE__ */ new Set;Object.keys(e).forEach(function(r){if(!n.has(r)&&(t=D(r,h.coercions),typeof t==`function`))try{let i=C(r,t(e[r]));[].concat(h.aliases[r]||[],r).forEach(t=>{n.add(t),e[t]=i})}catch(e){v=e}})}function T(e){return h.keys.forEach(t=>{~t.indexOf(`.`)||e[t]===void 0&&(e[t]=void 0)}),e}function le(e,t,n,r=!1){Object.keys(n).forEach(function(i){ue(e,i.split(`.`))||(E(e,i.split(`.`),n[i]),r&&(p[i]=!0),(t[i]||[]).forEach(function(t){ue(e,t.split(`.`))||E(e,t.split(`.`),n[i])}))})}function ue(e,t){let n=e;o[`dot-notation`]||(t=[t.join(`.`)]),t.slice(0,-1).forEach(function(e){n=n[e]||{}});let r=t[t.length-1];return typeof n==`object`&&r in n}function E(e,t,n){let r=e;o[`dot-notation`]||(t=[t.join(`.`)]),t.slice(0,-1).forEach(function(e){e=je(e),typeof r==`object`&&r[e]===void 0&&(r[e]={}),typeof r[e]!=`object`||Array.isArray(r[e])?(Array.isArray(r[e])?r[e].push({}):r[e]=[r[e],{}],r=r[e][r[e].length-1]):r=r[e]});let i=je(t[t.length-1]),a=D(t.join(`.`),h.arrays),s=Array.isArray(n),c=o[`duplicate-arguments-array`];!c&&D(i,h.nargs)&&(c=!0,(!A(r[i])&&h.nargs[i]===1||Array.isArray(r[i])&&r[i].length===h.nargs[i])&&(r[i]=void 0)),n===Ae()?r[i]=Ae(r[i]):Array.isArray(r[i])?c&&a&&s?r[i]=o[`flatten-duplicate-arrays`]?r[i].concat(n):(Array.isArray(r[i][0])?r[i]:[r[i]]).concat([n]):!c&&!!a==!!s?r[i]=n:r[i]=r[i].concat([n]):r[i]===void 0&&a?r[i]=s?n:[n]:c&&!(r[i]===void 0||D(i,h.counts)||D(i,h.bools))?r[i]=[r[i],n]:r[i]=n}function de(...e){e.forEach(function(e){Object.keys(e||{}).forEach(function(e){h.aliases[e]||(h.aliases[e]=[].concat(a[e]||[]),h.aliases[e].concat(e).forEach(function(t){if(/-/.test(t)&&o[`camel-case-expansion`]){let n=Ce(t);n!==e&&h.aliases[e].indexOf(n)===-1&&(h.aliases[e].push(n),f[n]=!0)}}),h.aliases[e].concat(e).forEach(function(t){if(t.length>1&&/[A-Z]/.test(t)&&o[`camel-case-expansion`]){let n=we(t,`-`);n!==e&&h.aliases[e].indexOf(n)===-1&&(h.aliases[e].push(n),f[n]=!0)}}),h.aliases[e].forEach(function(t){h.aliases[t]=[e].concat(h.aliases[e].filter(function(e){return t!==e}))}))})})}function D(e,t){let n=[].concat(h.aliases[e]||[],e),r=Object.keys(t),i=n.find(e=>r.includes(e));return i?t[i]:!1}function fe(e){let t=Object.keys(h);return[].concat(t.map(e=>h[e])).some(function(t){return Array.isArray(t)?t.includes(e):t[e]})}function pe(e,...t){return[].concat(...t).some(function(t){let n=e.match(t);return n&&fe(n[1])})}function me(e){if(e.match(g)||!e.match(/^-[^-]+/))return!1;let t=!0,n,r=e.slice(1).split(``);for(let i=0;i<r.length;i++){if(n=e.slice(i+2),!fe(r[i])){t=!1;break}if(r[i+1]&&r[i+1]===`=`||n===`-`||/[A-Za-z]/.test(r[i])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(n)||r[i+1]&&r[i+1].match(/\W/))break}return t}function he(e){return o[`unknown-options-as-args`]&&ge(e)}function ge(e){return e=e.replace(/^-{3,}/,`--`),e.match(g)||me(e)?!1:!pe(e,/^-+([^=]+?)=[\s\S]*$/,_,/^-+([^=]+?)$/,/^-+([^=]+?)-$/,/^-+([^=]+?\d+)$/,/^-+([^=]+?)\W+.*$/)}function O(e){return!D(e,h.bools)&&!D(e,h.counts)&&`${e}`in s?s[e]:_e(k(e))}function _e(e){return{[M.BOOLEAN]:!0,[M.STRING]:``,[M.NUMBER]:void 0,[M.ARRAY]:[]}[e]}function k(e){let t=M.BOOLEAN;return D(e,h.strings)?t=M.STRING:D(e,h.numbers)?t=M.NUMBER:D(e,h.bools)?t=M.BOOLEAN:D(e,h.arrays)&&(t=M.ARRAY),t}function A(e){return e===void 0}function ve(){Object.keys(h.counts).find(e=>D(e,h.arrays)?(v=Error(m(`Invalid configuration: %s, opts.count excludes opts.array.`,e)),!0):D(e,h.nargs)?(v=Error(m(`Invalid configuration: %s, opts.count excludes opts.narg.`,e)),!0):!1)}return{aliases:Object.assign({},h.aliases),argv:Object.assign(te,y),configuration:o,defaulted:Object.assign({},p),error:v,newAliases:Object.assign({},f)}}};function ke(e){let t=[],n=Object.create(null),r=!0;for(Object.keys(e).forEach(function(n){t.push([].concat(e[n],n))});r;){r=!1;for(let e=0;e<t.length;e++)for(let n=e+1;n<t.length;n++)if(t[e].filter(function(e){return t[n].indexOf(e)!==-1}).length){t[e]=t[e].concat(t[n]),t.splice(n,1),r=!0;break}}return t.forEach(function(e){e=e.filter(function(e,t,n){return n.indexOf(e)===t});let t=e.pop();t!==void 0&&typeof t==`string`&&(n[t]=e)}),n}function Ae(e){return e===void 0?1:e+1}function je(e){return e===`__proto__`?`___proto___`:e}function Me(e){return typeof e==`string`&&(e[0]===`'`||e[0]===`"`)&&e[e.length-1]===e[0]?e.substring(1,e.length-1):e}
30
+ let j;var je=class{constructor(e){j=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=Ae(e),i=typeof e==`string`,a=Me(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.__||j.format,h={aliases:Object.create(null),arrays:Object.create(null),bools:Object.create(null),strings:Object.create(null),numbers:Object.create(null),counts:Object.create(null),normalize:Object.create(null),configs:Object.create(null),nargs:Object.create(null),coercions:Object.create(null),keys:[]},g=/^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/,_=RegExp(`^--`+o[`negation-prefix`]+`(.+)`);[].concat(n.array||[]).filter(Boolean).forEach(function(e){let t=typeof e==`object`?e.key:e,n=Object.keys(e).map(function(e){return{boolean:`bools`,string:`strings`,number:`numbers`}[e]}).filter(Boolean).pop();n&&(h[n][t]=!0),h.arrays[t]=!0,h.keys.push(t)}),[].concat(n.boolean||[]).filter(Boolean).forEach(function(e){h.bools[e]=!0,h.keys.push(e)}),[].concat(n.string||[]).filter(Boolean).forEach(function(e){h.strings[e]=!0,h.keys.push(e)}),[].concat(n.number||[]).filter(Boolean).forEach(function(e){h.numbers[e]=!0,h.keys.push(e)}),[].concat(n.count||[]).filter(Boolean).forEach(function(e){h.counts[e]=!0,h.keys.push(e)}),[].concat(n.normalize||[]).filter(Boolean).forEach(function(e){h.normalize[e]=!0,h.keys.push(e)}),typeof n.narg==`object`&&Object.entries(n.narg).forEach(([e,t])=>{typeof t==`number`&&(h.nargs[e]=t,h.keys.push(e))}),typeof n.coerce==`object`&&Object.entries(n.coerce).forEach(([e,t])=>{typeof t==`function`&&(h.coercions[e]=t,h.keys.push(e))}),n.config!==void 0&&(Array.isArray(n.config)||typeof n.config==`string`?[].concat(n.config).filter(Boolean).forEach(function(e){h.configs[e]=!0}):typeof n.config==`object`&&Object.entries(n.config).forEach(([e,t])=>{(typeof t==`boolean`||typeof t==`function`)&&(h.configs[e]=t)})),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 v=null;Se();let ee=[],y=Object.assign(Object.create(null),{_:[]}),te={};for(let e=0;e<r.length;e++){let t=r[e],n=t.replace(/^-{3,}/,`---`),i,a,s,c,l,u;if(t!==`--`&&/^-/.test(t)&&_e(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(_)&&o[`boolean-negation`])c=t.match(_),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,ye(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,ye(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],ye(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,ye(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,ye(a));else if(t===`--`){ee=r.slice(e+1);break}else if(o[`halt-at-non-option`]){ee=r.slice(e);break}else ne(t)}C(y,!0),C(y,!1),oe(y),ce(),de(y,h.aliases,s,!0),le(y),o[`set-placeholder-key`]&&ue(y),Object.keys(h.counts).forEach(function(e){fe(y,e.split(`.`))||x(e,0)}),u&&ee.length&&(y[d]=[]),ee.forEach(function(e){y[d].push(e)}),o[`camel-case-expansion`]&&o[`strip-dashed`]&&Object.keys(y).filter(e=>e!==`--`&&e.includes(`-`)).forEach(e=>{delete y[e]}),o[`strip-aliased`]&&[].concat(...Object.keys(a).map(e=>a[e])).forEach(e=>{o[`camel-case-expansion`]&&e.includes(`-`)&&delete y[e.split(`.`).map(e=>Oe(e)).join(`.`)],delete y[e]});function ne(e){let t=S(`_`,e);(typeof t==`string`||typeof t==`number`)&&y._.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 E(r)||(v=Error(m(`Argument unexpected for: %s`,t))),x(t,ye(t)),e;let s=+!E(r);if(o[`nargs-eats-options`])n.length-(e+1)+s<a&&(v=Error(m(`Not enough arguments following: %s`,t))),s=a;else{for(i=e+1;i<n.length&&(!n[i].match(/^-[^0-9]/)||n[i].match(g)||_e(n[i]));i++)s++;s<a&&(v=Error(m(`Not enough arguments following: %s`,t)))}let c=Math.min(s,a);for(!E(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(E(c)||E(r)&&/^-/.test(c)&&!g.test(c)&&!_e(c)){if(s[t]!==void 0){let e=s[t];a=Array.isArray(e)?e:[e]}}else{E(r)||a.push(ae(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)&&!_e(c)));r++)e=r,a.push(ae(t,c,i))}return typeof l==`number`&&(l&&a.length<l||isNaN(l)&&a.length===0)&&(v=Error(m(`Not enough arguments following: %s`,t))),x(t,a),e}function x(e,t,n=i){/-/.test(e)&&o[`camel-case-expansion`]&&ie(e,e.split(`.`).map(function(e){return Oe(e)}).join(`.`));let r=ae(e,t,n),a=e.split(`.`);w(y,a,r),h.aliases[e]&&h.aliases[e].forEach(function(e){let t=e.split(`.`);w(y,t,r)}),a.length>1&&o[`dot-notation`]&&(h.aliases[a[0]]||[]).forEach(function(t){let n=t.split(`.`),i=[].concat(a);i.shift(),n=n.concat(i),(h.aliases[e]||[]).includes(n.join(`.`))||w(y,n,r)}),T(e,h.normalize)&&!T(e,h.arrays)&&[e].concat(h.aliases[e]||[]).forEach(function(e){Object.defineProperty(te,e,{enumerable:!0,get(){return t},set(e){t=typeof e==`string`?j.normalize(e):e}})})}function ie(e,t){h.aliases[e]&&h.aliases[e].length||(h.aliases[e]=[t],f[t]=!0),h.aliases[t]&&h.aliases[t].length||ie(t,e)}function ae(e,t,n){n&&(t=Fe(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 S(e,t)}):S(e,t);return T(e,h.counts)&&(E(r)||typeof r==`boolean`)&&(r=Ne()),T(e,h.normalize)&&T(e,h.arrays)&&(r=Array.isArray(t)?t.map(e=>j.normalize(e)):j.normalize(t)),r}function S(e,t){return!o[`parse-positional-numbers`]&&e===`_`||!T(e,h.strings)&&!T(e,h.bools)&&!Array.isArray(t)&&(ke(t)&&o[`parse-numbers`]&&Number.isSafeInteger(Math.floor(parseFloat(`${t}`)))||!E(t)&&T(e,h.numbers))&&(t=Number(t)),t}function oe(e){let t=Object.create(null);de(t,h.aliases,s),Object.keys(h.configs).forEach(function(n){let r=e[n]||t[n];if(r)try{let e=null,t=j.resolve(j.cwd(),r),i=h.configs[n];if(typeof i==`function`){try{e=i(t)}catch(t){e=t}if(e instanceof Error){v=e;return}}else e=j.require(t);se(e)}catch(t){t.name===`PermissionDenied`?v=t:e[n]&&(v=Error(m(`Invalid JSON config file: %s`,r)))}})}function se(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`]?se(r,i):(!fe(y,i.split(`.`))||T(i,h.arrays)&&o[`combine-arrays`])&&x(i,r)})}function ce(){c!==void 0&&c.forEach(function(e){se(e)})}function C(e,t){if(l===void 0)return;let n=typeof l==`string`?l:``,r=j.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)),Oe(e)});(t&&h.configs[a.join(`.`)]||!t)&&!fe(e,a)&&x(a.join(`.`),r[i])}})}function le(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=S(r,t(e[r]));[].concat(h.aliases[r]||[],r).forEach(t=>{n.add(t),e[t]=i})}catch(e){v=e}})}function ue(e){return h.keys.forEach(t=>{~t.indexOf(`.`)||e[t]===void 0&&(e[t]=void 0)}),e}function de(e,t,n,r=!1){Object.keys(n).forEach(function(i){fe(e,i.split(`.`))||(w(e,i.split(`.`),n[i]),r&&(p[i]=!0),(t[i]||[]).forEach(function(t){fe(e,t.split(`.`))||w(e,t.split(`.`),n[i])}))})}function fe(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 w(e,t,n){let r=e;o[`dot-notation`]||(t=[t.join(`.`)]),t.slice(0,-1).forEach(function(e){e=Pe(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=Pe(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,(!E(r[i])&&h.nargs[i]===1||Array.isArray(r[i])&&r[i].length===h.nargs[i])&&(r[i]=void 0)),n===Ne()?r[i]=Ne(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=Oe(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=k(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 ge(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 _e(e){return o[`unknown-options-as-args`]&&ve(e)}function ve(e){return e=e.replace(/^-{3,}/,`--`),e.match(g)||ge(e)?!1:!he(e,/^-+([^=]+?)=[\s\S]*$/,_,/^-+([^=]+?)$/,/^-+([^=]+?)-$/,/^-+([^=]+?\d+)$/,/^-+([^=]+?)\W+.*$/)}function ye(e){return!T(e,h.bools)&&!T(e,h.counts)&&`${e}`in s?s[e]:be(xe(e))}function be(e){return{[A.BOOLEAN]:!0,[A.STRING]:``,[A.NUMBER]:void 0,[A.ARRAY]:[]}[e]}function xe(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 E(e){return e===void 0}function Se(){Object.keys(h.counts).find(e=>T(e,h.arrays)?(v=Error(m(`Invalid configuration: %s, opts.count excludes opts.array.`,e)),!0):T(e,h.nargs)?(v=Error(m(`Invalid configuration: %s, opts.count excludes opts.narg.`,e)),!0):!1)}return{aliases:Object.assign({},h.aliases),argv:Object.assign(te,y),configuration:o,defaulted:Object.assign({},p),error:v,newAliases:Object.assign({},f)}}};function Me(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 Ne(e){return e===void 0?1:e+1}function Pe(e){return e===`__proto__`?`___proto___`:e}function Fe(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 De;var Oe=class{constructor(e){De=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 Ne=process&&process.env&&process.env.YARGS_MIN_NODE_VERSION?Number(process.env.YARGS_MIN_NODE_VERSION):12,Pe=(process==null?void 0:process.versions)?.node??(process==null?void 0:process.version)?.slice(1);if(Pe&&Number(Pe.match(/^([^.]+)/)[1])<Ne)throw Error(`yargs parser supports a minimum Node.js version of ${Ne}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`);const Fe=process?process.env:{},Ie=new Oe({cwd:process.cwd,env:()=>Fe,format:y,normalize:p,resolve:h,require:e=>{if(fe!==void 0)return fe(e);if(e.match(/\.json$/))return JSON.parse(g(e,`utf8`));throw Error(`only .json config files are supported in ESM`)}}),Le=function(e,t){return Ie.parse(e.slice(),t).argv};Le.detailed=function(e,t){return Ie.parse(e.slice(),t)},Le.camelCase=Ce,Le.decamelize=we,Le.looksLikeNumber=Te;function Re(){return+!ze()}function ze(){return Be()&&!process.defaultApp}function Be(){return!!process.versions.electron}function N(){return process.argv[Re()]}var P=class e extends Error{constructor(t){super(t||`yargs error`),this.name=`YError`,Error.captureStackTrace&&Error.captureStackTrace(this,e)}},Ve={fs:{readFileSync:g,writeFile:ee},format:y,resolve:h,exists:e=>{try{return v(e).isFile()}catch{return!1}}};let He;var Ue=class{constructor(e){e||={},this.directory=e.directory||`./locales`,this.updateFiles=typeof e.updateFiles!=`boolean`||e.updateFiles,this.locale=e.locale||`en`,this.fallbackToLanguage=typeof e.fallbackToLanguage!=`boolean`||e.fallbackToLanguage,this.cache=Object.create(null),this.writeQueue=[]}__(...e){if(typeof arguments[0]!=`string`)return this._taggedLiteral(arguments[0],...arguments);let t=e.shift(),n=function(){};return typeof e[e.length-1]==`function`&&(n=e.pop()),n||=function(){},this.cache[this.locale]||this._readLocaleFile(),!this.cache[this.locale][t]&&this.updateFiles?(this.cache[this.locale][t]=t,this._enqueueWrite({directory:this.directory,locale:this.locale,cb:n})):n(),He.format.apply(He.format,[this.cache[this.locale][t]||t].concat(e))}__n(){let e=Array.prototype.slice.call(arguments),t=e.shift(),n=e.shift(),r=e.shift(),i=function(){};typeof e[e.length-1]==`function`&&(i=e.pop()),this.cache[this.locale]||this._readLocaleFile();let a=r===1?t:n;this.cache[this.locale][t]&&(a=this.cache[this.locale][t][r===1?`one`:`other`]),!this.cache[this.locale][t]&&this.updateFiles?(this.cache[this.locale][t]={one:t,other:n},this._enqueueWrite({directory:this.directory,locale:this.locale,cb:i})):i();let o=[a];return~a.indexOf(`%d`)&&o.push(r),He.format.apply(He.format,o.concat(e))}setLocale(e){this.locale=e}getLocale(){return this.locale}updateLocale(e){this.cache[this.locale]||this._readLocaleFile();for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&(this.cache[this.locale][t]=e[t])}_taggedLiteral(e,...t){let n=``;return e.forEach(function(e,r){let i=t[r+1];n+=e,i!==void 0&&(n+=`%s`)}),this.__.apply(this,[n].concat([].slice.call(t,1)))}_enqueueWrite(e){this.writeQueue.push(e),this.writeQueue.length===1&&this._processWriteQueue()}_processWriteQueue(){let e=this,t=this.writeQueue[0],n=t.directory,r=t.locale,i=t.cb,a=this._resolveLocaleFile(n,r),o=JSON.stringify(this.cache[r],null,2);He.fs.writeFile(a,o,`utf-8`,function(t){e.writeQueue.shift(),e.writeQueue.length>0&&e._processWriteQueue(),i(t)})}_readLocaleFile(){let e={},t=this._resolveLocaleFile(this.directory,this.locale);try{He.fs.readFileSync&&(e=JSON.parse(He.fs.readFileSync(t,`utf-8`)))}catch(n){if(n instanceof SyntaxError&&(n.message=`syntax error in `+t),n.code===`ENOENT`)e={};else throw n}this.cache[this.locale]=e}_resolveLocaleFile(e,t){let n=He.resolve(e,`./`,t+`.json`);if(this.fallbackToLanguage&&!this._fileExistsSync(n)&&~t.lastIndexOf(`_`)){let r=He.resolve(e,`./`,t.split(`_`)[0]+`.json`);this._fileExistsSync(r)&&(n=r)}return n}_fileExistsSync(e){return He.exists(e)}};function We(e,t){He=t;let n=new Ue(e);return{__:n.__.bind(n),__n:n.__n.bind(n),setLocale:n.setLocale.bind(n),getLocale:n.getLocale.bind(n),updateLocale:n.updateLocale.bind(n),locale:n.locale}}const Ge=e=>We(e,Ve),Ke=`loading a directory of commands is not supported yet for ESM`;let qe;try{qe=ne(import.meta.url)}catch{qe=process.cwd()}const Je=qe.substring(0,qe.lastIndexOf(`node_modules`));var Ye={assert:{notStrictEqual:c,strictEqual:l},cliui:Se,findUp:j,getEnv:e=>process.env[e],inspect:te,getCallerFile:()=>{throw new P(Ke)},getProcessArgvBin:N,mainFilename:Je||process.cwd(),Parser:Le,path:{basename:u,dirname:d,extname:f,relative:m,resolve:h},process:{argv:()=>process.argv,cwd:process.cwd,emitWarning:(e,t)=>process.emitWarning(e,t),execPath:()=>process.execPath,exit:process.exit,nextTick:process.nextTick,stdColumns:process.stdout.columns===void 0?null:process.stdout.columns},readFileSync:g,require:()=>{throw new P(`require is not supported by ESM`)},requireDirectory:()=>{throw new P(Ke)},stringWidth:e=>[...e].length,y18n:Ge({directory:h(qe,`../../../locales`),updateFiles:!1})};function Xe(e,t,n,r){n.assert.notStrictEqual(e,t,r)}function Ze(e,t){t.assert.strictEqual(typeof e,`string`)}function Qe(e){return Object.keys(e)}function F(e){return!!e&&!!e.then&&typeof e.then==`function`}function $e(e){let t=e.replace(/\s{2,}/g,` `).split(/\s+(?![^[]*]|[^<]*>)/),n=/\.*[\][<>]/g,r=t.shift();if(!r)throw Error(`No command found in: ${e}`);let i={cmd:r.replace(n,``),demanded:[],optional:[]};return t.forEach((e,r)=>{let a=!1;e=e.replace(/\s/g,``),/\.+[\]>]/.test(e)&&r===t.length-1&&(a=!0),/^\[/.test(e)?i.optional.push({cmd:e.replace(n,``).split(`|`),variadic:a}):i.demanded.push({cmd:e.replace(n,``).split(`|`),variadic:a})}),i}const et=[`first`,`second`,`third`,`fourth`,`fifth`,`sixth`];function I(e,t,n){function r(){return typeof e==`object`?[{demanded:[],optional:[]},e,t]:[$e(`cmd ${e}`),t,n]}try{let e=0,[t,n,i]=r(),a=[].slice.call(n);for(;a.length&&a[a.length-1]===void 0;)a.pop();let o=i||a.length;if(o<t.demanded.length)throw new P(`Not enough arguments provided. Expected ${t.demanded.length} but received ${a.length}.`);let s=t.demanded.length+t.optional.length;if(o>s)throw new P(`Too many arguments provided. Expected max ${s} but received ${o}.`);t.demanded.forEach(t=>{let n=tt(a.shift());t.cmd.filter(e=>e===n||e===`*`).length===0&&nt(n,t.cmd,e),e+=1}),t.optional.forEach(t=>{if(a.length===0)return;let n=tt(a.shift());t.cmd.filter(e=>e===n||e===`*`).length===0&&nt(n,t.cmd,e),e+=1})}catch(e){console.warn(e.stack)}}function tt(e){return Array.isArray(e)?`array`:e===null?`null`:typeof e}function nt(e,t,n){throw new P(`Invalid ${et[n]||`manyith`} argument. Expected ${t.join(` or `)} but received ${e}.`)}var rt=class{constructor(e){this.globalMiddleware=[],this.frozens=[],this.yargs=e}addMiddleware(e,t,n=!0,r=!1){if(I(`<array|function> [boolean] [boolean] [boolean]`,[e,t,n],arguments.length),Array.isArray(e)){for(let r=0;r<e.length;r++){if(typeof e[r]!=`function`)throw Error(`middleware must be a function`);let i=e[r];i.applyBeforeValidation=t,i.global=n}Array.prototype.push.apply(this.globalMiddleware,e)}else if(typeof e==`function`){let i=e;i.applyBeforeValidation=t,i.global=n,i.mutates=r,this.globalMiddleware.push(e)}return this.yargs}addCoerceMiddleware(e,t){let n=this.yargs.getAliases();return this.globalMiddleware=this.globalMiddleware.filter(e=>{let r=[...n[t]||[],t];return!e.option||!r.includes(e.option)}),e.option=t,this.addMiddleware(e,!0,!0,!0)}getMiddleware(){return this.globalMiddleware}freeze(){this.frozens.push([...this.globalMiddleware])}unfreeze(){let e=this.frozens.pop();e!==void 0&&(this.globalMiddleware=e)}reset(){this.globalMiddleware=this.globalMiddleware.filter(e=>e.global)}};function it(e){return e?e.map(e=>(e.applyBeforeValidation=!1,e)):[]}function at(e,t,n,r){return n.reduce((e,n)=>{if(n.applyBeforeValidation!==r)return e;if(n.mutates){if(n.applied)return e;n.applied=!0}if(F(e))return e.then(e=>Promise.all([e,n(e,t)])).then(([e,t])=>Object.assign(e,t));{let r=n(e,t);return F(r)?r.then(t=>Object.assign(e,t)):Object.assign(e,r)}},e)}function ot(e,t,n=e=>{throw e}){try{let n=st(e)?e():e;return F(n)?n.then(e=>t(e)):t(n)}catch(e){return n(e)}}function st(e){return typeof e==`function`}function ct(e){if(fe===void 0)return null;for(let t=0,n=Object.keys(fe.cache),r;t<n.length;t++)if(r=fe.cache[n[t]],r.exports===e)return r;return null}const lt=/(^\*)|(^\$0)/;var ut=class{constructor(e,t,n,r){this.requireCache=/* @__PURE__ */ new Set,this.handlers={},this.aliasMap={},this.frozens=[],this.shim=r,this.usage=e,this.globalMiddleware=n,this.validation=t}addDirectory(e,t,n,r){r||={},typeof r.recurse!=`boolean`&&(r.recurse=!1),Array.isArray(r.extensions)||(r.extensions=[`js`]);let i=typeof r.visit==`function`?r.visit:e=>e;r.visit=(e,t,n)=>{let r=i(e,t,n);if(r){if(this.requireCache.has(t))return r;this.requireCache.add(t),this.addHandler(r)}return r},this.shim.requireDirectory({require:t,filename:n},e,r)}addHandler(e,t,n,r,i,a){let o=[],s=it(i);if(r||=(()=>{}),Array.isArray(e)){if(pt(e))[e,...o]=e;else for(let t of e)this.addHandler(t)}else if(gt(e)){let t=Array.isArray(e.command)||typeof e.command==`string`?e.command:this.moduleName(e);e.aliases&&(t=[].concat(t,e.aliases)),this.addHandler(t,this.extractDesc(e),e.builder,e.handler,e.middlewares,e.deprecated);return}else if(ft(n)){this.addHandler([e].concat(o),t,n.builder,n.handler,n.middlewares,n.deprecated);return}if(typeof e==`string`){let i=$e(e);o=o.map(e=>$e(e).cmd);let c=!1,l=[i.cmd].concat(o).filter(e=>!lt.test(e)||(c=!0,!1));l.length===0&&c&&l.push(`$0`),c&&(i.cmd=l[0],o=l.slice(1),e=e.replace(lt,i.cmd)),o.forEach(e=>{this.aliasMap[e]=i.cmd}),t!==!1&&this.usage.command(e,t,c,o,a),this.handlers[i.cmd]={original:e,description:t,handler:r,builder:n||{},middlewares:s,deprecated:a,demanded:i.demanded,optional:i.optional},c&&(this.defaultCommand=this.handlers[i.cmd])}}getCommandHandlers(){return this.handlers}getCommands(){return Object.keys(this.handlers).concat(Object.keys(this.aliasMap))}hasDefaultCommand(){return!!this.defaultCommand}runCommand(e,t,n,r,i,a){let o=this.handlers[e]||this.handlers[this.aliasMap[e]]||this.defaultCommand,s=t.getInternalMethods().getContext(),c=s.commands.slice(),l=!e;e&&(s.commands.push(e),s.fullCommands.push(o.original));let u=this.applyBuilderUpdateUsageAndParse(l,o,t,n.aliases,c,r,i,a);return F(u)?u.then(e=>this.applyMiddlewareAndGetResult(l,o,e.innerArgv,s,i,e.aliases,t)):this.applyMiddlewareAndGetResult(l,o,u.innerArgv,s,i,u.aliases,t)}applyBuilderUpdateUsageAndParse(e,t,n,r,i,a,o,s){let c=t.builder,l=n;if(mt(c)){n.getInternalMethods().getUsageInstance().freeze();let u=c(n.getInternalMethods().reset(r),s);if(F(u))return u.then(r=>(l=Qn(r)?r:n,this.parseAndUpdateUsage(e,t,l,i,a,o)))}else ht(c)&&(n.getInternalMethods().getUsageInstance().freeze(),l=n.getInternalMethods().reset(r),Object.keys(t.builder).forEach(e=>{l.option(e,c[e])}));return this.parseAndUpdateUsage(e,t,l,i,a,o)}parseAndUpdateUsage(e,t,n,r,i,a){e&&n.getInternalMethods().getUsageInstance().unfreeze(!0),this.shouldUpdateUsage(n)&&n.getInternalMethods().getUsageInstance().usage(this.usageFromParentCommandsCommandHandler(r,t),t.description);let o=n.getInternalMethods().runYargsParserAndExecuteCommands(null,void 0,!0,i,a);return F(o)?o.then(e=>({aliases:n.parsed.aliases,innerArgv:e})):{aliases:n.parsed.aliases,innerArgv:o}}shouldUpdateUsage(e){return!e.getInternalMethods().getUsageInstance().getUsageDisabled()&&e.getInternalMethods().getUsageInstance().getUsage().length===0}usageFromParentCommandsCommandHandler(e,t){let n=lt.test(t.original)?t.original.replace(lt,``).trim():t.original,r=e.filter(e=>!lt.test(e));return r.push(n),`$0 ${r.join(` `)}`}handleValidationAndGetResult(e,t,n,r,i,a,o,s){if(!a.getInternalMethods().getHasOutput()){let t=a.getInternalMethods().runValidation(i,s,a.parsed.error,e);n=ot(n,e=>(t(e),e))}if(t.handler&&!a.getInternalMethods().getHasOutput()){a.getInternalMethods().setHasOutput();let r=!!a.getOptions().configuration[`populate--`];a.getInternalMethods().postProcess(n,r,!1,!1),n=at(n,a,o,!1),n=ot(n,e=>{let n=t.handler(e);return F(n)?n.then(()=>e):e}),e||a.getInternalMethods().getUsageInstance().cacheHelpMessage(),F(n)&&!a.getInternalMethods().hasParseCallback()&&n.catch(e=>{try{a.getInternalMethods().getUsageInstance().fail(null,e)}catch{}})}return e||(r.commands.pop(),r.fullCommands.pop()),n}applyMiddlewareAndGetResult(e,t,n,r,i,a,o){let s={};if(i)return n;o.getInternalMethods().getHasOutput()||(s=this.populatePositionals(t,n,r,o));let c=this.globalMiddleware.getMiddleware().slice(0).concat(t.middlewares),l=at(n,o,c,!0);return F(l)?l.then(n=>this.handleValidationAndGetResult(e,t,n,r,a,o,c,s)):this.handleValidationAndGetResult(e,t,l,r,a,o,c,s)}populatePositionals(e,t,n,r){t._=t._.slice(n.commands.length);let i=e.demanded.slice(0),a=e.optional.slice(0),o={};for(this.validation.positionalCount(i.length,t._.length);i.length;){let e=i.shift();this.populatePositional(e,t,o)}for(;a.length;){let e=a.shift();this.populatePositional(e,t,o)}return t._=n.commands.concat(t._.map(e=>``+e)),this.postProcessPositionals(t,o,this.cmdToParseOptions(e.original),r),o}populatePositional(e,t,n){let r=e.cmd[0];e.variadic?n[r]=t._.splice(0).map(String):t._.length&&(n[r]=[String(t._.shift())])}cmdToParseOptions(e){let t={array:[],default:{},alias:{},demand:{}},n=$e(e);return n.demanded.forEach(e=>{let[n,...r]=e.cmd;e.variadic&&(t.array.push(n),t.default[n]=[]),t.alias[n]=r,t.demand[n]=!0}),n.optional.forEach(e=>{let[n,...r]=e.cmd;e.variadic&&(t.array.push(n),t.default[n]=[]),t.alias[n]=r}),t}postProcessPositionals(e,t,n,r){let i=Object.assign({},r.getOptions());i.default=Object.assign(n.default,i.default);for(let e of Object.keys(n.alias))i.alias[e]=(i.alias[e]||[]).concat(n.alias[e]);i.array=i.array.concat(n.array),i.config={};let a=[];if(Object.keys(t).forEach(e=>{t[e].map(t=>{i.configuration[`unknown-options-as-args`]&&(i.key[e]=!0),a.push(`--${e}`),a.push(t)})}),!a.length)return;let o=Object.assign({},i.configuration,{"populate--":!1}),s=this.shim.Parser.detailed(a,Object.assign({},i,{configuration:o}));if(s.error)r.getInternalMethods().getUsageInstance().fail(s.error.message,s.error);else{let n=Object.keys(t);Object.keys(t).forEach(e=>{n.push(...s.aliases[e])}),Object.keys(s.argv).forEach(i=>{n.includes(i)&&(t[i]||(t[i]=s.argv[i]),e[i]=!this.isInConfigs(r,i)&&!this.isDefaulted(r,i)&&Object.prototype.hasOwnProperty.call(e,i)&&Object.prototype.hasOwnProperty.call(s.argv,i)&&(Array.isArray(e[i])||Array.isArray(s.argv[i]))?[].concat(e[i],s.argv[i]):s.argv[i])})}}isDefaulted(e,t){let{default:n}=e.getOptions();return Object.prototype.hasOwnProperty.call(n,t)||Object.prototype.hasOwnProperty.call(n,this.shim.Parser.camelCase(t))}isInConfigs(e,t){let{configObjects:n}=e.getOptions();return n.some(e=>Object.prototype.hasOwnProperty.call(e,t))||n.some(e=>Object.prototype.hasOwnProperty.call(e,this.shim.Parser.camelCase(t)))}runDefaultBuilderOn(e){if(!this.defaultCommand)return;if(this.shouldUpdateUsage(e)){let t=lt.test(this.defaultCommand.original)?this.defaultCommand.original:this.defaultCommand.original.replace(/^[^[\]<>]*/,`$0 `);e.getInternalMethods().getUsageInstance().usage(t,this.defaultCommand.description)}let t=this.defaultCommand.builder;if(mt(t))return t(e,!0);ft(t)||Object.keys(t).forEach(n=>{e.option(n,t[n])})}moduleName(e){let t=ct(e);if(!t)throw Error(`No command name given for module: ${this.shim.inspect(e)}`);return this.commandFromFilename(t.filename)}commandFromFilename(e){return this.shim.path.basename(e,this.shim.path.extname(e))}extractDesc({describe:e,description:t,desc:n}){for(let r of[e,t,n]){if(typeof r==`string`||r===!1)return r;Xe(r,!0,this.shim)}return!1}freeze(){this.frozens.push({handlers:this.handlers,aliasMap:this.aliasMap,defaultCommand:this.defaultCommand})}unfreeze(){let e=this.frozens.pop();Xe(e,void 0,this.shim),{handlers:this.handlers,aliasMap:this.aliasMap,defaultCommand:this.defaultCommand}=e}reset(){return this.handlers={},this.aliasMap={},this.defaultCommand=void 0,this.requireCache=/* @__PURE__ */ new Set,this}};function dt(e,t,n,r){return new ut(e,t,n,r)}function ft(e){return typeof e==`object`&&!!e.builder&&typeof e.handler==`function`}function pt(e){return e.every(e=>typeof e==`string`)}function mt(e){return typeof e==`function`}function ht(e){return typeof e==`object`}function gt(e){return typeof e==`object`&&!Array.isArray(e)}function _t(e={},t=()=>!0){let n={};return Qe(e).forEach(r=>{t(r,e[r])&&(n[r]=e[r])}),n}function vt(e){typeof process<`u`&&[process.stdout,process.stderr].forEach(t=>{let n=t;n._handle&&n.isTTY&&typeof n._handle.setBlocking==`function`&&n._handle.setBlocking(e)})}function yt(e){return typeof e==`boolean`}function bt(e,t){let n=t.y18n.__,r={},i=[];r.failFn=function(e){i.push(e)};let a=null,o=null,s=!0;r.showHelpOnFail=function(t=!0,n){let[i,c]=typeof t==`string`?[!0,t]:[t,n];return e.getInternalMethods().isGlobalContext()&&(o=c),a=c,s=i,r};let c=!1;r.fail=function(t,n){let l=e.getInternalMethods().getLoggerInstance();if(i.length)for(let e=i.length-1;e>=0;--e){let a=i[e];if(yt(a)){if(n)throw n;if(t)throw Error(t)}else a(t,n,r)}else{if(e.getExitProcess()&&vt(!0),!c){c=!0,s&&(e.showHelp(`error`),l.error()),(t||n)&&l.error(t||n);let r=a||o;r&&((t||n)&&l.error(``),l.error(r))}if(n||=new P(t),e.getExitProcess())return e.exit(1);if(e.getInternalMethods().hasParseCallback())return e.exit(1,n);throw n}};let l=[],u=!1;r.usage=(e,t)=>e===null?(u=!0,l=[],r):(u=!1,l.push([e,t||``]),r),r.getUsage=()=>l,r.getUsageDisabled=()=>u,r.getPositionalGroupName=()=>n(`Positionals:`);let d=[];r.example=(e,t)=>{d.push([e,t||``])};let f=[];r.command=function(e,t,n,r,i=!1){n&&(f=f.map(e=>(e[2]=!1,e))),f.push([e,t||``,n,r,i])},r.getCommands=()=>f;let p={};r.describe=function(e,t){Array.isArray(e)?e.forEach(e=>{r.describe(e,t)}):typeof e==`object`?Object.keys(e).forEach(t=>{r.describe(t,e[t])}):p[e]=t},r.getDescriptions=()=>p;let m=[];r.epilog=e=>{m.push(e)};let h=!1,g;r.wrap=e=>{h=!0,g=e},r.getWrap=()=>t.getEnv(`YARGS_DISABLE_WRAP`)?null:(h||=(g=b(),!0),g);let _=`__yargsString__:`;r.deferY18nLookup=e=>_+e,r.help=function(){if(y)return y;ee();let i=e.customScriptName?e.$0:t.path.basename(e.$0),a=e.getDemandedOptions(),o=e.getDemandedCommands(),s=e.getDeprecatedOptions(),c=e.getGroups(),h=e.getOptions(),g=[];g=g.concat(Object.keys(p)),g=g.concat(Object.keys(a)),g=g.concat(Object.keys(o)),g=g.concat(Object.keys(h.default)),g=g.filter(ne),g=Object.keys(g.reduce((e,t)=>(t!==`_`&&(e[t]=!0),e),{}));let b=r.getWrap(),x=t.cliui({width:b,wrap:!!b});if(!u){if(l.length)l.forEach(e=>{x.div({text:`${e[0].replace(/\$0/g,i)}`}),e[1]&&x.div({text:`${e[1]}`,padding:[1,0,0,0]})}),x.div();else if(f.length){let e=null;e=o._?`${i} <${n(`command`)}>\n`:`${i} [${n(`command`)}]\n`,x.div(`${e}`)}}if(f.length>1||f.length===1&&!f[0][2]){x.div(n(`Commands:`));let t=e.getInternalMethods().getContext(),r=t.commands.length?`${t.commands.join(` `)} `:``;e.getInternalMethods().getParserConfiguration()[`sort-commands`]===!0&&(f=f.sort((e,t)=>e[0].localeCompare(t[0])));let a=i?`${i} `:``;f.forEach(e=>{let t=`${a}${r}${e[0].replace(/^\$0 ?/,``)}`;x.span({text:t,padding:[0,2,0,2],width:v(f,b,`${i}${r}`)+4},{text:e[1]});let o=[];e[2]&&o.push(`[${n(`default`)}]`),e[3]&&e[3].length&&o.push(`[${n(`aliases:`)} ${e[3].join(`, `)}]`),e[4]&&(typeof e[4]==`string`?o.push(`[${n(`deprecated: %s`,e[4])}]`):o.push(`[${n(`deprecated`)}]`)),o.length?x.div({text:o.join(` `),padding:[0,0,0,2],align:`right`}):x.div()}),x.div()}let ie=(Object.keys(h.alias)||[]).concat(Object.keys(e.parsed.newAliases)||[]);g=g.filter(t=>!e.parsed.newAliases[t]&&ie.every(e=>(h.alias[e]||[]).indexOf(t)===-1));let S=n(`Options:`);c[S]||(c[S]=[]),te(g,h.alias,c,S);let C=e=>/^--/.test(wt(e)),w=Object.keys(c).filter(e=>c[e].length>0).map(e=>({groupName:e,normalizedKeys:c[e].filter(ne).map(e=>{if(ie.includes(e))return e;for(let t=0,n;(n=ie[t])!==void 0;t++)if((h.alias[n]||[]).includes(e))return n;return e})})).filter(({normalizedKeys:e})=>e.length>0).map(({groupName:e,normalizedKeys:t})=>({groupName:e,normalizedKeys:t,switches:t.reduce((t,n)=>(t[n]=[n].concat(h.alias[n]||[]).map(t=>e===r.getPositionalGroupName()?t:(/^[0-9]$/.test(t)?h.boolean.includes(n)?`-`:`--`:t.length>1?`--`:`-`)+t).sort((e,t)=>C(e)===C(t)?0:C(e)?1:-1).join(`, `),t),{})}));if(w.filter(({groupName:e})=>e!==r.getPositionalGroupName()).some(({normalizedKeys:e,switches:t})=>!e.every(e=>C(t[e])))&&w.filter(({groupName:e})=>e!==r.getPositionalGroupName()).forEach(({normalizedKeys:e,switches:t})=>{e.forEach(e=>{C(t[e])&&(t[e]=St(t[e],4))})}),w.forEach(({groupName:t,normalizedKeys:i,switches:o})=>{x.div(t),i.forEach(t=>{let i=o[t],c=p[t]||``,l=null;c.includes(_)&&(c=n(c.substring(16))),h.boolean.includes(t)&&(l=`[${n(`boolean`)}]`),h.count.includes(t)&&(l=`[${n(`count`)}]`),h.string.includes(t)&&(l=`[${n(`string`)}]`),h.normalize.includes(t)&&(l=`[${n(`string`)}]`),h.array.includes(t)&&(l=`[${n(`array`)}]`),h.number.includes(t)&&(l=`[${n(`number`)}]`);let u=[t in s?(e=>typeof e==`string`?`[${n(`deprecated: %s`,e)}]`:`[${n(`deprecated`)}]`)(s[t]):null,l,t in a?`[${n(`required`)}]`:null,h.choices&&h.choices[t]?`[${n(`choices:`)} ${r.stringifiedValues(h.choices[t])}]`:null,re(h.default[t],h.defaultDescription[t])].filter(Boolean).join(` `);x.span({text:wt(i),padding:[0,2,0,2+Ct(i)],width:v(o,b)+4},c);let d=e.getInternalMethods().getUsageConfiguration()[`hide-types`]===!0;u&&!d?x.div({text:u,padding:[0,0,0,2],align:`right`}):x.div()}),x.div()}),d.length&&(x.div(n(`Examples:`)),d.forEach(e=>{e[0]=e[0].replace(/\$0/g,i)}),d.forEach(e=>{e[1]===``?x.div({text:e[0],padding:[0,2,0,2]}):x.div({text:e[0],padding:[0,2,0,2],width:v(d,b)+4},{text:e[1]})}),x.div()),m.length>0){let e=m.map(e=>e.replace(/\$0/g,i)).join(`
40
- `);x.div(`${e}\n`)}return x.toString().replace(/\s*$/,``)};function v(e,n,r){let i=0;return Array.isArray(e)||(e=Object.values(e).map(e=>[e])),e.forEach(e=>{i=Math.max(t.stringWidth(r?`${r} ${wt(e[0])}`:wt(e[0]))+Ct(e[0]),i)}),n&&(i=Math.min(i,parseInt((n*.5).toString(),10))),i}function ee(){let t=e.getDemandedOptions(),n=e.getOptions();(Object.keys(n.alias)||[]).forEach(i=>{n.alias[i].forEach(a=>{p[a]&&r.describe(i,p[a]),a in t&&e.demandOption(i,t[a]),n.boolean.includes(a)&&e.boolean(i),n.count.includes(a)&&e.count(i),n.string.includes(a)&&e.string(i),n.normalize.includes(a)&&e.normalize(i),n.array.includes(a)&&e.array(i),n.number.includes(a)&&e.number(i)})})}let y;r.cacheHelpMessage=function(){y=this.help()},r.clearCachedHelpMessage=function(){y=void 0},r.hasCachedHelpMessage=function(){return!!y};function te(e,t,n,r){let i=[],a=null;return Object.keys(n).forEach(e=>{i=i.concat(n[e])}),e.forEach(e=>{a=[e].concat(t[e]),a.some(e=>i.indexOf(e)!==-1)||n[r].push(e)}),i}function ne(t){return e.getOptions().hiddenOptions.indexOf(t)<0||e.parsed.argv[e.getOptions().showHiddenOpt]}r.showHelp=t=>{let n=e.getInternalMethods().getLoggerInstance();t||=`error`,(typeof t==`function`?t:n[t])(r.help())},r.functionDescription=e=>[`(`,e.name?t.Parser.decamelize(e.name,`-`):n(`generated-value`),`)`].join(``),r.stringifiedValues=function(e,t){let n=``,r=t||`, `,i=[].concat(e);return!e||!i.length||i.forEach(e=>{n.length&&(n+=r),n+=JSON.stringify(e)}),n};function re(e,t){let r=`[${n(`default:`)} `;if(e===void 0&&!t)return null;if(t)r+=t;else switch(typeof e){case`string`:r+=`"${e}"`;break;case`object`:r+=JSON.stringify(e);break;default:r+=e}return`${r}]`}function b(){return t.process.stdColumns?Math.min(80,t.process.stdColumns):80}let x=null;r.version=e=>{x=e},r.showVersion=t=>{let n=e.getInternalMethods().getLoggerInstance();t||=`error`,(typeof t==`function`?t:n[t])(x)},r.reset=function(e){return a=null,c=!1,l=[],u=!1,m=[],d=[],f=[],p=_t(p,t=>!e[t]),r};let ie=[];return r.freeze=function(){ie.push({failMessage:a,failureOutput:c,usages:l,usageDisabled:u,epilogs:m,examples:d,commands:f,descriptions:p})},r.unfreeze=function(e=!1){let t=ie.pop();t&&(e?(p={...t.descriptions,...p},f=[...t.commands,...f],l=[...t.usages,...l],d=[...t.examples,...d],m=[...t.epilogs,...m]):{failMessage:a,failureOutput:c,usages:l,usageDisabled:u,epilogs:m,examples:d,commands:f,descriptions:p}=t)},r}function xt(e){return typeof e==`object`}function St(e,t){return xt(e)?{text:e.text,indentation:e.indentation+t}:{text:e,indentation:t}}function Ct(e){return xt(e)?e.indentation:0}function wt(e){return xt(e)?e.text:e}var Tt=class{constructor(e,t,n,r){this.yargs=e,this.usage=t,this.command=n,this.shim=r,this.completionKey=`get-yargs-completions`,this.aliases=null,this.customCompletionFunction=null,this.indexAfterLastReset=0,this.zshShell=(this.shim.getEnv(`SHELL`)?.includes(`zsh`)||this.shim.getEnv(`ZSH_NAME`)?.includes(`zsh`))??!1}defaultCompletion(e,t,n,r){let i=this.command.getCommandHandlers();for(let t=0,n=e.length;t<n;++t)if(i[e[t]]&&i[e[t]].builder){let n=i[e[t]].builder;if(mt(n)){this.indexAfterLastReset=t+1;let e=this.yargs.getInternalMethods().reset();return n(e,!0),e.argv}}let a=[];this.commandCompletions(a,e,n),this.optionCompletions(a,e,t,n),this.choicesFromOptionsCompletions(a,e,t,n),this.choicesFromPositionalsCompletions(a,e,t,n),r(null,a)}commandCompletions(e,t,n){let r=this.yargs.getInternalMethods().getContext().commands;!n.match(/^-/)&&r[r.length-1]!==n&&!this.previousArgHasChoices(t)&&this.usage.getCommands().forEach(n=>{let r=$e(n[0]).cmd;if(t.indexOf(r)===-1){if(!this.zshShell)e.push(r);else{let t=n[1]||``;e.push(r.replace(/:/g,`\\:`)+`:`+t)}}})}optionCompletions(e,t,n,r){if((r.match(/^-/)||r===``&&e.length===0)&&!this.previousArgHasChoices(t)){let n=this.yargs.getOptions(),i=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[];Object.keys(n.key).forEach(a=>{let o=!!n.configuration[`boolean-negation`]&&n.boolean.includes(a);i.includes(a)||n.hiddenOptions.includes(a)||this.argsContainKey(t,a,o)||this.completeOptionKey(a,e,r,o&&!!n.default[a])})}}choicesFromOptionsCompletions(e,t,n,r){if(this.previousArgHasChoices(t)){let n=this.getPreviousArgChoices(t);n&&n.length>0&&e.push(...n.map(e=>e.replace(/:/g,`\\:`)))}}choicesFromPositionalsCompletions(e,t,n,r){if(r===``&&e.length>0&&this.previousArgHasChoices(t))return;let i=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[],a=Math.max(this.indexAfterLastReset,this.yargs.getInternalMethods().getContext().commands.length+1),o=i[n._.length-a-1];if(!o)return;let s=this.yargs.getOptions().choices[o]||[];for(let t of s)t.startsWith(r)&&e.push(t.replace(/:/g,`\\:`))}getPreviousArgChoices(e){if(e.length<1)return;let t=e[e.length-1],n=``;if(!t.startsWith(`-`)&&e.length>1&&(n=t,t=e[e.length-2]),!t.startsWith(`-`))return;let r=t.replace(/^-+/,``),i=this.yargs.getOptions(),a=[r,...this.yargs.getAliases()[r]||[]],o;for(let e of a)if(Object.prototype.hasOwnProperty.call(i.key,e)&&Array.isArray(i.choices[e])){o=i.choices[e];break}if(o)return o.filter(e=>!n||e.startsWith(n))}previousArgHasChoices(e){let t=this.getPreviousArgChoices(e);return t!==void 0&&t.length>0}argsContainKey(e,t,n){let r=t=>e.indexOf((/^[^0-9]$/.test(t)?`-`:`--`)+t)!==-1;if(r(t)||n&&r(`no-${t}`))return!0;if(this.aliases){for(let e of this.aliases[t])if(r(e))return!0}return!1}completeOptionKey(e,t,n,r){let i=e;if(this.zshShell){let t=this.usage.getDescriptions(),n=((this===null||this===void 0?void 0:this.aliases)?.[e])?.find(e=>{let n=t[e];return typeof n==`string`&&n.length>0}),r=n?t[n]:void 0,a=t[e]??r??``;i=`${e.replace(/:/g,`\\:`)}:${a.replace(`__yargsString__:`,``).replace(/(\r\n|\n|\r)/gm,` `)}`}let a=!(e=>/^--/.test(e))(n)&&(e=>/^[^0-9]$/.test(e))(e)?`-`:`--`;t.push(a+i),r&&t.push(a+`no-`+i)}customCompletion(e,t,n,r){if(Xe(this.customCompletionFunction,null,this.shim),Dt(this.customCompletionFunction)){let e=this.customCompletionFunction(n,t);return F(e)?e.then(e=>{this.shim.process.nextTick(()=>{r(null,e)})}).catch(e=>{this.shim.process.nextTick(()=>{r(e,void 0)})}):r(null,e)}return Ot(this.customCompletionFunction)?this.customCompletionFunction(n,t,(i=r)=>this.defaultCompletion(e,t,n,i),e=>{r(null,e)}):this.customCompletionFunction(n,t,e=>{r(null,e)})}getCompletion(e,t){let n=e.length?e[e.length-1]:``,r=this.yargs.parse(e,!0),i=this.customCompletionFunction?r=>this.customCompletion(e,r,n,t):r=>this.defaultCompletion(e,r,n,t);return F(r)?r.then(i):i(r)}generateCompletionScript(e,t){let n=this.zshShell?`#compdef {{app_name}}
39
+ const Ie=process&&process.env&&process.env.YARGS_MIN_NODE_VERSION?Number(process.env.YARGS_MIN_NODE_VERSION):12,Le=(process==null?void 0:process.versions)?.node??(process==null?void 0:process.version)?.slice(1);if(Le&&Number(Le.match(/^([^.]+)/)[1])<Ie)throw Error(`yargs parser supports a minimum Node.js version of ${Ie}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`);const Re=process?process.env:{},ze=new je({cwd:process.cwd,env:()=>Re,format:y,normalize:p,resolve:h,require:e=>{if(ge!==void 0)return ge(e);if(e.match(/\.json$/))return JSON.parse(g(e,`utf8`));throw Error(`only .json config files are supported in ESM`)}}),Be=function(e,t){return ze.parse(e.slice(),t).argv};Be.detailed=function(e,t){return ze.parse(e.slice(),t)},Be.camelCase=Oe,Be.decamelize=k,Be.looksLikeNumber=ke;function Ve(){return+!He()}function He(){return Ue()&&!process.defaultApp}function Ue(){return!!process.versions.electron}function We(){return process.argv[Ve()]}var M=class e extends Error{constructor(t){super(t||`yargs error`),this.name=`YError`,Error.captureStackTrace&&Error.captureStackTrace(this,e)}},N={fs:{readFileSync:g,writeFile:ee},format:y,resolve:h,exists:e=>{try{return v(e).isFile()}catch{return!1}}};let P;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(),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 Ke(e,t){P=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,N),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:Ee,findUp:De,getEnv:e=>process.env[e],inspect:te,getCallerFile:()=>{throw new M(Je)},getProcessArgvBin:We,mainFilename:Xe||process.cwd(),Parser:Be,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 F(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 I(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(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 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(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 ct(e,t,n=e=>{throw e}){try{let n=lt(e)?e():e;return F(n)?n.then(e=>t(e)):t(n)}catch(e){return n(e)}}function lt(e){return typeof e==`function`}function ut(e){if(ge===void 0)return null;for(let t=0,n=Object.keys(ge.cache),r;t<n.length;t++)if(r=ge.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 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(gt(c)){n.getInternalMethods().getUsageInstance().freeze();let u=c(n.getInternalMethods().reset(r),s);if(F(u))return u.then(r=>(l=er(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 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=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 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=st(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=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 _=`__yargsString__:`;r.deferY18nLookup=e=>_+e,r.help=function(){if(y)return y;ee();let i=e.customScriptName?e.$0:t.path.basename(e.$0),a=e.getDemandedOptions(),o=e.getDemandedCommands(),s=e.getDeprecatedOptions(),c=e.getGroups(),h=e.getOptions(),g=[];g=g.concat(Object.keys(p)),g=g.concat(Object.keys(a)),g=g.concat(Object.keys(o)),g=g.concat(Object.keys(h.default)),g=g.filter(ne),g=Object.keys(g.reduce((e,t)=>(t!==`_`&&(e[t]=!0),e),{}));let b=r.getWrap(),x=t.cliui({width:b,wrap:!!b});if(!u){if(l.length)l.forEach(e=>{x.div({text:`${e[0].replace(/\$0/g,i)}`}),e[1]&&x.div({text:`${e[1]}`,padding:[1,0,0,0]})}),x.div();else if(f.length){let e=null;e=o._?`${i} <${n(`command`)}>\n`:`${i} [${n(`command`)}]\n`,x.div(`${e}`)}}if(f.length>1||f.length===1&&!f[0][2]){x.div(n(`Commands:`));let t=e.getInternalMethods().getContext(),r=t.commands.length?`${t.commands.join(` `)} `:``;e.getInternalMethods().getParserConfiguration()[`sort-commands`]===!0&&(f=f.sort((e,t)=>e[0].localeCompare(t[0])));let a=i?`${i} `:``;f.forEach(e=>{let t=`${a}${r}${e[0].replace(/^\$0 ?/,``)}`;x.span({text:t,padding:[0,2,0,2],width:v(f,b,`${i}${r}`)+4},{text:e[1]});let o=[];e[2]&&o.push(`[${n(`default`)}]`),e[3]&&e[3].length&&o.push(`[${n(`aliases:`)} ${e[3].join(`, `)}]`),e[4]&&(typeof e[4]==`string`?o.push(`[${n(`deprecated: %s`,e[4])}]`):o.push(`[${n(`deprecated`)}]`)),o.length?x.div({text:o.join(` `),padding:[0,0,0,2],align:`right`}):x.div()}),x.div()}let ie=(Object.keys(h.alias)||[]).concat(Object.keys(e.parsed.newAliases)||[]);g=g.filter(t=>!e.parsed.newAliases[t]&&ie.every(e=>(h.alias[e]||[]).indexOf(t)===-1));let ae=n(`Options:`);c[ae]||(c[ae]=[]),te(g,h.alias,c,ae);let S=e=>/^--/.test(Et(e)),oe=Object.keys(c).filter(e=>c[e].length>0).map(e=>({groupName:e,normalizedKeys:c[e].filter(ne).map(e=>{if(ie.includes(e))return e;for(let t=0,n;(n=ie[t])!==void 0;t++)if((h.alias[n]||[]).includes(e))return n;return e})})).filter(({normalizedKeys:e})=>e.length>0).map(({groupName:e,normalizedKeys:t})=>({groupName:e,normalizedKeys:t,switches:t.reduce((t,n)=>(t[n]=[n].concat(h.alias[n]||[]).map(t=>e===r.getPositionalGroupName()?t:(/^[0-9]$/.test(t)?h.boolean.includes(n)?`-`:`--`:t.length>1?`--`:`-`)+t).sort((e,t)=>S(e)===S(t)?0:S(e)?1:-1).join(`, `),t),{})}));if(oe.filter(({groupName:e})=>e!==r.getPositionalGroupName()).some(({normalizedKeys:e,switches:t})=>!e.every(e=>S(t[e])))&&oe.filter(({groupName:e})=>e!==r.getPositionalGroupName()).forEach(({normalizedKeys:e,switches:t})=>{e.forEach(e=>{S(t[e])&&(t[e]=wt(t[e],4))})}),oe.forEach(({groupName:t,normalizedKeys:i,switches:o})=>{x.div(t),i.forEach(t=>{let i=o[t],c=p[t]||``,l=null;c.includes(_)&&(c=n(c.substring(16))),h.boolean.includes(t)&&(l=`[${n(`boolean`)}]`),h.count.includes(t)&&(l=`[${n(`count`)}]`),h.string.includes(t)&&(l=`[${n(`string`)}]`),h.normalize.includes(t)&&(l=`[${n(`string`)}]`),h.array.includes(t)&&(l=`[${n(`array`)}]`),h.number.includes(t)&&(l=`[${n(`number`)}]`);let u=[t in s?(e=>typeof e==`string`?`[${n(`deprecated: %s`,e)}]`:`[${n(`deprecated`)}]`)(s[t]):null,l,t in a?`[${n(`required`)}]`:null,h.choices&&h.choices[t]?`[${n(`choices:`)} ${r.stringifiedValues(h.choices[t])}]`:null,re(h.default[t],h.defaultDescription[t])].filter(Boolean).join(` `);x.span({text:Et(i),padding:[0,2,0,2+Tt(i)],width:v(o,b)+4},c);let d=e.getInternalMethods().getUsageConfiguration()[`hide-types`]===!0;u&&!d?x.div({text:u,padding:[0,0,0,2],align:`right`}):x.div()}),x.div()}),d.length&&(x.div(n(`Examples:`)),d.forEach(e=>{e[0]=e[0].replace(/\$0/g,i)}),d.forEach(e=>{e[1]===``?x.div({text:e[0],padding:[0,2,0,2]}):x.div({text:e[0],padding:[0,2,0,2],width:v(d,b)+4},{text:e[1]})}),x.div()),m.length>0){let e=m.map(e=>e.replace(/\$0/g,i)).join(`
40
+ `);x.div(`${e}\n`)}return x.toString().replace(/\s*$/,``)};function v(e,n,r){let i=0;return Array.isArray(e)||(e=Object.values(e).map(e=>[e])),e.forEach(e=>{i=Math.max(t.stringWidth(r?`${r} ${Et(e[0])}`:Et(e[0]))+Tt(e[0]),i)}),n&&(i=Math.min(i,parseInt((n*.5).toString(),10))),i}function ee(){let t=e.getDemandedOptions(),n=e.getOptions();(Object.keys(n.alias)||[]).forEach(i=>{n.alias[i].forEach(a=>{p[a]&&r.describe(i,p[a]),a in t&&e.demandOption(i,t[a]),n.boolean.includes(a)&&e.boolean(i),n.count.includes(a)&&e.count(i),n.string.includes(a)&&e.string(i),n.normalize.includes(a)&&e.normalize(i),n.array.includes(a)&&e.array(i),n.number.includes(a)&&e.number(i)})})}let y;r.cacheHelpMessage=function(){y=this.help()},r.clearCachedHelpMessage=function(){y=void 0},r.hasCachedHelpMessage=function(){return!!y};function te(e,t,n,r){let i=[],a=null;return Object.keys(n).forEach(e=>{i=i.concat(n[e])}),e.forEach(e=>{a=[e].concat(t[e]),a.some(e=>i.indexOf(e)!==-1)||n[r].push(e)}),i}function ne(t){return e.getOptions().hiddenOptions.indexOf(t)<0||e.parsed.argv[e.getOptions().showHiddenOpt]}r.showHelp=t=>{let n=e.getInternalMethods().getLoggerInstance();t||=`error`,(typeof t==`function`?t:n[t])(r.help())},r.functionDescription=e=>[`(`,e.name?t.Parser.decamelize(e.name,`-`):n(`generated-value`),`)`].join(``),r.stringifiedValues=function(e,t){let n=``,r=t||`, `,i=[].concat(e);return!e||!i.length||i.forEach(e=>{n.length&&(n+=r),n+=JSON.stringify(e)}),n};function re(e,t){let r=`[${n(`default:`)} `;if(e===void 0&&!t)return null;if(t)r+=t;else switch(typeof e){case`string`:r+=`"${e}"`;break;case`object`:r+=JSON.stringify(e);break;default:r+=e}return`${r}]`}function b(){return t.process.stdColumns?Math.min(80,t.process.stdColumns):80}let x=null;r.version=e=>{x=e},r.showVersion=t=>{let n=e.getInternalMethods().getLoggerInstance();t||=`error`,(typeof t==`function`?t:n[t])(x)},r.reset=function(e){return a=null,c=!1,l=[],u=!1,m=[],d=[],f=[],p=yt(p,t=>!e[t]),r};let ie=[];return r.freeze=function(){ie.push({failMessage:a,failureOutput:c,usages:l,usageDisabled:u,epilogs:m,examples:d,commands:f,descriptions:p})},r.unfreeze=function(e=!1){let t=ie.pop();t&&(e?(p={...t.descriptions,...p},f=[...t.commands,...f],l=[...t.usages,...l],d=[...t.examples,...d],m=[...t.epilogs,...m]):{failMessage:a,failureOutput:c,usages:l,usageDisabled:u,epilogs:m,examples:d,commands:f,descriptions:p}=t)},r}function 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 F(e)?e.then(e=>{this.shim.process.nextTick(()=>{r(null,e)})}).catch(e=>{this.shim.process.nextTick(()=>{r(e,void 0)})}):r(null,e)}return 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 F(r)?r.then(i):i(r)}generateCompletionScript(e,t){let n=this.zshShell?`#compdef {{app_name}}
41
41
  ###-begin-{{app_name}}-completions-###
42
42
  #
43
43
  # yargs command completion script
@@ -84,83 +84,83 @@ _{{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 Et(e,t,n,r){return new Tt(e,t,n,r)}function Dt(e){return e.length<3}function Ot(e){return e.length>3}function kt(e,t){if(e.length===0)return t.length;if(t.length===0)return e.length;let n=[],r=0;for(;r<=t.length;r++)n[r]=[r];let i=0;for(;i<=e.length;i++)n[0][i]=i;for(r=1;r<=t.length;r++)for(i=1;i<=e.length;i++)t.charAt(r-1)===e.charAt(i-1)?n[r][i]=n[r-1][i-1]:r>1&&i>1&&t.charAt(r-2)===e.charAt(i-1)&&t.charAt(r-1)===e.charAt(i-2)?n[r][i]=n[r-2][i-2]+1:n[r][i]=Math.min(n[r-1][i-1]+1,Math.min(n[r][i-1]+1,n[r-1][i]+1));return n[t.length][e.length]}const At=[`$0`,`--`,`_`];function jt(e,t,n){let r=n.y18n.__,i=n.y18n.__n,a={};a.nonOptionCount=function(n){let r=e.getDemandedCommands(),a=n._.length+(n[`--`]?n[`--`].length:0)-e.getInternalMethods().getContext().commands.length;r._&&(a<r._.min||a>r._.max)&&(a<r._.min?r._.minMsg===void 0?t.fail(i(`Not enough non-option arguments: got %s, need at least %s`,`Not enough non-option arguments: got %s, need at least %s`,a,a.toString(),r._.min.toString())):t.fail(r._.minMsg?r._.minMsg.replace(/\$0/g,a.toString()).replace(/\$1/,r._.min.toString()):null):a>r._.max&&(r._.maxMsg===void 0?t.fail(i(`Too many non-option arguments: got %s, maximum of %s`,`Too many non-option arguments: got %s, maximum of %s`,a,a.toString(),r._.max.toString())):t.fail(r._.maxMsg?r._.maxMsg.replace(/\$0/g,a.toString()).replace(/\$1/,r._.max.toString()):null)))},a.positionalCount=function(e,n){n<e&&t.fail(i(`Not enough non-option arguments: got %s, need at least %s`,`Not enough non-option arguments: got %s, need at least %s`,n,n+``,e+``))},a.requiredArguments=function(e,n){let r=null;for(let t of Object.keys(n))Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==void 0||(r||={},r[t]=n[t]);if(r){let e=[];for(let t of Object.keys(r)){let n=r[t];n&&e.indexOf(n)<0&&e.push(n)}let n=e.length?`\n${e.join(`
88
- `)}`:``;t.fail(i(`Missing required argument: %s`,`Missing required arguments: %s`,Object.keys(r).length,Object.keys(r).join(`, `)+n))}},a.unknownArguments=function(n,r,o,s,c=!0){let l=e.getInternalMethods().getCommandInstance().getCommands(),u=[],d=e.getInternalMethods().getContext();if(Object.keys(n).forEach(t=>{At.includes(t)||Object.prototype.hasOwnProperty.call(o,t)||Object.prototype.hasOwnProperty.call(e.getInternalMethods().getParseContext(),t)||a.isValidAndSomeAliasIsNotNew(t,r)||u.push(t)}),c&&(d.commands.length>0||l.length>0||s)&&n._.slice(d.commands.length).forEach(e=>{l.includes(``+e)||u.push(``+e)}),c){let t=e.getDemandedCommands()._?.max||0,r=d.commands.length+t;r<n._.length&&n._.slice(r).forEach(e=>{e=String(e),!d.commands.includes(e)&&!u.includes(e)&&u.push(e)})}u.length&&t.fail(i(`Unknown argument: %s`,`Unknown arguments: %s`,u.length,u.map(e=>e.trim()?e:`"${e}"`).join(`, `)))},a.unknownCommands=function(n){let r=e.getInternalMethods().getCommandInstance().getCommands(),a=[],o=e.getInternalMethods().getContext();return(o.commands.length>0||r.length>0)&&n._.slice(o.commands.length).forEach(e=>{r.includes(``+e)||a.push(``+e)}),a.length>0&&(t.fail(i(`Unknown command: %s`,`Unknown commands: %s`,a.length,a.join(`, `))),!0)},a.isValidAndSomeAliasIsNotNew=function(t,n){if(!Object.prototype.hasOwnProperty.call(n,t))return!1;let r=e.parsed.newAliases;return[t,...n[t]].some(e=>!Object.prototype.hasOwnProperty.call(r,e)||!r[t])},a.limitedChoices=function(n){let i=e.getOptions(),a={};if(!Object.keys(i.choices).length)return;Object.keys(n).forEach(e=>{At.indexOf(e)===-1&&Object.prototype.hasOwnProperty.call(i.choices,e)&&[].concat(n[e]).forEach(t=>{i.choices[e].indexOf(t)===-1&&t!==void 0&&(a[e]=(a[e]||[]).concat(t))})});let o=Object.keys(a);if(!o.length)return;let s=r(`Invalid values:`);o.forEach(e=>{s+=`\n ${r(`Argument: %s, Given: %s, Choices: %s`,e,t.stringifiedValues(a[e]),t.stringifiedValues(i.choices[e]))}`}),t.fail(s)};let o={};a.implies=function(t,r){I(`<string|object> [array|number|string]`,[t,r],arguments.length),typeof t==`object`?Object.keys(t).forEach(e=>{a.implies(e,t[e])}):(e.global(t),o[t]||(o[t]=[]),Array.isArray(r)?r.forEach(e=>a.implies(t,e)):(Xe(r,void 0,n),o[t].push(r)))},a.getImplied=function(){return o};function s(e,t){let n=Number(t);return t=isNaN(n)?t:n,typeof t==`number`?t=e._.length>=t:t.match(/^--no-.+/)?(t=t.match(/^--no-(.+)/)[1],t=!Object.prototype.hasOwnProperty.call(e,t)):t=Object.prototype.hasOwnProperty.call(e,t),t}a.implications=function(e){let n=[];if(Object.keys(o).forEach(t=>{let r=t;(o[t]||[]).forEach(t=>{let i=r,a=t;i=s(e,i),t=s(e,t),i&&!t&&n.push(` ${r} -> ${a}`)})}),n.length){let e=`${r(`Implications failed:`)}\n`;n.forEach(t=>{e+=t}),t.fail(e)}};let c={};a.conflicts=function(t,n){I(`<string|object> [array|string]`,[t,n],arguments.length),typeof t==`object`?Object.keys(t).forEach(e=>{a.conflicts(e,t[e])}):(e.global(t),c[t]||(c[t]=[]),Array.isArray(n)?n.forEach(e=>a.conflicts(t,e)):c[t].push(n))},a.getConflicting=()=>c,a.conflicting=function(i){Object.keys(i).forEach(e=>{c[e]&&c[e].forEach(n=>{n&&i[e]!==void 0&&i[n]!==void 0&&t.fail(r(`Arguments %s and %s are mutually exclusive`,e,n))})}),e.getInternalMethods().getParserConfiguration()[`strip-dashed`]&&Object.keys(c).forEach(e=>{c[e].forEach(a=>{a&&i[n.Parser.camelCase(e)]!==void 0&&i[n.Parser.camelCase(a)]!==void 0&&t.fail(r(`Arguments %s and %s are mutually exclusive`,e,a))})})},a.recommendCommands=function(e,n){n=n.sort((e,t)=>t.length-e.length);let i=null,a=1/0;for(let t=0,r;(r=n[t])!==void 0;t++){let t=kt(e,r);t<=3&&t<a&&(a=t,i=r)}i&&t.fail(r(`Did you mean %s?`,i))},a.reset=function(e){return o=_t(o,t=>!e[t]),c=_t(c,t=>!e[t]),a};let l=[];return a.freeze=function(){l.push({implied:o,conflicting:c})},a.unfreeze=function(){let e=l.pop();Xe(e,void 0,n),{implied:o,conflicting:c}=e},a}let Mt=[],Nt;function Pt(e,t,n,r){Nt=r;let i={};if(Object.prototype.hasOwnProperty.call(e,`extends`)){if(typeof e.extends!=`string`)return i;let r=/\.json|\..*rc$/.test(e.extends),a=null;if(r)a=It(t,e.extends);else try{a=fe.resolve(e.extends)}catch{return e}Ft(a),Mt.push(a),i=r?JSON.parse(Nt.readFileSync(a,`utf8`)):fe(e.extends),delete e.extends,i=Pt(i,Nt.path.dirname(a),n,Nt)}return Mt=[],n?Lt(i,e):Object.assign({},i,e)}function Ft(e){if(Mt.indexOf(e)>-1)throw new P(`Circular extended configurations: '${e}'.`)}function It(e,t){return Nt.path.resolve(e,t)}function Lt(e,t){let n={};function r(e){return e&&typeof e==`object`&&!Array.isArray(e)}Object.assign(n,e);for(let i of Object.keys(t))n[i]=r(t[i])&&r(n[i])?Lt(e[i],t[i]):t[i];return n}var L=function(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n},R=function(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)},z,Rt,zt,Bt,Vt,Ht,Ut,Wt,Gt,Kt,qt,Jt,Yt,Xt,Zt,Qt,$t,B,V,en,tn,nn,rn,an,on,sn,cn,H,ln,un,dn,U,fn,pn,W;function mn(e){return(t=[],n=e.process.cwd(),r)=>{let i=new Zn(t,n,r,e);return Object.defineProperty(i,"argv",{get:()=>i.parse(),enumerable:!0}),i.help(),i.version(),i}}const hn=Symbol(`copyDoubleDash`),gn=Symbol(`copyDoubleDash`),_n=Symbol(`deleteFromParserHintObject`),vn=Symbol(`emitWarning`),yn=Symbol(`freeze`),bn=Symbol(`getDollarZero`),xn=Symbol(`getParserConfiguration`),Sn=Symbol(`getUsageConfiguration`),Cn=Symbol(`guessLocale`),wn=Symbol(`guessVersion`),Tn=Symbol(`parsePositionalNumbers`),En=Symbol(`pkgUp`),Dn=Symbol(`populateParserHintArray`),On=Symbol(`populateParserHintSingleValueDictionary`),kn=Symbol(`populateParserHintArrayDictionary`),An=Symbol(`populateParserHintDictionary`),jn=Symbol(`sanitizeKey`),Mn=Symbol(`setKey`),Nn=Symbol(`unfreeze`),Pn=Symbol(`validateAsync`),Fn=Symbol(`getCommandInstance`),In=Symbol(`getContext`),Ln=Symbol(`getHasOutput`),Rn=Symbol(`getLoggerInstance`),zn=Symbol(`getParseContext`),Bn=Symbol(`getUsageInstance`),Vn=Symbol(`getValidationInstance`),Hn=Symbol(`hasParseCallback`),Un=Symbol(`isGlobalContext`),Wn=Symbol(`postProcess`),Gn=Symbol(`rebase`),Kn=Symbol(`reset`),qn=Symbol(`runYargsParserAndExecuteCommands`),Jn=Symbol(`runValidation`),Yn=Symbol(`setHasOutput`),Xn=Symbol(`kTrackManuallySetKeys`);var Zn=class{constructor(e=[],t,n,r){this.customScriptName=!1,this.parsed=!1,z.set(this,void 0),Rt.set(this,void 0),zt.set(this,{commands:[],fullCommands:[]}),Bt.set(this,null),Vt.set(this,null),Ht.set(this,`show-hidden`),Ut.set(this,null),Wt.set(this,!0),Gt.set(this,{}),Kt.set(this,!0),qt.set(this,[]),Jt.set(this,void 0),Yt.set(this,{}),Xt.set(this,!1),Zt.set(this,null),Qt.set(this,!0),$t.set(this,void 0),B.set(this,``),V.set(this,void 0),en.set(this,void 0),tn.set(this,{}),nn.set(this,null),rn.set(this,null),an.set(this,{}),on.set(this,{}),sn.set(this,void 0),cn.set(this,!1),H.set(this,void 0),ln.set(this,!1),un.set(this,!1),dn.set(this,!1),U.set(this,void 0),fn.set(this,{}),pn.set(this,null),W.set(this,void 0),L(this,H,r,`f`),L(this,sn,e,`f`),L(this,Rt,t,`f`),L(this,en,n,`f`),L(this,Jt,new rt(this),`f`),this.$0=this[bn](),this[Kn](),L(this,z,R(this,z,`f`),`f`),L(this,U,R(this,U,`f`),`f`),L(this,W,R(this,W,`f`),`f`),L(this,V,R(this,V,`f`),`f`),R(this,V,`f`).showHiddenOpt=R(this,Ht,`f`),L(this,$t,this[gn](),`f`)}addHelpOpt(e,t){return I(`[string|boolean] [string]`,[e,t],arguments.length),R(this,Zt,`f`)&&(this[_n](R(this,Zt,`f`)),L(this,Zt,null,`f`)),e===!1&&t===void 0||(L(this,Zt,typeof e==`string`?e:`help`,`f`),this.boolean(R(this,Zt,`f`)),this.describe(R(this,Zt,`f`),t||R(this,U,`f`).deferY18nLookup(`Show help`))),this}help(e,t){return this.addHelpOpt(e,t)}addShowHiddenOpt(e,t){if(I(`[string|boolean] [string]`,[e,t],arguments.length),e===!1&&t===void 0)return this;let n=typeof e==`string`?e:R(this,Ht,`f`);return this.boolean(n),this.describe(n,t||R(this,U,`f`).deferY18nLookup(`Show hidden options`)),R(this,V,`f`).showHiddenOpt=n,this}showHidden(e,t){return this.addShowHiddenOpt(e,t)}alias(e,t){return I(`<object|string|array> [string|array]`,[e,t],arguments.length),this[kn](this.alias.bind(this),`alias`,e,t),this}array(e){return I(`<array|string>`,[e],arguments.length),this[Dn](`array`,e),this[Xn](e),this}boolean(e){return I(`<array|string>`,[e],arguments.length),this[Dn](`boolean`,e),this[Xn](e),this}check(e,t){return I(`<function> [boolean]`,[e,t],arguments.length),this.middleware((t,n)=>ot(()=>e(t,n.getOptions()),n=>(n?(typeof n==`string`||n instanceof Error)&&R(this,U,`f`).fail(n.toString(),n):R(this,U,`f`).fail(R(this,H,`f`).y18n.__(`Argument check failed: %s`,e.toString())),t),e=>(R(this,U,`f`).fail(e.message?e.message:e.toString(),e),t)),!1,t),this}choices(e,t){return I(`<object|string|array> [string|array]`,[e,t],arguments.length),this[kn](this.choices.bind(this),`choices`,e,t),this}coerce(e,t){if(I(`<object|string|array> [function]`,[e,t],arguments.length),Array.isArray(e)){if(!t)throw new P(`coerce callback must be provided`);for(let n of e)this.coerce(n,t);return this}if(typeof e==`object`){for(let t of Object.keys(e))this.coerce(t,e[t]);return this}if(!t)throw new P(`coerce callback must be provided`);return R(this,V,`f`).key[e]=!0,R(this,Jt,`f`).addCoerceMiddleware((n,r)=>{let i;return Object.prototype.hasOwnProperty.call(n,e)?ot(()=>(i=r.getAliases(),t(n[e])),t=>{n[e]=t;let a=r.getInternalMethods().getParserConfiguration()[`strip-aliased`];if(i[e]&&a!==!0)for(let r of i[e])n[r]=t;return n},e=>{throw new P(e.message)}):n},e),this}conflicts(e,t){return I(`<string|object> [string|array]`,[e,t],arguments.length),R(this,W,`f`).conflicts(e,t),this}config(e=`config`,t,n){return I(`[object|string] [string|function] [function]`,[e,t,n],arguments.length),typeof e==`object`&&!Array.isArray(e)?(e=Pt(e,R(this,Rt,`f`),this[xn]()[`deep-merge-config`]||!1,R(this,H,`f`)),R(this,V,`f`).configObjects=(R(this,V,`f`).configObjects||[]).concat(e),this):(typeof t==`function`&&(n=t,t=void 0),this.describe(e,t||R(this,U,`f`).deferY18nLookup(`Path to JSON config file`)),(Array.isArray(e)?e:[e]).forEach(e=>{R(this,V,`f`).config[e]=n||!0}),this)}completion(e,t,n){return I(`[string] [string|boolean|function] [function]`,[e,t,n],arguments.length),typeof t==`function`&&(n=t,t=void 0),L(this,Vt,e||R(this,Vt,`f`)||`completion`,`f`),!t&&t!==!1&&(t=`generate completion script`),this.command(R(this,Vt,`f`),t),n&&R(this,Bt,`f`).registerFunction(n),this}command(e,t,n,r,i,a){return I(`<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]`,[e,t,n,r,i,a],arguments.length),R(this,z,`f`).addHandler(e,t,n,r,i,a),this}commands(e,t,n,r,i,a){return this.command(e,t,n,r,i,a)}commandDir(e,t){I(`<string> [object]`,[e,t],arguments.length);let n=R(this,en,`f`)||R(this,H,`f`).require;return R(this,z,`f`).addDirectory(e,n,R(this,H,`f`).getCallerFile(),t),this}count(e){return I(`<array|string>`,[e],arguments.length),this[Dn](`count`,e),this[Xn](e),this}default(e,t,n){return I(`<object|string|array> [*] [string]`,[e,t,n],arguments.length),n&&(Ze(e,R(this,H,`f`)),R(this,V,`f`).defaultDescription[e]=n),typeof t==`function`&&(Ze(e,R(this,H,`f`)),R(this,V,`f`).defaultDescription[e]||(R(this,V,`f`).defaultDescription[e]=R(this,U,`f`).functionDescription(t)),t=t.call()),this[On](this.default.bind(this),`default`,e,t),this}defaults(e,t,n){return this.default(e,t,n)}demandCommand(e=1,t,n,r){return I(`[number] [number|string] [string|null|undefined] [string|null|undefined]`,[e,t,n,r],arguments.length),typeof t!=`number`&&(n=t,t=1/0),this.global(`_`,!1),R(this,V,`f`).demandedCommands._={min:e,max:t,minMsg:n,maxMsg:r},this}demand(e,t,n){return Array.isArray(t)?(t.forEach(e=>{Xe(n,!0,R(this,H,`f`)),this.demandOption(e,n)}),t=1/0):typeof t!=`number`&&(n=t,t=1/0),typeof e==`number`?(Xe(n,!0,R(this,H,`f`)),this.demandCommand(e,t,n,n)):Array.isArray(e)?e.forEach(e=>{Xe(n,!0,R(this,H,`f`)),this.demandOption(e,n)}):typeof n==`string`?this.demandOption(e,n):(n===!0||n===void 0)&&this.demandOption(e),this}demandOption(e,t){return I(`<object|string|array> [string]`,[e,t],arguments.length),this[On](this.demandOption.bind(this),`demandedOptions`,e,t),this}deprecateOption(e,t){return I(`<string> [string|boolean]`,[e,t],arguments.length),R(this,V,`f`).deprecatedOptions[e]=t,this}describe(e,t){return I(`<object|string|array> [string]`,[e,t],arguments.length),this[Mn](e,!0),R(this,U,`f`).describe(e,t),this}detectLocale(e){return I(`<boolean>`,[e],arguments.length),L(this,Wt,e,`f`),this}env(e){return I(`[string|boolean]`,[e],arguments.length),e===!1?delete R(this,V,`f`).envPrefix:R(this,V,`f`).envPrefix=e||``,this}epilogue(e){return I(`<string>`,[e],arguments.length),R(this,U,`f`).epilog(e),this}epilog(e){return this.epilogue(e)}example(e,t){return I(`<string|array> [string]`,[e,t],arguments.length),Array.isArray(e)?e.forEach(e=>this.example(...e)):R(this,U,`f`).example(e,t),this}exit(e,t){L(this,Xt,!0,`f`),L(this,Ut,t,`f`),R(this,Kt,`f`)&&R(this,H,`f`).process.exit(e)}exitProcess(e=!0){return I(`[boolean]`,[e],arguments.length),L(this,Kt,e,`f`),this}fail(e){if(I(`<function|boolean>`,[e],arguments.length),typeof e==`boolean`&&e!==!1)throw new P(`Invalid first argument. Expected function or boolean 'false'`);return R(this,U,`f`).failFn(e),this}getAliases(){return this.parsed?this.parsed.aliases:{}}async getCompletion(e,t){return I(`<array> [function]`,[e,t],arguments.length),t?R(this,Bt,`f`).getCompletion(e,t):new Promise((t,n)=>{R(this,Bt,`f`).getCompletion(e,(e,r)=>{e?n(e):t(r)})})}getDemandedOptions(){return I([],0),R(this,V,`f`).demandedOptions}getDemandedCommands(){return I([],0),R(this,V,`f`).demandedCommands}getDeprecatedOptions(){return I([],0),R(this,V,`f`).deprecatedOptions}getDetectLocale(){return R(this,Wt,`f`)}getExitProcess(){return R(this,Kt,`f`)}getGroups(){return Object.assign({},R(this,Yt,`f`),R(this,on,`f`))}getHelp(){if(L(this,Xt,!0,`f`),!R(this,U,`f`).hasCachedHelpMessage()){if(!this.parsed){let e=this[qn](R(this,sn,`f`),void 0,void 0,0,!0);if(F(e))return e.then(()=>R(this,U,`f`).help())}let e=R(this,z,`f`).runDefaultBuilderOn(this);if(F(e))return e.then(()=>R(this,U,`f`).help())}return Promise.resolve(R(this,U,`f`).help())}getOptions(){return R(this,V,`f`)}getStrict(){return R(this,ln,`f`)}getStrictCommands(){return R(this,un,`f`)}getStrictOptions(){return R(this,dn,`f`)}global(e,t){return I(`<string|array> [boolean]`,[e,t],arguments.length),e=[].concat(e),t===!1?e.forEach(e=>{R(this,V,`f`).local.includes(e)||R(this,V,`f`).local.push(e)}):R(this,V,`f`).local=R(this,V,`f`).local.filter(t=>e.indexOf(t)===-1),this}group(e,t){I(`<string|array> <string>`,[e,t],arguments.length);let n=R(this,on,`f`)[t]||R(this,Yt,`f`)[t];R(this,on,`f`)[t]&&delete R(this,on,`f`)[t];let r={};return R(this,Yt,`f`)[t]=(n||[]).concat(e).filter(e=>r[e]?!1:r[e]=!0),this}hide(e){return I(`<string>`,[e],arguments.length),R(this,V,`f`).hiddenOptions.push(e),this}implies(e,t){return I(`<string|object> [number|string|array]`,[e,t],arguments.length),R(this,W,`f`).implies(e,t),this}locale(e){return I(`[string]`,[e],arguments.length),e===void 0?(this[Cn](),R(this,H,`f`).y18n.getLocale()):(L(this,Wt,!1,`f`),R(this,H,`f`).y18n.setLocale(e),this)}middleware(e,t,n){return R(this,Jt,`f`).addMiddleware(e,!!t,n)}nargs(e,t){return I(`<string|object|array> [number]`,[e,t],arguments.length),this[On](this.nargs.bind(this),`narg`,e,t),this}normalize(e){return I(`<array|string>`,[e],arguments.length),this[Dn](`normalize`,e),this}number(e){return I(`<array|string>`,[e],arguments.length),this[Dn](`number`,e),this[Xn](e),this}option(e,t){if(I(`<string|object> [object]`,[e,t],arguments.length),typeof e==`object`)Object.keys(e).forEach(t=>{this.options(t,e[t])});else{typeof t!=`object`&&(t={}),this[Xn](e),R(this,pn,`f`)&&(e===`version`||t?.alias===`version`)&&this[vn](`"version" is a reserved word.
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){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)):(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){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=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=ge.resolve(e.extends)}catch{return e}Lt(a),Pt.push(a),i=r?JSON.parse(Ft.readFileSync(a,`utf8`)):ge(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 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,Bt,Vt,Ht,Ut,Wt,Gt,Kt,qt,Jt,Yt,Xt,Zt,Qt,$t,en,tn,B,V,nn,rn,an,on,sn,cn,ln,un,H,dn,fn,pn,U,mn,hn,W;function gn(e){return(t=[],n=e.process.cwd(),r)=>{let i=new $n(t,n,r,e);return Object.defineProperty(i,"argv",{get:()=>i.parse(),enumerable:!0}),i.help(),i.version(),i}}const _n=Symbol(`copyDoubleDash`),vn=Symbol(`copyDoubleDash`),yn=Symbol(`deleteFromParserHintObject`),bn=Symbol(`emitWarning`),xn=Symbol(`freeze`),Sn=Symbol(`getDollarZero`),Cn=Symbol(`getParserConfiguration`),wn=Symbol(`getUsageConfiguration`),Tn=Symbol(`guessLocale`),En=Symbol(`guessVersion`),Dn=Symbol(`parsePositionalNumbers`),On=Symbol(`pkgUp`),kn=Symbol(`populateParserHintArray`),An=Symbol(`populateParserHintSingleValueDictionary`),jn=Symbol(`populateParserHintArrayDictionary`),Mn=Symbol(`populateParserHintDictionary`),Nn=Symbol(`sanitizeKey`),Pn=Symbol(`setKey`),Fn=Symbol(`unfreeze`),In=Symbol(`validateAsync`),Ln=Symbol(`getCommandInstance`),Rn=Symbol(`getContext`),zn=Symbol(`getHasOutput`),Bn=Symbol(`getLoggerInstance`),Vn=Symbol(`getParseContext`),Hn=Symbol(`getUsageInstance`),Un=Symbol(`getValidationInstance`),Wn=Symbol(`hasParseCallback`),Gn=Symbol(`isGlobalContext`),Kn=Symbol(`postProcess`),qn=Symbol(`rebase`),Jn=Symbol(`reset`),Yn=Symbol(`runYargsParserAndExecuteCommands`),Xn=Symbol(`runValidation`),Zn=Symbol(`setHasOutput`),Qn=Symbol(`kTrackManuallySetKeys`);var $n=class{constructor(e=[],t,n,r){this.customScriptName=!1,this.parsed=!1,z.set(this,void 0),Bt.set(this,void 0),Vt.set(this,{commands:[],fullCommands:[]}),Ht.set(this,null),Ut.set(this,null),Wt.set(this,`show-hidden`),Gt.set(this,null),Kt.set(this,!0),qt.set(this,{}),Jt.set(this,!0),Yt.set(this,[]),Xt.set(this,void 0),Zt.set(this,{}),Qt.set(this,!1),$t.set(this,null),en.set(this,!0),tn.set(this,void 0),B.set(this,``),V.set(this,void 0),nn.set(this,void 0),rn.set(this,{}),an.set(this,null),on.set(this,null),sn.set(this,{}),cn.set(this,{}),ln.set(this,void 0),un.set(this,!1),H.set(this,void 0),dn.set(this,!1),fn.set(this,!1),pn.set(this,!1),U.set(this,void 0),mn.set(this,{}),hn.set(this,null),W.set(this,void 0),L(this,H,r,`f`),L(this,ln,e,`f`),L(this,Bt,t,`f`),L(this,nn,n,`f`),L(this,Xt,new at(this),`f`),this.$0=this[Sn](),this[Jn](),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,Wt,`f`),L(this,tn,this[vn](),`f`)}addHelpOpt(e,t){return I(`[string|boolean] [string]`,[e,t],arguments.length),R(this,$t,`f`)&&(this[yn](R(this,$t,`f`)),L(this,$t,null,`f`)),e===!1&&t===void 0||(L(this,$t,typeof e==`string`?e:`help`,`f`),this.boolean(R(this,$t,`f`)),this.describe(R(this,$t,`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,Wt,`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[jn](this.alias.bind(this),`alias`,e,t),this}array(e){return I(`<array|string>`,[e],arguments.length),this[kn](`array`,e),this[Qn](e),this}boolean(e){return I(`<array|string>`,[e],arguments.length),this[kn](`boolean`,e),this[Qn](e),this}check(e,t){return I(`<function> [boolean]`,[e,t],arguments.length),this.middleware((t,n)=>ct(()=>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[jn](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 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 R(this,V,`f`).key[e]=!0,R(this,Xt,`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 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=It(e,R(this,Bt,`f`),this[Cn]()[`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,Ut,e||R(this,Ut,`f`)||`completion`,`f`),!t&&t!==!1&&(t=`generate completion script`),this.command(R(this,Ut,`f`),t),n&&R(this,Ht,`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,nn,`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[kn](`count`,e),this[Qn](e),this}default(e,t,n){return I(`<object|string|array> [*] [string]`,[e,t,n],arguments.length),n&&($e(e,R(this,H,`f`)),R(this,V,`f`).defaultDescription[e]=n),typeof t==`function`&&($e(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[An](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=>{Qe(n,!0,R(this,H,`f`)),this.demandOption(e,n)}),t=1/0):typeof t!=`number`&&(n=t,t=1/0),typeof e==`number`?(Qe(n,!0,R(this,H,`f`)),this.demandCommand(e,t,n,n)):Array.isArray(e)?e.forEach(e=>{Qe(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[An](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[Pn](e,!0),R(this,U,`f`).describe(e,t),this}detectLocale(e){return I(`<boolean>`,[e],arguments.length),L(this,Kt,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,Qt,!0,`f`),L(this,Gt,t,`f`),R(this,Jt,`f`)&&R(this,H,`f`).process.exit(e)}exitProcess(e=!0){return I(`[boolean]`,[e],arguments.length),L(this,Jt,e,`f`),this}fail(e){if(I(`<function|boolean>`,[e],arguments.length),typeof e==`boolean`&&e!==!1)throw new M(`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,Ht,`f`).getCompletion(e,t):new Promise((t,n)=>{R(this,Ht,`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,Kt,`f`)}getExitProcess(){return R(this,Jt,`f`)}getGroups(){return Object.assign({},R(this,Zt,`f`),R(this,cn,`f`))}getHelp(){if(L(this,Qt,!0,`f`),!R(this,U,`f`).hasCachedHelpMessage()){if(!this.parsed){let e=this[Yn](R(this,ln,`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,dn,`f`)}getStrictCommands(){return R(this,fn,`f`)}getStrictOptions(){return R(this,pn,`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,cn,`f`)[t]||R(this,Zt,`f`)[t];R(this,cn,`f`)[t]&&delete R(this,cn,`f`)[t];let r={};return R(this,Zt,`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[Tn](),R(this,H,`f`).y18n.getLocale()):(L(this,Kt,!1,`f`),R(this,H,`f`).y18n.setLocale(e),this)}middleware(e,t,n){return R(this,Xt,`f`).addMiddleware(e,!!t,n)}nargs(e,t){return I(`<string|object|array> [number]`,[e,t],arguments.length),this[An](this.nargs.bind(this),`narg`,e,t),this}normalize(e){return I(`<array|string>`,[e],arguments.length),this[kn](`normalize`,e),this}number(e){return I(`<array|string>`,[e],arguments.length),this[kn](`number`,e),this[Qn](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[Qn](e),R(this,hn,`f`)&&(e===`version`||t?.alias===`version`)&&this[bn](`"version" is a reserved word.
89
89
  Please do one of the following:
90
90
  - Disable version with \`yargs.version(false)\` if using "version" as an option
91
91
  - Use the built-in \`yargs.version\` method instead (if applicable)
92
92
  - Use a different option key
93
- https://yargs.js.org/docs/#api-reference-version`,void 0,`versionWarning`),R(this,V,`f`).key[e]=!0,t.alias&&this.alias(e,t.alias);let n=t.deprecate||t.deprecated;n&&this.deprecateOption(e,n);let r=t.demand||t.required||t.require;r&&this.demand(e,r),t.demandOption&&this.demandOption(e,typeof t.demandOption==`string`?t.demandOption:void 0),t.conflicts&&this.conflicts(e,t.conflicts),`default`in t&&this.default(e,t.default),t.implies!==void 0&&this.implies(e,t.implies),t.nargs!==void 0&&this.nargs(e,t.nargs),t.config&&this.config(e,t.configParser),t.normalize&&this.normalize(e),t.choices&&this.choices(e,t.choices),t.coerce&&this.coerce(e,t.coerce),t.group&&this.group(e,t.group),(t.boolean||t.type===`boolean`)&&(this.boolean(e),t.alias&&this.boolean(t.alias)),(t.array||t.type===`array`)&&(this.array(e),t.alias&&this.array(t.alias)),(t.number||t.type===`number`)&&(this.number(e),t.alias&&this.number(t.alias)),(t.string||t.type===`string`)&&(this.string(e),t.alias&&this.string(t.alias)),(t.count||t.type===`count`)&&this.count(e),typeof t.global==`boolean`&&this.global(e,t.global),t.defaultDescription&&(R(this,V,`f`).defaultDescription[e]=t.defaultDescription),t.skipValidation&&this.skipValidation(e);let i=t.describe||t.description||t.desc,a=R(this,U,`f`).getDescriptions();Object.prototype.hasOwnProperty.call(a,e)&&typeof i!=`string`||this.describe(e,i),t.hidden&&this.hide(e),t.requiresArg&&this.requiresArg(e)}return this}options(e,t){return this.option(e,t)}parse(e,t,n){I(`[string|array] [function|boolean|object] [function]`,[e,t,n],arguments.length),this[yn](),e===void 0&&(e=R(this,sn,`f`)),typeof t==`object`&&(L(this,rn,t,`f`),t=n),typeof t==`function`&&(L(this,nn,t,`f`),t=!1),t||L(this,sn,e,`f`),R(this,nn,`f`)&&L(this,Kt,!1,`f`);let r=this[qn](e,!!t),i=this.parsed;return R(this,Bt,`f`).setParsed(this.parsed),F(r)?r.then(e=>(R(this,nn,`f`)&&R(this,nn,`f`).call(this,R(this,Ut,`f`),e,R(this,B,`f`)),e)).catch(e=>{throw R(this,nn,`f`)&&R(this,nn,`f`)(e,this.parsed.argv,R(this,B,`f`)),e}).finally(()=>{this[Nn](),this.parsed=i}):(R(this,nn,`f`)&&R(this,nn,`f`).call(this,R(this,Ut,`f`),r,R(this,B,`f`)),this[Nn](),this.parsed=i,r)}parseAsync(e,t,n){let r=this.parse(e,t,n);return F(r)?r:Promise.resolve(r)}parseSync(e,t,n){let r=this.parse(e,t,n);if(F(r))throw new P(`.parseSync() must not be used with asynchronous builders, handlers, or middleware`);return r}parserConfiguration(e){return I(`<object>`,[e],arguments.length),L(this,tn,e,`f`),this}pkgConf(e,t){I(`<string> [string]`,[e,t],arguments.length);let n=null,r=this[En](t||R(this,Rt,`f`));return r[e]&&typeof r[e]==`object`&&(n=Pt(r[e],t||R(this,Rt,`f`),this[xn]()[`deep-merge-config`]||!1,R(this,H,`f`)),R(this,V,`f`).configObjects=(R(this,V,`f`).configObjects||[]).concat(n)),this}positional(e,t){I(`<string> <object>`,[e,t],arguments.length);let n=[`default`,`defaultDescription`,`implies`,`normalize`,`choices`,`conflicts`,`coerce`,`type`,`describe`,`desc`,`description`,`alias`];t=_t(t,(e,t)=>e===`type`&&![`string`,`number`,`boolean`].includes(t)?!1:n.includes(e));let r=R(this,zt,`f`).fullCommands[R(this,zt,`f`).fullCommands.length-1],i=r?R(this,z,`f`).cmdToParseOptions(r):{array:[],alias:{},default:{},demand:{}};return Qe(i).forEach(n=>{let r=i[n];Array.isArray(r)?r.indexOf(e)!==-1&&(t[n]=!0):r[e]&&!(n in t)&&(t[n]=r[e])}),this.group(e,R(this,U,`f`).getPositionalGroupName()),this.option(e,t)}recommendCommands(e=!0){return I(`[boolean]`,[e],arguments.length),L(this,cn,e,`f`),this}required(e,t,n){return this.demand(e,t,n)}require(e,t,n){return this.demand(e,t,n)}requiresArg(e){return I(`<array|string|object> [number]`,[e],arguments.length),typeof e==`string`&&R(this,V,`f`).narg[e]||this[On](this.requiresArg.bind(this),`narg`,e,NaN),this}showCompletionScript(e,t){return I(`[string] [string]`,[e,t],arguments.length),e||=this.$0,R(this,$t,`f`).log(R(this,Bt,`f`).generateCompletionScript(e,t||R(this,Vt,`f`)||`completion`)),this}showHelp(e){if(I(`[string|function]`,[e],arguments.length),L(this,Xt,!0,`f`),!R(this,U,`f`).hasCachedHelpMessage()){if(!this.parsed){let t=this[qn](R(this,sn,`f`),void 0,void 0,0,!0);if(F(t))return t.then(()=>{R(this,U,`f`).showHelp(e)}),this}let t=R(this,z,`f`).runDefaultBuilderOn(this);if(F(t))return t.then(()=>{R(this,U,`f`).showHelp(e)}),this}return R(this,U,`f`).showHelp(e),this}scriptName(e){return this.customScriptName=!0,this.$0=e,this}showHelpOnFail(e,t){return I(`[boolean|string] [string]`,[e,t],arguments.length),R(this,U,`f`).showHelpOnFail(e,t),this}showVersion(e){return I(`[string|function]`,[e],arguments.length),R(this,U,`f`).showVersion(e),this}skipValidation(e){return I(`<array|string>`,[e],arguments.length),this[Dn](`skipValidation`,e),this}strict(e){return I(`[boolean]`,[e],arguments.length),L(this,ln,e!==!1,`f`),this}strictCommands(e){return I(`[boolean]`,[e],arguments.length),L(this,un,e!==!1,`f`),this}strictOptions(e){return I(`[boolean]`,[e],arguments.length),L(this,dn,e!==!1,`f`),this}string(e){return I(`<array|string>`,[e],arguments.length),this[Dn](`string`,e),this[Xn](e),this}terminalWidth(){return I([],0),R(this,H,`f`).process.stdColumns}updateLocale(e){return this.updateStrings(e)}updateStrings(e){return I(`<object>`,[e],arguments.length),L(this,Wt,!1,`f`),R(this,H,`f`).y18n.updateLocale(e),this}usage(e,t,n,r){if(I(`<string|null|undefined> [string|boolean] [function|object] [function]`,[e,t,n,r],arguments.length),t!==void 0){if(Xe(e,null,R(this,H,`f`)),(e||``).match(/^\$0( |$)/))return this.command(e,t,n,r);throw new P(`.usage() description must start with $0 if being used as alias for .command()`)}return R(this,U,`f`).usage(e),this}usageConfiguration(e){return I(`<object>`,[e],arguments.length),L(this,fn,e,`f`),this}version(e,t,n){let r=`version`;if(I(`[boolean|string] [string] [string]`,[e,t,n],arguments.length),R(this,pn,`f`)&&(this[_n](R(this,pn,`f`)),R(this,U,`f`).version(void 0),L(this,pn,null,`f`)),arguments.length===0)n=this[wn](),e=r;else if(arguments.length===1){if(e===!1)return this;n=e,e=r}else arguments.length===2&&(n=t,t=void 0);return L(this,pn,typeof e==`string`?e:r,`f`),t||=R(this,U,`f`).deferY18nLookup(`Show version number`),R(this,U,`f`).version(n||void 0),this.boolean(R(this,pn,`f`)),this.describe(R(this,pn,`f`),t),this}wrap(e){return I(`<number|null|undefined>`,[e],arguments.length),R(this,U,`f`).wrap(e),this}[(z=/* @__PURE__ */ new WeakMap,Rt=/* @__PURE__ */ new WeakMap,zt=/* @__PURE__ */ new WeakMap,Bt=/* @__PURE__ */ new WeakMap,Vt=/* @__PURE__ */ new WeakMap,Ht=/* @__PURE__ */ new WeakMap,Ut=/* @__PURE__ */ new WeakMap,Wt=/* @__PURE__ */ new WeakMap,Gt=/* @__PURE__ */ new WeakMap,Kt=/* @__PURE__ */ new WeakMap,qt=/* @__PURE__ */ new WeakMap,Jt=/* @__PURE__ */ new WeakMap,Yt=/* @__PURE__ */ new WeakMap,Xt=/* @__PURE__ */ new WeakMap,Zt=/* @__PURE__ */ new WeakMap,Qt=/* @__PURE__ */ new WeakMap,$t=/* @__PURE__ */ new WeakMap,B=/* @__PURE__ */ new WeakMap,V=/* @__PURE__ */ new WeakMap,en=/* @__PURE__ */ new WeakMap,tn=/* @__PURE__ */ new WeakMap,nn=/* @__PURE__ */ new WeakMap,rn=/* @__PURE__ */ new WeakMap,an=/* @__PURE__ */ new WeakMap,on=/* @__PURE__ */ new WeakMap,sn=/* @__PURE__ */ new WeakMap,cn=/* @__PURE__ */ new WeakMap,H=/* @__PURE__ */ new WeakMap,ln=/* @__PURE__ */ new WeakMap,un=/* @__PURE__ */ new WeakMap,dn=/* @__PURE__ */ new WeakMap,U=/* @__PURE__ */ new WeakMap,fn=/* @__PURE__ */ new WeakMap,pn=/* @__PURE__ */ new WeakMap,W=/* @__PURE__ */ new WeakMap,hn)](e){if(!e._||!e[`--`])return e;e._.push.apply(e._,e[`--`]);try{delete e[`--`]}catch{}return e}[gn](){return{log:(...e)=>{this[Hn]()||console.log(...e),L(this,Xt,!0,`f`),R(this,B,`f`).length&&L(this,B,R(this,B,`f`)+`
94
- `,`f`),L(this,B,R(this,B,`f`)+e.join(` `),`f`)},error:(...e)=>{this[Hn]()||console.error(...e),L(this,Xt,!0,`f`),R(this,B,`f`).length&&L(this,B,R(this,B,`f`)+`
95
- `,`f`),L(this,B,R(this,B,`f`)+e.join(` `),`f`)}}}[_n](e){Qe(R(this,V,`f`)).forEach(t=>{if((e=>e===`configObjects`)(t))return;let n=R(this,V,`f`)[t];Array.isArray(n)?n.includes(e)&&n.splice(n.indexOf(e),1):typeof n==`object`&&delete n[e]}),delete R(this,U,`f`).getDescriptions()[e]}[vn](e,t,n){R(this,Gt,`f`)[n]||(R(this,H,`f`).process.emitWarning(e,t),R(this,Gt,`f`)[n]=!0)}[yn](){R(this,qt,`f`).push({options:R(this,V,`f`),configObjects:R(this,V,`f`).configObjects.slice(0),exitProcess:R(this,Kt,`f`),groups:R(this,Yt,`f`),strict:R(this,ln,`f`),strictCommands:R(this,un,`f`),strictOptions:R(this,dn,`f`),completionCommand:R(this,Vt,`f`),output:R(this,B,`f`),exitError:R(this,Ut,`f`),hasOutput:R(this,Xt,`f`),parsed:this.parsed,parseFn:R(this,nn,`f`),parseContext:R(this,rn,`f`)}),R(this,U,`f`).freeze(),R(this,W,`f`).freeze(),R(this,z,`f`).freeze(),R(this,Jt,`f`).freeze()}[bn](){let e=``,t;return t=/\b(node|iojs|electron)(\.exe)?$/.test(R(this,H,`f`).process.argv()[0])?R(this,H,`f`).process.argv().slice(1,2):R(this,H,`f`).process.argv().slice(0,1),e=t.map(e=>{let t=this[Gn](R(this,Rt,`f`),e);return e.match(/^(\/|([a-zA-Z]:)?\\)/)&&t.length<e.length?t:e}).join(` `).trim(),R(this,H,`f`).getEnv(`_`)&&R(this,H,`f`).getProcessArgvBin()===R(this,H,`f`).getEnv(`_`)&&(e=R(this,H,`f`).getEnv(`_`).replace(`${R(this,H,`f`).path.dirname(R(this,H,`f`).process.execPath())}/`,``)),e}[xn](){return R(this,tn,`f`)}[Sn](){return R(this,fn,`f`)}[Cn](){if(!R(this,Wt,`f`))return;let e=R(this,H,`f`).getEnv(`LC_ALL`)||R(this,H,`f`).getEnv(`LC_MESSAGES`)||R(this,H,`f`).getEnv(`LANG`)||R(this,H,`f`).getEnv(`LANGUAGE`)||`en_US`;this.locale(e.replace(/[.:].*/,``))}[wn](){return this[En]().version||`unknown`}[Tn](e){let t=e[`--`]?e[`--`]:e._;for(let e=0,n;(n=t[e])!==void 0;e++)R(this,H,`f`).Parser.looksLikeNumber(n)&&Number.isSafeInteger(Math.floor(parseFloat(`${n}`)))&&(t[e]=Number(n));return e}[En](e){let t=e||`*`;if(R(this,an,`f`)[t])return R(this,an,`f`)[t];let n={};try{let t=e||R(this,H,`f`).mainFilename;!e&&R(this,H,`f`).path.extname(t)&&(t=R(this,H,`f`).path.dirname(t));let r=R(this,H,`f`).findUp(t,(e,t)=>{if(t.includes(`package.json`))return`package.json`});Xe(r,void 0,R(this,H,`f`)),n=JSON.parse(R(this,H,`f`).readFileSync(r,`utf8`))}catch{}return R(this,an,`f`)[t]=n||{},R(this,an,`f`)[t]}[Dn](e,t){t=[].concat(t),t.forEach(t=>{t=this[jn](t),R(this,V,`f`)[e].push(t)})}[On](e,t,n,r){this[An](e,t,n,r,(e,t,n)=>{R(this,V,`f`)[e][t]=n})}[kn](e,t,n,r){this[An](e,t,n,r,(e,t,n)=>{R(this,V,`f`)[e][t]=(R(this,V,`f`)[e][t]||[]).concat(n)})}[An](e,t,n,r,i){if(Array.isArray(n))n.forEach(t=>{e(t,r)});else if((e=>typeof e==`object`)(n))for(let t of Qe(n))e(t,n[t]);else i(t,this[jn](n),r)}[jn](e){return e===`__proto__`?`___proto___`:e}[Mn](e,t){return this[On](this[Mn].bind(this),`key`,e,t),this}[Nn](){var e,t,n,r,i,a,o,s,c,l,u,d;let f=R(this,qt,`f`).pop();Xe(f,void 0,R(this,H,`f`));let p;e=this,t=this,n=this,r=this,i=this,a=this,o=this,s=this,c=this,l=this,u=this,d=this,{options:{set value(t){L(e,V,t,`f`)}}.value,configObjects:p,exitProcess:{set value(e){L(t,Kt,e,`f`)}}.value,groups:{set value(e){L(n,Yt,e,`f`)}}.value,output:{set value(e){L(r,B,e,`f`)}}.value,exitError:{set value(e){L(i,Ut,e,`f`)}}.value,hasOutput:{set value(e){L(a,Xt,e,`f`)}}.value,parsed:this.parsed,strict:{set value(e){L(o,ln,e,`f`)}}.value,strictCommands:{set value(e){L(s,un,e,`f`)}}.value,strictOptions:{set value(e){L(c,dn,e,`f`)}}.value,completionCommand:{set value(e){L(l,Vt,e,`f`)}}.value,parseFn:{set value(e){L(u,nn,e,`f`)}}.value,parseContext:{set value(e){L(d,rn,e,`f`)}}.value}=f,R(this,V,`f`).configObjects=p,R(this,U,`f`).unfreeze(),R(this,W,`f`).unfreeze(),R(this,z,`f`).unfreeze(),R(this,Jt,`f`).unfreeze()}[Pn](e,t){return ot(t,t=>(e(t),t))}getInternalMethods(){return{getCommandInstance:this[Fn].bind(this),getContext:this[In].bind(this),getHasOutput:this[Ln].bind(this),getLoggerInstance:this[Rn].bind(this),getParseContext:this[zn].bind(this),getParserConfiguration:this[xn].bind(this),getUsageConfiguration:this[Sn].bind(this),getUsageInstance:this[Bn].bind(this),getValidationInstance:this[Vn].bind(this),hasParseCallback:this[Hn].bind(this),isGlobalContext:this[Un].bind(this),postProcess:this[Wn].bind(this),reset:this[Kn].bind(this),runValidation:this[Jn].bind(this),runYargsParserAndExecuteCommands:this[qn].bind(this),setHasOutput:this[Yn].bind(this)}}[Fn](){return R(this,z,`f`)}[In](){return R(this,zt,`f`)}[Ln](){return R(this,Xt,`f`)}[Rn](){return R(this,$t,`f`)}[zn](){return R(this,rn,`f`)||{}}[Bn](){return R(this,U,`f`)}[Vn](){return R(this,W,`f`)}[Hn](){return!!R(this,nn,`f`)}[Un](){return R(this,Qt,`f`)}[Wn](e,t,n,r){return n||F(e)||(t||(e=this[hn](e)),(this[xn]()[`parse-positional-numbers`]||this[xn]()[`parse-positional-numbers`]===void 0)&&(e=this[Tn](e)),r&&(e=at(e,this,R(this,Jt,`f`).getMiddleware(),!1))),e}[Kn](e={}){L(this,V,R(this,V,`f`)||{},`f`);let t={};t.local=R(this,V,`f`).local||[],t.configObjects=R(this,V,`f`).configObjects||[];let n={};return t.local.forEach(t=>{n[t]=!0,(e[t]||[]).forEach(e=>{n[e]=!0})}),Object.assign(R(this,on,`f`),Object.keys(R(this,Yt,`f`)).reduce((e,t)=>{let r=R(this,Yt,`f`)[t].filter(e=>!(e in n));return r.length>0&&(e[t]=r),e},{})),L(this,Yt,{},`f`),[`array`,`boolean`,`string`,`skipValidation`,`count`,`normalize`,`number`,`hiddenOptions`].forEach(e=>{t[e]=(R(this,V,`f`)[e]||[]).filter(e=>!n[e])}),[`narg`,`key`,`alias`,`default`,`defaultDescription`,`config`,`choices`,`demandedOptions`,`demandedCommands`,`deprecatedOptions`].forEach(e=>{t[e]=_t(R(this,V,`f`)[e],e=>!n[e])}),t.envPrefix=R(this,V,`f`).envPrefix,L(this,V,t,`f`),L(this,U,R(this,U,`f`)?R(this,U,`f`).reset(n):bt(this,R(this,H,`f`)),`f`),L(this,W,R(this,W,`f`)?R(this,W,`f`).reset(n):jt(this,R(this,U,`f`),R(this,H,`f`)),`f`),L(this,z,R(this,z,`f`)?R(this,z,`f`).reset():dt(R(this,U,`f`),R(this,W,`f`),R(this,Jt,`f`),R(this,H,`f`)),`f`),R(this,Bt,`f`)||L(this,Bt,Et(this,R(this,U,`f`),R(this,z,`f`),R(this,H,`f`)),`f`),R(this,Jt,`f`).reset(),L(this,Vt,null,`f`),L(this,B,``,`f`),L(this,Ut,null,`f`),L(this,Xt,!1,`f`),this.parsed=!1,this}[Gn](e,t){return R(this,H,`f`).path.relative(e,t)}[qn](e,t,n,r=0,i=!1){let a=!!n||i;e||=R(this,sn,`f`),R(this,V,`f`).__=R(this,H,`f`).y18n.__,R(this,V,`f`).configuration=this[xn]();let o=!!R(this,V,`f`).configuration[`populate--`],s=Object.assign({},R(this,V,`f`).configuration,{"populate--":!0}),c=R(this,H,`f`).Parser.detailed(e,Object.assign({},R(this,V,`f`),{configuration:{"parse-positional-numbers":!1,...s}})),l=Object.assign(c.argv,R(this,rn,`f`)),u,d=c.aliases,f=!1,p=!1;Object.keys(l).forEach(e=>{e===R(this,Zt,`f`)&&l[e]?f=!0:e===R(this,pn,`f`)&&l[e]&&(p=!0)}),l.$0=this.$0,this.parsed=c,r===0&&R(this,U,`f`).clearCachedHelpMessage();try{if(this[Cn](),t)return this[Wn](l,o,!!n,!1);R(this,Zt,`f`)&&[R(this,Zt,`f`)].concat(d[R(this,Zt,`f`)]||[]).filter(e=>e.length>1).includes(``+l._[l._.length-1])&&(l._.pop(),f=!0),L(this,Qt,!1,`f`);let s=R(this,z,`f`).getCommands(),m=R(this,Bt,`f`).completionKey in l,h=f||m||i;if(l._.length){if(s.length){let e;for(let t=r||0,a;l._[t]!==void 0;t++){if(a=String(l._[t]),s.includes(a)&&a!==R(this,Vt,`f`)){let e=R(this,z,`f`).runCommand(a,this,c,t+1,i,f||p||i);return this[Wn](e,o,!!n,!1)}if(!e&&a!==R(this,Vt,`f`)){e=a;break}}!R(this,z,`f`).hasDefaultCommand()&&R(this,cn,`f`)&&e&&!h&&R(this,W,`f`).recommendCommands(e,s)}R(this,Vt,`f`)&&l._.includes(R(this,Vt,`f`))&&!m&&(R(this,Kt,`f`)&&vt(!0),this.showCompletionScript(),this.exit(0))}if(R(this,z,`f`).hasDefaultCommand()&&!h){let e=R(this,z,`f`).runCommand(null,this,c,0,i,f||p||i);return this[Wn](e,o,!!n,!1)}if(m){R(this,Kt,`f`)&&vt(!0),e=[].concat(e);let t=e.slice(e.indexOf(`--${R(this,Bt,`f`).completionKey}`)+1);return R(this,Bt,`f`).getCompletion(t,(e,t)=>{if(e)throw new P(e.message);(t||[]).forEach(e=>{R(this,$t,`f`).log(e)}),this.exit(0)}),this[Wn](l,!o,!!n,!1)}if(R(this,Xt,`f`)||(f?(R(this,Kt,`f`)&&vt(!0),a=!0,this.showHelp(`log`),this.exit(0)):p&&(R(this,Kt,`f`)&&vt(!0),a=!0,R(this,U,`f`).showVersion(`log`),this.exit(0))),!a&&R(this,V,`f`).skipValidation.length>0&&(a=Object.keys(l).some(e=>R(this,V,`f`).skipValidation.indexOf(e)>=0&&l[e]===!0)),!a){if(c.error)throw new P(c.error.message);if(!m){let e=this[Jn](d,{},c.error);n||(u=at(l,this,R(this,Jt,`f`).getMiddleware(),!0)),u=this[Pn](e,u??l),F(u)&&!n&&(u=u.then(()=>at(l,this,R(this,Jt,`f`).getMiddleware(),!1)))}}}catch(e){if(e instanceof P)R(this,U,`f`).fail(e.message,e);else throw e}return this[Wn](u??l,o,!!n,!0)}[Jn](e,t,n,r){let i={...this.getDemandedOptions()};return a=>{if(n)throw new P(n.message);R(this,W,`f`).nonOptionCount(a),R(this,W,`f`).requiredArguments(a,i);let o=!1;R(this,un,`f`)&&(o=R(this,W,`f`).unknownCommands(a)),R(this,ln,`f`)&&!o?R(this,W,`f`).unknownArguments(a,e,t,!!r):R(this,dn,`f`)&&R(this,W,`f`).unknownArguments(a,e,{},!1,!1),R(this,W,`f`).limitedChoices(a),R(this,W,`f`).implications(a),R(this,W,`f`).conflicting(a)}}[Yn](){L(this,Xt,!0,`f`)}[Xn](e){if(typeof e==`string`)R(this,V,`f`).key[e]=!0;else for(let t of e)R(this,V,`f`).key[t]=!0}};function Qn(e){return!!e&&typeof e.getInternalMethods==`function`}const $n=mn(Ye);var er=class extends Error{};function tr(e){if(!Number.isInteger(e)||e<60||e>600)throw new er(`Expected a whole number of seconds from 60 to 600.`);return e}function nr(e,t=`https://astralbeam.ai/api`){return`${t.replace(/\/+$/,``)}${e.replace(/^\/api(?=\/)/,``)}`}function rr(e,t){if(!e||typeof e!=`object`)return!1;let n=e;return n.status===t&&typeof n.type==`string`&&typeof n.title==`string`&&typeof n.detail==`string`&&(n.reference===void 0||typeof n.reference==`string`)&&(n.issues===void 0||Array.isArray(n.issues)&&n.issues.every(e=>e&&typeof e.path==`string`&&typeof e.message==`string`))}async function ir(e,t){let{apiUrl:n,apiKey:r,astralBeamToken:i,fetchClient:a=globalThis.fetch,...o}=t,s=new Headers,c=o.headers instanceof Headers?o.headers.entries():Array.isArray(o.headers)?o.headers:Object.entries(o.headers??{});for(let[e,t]of c)s.set(e,t);s.delete(`authorization`),s.delete(`x-api-key`),r&&s.set(`x-api-key`,r),i&&s.set(`authorization`,`Bearer ${i}`);let l=await a(nr(e,n),{...o,headers:s,...r?{redirect:`error`}:{}});if(l.ok)return l;let u=await l.json().catch(e=>{if(!(e instanceof SyntaxError))throw e}),d=rr(u,l.status)?u:void 0;throw Object.assign(Error(d?.detail??`AstralBeam API returned HTTP ${l.status}`),{name:`AstralBeamApiError`,status:l.status,headers:l.headers,body:d})}async function ar(e,t){let n=await ir(e,t);if(n.status!==204)return await n.json()}function or(e){return e instanceof Error&&e.name===`AstralBeamApiError`&&`status`in e&&typeof e.status==`number`}function sr(e,t=`https://astralbeam.ai/api`){return`${t.replace(/\/+$/,``)}${e.replace(/^\/api(?=\/)/,``)}`}function cr(e,t){if(!e||typeof e!=`object`)return!1;let n=e;return n.status===t&&typeof n.type==`string`&&typeof n.title==`string`&&typeof n.detail==`string`&&(n.reference===void 0||typeof n.reference==`string`)&&(n.issues===void 0||Array.isArray(n.issues)&&n.issues.every(e=>e&&typeof e.path==`string`&&typeof e.message==`string`))}async function lr(e,t){let{apiUrl:n,apiKey:r,astralBeamToken:i,fetchClient:a=globalThis.fetch,...o}=t,s=new Headers,c=o.headers instanceof Headers?o.headers.entries():Array.isArray(o.headers)?o.headers:Object.entries(o.headers??{});for(let[e,t]of c)s.set(e,t);s.delete(`authorization`),s.delete(`x-api-key`),r&&s.set(`x-api-key`,r),i&&s.set(`authorization`,`Bearer ${i}`);let l=await a(sr(e,n),{...o,headers:s,...r?{redirect:`error`}:{}});if(l.ok)return l;let u=await l.json().catch(e=>{if(!(e instanceof SyntaxError))throw e}),d=cr(u,l.status)?u:void 0;throw Object.assign(Error(d?.detail??`AstralBeam API returned HTTP ${l.status}`),{name:`AstralBeamApiError`,status:l.status,headers:l.headers,body:d})}async function ur(e,t){let n=await lr(e,t);if(n.status!==204)return await n.json()}function G(e,t){return ur(e,t)}async function dr(e,t){let n=await lr(e,t),r=n.status===204?n.headers.get(`location`):null;if(!r)return n;let i=await globalThis.fetch(r,{credentials:`omit`,redirect:`error`,referrerPolicy:`no-referrer`,signal:t.signal??null});if(!i.ok)throw Error(`The file could not be downloaded. Please try again.`);return i}function fr(e,t){return lr(e,t)}const pr=()=>`/api/v1/organization`,mr=e=>ur(pr(),{...e,method:`GET`}),hr=()=>`/api/v1/chat/files`,gr=(e,t)=>{let n=e=>{if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Symbol.iterator in e)return Object.fromEntries(Array.from(e,e=>Array.from(e)));let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t};return G(hr(),{...t,method:`POST`,headers:{"Content-Type":`application/json`,...n(t?.headers)},body:JSON.stringify(e)})},_r=e=>{let t=new URLSearchParams;Object.entries(e||{}).forEach(([e,n])=>{n!==void 0&&t.append(e,n===null?`null`:String(n))});let n=t.toString();return n.length>0?`/api/v1/chat/files?${n}`:`/api/v1/chat/files`},vr=(e,t)=>dr(_r(e),{...t,method:`GET`}),yr=()=>`/api/v1/chat`,br=e=>{let t=new URLSearchParams;Object.entries(e||{}).forEach(([e,n])=>{n!==void 0&&t.append(e,n===null?`null`:String(n))});let n=t.toString();return n.length>0?`/api/v1/chat/config?${n}`:`/api/v1/chat/config`},xr=(e,t)=>G(br(e),{...t,method:`GET`}),Sr=()=>`/api/v1/chat/threads`,Cr=(e,t)=>{let n=e=>{if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Symbol.iterator in e)return Object.fromEntries(Array.from(e,e=>Array.from(e)));let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t};return G(Sr(),{...t,method:`POST`,headers:{"Content-Type":`application/json`,...n(t?.headers)},body:JSON.stringify(e)})},wr=e=>{let t=new URLSearchParams;Object.entries(e||{}).forEach(([e,n])=>{n!==void 0&&t.append(e,n===null?`null`:String(n))});let n=t.toString();return n.length>0?`/api/v1/chat/threads?${n}`:`/api/v1/chat/threads`},Tr=(e,t)=>G(wr(e),{...t,method:`GET`}),Er=e=>`/api/v1/chat/threads/${encodeURIComponent(String(e))}`,Dr=(e,t,n)=>{let r=e=>{if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Symbol.iterator in e)return Object.fromEntries(Array.from(e,e=>Array.from(e)));let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t};return G(Er(e),{...n,method:`PATCH`,headers:{"Content-Type":`application/json`,...r(n?.headers)},body:JSON.stringify(t)})},Or=(e,t)=>{let n=new URLSearchParams;Object.entries(t||{}).forEach(([e,t])=>{t!==void 0&&n.append(e,t===null?`null`:String(t))});let r=n.toString();return r.length>0?`/api/v1/chat/threads/${encodeURIComponent(String(e))}?${r}`:`/api/v1/chat/threads/${encodeURIComponent(String(e))}`},kr=(e,t,n)=>G(Or(e,t),{...n,method:`DELETE`}),Ar=(e,t)=>{let n=new URLSearchParams;Object.entries(t||{}).forEach(([e,t])=>{t!==void 0&&n.append(e,t===null?`null`:String(t))});let r=n.toString();return r.length>0?`/api/v1/chat/threads/${encodeURIComponent(String(e))}/messages?${r}`:`/api/v1/chat/threads/${encodeURIComponent(String(e))}/messages`},jr=(e,t,n)=>G(Ar(e,t),{...n,method:`GET`}),Mr=e=>`/api/v1/chat/threads/${encodeURIComponent(String(e))}/tool-results`,Nr=()=>`/api/v1/me`,Pr=e=>G(Nr(),{...e,method:`POST`}),Fr=()=>`/api/v1/me/mcp/catalog`,Ir=e=>G(Fr(),{...e,method:`GET`}),Lr=()=>`/api/v1/me/mcp/connections`,Rr=(e,t)=>{let n=e=>{if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Symbol.iterator in e)return Object.fromEntries(Array.from(e,e=>Array.from(e)));let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t};return G(Lr(),{...t,method:`POST`,headers:{"Content-Type":`application/json`,...n(t?.headers)},body:JSON.stringify(e)})},zr=e=>`/api/v1/me/mcp/connections/${encodeURIComponent(String(e))}/headers`,Br=(e,t,n)=>{let r=e=>{if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Symbol.iterator in e)return Object.fromEntries(Array.from(e,e=>Array.from(e)));let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t};return G(zr(e),{...n,method:`POST`,headers:{"Content-Type":`application/json`,...r(n?.headers)},body:JSON.stringify(t)})},Vr=e=>`/api/v1/me/mcp/connections/${encodeURIComponent(String(e))}`,Hr=(e,t)=>G(Vr(e),{...t,method:`DELETE`}),Ur=e=>`/api/v1/me/mcp/connections/${encodeURIComponent(String(e))}/test`,Wr=(e,t)=>G(Ur(e),{...t,method:`POST`}),Gr=e=>`/api/v1/me/mcp/connections/${encodeURIComponent(String(e))}/authorize`,Kr=(e,t)=>G(Gr(e),{...t,method:`POST`}),qr=e=>`/api/v1/me/mcp/connections/${encodeURIComponent(String(e))}/oauth/bind`,Jr=(e,t,n)=>{let r=e=>{if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Symbol.iterator in e)return Object.fromEntries(Array.from(e,e=>Array.from(e)));let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t};return G(qr(e),{...n,method:`POST`,headers:{"Content-Type":`application/json`,...r(n?.headers)},body:JSON.stringify(t)})},Yr=e=>`/api/v1/me/mcp/connections/${encodeURIComponent(String(e))}/oauth/complete`,Xr=(e,t,n)=>{let r=e=>{if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Symbol.iterator in e)return Object.fromEntries(Array.from(e,e=>Array.from(e)));let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t};return G(Yr(e),{...n,method:`POST`,headers:{"Content-Type":`application/json`,...r(n?.headers)},body:JSON.stringify(t)})};var Zr=`0.30.7`;function Qr(e){s.write(`${JSON.stringify(e,null,2)}\n`)}function $r(e,t=``){let n=``;for(let r of e){let e=r.codePointAt(0)??0;n+=(e<32||e>=127&&e<160)&&!t.includes(r)?`\\u${e.toString(16).padStart(4,`0`)}`:r}return n}function ei(e){return e==null?``:$r(typeof e==`string`?e:JSON.stringify(e))}function ti(e){let t=Object.entries(e),n=Math.max(...t.map(([e])=>e.length));for(let[e,r]of t)s.write(`${e.padEnd(n)} ${ei(r)}\n`)}function ni(e,t){t?Qr(e):ti(e)}function ri(e,t){let n=e.map(e=>t.map(t=>ei(e[t]))),r=t.map((e,t)=>n.reduce((e,n)=>Math.max(e,n[t]?.length??0),e.length)),i=e=>`${e.map((e,t)=>e.padEnd(r[t]??0)).join(` `)}`.trimEnd();s.write(`${i(t.map(e=>e.toUpperCase()))}\n`);for(let e of n)s.write(`${i(e)}\n`)}function ii(e){if(e.status===401)return"The API key was rejected. It may be revoked or deleted, so create a new one and run `astralbeam auth login` again.";if(e.status===404&&e.body?.detail===`Resource not found.`)return`This server does not serve that endpoint. Check the API URL, or the server may run an older AstralBeam release than this CLI (${Zr}).`;if(e.status===429)return`The API rate limit was reached. Wait a few minutes and retry.`}function ai(e,t,n,r){let i=e instanceof Error?e.message:String(e);if(t){let t=or(e)?e.body??{status:e.status,detail:i}:{detail:i};a.write(`${JSON.stringify({error:t,context:n??null})}\n`);return}if(!or(e))return void a.write(`Error: ${$r(i)}\n`);let o=r?` from ${r}`:``;a.write(`Error: ${$r(i)} (HTTP ${e.status}${o})\n`);for(let t of e.body?.issues??[])a.write(` ${$r(t.path)}: ${$r(t.message)}\n`);let s=ii(e);s&&a.write(`${s}\n`)}const oi=`https://astralbeam.ai/api`,si=/^key_([0-9a-f-]{36})_[0-9a-f-]{36}_abo_[A-Za-z]{64}$/;function ci(){if(n.ASTRALBEAM_CONFIG_DIR)return se(n.ASTRALBEAM_CONFIG_DIR,`config.json`);let e=i===`win32`?n.APPDATA??ae():n.XDG_CONFIG_HOME??se(ae(),`.config`);return se(e,`astralbeam`,`config.json`)}function li(e){let t=si.exec(e)?.[1];if(!t)throw Error(`The API key must match key_<organizationId>_<id>_abo_<secret>.`);return t}function ui(e){let t;try{t=new URL(e)}catch{throw Error(`The API URL "${e}" is not a valid URL.`)}let n=t.hostname,r=n===`localhost`||n===`[::1]`||w(n)&&n.startsWith(`127.`);if(t.protocol!==`https:`&&!(t.protocol===`http:`&&r))throw Error(`The API URL "${e}" must use https://, or http:// only for loopback hosts.`);return e}function di(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function fi(e){return di(e)&&Object.values(e).every(e=>di(e)&&typeof e.api_url==`string`&&typeof e.api_key==`string`&&di(e.organization)&&typeof e.organization.id==`string`&&typeof e.organization.name==`string`&&typeof e.organization.slug==`string`)}function pi(e){try{let t=JSON.parse(e);if(di(t)){let e=t.bindings===void 0?{}:t.bindings;if(fi(e))return{bindings:e}}}catch{}throw Error(`Invalid AstralBeam login bindings in ${ci()}`)}async function mi(){try{return pi(await b(ci(),`utf8`))}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return{bindings:{}};throw e}}async function hi(e){let t=ci();await re(oe(t),{recursive:!0,mode:448});let n=`${t}.${r}.tmp`;try{await C(n,`${JSON.stringify(e,null,2)}\n`,{mode:384,flag:`wx`}),await ie(n,t)}catch(e){throw await S(n,{force:!0}),e}}async function gi(){return await x(t())}function _i(e,t){for(let n=t;;n=oe(n)){let t=e.bindings[n];if(t)return{directory:n,binding:t};if(oe(n)===n)return}}function vi(e){let t=ae();return e===t||e.startsWith(t+T)?`~${e.slice(t.length)}`:e}const K={json:!1,context:void 0,failedRequest:void 0};function yi(e){K.context={organization:e.organization,bound_directory:e.directory??null},K.json||a.write(bi(e))}function bi(e){let{organization:t,directory:n}=e,r=t.name?`${$r(t.name)} (${$r(t.slug??``)}) · `:``,i=n?`bound at ${vi(n)}`:`from ASTRALBEAM_API_KEY`;return`▸ ${r}org ${t.id} · ${i}\n`}async function xi(){let e=n.ASTRALBEAM_API_KEY,t;if(e)t={apiKey:e,apiUrl:ui(n.ASTRALBEAM_API_URL??`https://astralbeam.ai/api`),organization:{id:li(e)}};else{let e=await gi(),r=_i(await mi(),e);if(!r)throw Error(`No AstralBeam login covers ${vi(e)}. Run \`astralbeam auth login\` in this directory or a parent, or set ASTRALBEAM_API_KEY.`);let{binding:i}=r;t={apiKey:i.api_key,apiUrl:ui(n.ASTRALBEAM_API_URL??i.api_url),organization:i.organization,directory:r.directory}}return yi(t),t}function Si(e,t=[]){let n=(e,r)=>{if(Array.isArray(e)||typeof e!=`object`||!e)return e;let i=Object.entries(e).flatMap(([e,i])=>{let a=[...r,e],o=t.some(e=>e.length===a.length&&e.every((e,t)=>e===a[t])),s=o?i:n(i,a);return s===void 0||!o&&typeof s==`object`&&s&&!Array.isArray(s)&&Object.keys(s).length===0?[]:[[e,s]]});return Object.fromEntries(i)};return n(e,[])}function Ci(e,t){let n=t.startsWith(`--`)?t:`--${t}`,r=e;if(e.startsWith(`@`)){let t=e.slice(1);if(t.length===0)throw Error(`${n} '@' must be followed by a file path (got empty path)`);let i=ce(t);try{r=le(i,`utf-8`)}catch(e){let r=e instanceof Error?e.message:`unknown read error`;throw Error(`${n}: cannot read file at '${t}': ${r}`)}}try{return JSON.parse(r)}catch{throw Error(`Invalid JSON in ${n}. Expected valid JSON.`)}}function wi(e,t=[]){let n=Ci(e,`body`);for(let{path:e,flag:r}of t){let t=n;for(let n of e)t=Ti(t)&&Object.hasOwn(t,n)?t[n]:void 0;if(!Ti(t))throw Error(`--body must include a JSON object at ${e.join(`.`)} (for --${r}).`)}return n}function Ti(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ei(e,t,n=!1){let r=t.startsWith(`--`)?t:`--${t}`;if(e===void 0){if(n)throw Error(`${r} is required (or pass --body with this field set).`);return}if(typeof e!=`string`)throw Error(`${r} must be provided once as a JSON object.`);let i=Ci(e,t);if(!Ti(i))throw Error(`${r} must be a JSON object.`);return i}function Di(e,t,n=`text`){if(e===void 0||!e.startsWith(`@`))return e;let r=e.slice(1);if(r.length===0)throw Error(`--${t} '@' must be followed by a file path (got empty path)`);let i=ce(r),a;try{a=le(i)}catch(e){let n=e instanceof Error?e.message:`unknown read error`;throw Error(`--${t}: cannot read file at '${r}': ${n}`)}switch(n){case`text`:return a.toString(`utf-8`);case`binary`:return a;case`base64`:return a.toString(`base64`);case`json`:{let e=a.toString(`utf-8`);try{return JSON.parse(e)}catch(e){let n=e instanceof Error?e.message:`unknown JSON parse error`;throw Error(`--${t}: file at '${r}' is not valid JSON: ${n}`)}}}}function Oi(e){return e.replace(/^filter_(.+)$/,`filter[$1]`)}async function ki(e){let{apiKey:t,apiUrl:n}=await xi();return{send(e,r={}){let i=new URLSearchParams;for(let t of e.query??[]){let e=r[t];e!==void 0&&i.set(Oi(t),typeof e==`string`?e:JSON.stringify(e))}return ar(e.path(r)+(i.size?`?${i.toString()}`:``),{apiKey:t,apiUrl:n,method:e.method,...e.body?{headers:{"content-type":`application/json`},body:JSON.stringify(r.body)}:{}})}}}function q(e,t){if(e!==void 0){if(K.json||typeof e!=`object`||!e)return Qr(e);if(`items`in e&&Array.isArray(e.items)){let t=e.items;t.length?ri(t,Object.keys(t[0])):a.write(`No results.
96
- `),`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
+ https://yargs.js.org/docs/#api-reference-version`,void 0,`versionWarning`),R(this,V,`f`).key[e]=!0,t.alias&&this.alias(e,t.alias);let n=t.deprecate||t.deprecated;n&&this.deprecateOption(e,n);let r=t.demand||t.required||t.require;r&&this.demand(e,r),t.demandOption&&this.demandOption(e,typeof t.demandOption==`string`?t.demandOption:void 0),t.conflicts&&this.conflicts(e,t.conflicts),`default`in t&&this.default(e,t.default),t.implies!==void 0&&this.implies(e,t.implies),t.nargs!==void 0&&this.nargs(e,t.nargs),t.config&&this.config(e,t.configParser),t.normalize&&this.normalize(e),t.choices&&this.choices(e,t.choices),t.coerce&&this.coerce(e,t.coerce),t.group&&this.group(e,t.group),(t.boolean||t.type===`boolean`)&&(this.boolean(e),t.alias&&this.boolean(t.alias)),(t.array||t.type===`array`)&&(this.array(e),t.alias&&this.array(t.alias)),(t.number||t.type===`number`)&&(this.number(e),t.alias&&this.number(t.alias)),(t.string||t.type===`string`)&&(this.string(e),t.alias&&this.string(t.alias)),(t.count||t.type===`count`)&&this.count(e),typeof t.global==`boolean`&&this.global(e,t.global),t.defaultDescription&&(R(this,V,`f`).defaultDescription[e]=t.defaultDescription),t.skipValidation&&this.skipValidation(e);let i=t.describe||t.description||t.desc,a=R(this,U,`f`).getDescriptions();Object.prototype.hasOwnProperty.call(a,e)&&typeof i!=`string`||this.describe(e,i),t.hidden&&this.hide(e),t.requiresArg&&this.requiresArg(e)}return this}options(e,t){return this.option(e,t)}parse(e,t,n){I(`[string|array] [function|boolean|object] [function]`,[e,t,n],arguments.length),this[xn](),e===void 0&&(e=R(this,ln,`f`)),typeof t==`object`&&(L(this,on,t,`f`),t=n),typeof t==`function`&&(L(this,an,t,`f`),t=!1),t||L(this,ln,e,`f`),R(this,an,`f`)&&L(this,Jt,!1,`f`);let r=this[Yn](e,!!t),i=this.parsed;return R(this,Ht,`f`).setParsed(this.parsed),F(r)?r.then(e=>(R(this,an,`f`)&&R(this,an,`f`).call(this,R(this,Gt,`f`),e,R(this,B,`f`)),e)).catch(e=>{throw R(this,an,`f`)&&R(this,an,`f`)(e,this.parsed.argv,R(this,B,`f`)),e}).finally(()=>{this[Fn](),this.parsed=i}):(R(this,an,`f`)&&R(this,an,`f`).call(this,R(this,Gt,`f`),r,R(this,B,`f`)),this[Fn](),this.parsed=i,r)}parseAsync(e,t,n){let r=this.parse(e,t,n);return F(r)?r:Promise.resolve(r)}parseSync(e,t,n){let r=this.parse(e,t,n);if(F(r))throw new M(`.parseSync() must not be used with asynchronous builders, handlers, or middleware`);return r}parserConfiguration(e){return I(`<object>`,[e],arguments.length),L(this,rn,e,`f`),this}pkgConf(e,t){I(`<string> [string]`,[e,t],arguments.length);let n=null,r=this[On](t||R(this,Bt,`f`));return r[e]&&typeof r[e]==`object`&&(n=It(r[e],t||R(this,Bt,`f`),this[Cn]()[`deep-merge-config`]||!1,R(this,H,`f`)),R(this,V,`f`).configObjects=(R(this,V,`f`).configObjects||[]).concat(n)),this}positional(e,t){I(`<string> <object>`,[e,t],arguments.length);let n=[`default`,`defaultDescription`,`implies`,`normalize`,`choices`,`conflicts`,`coerce`,`type`,`describe`,`desc`,`description`,`alias`];t=yt(t,(e,t)=>e===`type`&&![`string`,`number`,`boolean`].includes(t)?!1:n.includes(e));let r=R(this,Vt,`f`).fullCommands[R(this,Vt,`f`).fullCommands.length-1],i=r?R(this,z,`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,R(this,U,`f`).getPositionalGroupName()),this.option(e,t)}recommendCommands(e=!0){return I(`[boolean]`,[e],arguments.length),L(this,un,e,`f`),this}required(e,t,n){return this.demand(e,t,n)}require(e,t,n){return this.demand(e,t,n)}requiresArg(e){return I(`<array|string|object> [number]`,[e],arguments.length),typeof e==`string`&&R(this,V,`f`).narg[e]||this[An](this.requiresArg.bind(this),`narg`,e,NaN),this}showCompletionScript(e,t){return I(`[string] [string]`,[e,t],arguments.length),e||=this.$0,R(this,tn,`f`).log(R(this,Ht,`f`).generateCompletionScript(e,t||R(this,Ut,`f`)||`completion`)),this}showHelp(e){if(I(`[string|function]`,[e],arguments.length),L(this,Qt,!0,`f`),!R(this,U,`f`).hasCachedHelpMessage()){if(!this.parsed){let t=this[Yn](R(this,ln,`f`),void 0,void 0,0,!0);if(F(t))return t.then(()=>{R(this,U,`f`).showHelp(e)}),this}let t=R(this,z,`f`).runDefaultBuilderOn(this);if(F(t))return t.then(()=>{R(this,U,`f`).showHelp(e)}),this}return R(this,U,`f`).showHelp(e),this}scriptName(e){return this.customScriptName=!0,this.$0=e,this}showHelpOnFail(e,t){return I(`[boolean|string] [string]`,[e,t],arguments.length),R(this,U,`f`).showHelpOnFail(e,t),this}showVersion(e){return I(`[string|function]`,[e],arguments.length),R(this,U,`f`).showVersion(e),this}skipValidation(e){return I(`<array|string>`,[e],arguments.length),this[kn](`skipValidation`,e),this}strict(e){return I(`[boolean]`,[e],arguments.length),L(this,dn,e!==!1,`f`),this}strictCommands(e){return I(`[boolean]`,[e],arguments.length),L(this,fn,e!==!1,`f`),this}strictOptions(e){return I(`[boolean]`,[e],arguments.length),L(this,pn,e!==!1,`f`),this}string(e){return I(`<array|string>`,[e],arguments.length),this[kn](`string`,e),this[Qn](e),this}terminalWidth(){return I([],0),R(this,H,`f`).process.stdColumns}updateLocale(e){return this.updateStrings(e)}updateStrings(e){return I(`<object>`,[e],arguments.length),L(this,Kt,!1,`f`),R(this,H,`f`).y18n.updateLocale(e),this}usage(e,t,n,r){if(I(`<string|null|undefined> [string|boolean] [function|object] [function]`,[e,t,n,r],arguments.length),t!==void 0){if(Qe(e,null,R(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 R(this,U,`f`).usage(e),this}usageConfiguration(e){return I(`<object>`,[e],arguments.length),L(this,mn,e,`f`),this}version(e,t,n){let r=`version`;if(I(`[boolean|string] [string] [string]`,[e,t,n],arguments.length),R(this,hn,`f`)&&(this[yn](R(this,hn,`f`)),R(this,U,`f`).version(void 0),L(this,hn,null,`f`)),arguments.length===0)n=this[En](),e=r;else if(arguments.length===1){if(e===!1)return this;n=e,e=r}else arguments.length===2&&(n=t,t=void 0);return L(this,hn,typeof e==`string`?e:r,`f`),t||=R(this,U,`f`).deferY18nLookup(`Show version number`),R(this,U,`f`).version(n||void 0),this.boolean(R(this,hn,`f`)),this.describe(R(this,hn,`f`),t),this}wrap(e){return I(`<number|null|undefined>`,[e],arguments.length),R(this,U,`f`).wrap(e),this}[(z=/* @__PURE__ */ new WeakMap,Bt=/* @__PURE__ */ new WeakMap,Vt=/* @__PURE__ */ new WeakMap,Ht=/* @__PURE__ */ new WeakMap,Ut=/* @__PURE__ */ new WeakMap,Wt=/* @__PURE__ */ new WeakMap,Gt=/* @__PURE__ */ new WeakMap,Kt=/* @__PURE__ */ new WeakMap,qt=/* @__PURE__ */ new WeakMap,Jt=/* @__PURE__ */ new WeakMap,Yt=/* @__PURE__ */ new WeakMap,Xt=/* @__PURE__ */ new WeakMap,Zt=/* @__PURE__ */ new WeakMap,Qt=/* @__PURE__ */ new WeakMap,$t=/* @__PURE__ */ new WeakMap,en=/* @__PURE__ */ new WeakMap,tn=/* @__PURE__ */ new WeakMap,B=/* @__PURE__ */ new WeakMap,V=/* @__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,ln=/* @__PURE__ */ new WeakMap,un=/* @__PURE__ */ new WeakMap,H=/* @__PURE__ */ new WeakMap,dn=/* @__PURE__ */ new WeakMap,fn=/* @__PURE__ */ new WeakMap,pn=/* @__PURE__ */ new WeakMap,U=/* @__PURE__ */ new WeakMap,mn=/* @__PURE__ */ new WeakMap,hn=/* @__PURE__ */ new WeakMap,W=/* @__PURE__ */ new WeakMap,_n)](e){if(!e._||!e[`--`])return e;e._.push.apply(e._,e[`--`]);try{delete e[`--`]}catch{}return e}[vn](){return{log:(...e)=>{this[Wn]()||console.log(...e),L(this,Qt,!0,`f`),R(this,B,`f`).length&&L(this,B,R(this,B,`f`)+`
94
+ `,`f`),L(this,B,R(this,B,`f`)+e.join(` `),`f`)},error:(...e)=>{this[Wn]()||console.error(...e),L(this,Qt,!0,`f`),R(this,B,`f`).length&&L(this,B,R(this,B,`f`)+`
95
+ `,`f`),L(this,B,R(this,B,`f`)+e.join(` `),`f`)}}}[yn](e){et(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]}[bn](e,t,n){R(this,qt,`f`)[n]||(R(this,H,`f`).process.emitWarning(e,t),R(this,qt,`f`)[n]=!0)}[xn](){R(this,Yt,`f`).push({options:R(this,V,`f`),configObjects:R(this,V,`f`).configObjects.slice(0),exitProcess:R(this,Jt,`f`),groups:R(this,Zt,`f`),strict:R(this,dn,`f`),strictCommands:R(this,fn,`f`),strictOptions:R(this,pn,`f`),completionCommand:R(this,Ut,`f`),output:R(this,B,`f`),exitError:R(this,Gt,`f`),hasOutput:R(this,Qt,`f`),parsed:this.parsed,parseFn:R(this,an,`f`),parseContext:R(this,on,`f`)}),R(this,U,`f`).freeze(),R(this,W,`f`).freeze(),R(this,z,`f`).freeze(),R(this,Xt,`f`).freeze()}[Sn](){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[qn](R(this,Bt,`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}[Cn](){return R(this,rn,`f`)}[wn](){return R(this,mn,`f`)}[Tn](){if(!R(this,Kt,`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(/[.:].*/,``))}[En](){return this[On]().version||`unknown`}[Dn](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}[On](e){let t=e||`*`;if(R(this,sn,`f`)[t])return R(this,sn,`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`});Qe(r,void 0,R(this,H,`f`)),n=JSON.parse(R(this,H,`f`).readFileSync(r,`utf8`))}catch{}return R(this,sn,`f`)[t]=n||{},R(this,sn,`f`)[t]}[kn](e,t){t=[].concat(t),t.forEach(t=>{t=this[Nn](t),R(this,V,`f`)[e].push(t)})}[An](e,t,n,r){this[Mn](e,t,n,r,(e,t,n)=>{R(this,V,`f`)[e][t]=n})}[jn](e,t,n,r){this[Mn](e,t,n,r,(e,t,n)=>{R(this,V,`f`)[e][t]=(R(this,V,`f`)[e][t]||[]).concat(n)})}[Mn](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[Nn](n),r)}[Nn](e){return e===`__proto__`?`___proto___`:e}[Pn](e,t){return this[An](this[Pn].bind(this),`key`,e,t),this}[Fn](){var e,t,n,r,i,a,o,s,c,l,u,d;let f=R(this,Yt,`f`).pop();Qe(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,Jt,e,`f`)}}.value,groups:{set value(e){L(n,Zt,e,`f`)}}.value,output:{set value(e){L(r,B,e,`f`)}}.value,exitError:{set value(e){L(i,Gt,e,`f`)}}.value,hasOutput:{set value(e){L(a,Qt,e,`f`)}}.value,parsed:this.parsed,strict:{set value(e){L(o,dn,e,`f`)}}.value,strictCommands:{set value(e){L(s,fn,e,`f`)}}.value,strictOptions:{set value(e){L(c,pn,e,`f`)}}.value,completionCommand:{set value(e){L(l,Ut,e,`f`)}}.value,parseFn:{set value(e){L(u,an,e,`f`)}}.value,parseContext:{set value(e){L(d,on,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,Xt,`f`).unfreeze()}[In](e,t){return ct(t,t=>(e(t),t))}getInternalMethods(){return{getCommandInstance:this[Ln].bind(this),getContext:this[Rn].bind(this),getHasOutput:this[zn].bind(this),getLoggerInstance:this[Bn].bind(this),getParseContext:this[Vn].bind(this),getParserConfiguration:this[Cn].bind(this),getUsageConfiguration:this[wn].bind(this),getUsageInstance:this[Hn].bind(this),getValidationInstance:this[Un].bind(this),hasParseCallback:this[Wn].bind(this),isGlobalContext:this[Gn].bind(this),postProcess:this[Kn].bind(this),reset:this[Jn].bind(this),runValidation:this[Xn].bind(this),runYargsParserAndExecuteCommands:this[Yn].bind(this),setHasOutput:this[Zn].bind(this)}}[Ln](){return R(this,z,`f`)}[Rn](){return R(this,Vt,`f`)}[zn](){return R(this,Qt,`f`)}[Bn](){return R(this,tn,`f`)}[Vn](){return R(this,on,`f`)||{}}[Hn](){return R(this,U,`f`)}[Un](){return R(this,W,`f`)}[Wn](){return!!R(this,an,`f`)}[Gn](){return R(this,en,`f`)}[Kn](e,t,n,r){return n||F(e)||(t||(e=this[_n](e)),(this[Cn]()[`parse-positional-numbers`]||this[Cn]()[`parse-positional-numbers`]===void 0)&&(e=this[Dn](e)),r&&(e=st(e,this,R(this,Xt,`f`).getMiddleware(),!1))),e}[Jn](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,cn,`f`),Object.keys(R(this,Zt,`f`)).reduce((e,t)=>{let r=R(this,Zt,`f`)[t].filter(e=>!(e in n));return r.length>0&&(e[t]=r),e},{})),L(this,Zt,{},`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]=yt(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):St(this,R(this,H,`f`)),`f`),L(this,W,R(this,W,`f`)?R(this,W,`f`).reset(n):Nt(this,R(this,U,`f`),R(this,H,`f`)),`f`),L(this,z,R(this,z,`f`)?R(this,z,`f`).reset():pt(R(this,U,`f`),R(this,W,`f`),R(this,Xt,`f`),R(this,H,`f`)),`f`),R(this,Ht,`f`)||L(this,Ht,Ot(this,R(this,U,`f`),R(this,z,`f`),R(this,H,`f`)),`f`),R(this,Xt,`f`).reset(),L(this,Ut,null,`f`),L(this,B,``,`f`),L(this,Gt,null,`f`),L(this,Qt,!1,`f`),this.parsed=!1,this}[qn](e,t){return R(this,H,`f`).path.relative(e,t)}[Yn](e,t,n,r=0,i=!1){let a=!!n||i;e||=R(this,ln,`f`),R(this,V,`f`).__=R(this,H,`f`).y18n.__,R(this,V,`f`).configuration=this[Cn]();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,on,`f`)),u,d=c.aliases,f=!1,p=!1;Object.keys(l).forEach(e=>{e===R(this,$t,`f`)&&l[e]?f=!0:e===R(this,hn,`f`)&&l[e]&&(p=!0)}),l.$0=this.$0,this.parsed=c,r===0&&R(this,U,`f`).clearCachedHelpMessage();try{if(this[Tn](),t)return this[Kn](l,o,!!n,!1);R(this,$t,`f`)&&[R(this,$t,`f`)].concat(d[R(this,$t,`f`)]||[]).filter(e=>e.length>1).includes(``+l._[l._.length-1])&&(l._.pop(),f=!0),L(this,en,!1,`f`);let s=R(this,z,`f`).getCommands(),m=R(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!==R(this,Ut,`f`)){let e=R(this,z,`f`).runCommand(a,this,c,t+1,i,f||p||i);return this[Kn](e,o,!!n,!1)}if(!e&&a!==R(this,Ut,`f`)){e=a;break}}!R(this,z,`f`).hasDefaultCommand()&&R(this,un,`f`)&&e&&!h&&R(this,W,`f`).recommendCommands(e,s)}R(this,Ut,`f`)&&l._.includes(R(this,Ut,`f`))&&!m&&(R(this,Jt,`f`)&&bt(!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[Kn](e,o,!!n,!1)}if(m){R(this,Jt,`f`)&&bt(!0),e=[].concat(e);let t=e.slice(e.indexOf(`--${R(this,Ht,`f`).completionKey}`)+1);return R(this,Ht,`f`).getCompletion(t,(e,t)=>{if(e)throw new M(e.message);(t||[]).forEach(e=>{R(this,tn,`f`).log(e)}),this.exit(0)}),this[Kn](l,!o,!!n,!1)}if(R(this,Qt,`f`)||(f?(R(this,Jt,`f`)&&bt(!0),a=!0,this.showHelp(`log`),this.exit(0)):p&&(R(this,Jt,`f`)&&bt(!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 M(c.error.message);if(!m){let e=this[Xn](d,{},c.error);n||(u=st(l,this,R(this,Xt,`f`).getMiddleware(),!0)),u=this[In](e,u??l),F(u)&&!n&&(u=u.then(()=>st(l,this,R(this,Xt,`f`).getMiddleware(),!1)))}}}catch(e){if(e instanceof M)R(this,U,`f`).fail(e.message,e);else throw e}return this[Kn](u??l,o,!!n,!0)}[Xn](e,t,n,r){let i={...this.getDemandedOptions()};return a=>{if(n)throw new M(n.message);R(this,W,`f`).nonOptionCount(a),R(this,W,`f`).requiredArguments(a,i);let o=!1;R(this,fn,`f`)&&(o=R(this,W,`f`).unknownCommands(a)),R(this,dn,`f`)&&!o?R(this,W,`f`).unknownArguments(a,e,t,!!r):R(this,pn,`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)}}[Zn](){L(this,Qt,!0,`f`)}[Qn](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 er(e){return!!e&&typeof e.getInternalMethods==`function`}const tr=gn(Ze);var nr=class extends Error{};function rr(e){if(!Number.isInteger(e)||e<60||e>600)throw new nr(`Expected a whole number of seconds from 60 to 600.`);return e}function ir(e,t=`https://astralbeam.ai/api`){return`${t.replace(/\/+$/,``)}${e.replace(/^\/api(?=\/)/,``)}`}function ar(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 or(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(ir(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=ar(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 sr(e,t){let n=await or(e,t);if(n.status!==204)return await n.json()}function cr(e){return e instanceof Error&&e.name===`AstralBeamApiError`&&`status`in e&&typeof e.status==`number`}function lr(e,t=`https://astralbeam.ai/api`){return`${t.replace(/\/+$/,``)}${e.replace(/^\/api(?=\/)/,``)}`}function ur(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 dr(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(lr(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=ur(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 fr(e,t){let n=await dr(e,t);if(n.status!==204)return await n.json()}function G(e,t){return fr(e,t)}async function pr(e,t){let n=await dr(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 mr(e,t){return dr(e,t)}const hr=()=>`/api/v1/organization`,gr=e=>fr(hr(),{...e,method:`GET`}),_r=()=>`/api/v1/chat/files`,vr=(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(_r(),{...t,method:`POST`,headers:{"Content-Type":`application/json`,...n(t?.headers)},body:JSON.stringify(e)})},yr=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`},br=(e,t)=>pr(yr(e),{...t,method:`GET`}),xr=()=>`/api/v1/chat`,Sr=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`},Cr=(e,t)=>G(Sr(e),{...t,method:`GET`}),wr=()=>`/api/v1/chat/threads`,Tr=(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(wr(),{...t,method:`POST`,headers:{"Content-Type":`application/json`,...n(t?.headers)},body:JSON.stringify(e)})},Er=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`},Dr=(e,t)=>G(Er(e),{...t,method:`GET`}),Or=e=>`/api/v1/chat/threads/${encodeURIComponent(String(e))}`,kr=(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(Or(e),{...n,method:`PATCH`,headers:{"Content-Type":`application/json`,...r(n?.headers)},body:JSON.stringify(t)})},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))}?${r}`:`/api/v1/chat/threads/${encodeURIComponent(String(e))}`},jr=(e,t,n)=>G(Ar(e,t),{...n,method:`DELETE`}),Mr=(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`},Nr=(e,t,n)=>G(Mr(e,t),{...n,method:`GET`}),Pr=e=>`/api/v1/chat/threads/${encodeURIComponent(String(e))}/tool-results`,Fr=()=>`/api/v1/me`,Ir=e=>G(Fr(),{...e,method:`POST`}),Lr=()=>`/api/v1/me/mcp/catalog`,Rr=e=>G(Lr(),{...e,method:`GET`}),zr=()=>`/api/v1/me/mcp/connections`,Br=(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(zr(),{...t,method:`POST`,headers:{"Content-Type":`application/json`,...n(t?.headers)},body:JSON.stringify(e)})},Vr=e=>`/api/v1/me/mcp/connections/${encodeURIComponent(String(e))}/headers`,Hr=(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(Vr(e),{...n,method:`POST`,headers:{"Content-Type":`application/json`,...r(n?.headers)},body:JSON.stringify(t)})},Ur=e=>`/api/v1/me/mcp/connections/${encodeURIComponent(String(e))}`,Wr=(e,t)=>G(Ur(e),{...t,method:`DELETE`}),Gr=e=>`/api/v1/me/mcp/connections/${encodeURIComponent(String(e))}/test`,Kr=(e,t)=>G(Gr(e),{...t,method:`POST`}),qr=e=>`/api/v1/me/mcp/connections/${encodeURIComponent(String(e))}/authorize`,Jr=(e,t)=>G(qr(e),{...t,method:`POST`}),Yr=e=>`/api/v1/me/mcp/connections/${encodeURIComponent(String(e))}/oauth/bind`,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)})},Zr=e=>`/api/v1/me/mcp/connections/${encodeURIComponent(String(e))}/oauth/complete`,Qr=(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)})};var $r=`0.30.8`;function ei(e){s.write(`${JSON.stringify(e,null,2)}\n`)}function ti(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 ni(e){return e==null?``:ti(typeof e==`string`?e:JSON.stringify(e))}function ri(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)} ${ni(r)}\n`)}function ii(e,t){t?ei(e):ri(e)}function ai(e,t){let n=e.map(e=>t.map(t=>ni(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 oi(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 (${$r}).`;if(e.status===429)return`The API rate limit was reached. Wait a few minutes and retry.`}function si(e,t,n,r){let i=e instanceof Error?e.message:String(e);if(t){let t=cr(e)?e.body??{status:e.status,detail:i}:{detail:i};a.write(`${JSON.stringify({error:t,context:n??null})}\n`);return}if(!cr(e))return void a.write(`Error: ${ti(i)}\n`);let o=r?` from ${r}`:``;a.write(`Error: ${ti(i)} (HTTP ${e.status}${o})\n`);for(let t of e.body?.issues??[])a.write(` ${ti(t.path)}: ${ti(t.message)}\n`);let s=oi(e);s&&a.write(`${s}\n`)}const ci=`https://astralbeam.ai/api`,li=/^key_([0-9a-f-]{36})_[0-9a-f-]{36}_abo_[A-Za-z]{64}$/;function ui(){if(n.ASTRALBEAM_CONFIG_DIR)return le(n.ASTRALBEAM_CONFIG_DIR,`config.json`);let e=i===`win32`?n.APPDATA??ce():n.XDG_CONFIG_HOME??le(ce(),`.config`);return le(e,`astralbeam`,`config.json`)}function di(e){let t=li.exec(e)?.[1];if(!t)throw Error(`The API key must match key_<organizationId>_<id>_abo_<secret>.`);return t}function fi(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]`||se(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 pi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function mi(e){return pi(e)&&Object.values(e).every(e=>pi(e)&&typeof e.api_url==`string`&&typeof e.api_key==`string`&&pi(e.organization)&&typeof e.organization.id==`string`&&typeof e.organization.name==`string`&&typeof e.organization.slug==`string`)}function hi(e){try{let t=JSON.parse(e);if(pi(t)){let e=t.bindings===void 0?{}:t.bindings;if(mi(e))return{bindings:e}}}catch{}throw Error(`Invalid AstralBeam login bindings in ${ui()}`)}async function gi(){try{return hi(await b(ui(),`utf8`))}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return{bindings:{}};throw e}}async function _i(e){let t=ui();await re(C(t),{recursive:!0,mode:448});let n=`${t}.${r}.tmp`;try{await oe(n,`${JSON.stringify(e,null,2)}\n`,{mode:384,flag:`wx`}),await ie(n,t)}catch(e){throw await ae(n,{force:!0}),e}}async function vi(e){let t=`${ui()}.lock`;await re(C(t),{recursive:!0,mode:448});let n=performance.now()+3e3;for(;;)try{await re(t,{mode:448});break}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`EEXIST`))throw e;if(performance.now()>=n)throw Error(`AstralBeam login bindings are locked. Retry shortly, or remove ${t} after confirming no other AstralBeam CLI process is updating the bindings.`);await fe(25)}try{return await e(await gi())}finally{await S(t)}}async function yi(){return await x(t())}function bi(e,t){for(let n=t;;n=C(n)){let t=e.bindings[n];if(t)return{directory:n,binding:t};if(C(n)===n)return}}function xi(e){let t=ce();return e===t||e.startsWith(t+de)?`~${e.slice(t.length)}`:e}const K={json:!1,context:void 0,failedRequest:void 0};function Si(e){K.context={organization:e.organization,bound_directory:e.directory??null},K.json||a.write(Ci(e))}function Ci(e){let{organization:t,directory:n}=e,r=t.name?`${ti(t.name)} (${ti(t.slug??``)}) · `:``,i=n?`bound at ${xi(n)}`:`from ASTRALBEAM_API_KEY`;return`▸ ${r}org ${t.id} · ${i}\n`}async function wi(){let e=n.ASTRALBEAM_API_KEY,t;if(e)t={apiKey:e,apiUrl:fi(n.ASTRALBEAM_API_URL??`https://astralbeam.ai/api`),organization:{id:di(e)}};else{let e=await yi(),r=bi(await gi(),e);if(!r)throw Error(`No AstralBeam login covers ${xi(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:fi(n.ASTRALBEAM_API_URL??i.api_url),organization:i.organization,directory:r.directory}}return Si(t),t}function Ti(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 Ei(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=ue(t);try{r=w(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 Di(e,t=[]){let n=Ei(e,`body`);for(let{path:e,flag:r}of t){let t=n;for(let n of e)t=Oi(t)&&Object.hasOwn(t,n)?t[n]:void 0;if(!Oi(t))throw Error(`--body must include a JSON object at ${e.join(`.`)} (for --${r}).`)}return n}function Oi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ki(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=Ei(e,t);if(!Oi(i))throw Error(`${r} must be a JSON object.`);return i}function Ai(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=ue(r),a;try{a=w(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 ji(e){return e.replace(/^filter_(.+)$/,`filter[$1]`)}async function Mi(e){let{apiKey:t,apiUrl:n}=await wi();return{send(e,r={}){let i=new URLSearchParams;for(let t of e.query??[]){let e=r[t];e!==void 0&&i.set(ji(t),typeof e==`string`?e:JSON.stringify(e))}return sr(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 ei(e);if(`items`in e&&Array.isArray(e.items)){let t=e.items;t.length?ai(t,Object.keys(t[0])):a.write(`No results.
96
+ `),`page_after`in e&&typeof e.page_after==`string`&&a.write(`More results: --page-after ${ti(e.page_after)}\n`)}else ii(e,!1)}}function J(e,t){return t()}let Ni=``;async function Pi(e,t,n){return t.dryRun&&(Ni=(await wi()).apiUrl),n()}function Fi(e){e.query&&=Object.fromEntries(Object.entries(e.query).map(([e,t])=>[ji(e),t])),ei({...e,note:`Local request preview only. No HTTP request or server-side validation is performed.`,command:e.command.replace(/^cf /,`astralbeam `),url:ir(new URL(e.url).pathname.replace(/^\/client\/v4/,``),Ni)})}function Ii(e,t){throw Error(`Missing required option --${e} (or pass --body).`)}var Li={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 Ri(e){return e.usage(`$0 docs search
97
97
 
98
- 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
98
+ 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 zi={command:`search`,describe:`Search documentation`,builder:Ri,handler:async e=>Pi({command:`docs search`,classification:{safeFlags:[`dry-run`]}},e,async()=>{let t={q:e.q};if(e.dryRun){Fi({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 Mi(e);q(await J(`Loading`,async()=>n.send(Li,t)),{successLabel:`Loaded`})})},Bi={command:`docs`,describe:`docs`,builder:e=>e.command(zi).demandCommand(1,`Please specify a subcommand`),handler:()=>{}};var Vi={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 Hi(e){return e.usage(`$0 organization get
99
99
 
100
- 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>
100
+ 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 Ui={command:`get`,describe:`Get the current Organization`,builder:Hi,handler:async e=>Pi({command:`organization get`,classification:{safeFlags:[`dry-run`]}},e,async()=>{if(e.dryRun){Fi({command:`cf organization get`,method:`GET`,url:`https://api.cloudflare.com/client/v4/api/v1/organization`,pathParams:{},bodyKind:`none`});return}let t=await Mi(e);q(await J(`Loading`,async()=>t.send(Vi)),{successLabel:`Loaded`})})},Wi={command:`organization`,describe:`organization`,builder:e=>e.command(Ui).demandCommand(1,`Please specify a subcommand`),handler:()=>{}};function Gi(e,...t){let n=e[0]??``;for(let[r,i]of t.entries())n+=encodeURIComponent(String(i))+(e[r+1]??``);return n}var Ki={method:`POST`,path:e=>Gi`/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 qi(e){return e.usage(`$0 tenant-users create <tenant-id>
101
101
 
102
- 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>
102
+ 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 Ji={command:`create <tenant-id>`,describe:`Create a TenantUser`,builder:qi,handler:async e=>Pi({command:`tenant-users create`,classification:{safeFlags:[`admin`,`dry-run`]}},e,async()=>{if(e.dryRun){Fi({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?Ti({external_id:Ai(e[`external-id`],`external-id`,`text`),name:Ai(e.name,`name`,`text`),metadata:ki(e.metadata,`metadata`),admin:e.admin},[[`metadata`]]):Di(e.body)});return}let t=await Mi(e);if(e.body){let n=Di(e.body);q(await J(`Creating`,async()=>t.send(Ki,{body:n,tenant_id:e[`tenant-id`]})),{successLabel:`Created`});return}e[`external-id`]===void 0&&(e[`external-id`]=await Ii(`external-id`,`Your stable external identity. Exact and case-sensitive; whitespace is preserved. Immutable after creation.`));let n=Ti({external_id:Ai(e[`external-id`],`external-id`,`text`),name:Ai(e.name,`name`,`text`),metadata:ki(e.metadata,`metadata`),admin:e.admin},[[`metadata`]]);q(await J(`Creating`,async()=>t.send(Ki,{body:n,tenant_id:e[`tenant-id`]})),{successLabel:`Created`})})};var Yi={method:`GET`,path:e=>Gi`/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 Xi(e){return e.usage(`$0 tenant-users get <id>
103
103
 
104
- 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
104
+ 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 Zi={command:`get <id>`,describe:`Get a TenantUser`,builder:Xi,handler:async e=>Pi({command:`tenant-users get`,classification:{safeFlags:[`dry-run`]}},e,async()=>{if(e.dryRun){Fi({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 Mi(e);q(await J(`Loading`,async()=>t.send(Yi,{tenant_id:e[`tenant-id`],id:e.id})),{successLabel:`Loaded`})})};var Qi={method:`GET`,path:e=>Gi`/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 $i(e){return e.usage(`$0 tenant-users list
105
105
 
106
- 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>
106
+ 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 ea={command:`list`,describe:`List TenantUsers`,builder:$i,handler:async e=>Pi({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){Fi({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 Mi(e);q(await J(`Loading`,async()=>n.send(Qi,{tenant_id:e[`tenant-id`],...t})),{successLabel:`Loaded`})})};var ta={method:`PATCH`,path:e=>Gi`/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 na(e){return e.usage(`$0 tenant-users update <id>
107
107
 
108
- 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>
108
+ 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 ra={command:`update <id>`,describe:`Update a TenantUser`,builder:na,handler:async e=>Pi({command:`tenant-users update`,classification:{safeFlags:[`admin`,`dry-run`]}},e,async()=>{if(e.dryRun){Fi({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?Ti({name:Ai(e.name,`name`,`text`),metadata:ki(e.metadata,`metadata`),admin:e.admin},[[`metadata`]]):Di(e.body)});return}let t=await Mi(e);if(e.body){let n=Di(e.body);q(await J(`Updating`,async()=>t.send(ta,{body:n,tenant_id:e[`tenant-id`],id:e.id})),{successLabel:`Updated`});return}let n=Ti({name:Ai(e.name,`name`,`text`),metadata:ki(e.metadata,`metadata`),admin:e.admin},[[`metadata`]]);q(await J(`Updating`,async()=>t.send(ta,{body:n,tenant_id:e[`tenant-id`],id:e.id})),{successLabel:`Updated`})})};var ia={method:`GET`,path:e=>Gi`/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 aa(e){return e.usage(`$0 tenant-users usage get <tenant-id>
109
109
 
110
- 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
110
+ 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 oa={command:`get <tenant-id>`,describe:`Get TenantUser usage`,builder:aa,handler:async e=>Pi({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){Fi({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 Mi(e);q(await J(`Loading`,async()=>n.send(ia,{tenant_id:e[`tenant-id`],...t})),{successLabel:`Loaded`})})},sa={command:`usage`,describe:`Operations for usage`,builder:e=>e.command(oa).demandCommand(1,`Please specify a subcommand`),handler:()=>{}},ca={command:`tenant-users`,describe:`tenant-users`,builder:e=>e.command(Ji).command(Zi).command(ea).command(ra).command(sa).demandCommand(1,`Please specify a subcommand`),handler:()=>{}};var la={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 ua(e){return e.usage(`$0 tenants create
111
111
 
112
- 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>
112
+ 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 da={command:`create`,describe:`Create a Tenant`,builder:ua,handler:async e=>Pi({command:`tenants create`,classification:{safeFlags:[`dry-run`]}},e,async()=>{if(e.dryRun){Fi({command:`cf tenants create`,method:`POST`,url:`https://api.cloudflare.com/client/v4/api/v1/tenants`,pathParams:{},bodyKind:`json`,body:e.body===void 0?Ti({external_id:Ai(e[`external-id`],`external-id`,`text`),name:Ai(e.name,`name`,`text`),metadata:ki(e.metadata,`metadata`)},[[`metadata`]]):Di(e.body)});return}let t=await Mi(e);if(e.body){let n=Di(e.body);q(await J(`Creating`,async()=>t.send(la,{body:n})),{successLabel:`Created`});return}e[`external-id`]===void 0&&(e[`external-id`]=await Ii(`external-id`,`Your stable external identity. Exact and case-sensitive; whitespace is preserved. Immutable after creation.`));let n=Ti({external_id:Ai(e[`external-id`],`external-id`,`text`),name:Ai(e.name,`name`,`text`),metadata:ki(e.metadata,`metadata`)},[[`metadata`]]);q(await J(`Creating`,async()=>t.send(la,{body:n})),{successLabel:`Created`})})};var fa={method:`GET`,path:e=>Gi`/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 pa(e){return e.usage(`$0 tenants get <id>
113
113
 
114
- 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
114
+ 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 ma={command:`get <id>`,describe:`Get a Tenant`,builder:pa,handler:async e=>Pi({command:`tenants get`,classification:{safeFlags:[`dry-run`]}},e,async()=>{if(e.dryRun){Fi({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 Mi(e);q(await J(`Loading`,async()=>t.send(fa,{id:e.id})),{successLabel:`Loaded`})})};var ha={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 ga(e){return e.usage(`$0 tenants list
115
115
 
116
- 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>
116
+ 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 _a={command:`list`,describe:`List Tenants`,builder:ga,handler:async e=>Pi({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){Fi({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 Mi(e);q(await J(`Loading`,async()=>n.send(ha,t)),{successLabel:`Loaded`})})};var va={method:`PATCH`,path:e=>Gi`/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 ya(e){return e.usage(`$0 tenants update <id>
117
117
 
118
- 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
118
+ 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 ba={command:`update <id>`,describe:`Update a Tenant`,builder:ya,handler:async e=>Pi({command:`tenants update`,classification:{safeFlags:[`dry-run`]}},e,async()=>{if(e.dryRun){Fi({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?Ti({name:Ai(e.name,`name`,`text`),metadata:ki(e.metadata,`metadata`)},[[`metadata`]]):Di(e.body)});return}let t=await Mi(e);if(e.body){let n=Di(e.body);q(await J(`Updating`,async()=>t.send(va,{body:n,id:e.id})),{successLabel:`Updated`});return}let n=Ti({name:Ai(e.name,`name`,`text`),metadata:ki(e.metadata,`metadata`)},[[`metadata`]]);q(await J(`Updating`,async()=>t.send(va,{body:n,id:e.id})),{successLabel:`Updated`})})};var xa={method:`GET`,path:e=>Gi`/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 Sa(e){return e.usage(`$0 tenants threads messages list
119
119
 
120
- 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
120
+ 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 Ca={command:`list`,describe:`Read conversation history for administration`,builder:Sa,handler:async e=>Pi({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){Fi({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 Mi(e);q(await J(`Loading`,async()=>n.send(xa,{tenantId:e[`tenant-id`],id:e.id,...t})),{successLabel:`Loaded`})})},wa={command:`messages`,describe:`Operations for threads.messages`,builder:e=>e.command(Ca).demandCommand(1,`Please specify a subcommand`),handler:()=>{}},Ta={command:`threads`,describe:`Operations for threads`,builder:e=>e.command(wa).demandCommand(1,`Please specify a subcommand`),handler:()=>{}},Ea={command:`tenants`,describe:`tenants`,builder:e=>e.command(da).command(ma).command(_a).command(ba).command(Ta).demandCommand(1,`Please specify a subcommand`),handler:()=>{}};var Da={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 Oa(e){return e.usage(`$0 threads list
121
121
 
122
- List nonempty conversations by activity, Tenant ID and thread ID descending. q searches titles as a case-insensitive literal substring. filter[tenant_id] narrows the verified scope. Keep filters unchanged when reusing cursors. This is a live listing, not a snapshot.`).option(`page-size`,{type:`number`,description:`Positive integer, default 20. Values above 100 are accepted and capped. page_after and page_before are mutually exclusive.`}).option(`page-after`,{type:`string`,description:`Page after`}).option(`page-before`,{type:`string`,description:`Page before`}).option(`q`,{type:`string`,description:`Case-insensitive literal substring of the conversation title. Trimmed, blank means no search.`}).option(`tenant-id`,{type:`string`,description:`Filter tenant ID`}).option(`dry-run`,{type:`boolean`,description:`Validate and show what would happen without executing`,default:!1})}const Ea={command:`list`,describe:`List conversations for administration`,builder:Ta,handler:async e=>ji({command:`threads list`,classification:{safeFlags:[`dry-run`]}},e,async()=>{let t={page_size:e[`page-size`],page_after:e[`page-after`],page_before:e[`page-before`],q:e.q,filter_tenant_id:e[`tenant-id`]};if(e.dryRun){Mi({command:`cf threads list`,method:`GET`,url:`https://api.cloudflare.com/client/v4/api/v1/threads`,pathParams:{},query:t,bodyKind:`none`});return}let n=await ki(e);q(await J(`Loading`,async()=>n.send(wa,t)),{successLabel:`Loaded`})})},Da={command:`threads`,describe:`threads`,builder:e=>e.command(Ea).demandCommand(1,`Please specify a subcommand`),handler:()=>{}};var Oa=/* @__PURE__ */ D({command0:()=>Li,command1:()=>Vi,command2:()=>aa,command3:()=>Ca,command4:()=>Da});function ka(e){o.setRawMode(!0),a.write(e),o.setEncoding(`utf8`),o.resume();let t=``;return new Promise((e,n)=>{let r=()=>{o.off(`data`,i),o.setRawMode(!1),o.pause(),a.write(`
122
+ 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 ka={command:`list`,describe:`List conversations for administration`,builder:Oa,handler:async e=>Pi({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){Fi({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 Mi(e);q(await J(`Loading`,async()=>n.send(Da,t)),{successLabel:`Loaded`})})},Aa={command:`threads`,describe:`threads`,builder:e=>e.command(ka).demandCommand(1,`Please specify a subcommand`),handler:()=>{}};var ja=/* @__PURE__ */ he({command0:()=>Bi,command1:()=>Wi,command2:()=>ca,command3:()=>Ea,command4:()=>Aa});function Ma(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(`
123
123
  `)},i=i=>{for(let a of i){if(a===`\r`||a===`
124
- `)return r(),e(t.trim());if(a===``)return r(),n(/* @__PURE__ */ Error(`Cancelled.`));t=a===``||a===`\b`?t.slice(0,-1):t+a}};o.on(`data`,i)})}async function Aa(){return o.isTTY?await ka(`Paste an organization API key: `):(await ue(o)).trim()}async function ja(e,t){let n=li(e),{id:r,name:i,slug:a}=await mr({apiKey:e,apiUrl:t});if(r!==n)throw Error(`The API returned a different organization.`);return{id:r,name:i,slug:a}}function Ma(e){return`${e.slice(0,e.indexOf(`_abo_`)+5)}…${e.slice(-4)}`}function Na(e){return e.command(`login`,`Verify an API key, read from a hidden prompt or stdin, and bind it to this directory and everything below it`,e=>e.option(`api-url`,{type:`string`,description:`API base URL, ending in /api (default ${oi})`}),async e=>{let t=ui(e.apiUrl??n.ASTRALBEAM_API_URL??`https://astralbeam.ai/api`),r=await Aa(),i=await ja(r,t),a=await gi(),o=await mi();o.bindings[a]={api_url:t,api_key:r,organization:i},await hi(o),yi({apiKey:r,apiUrl:t,organization:i,directory:a}),ni({directory:a,organization:i,api_url:t},K.json)}),e.command({command:`logout`,describe:`Remove the binding that covers this directory`,handler:async()=>{let e=await mi(),t=_i(e,await gi());if(!t)throw Error(`No AstralBeam login covers this directory.`);delete e.bindings[t.directory],await hi(e);let{organization:n}=t.binding;ni({directory:t.directory,organization:n},K.json)}}),e.command({command:`status`,describe:`Show which organization commands here use, and verify the key against the API`,handler:async()=>{let{apiKey:e,apiUrl:t,directory:n}=await xi(),r=await ja(e,t);if(K.context&&(K.context.organization=r),n){let e=await mi(),t=e.bindings[n];t&&JSON.stringify(t.organization)!==JSON.stringify(r)&&(t.organization=r,await hi(e))}ni({organization:r,api_url:t,api_key:Ma(e),source:n??`ASTRALBEAM_API_KEY`},K.json)}}),e.command({command:`list`,describe:`List every directory binding`,handler:async()=>{let{bindings:e}=await mi(),t=Object.entries(e).map(([e,t])=>({directory:e,organization:t.organization,api_url:t.api_url}));if(K.json)return Qr({items:t});if(t.length===0)return void a.write(`No bindings.
125
- `);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=Object.setPrototypeOf({},null);for(var r in e)no(n,r,{get:e[r],enumerable:!0});return t&1||no(n,Symbol.toStringTag,{value:`Module`}),t&2?n:Object.preventExtensions(n)};function ao(e){if(typeof e!=`string`)throw new Ga(`JWTs must use Compact JWS serialization, JWT must be a string`);let{1:t,length:n}=e.split(`.`);if(n===5)throw new Ga(`Only JWTs using Compact JWS serialization can be decoded`);if(n!==3)throw new Ga(`Invalid JWT`);if(!t)throw new Ga(`JWTs must contain a payload`);let r;try{r=Ka(t)}catch(e){throw new Ga(`Failed to base64url decode the payload`,{cause:e})}let i;try{i=JSON.parse(Ia.decode(r))}catch(e){throw new Ga(`Failed to parse the decoded payload as JSON`,{cause:e})}if(!Ja(i))throw new Ga(`Invalid JWT Claims Set`);return i}/* @__NO_SIDE_EFFECTS__ */
126
- 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]===`
127
- `;)n++},i=()=>{let t=n++;for(;n<e.length;)if(e[n]===`\\`)n+=2;else if(e[n++]===`"`)break;return e.slice(t,n)},a=t=>{r();let o=n;if(e[n]===`{`){n++,r();let s=/* @__PURE__ */ new Map;for(;e[n]!==`}`;){let o=i(),c=JSON.parse(o);r(),n++;let l=typeof t==`object`&&t&&typeof c==`string`?Reflect.get(t,c):void 0,u=a(l);if(typeof c==`string`&&s.set(c,{...u,keyToken:o}),r(),e[n]!==`,`)break;n++,r()}return n++,{start:o,end:n,value:t,properties:s}}if(e[n]===`[`){n++,r();let i=[];for(;e[n]!==`]`&&(i.push(a(Array.isArray(t)?t[i.length]:void 0)),r(),e[n]===`,`);)n++;return n++,{start:o,end:n,value:t,items:i}}if(e[n]===`"`)i();else for(;n<e.length&&!/[\s,}\]]/.test(e[n]??``);)n++;return{start:o,end:n,value:t}};return a(t)}function Yo(e,t,n,r){if(n&&qo(n.value,e))return t.slice(n.start,n.end);if(typeof e==`number`)return Object.is(e,-0)?`-0`:e===1/0?`1e999`:e===-1/0?`-1e999`:JSON.stringify(e);if(typeof e!=`object`||!e)return JSON.stringify(e);if(r.has(e))throw TypeError(`Cannot serialize circular tool input`);r.add(e);try{if(Array.isArray(e))return`[`+Array.from(e,(e,i)=>Yo(e,t,n?.items?.[i],r)??`null`).join(`,`)+`]`;let i=[];for(let a of Object.keys(e)){let o=Yo(Reflect.get(e,a),t,n?.properties?.get(a),r);o!==void 0&&i.push((n?.properties?.get(a)?.keyToken??JSON.stringify(a))+`:`+o)}return`{`+i.join(`,`)+`}`}finally{r.delete(e)}}function Xo(e,t){if(t===void 0)return e??``;if(e===void 0)return Yo(t,``,void 0,/* @__PURE__ */ new Set)??``;let n;try{n=JSON.parse(e)}catch{return e.trim()===``?Yo(t,``,void 0,/* @__PURE__ */ new Set)??e:e}return qo(n,t)?e:Yo(t,e,Jo(e,n),/* @__PURE__ */ new Set)??e}function Zo(e){if(e.trim()===``)return{};try{return JSON.parse(e)??void 0}catch{return}}function Qo(e,t){let n=Y(t),r=t.args??n?.args,i=typeof r==`string`?r:void 0,a=t.input??n?.input,o=typeof a==`object`&&a?a:void 0,s=i??e;if(i===void 0&&o!==void 0)try{JSON.parse(s)}catch{s=void 0}let c;try{c=Xo(s,o)}catch{c=s??e}return{args:c,input:Zo(c)}}var $o=`redacted_thinking-`;function es(e){return typeof e==`string`&&e.startsWith(`redacted_thinking-`)}var ts=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function ns(e,t){return e>>>t|e<<32-t}function rs(e){let t=new TextEncoder().encode(e),n=t.length*8,r=t.length+1,i=r+(56-r%64+64)%64+8,a=new Uint8Array(i);a.set(t),a[t.length]=128;let o=new DataView(a.buffer);o.setUint32(i-8,Math.floor(n/4294967296)),o.setUint32(i-4,n>>>0);let s=1779033703,c=3144134277,l=1013904242,u=2773480762,d=1359893119,f=2600822924,p=528734635,m=1541459225,h=/* @__PURE__ */ new Uint32Array(64);for(let e=0;e<i;e+=64){for(let t=0;t<16;t++)h[t]=o.getUint32(e+t*4);for(let e=16;e<64;e++){let t=h[e-15]??0,n=h[e-2]??0,r=ns(t,7)^ns(t,18)^t>>>3,i=ns(n,17)^ns(n,19)^n>>>10;h[e]=(h[e-16]??0)+r+(h[e-7]??0)+i>>>0}let t=s,n=c,r=l,i=u,a=d,g=f,_=p,v=m;for(let e=0;e<64;e++){let o=ns(a,6)^ns(a,11)^ns(a,25),s=a&g^~a&_,c=v+o+s+(ts[e]??0)+(h[e]??0)>>>0,l=(ns(t,2)^ns(t,13)^ns(t,22))+(t&n^t&r^n&r)>>>0;v=_,_=g,g=a,a=i+c>>>0,i=r,r=n,n=t,t=c+l>>>0}s=s+t>>>0,c=c+n>>>0,l=l+r>>>0,u=u+i>>>0,d=d+a>>>0,f=f+g>>>0,p=p+_>>>0,m=m+v>>>0}let g=e=>(e>>>0).toString(16).padStart(8,`0`);return g(s)+g(c)+g(l)+g(u)+g(d)+g(f)+g(p)+g(m)}function is(e){return`sha256:${rs(e)}`}function as(e,t){if(e===null)return`null`;if(typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return JSON.stringify(e);if(typeof e!=`object`)throw TypeError(`Interrupt values must be JSON-compatible.`);if(t.has(e))throw TypeError(`Interrupt values must not cycle.`);if(!Array.isArray(e)&&Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw TypeError(`Interrupt values must use plain JSON objects.`);t.add(e);let n;if(Array.isArray(e)){let r=[];for(let n=0;n<e.length;n++)r.push(as(e[n],t));n=`[${r.join(`,`)}]`}else{let r=e;n=`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${as(r[e],t)}`).join(`,`)}}`}return t.delete(e),n}function os(e){return as(e,/* @__PURE__ */ new WeakSet)}function ss(e,t=is){if(typeof e!=`string`)throw TypeError(`Interrupt digests require canonical JSON text.`);return t(e)}function cs(e){typeof e==`object`&&e&&!Object.isFrozen(e)&&(Object.values(e).forEach(cs),Object.freeze(e))}function Z(e){let t=JSON.parse(os(e));return cs(t),t}function ls(e){let t=Z([...e].sort((e,t)=>e.interruptId.localeCompare(t.interruptId))),n=os(t);return Object.freeze({resolutions:t,canonicalResolutions:n,fingerprint:ss(n)})}function us(e){let t={};for(let[n,r]of Object.entries(e))n!==`$schema`&&(t[n]=r);return t}function ds(e){return(typeof e==`object`||typeof e==`function`)&&e!==null}function fs(e){if(!ds(e)||!(`~standard`in e))return!1;let t=e[`~standard`];return typeof t!=`object`||!t||!(`version`in t)||t.version!==1||!(`jsonSchema`in t)||typeof t.jsonSchema!=`object`||t.jsonSchema===null||!(`input`in t.jsonSchema)?!1:typeof t.jsonSchema.input==`function`}function ps(e){return ds(e)&&`~standard`in e&&typeof e[`~standard`]==`object`&&e[`~standard`]!==null&&`version`in e[`~standard`]&&e[`~standard`].version===1&&`validate`in e[`~standard`]&&typeof e[`~standard`].validate==`function`}function ms(e){return Object.keys(e).length>0?e:void 0}function hs(e){if(Array.isArray(e)){let t=e.map(e=>gs(e,e.required||[])),n=t.map(e=>e.nullWidening??{});return{schema:t.map(e=>e.schema),itemMap:n.some(e=>Object.keys(e).length>0)?n:void 0}}let t=gs(e,e.required||[]);return{schema:t.schema,itemMap:t.nullWidening}}function gs(e,t=[]){let n={...e},r={};if(n.type===`object`&&n.properties){let e={...n.properties},i=Object.keys(e),a={};for(let n of i){let r=e[n];if(!r)continue;let i=!t.includes(n),o=!1,s;if(r.type===`object`&&r.properties){let t=gs(r,r.required||[]);e[n]=i?{...t.schema,type:[`object`,`null`]}:t.schema,o=i,s=t.nullWidening}else if(r.type===`array`&&r.items){let t=hs(r.items);e[n]={...r,items:t.schema,...i?{type:[`array`,`null`]}:{}},o=i,s=t.itemMap?{items:t.itemMap}:void 0}else i&&(r.type&&!Array.isArray(r.type)?(e[n]={...r,type:[r.type,`null`]},o=!0):Array.isArray(r.type)&&!r.type.includes(`null`)&&(e[n]={...r,type:[...r.type,`null`]},o=!0));(o||s)&&(a[n]={...s??{},...o?{widened:!0}:{}})}n.properties=e,n.required=i,n.additionalProperties=!1,Object.keys(a).length>0&&(r.properties=a)}if(n.type===`array`&&n.items){let e=hs(n.items);n.items=e.schema,e.itemMap&&(r.items=e.itemMap)}return{schema:n,nullWidening:ms(r)}}function _s(e,t=`input`){if(fs(e)){let n=us(e[`~standard`].jsonSchema[t]({target:`draft-07`}));return`properties`in n&&!n.type&&(n.type=`object`),n.type===`object`&&!(`properties`in n)&&(n.properties={}),n.type===`object`&&!(`required`in n)&&(n.required=[]),n}if(ps(e))throw Error("Schema is a Standard Schema validator but does not expose a JSON Schema converter on `~standard.jsonSchema`. Use Zod v4.2+, ArkType v2.1.28+, or wrap a Valibot schema with `toStandardJsonSchema()` from `@valibot/to-json-schema` before passing it as `outputSchema`.");return typeof e==`object`?us(e):e}function vs(e,t={}){if(!e)return;let{forStructuredOutput:n=!1,io:r}=t;if(!n&&!fs(e)&&!ps(e))return e;let i=_s(e,r);return!i||typeof i!=`object`||!n?i:gs(i,i.required||[]).schema}async function ys(e,t){if(!ps(e))return{success:!0,data:t};let n=await e[`~standard`].validate(t);return n.issues?{success:!1,issues:n.issues.map(e=>({message:e.message||`Validation failed`,path:e.path?.map(String)}))}:{success:!0,data:n.value}}var bs=/* @__PURE__ */ new Set([`$schema`,`$id`,`$ref`,`$defs`,`type`,`properties`,`required`,`additionalProperties`,`items`,`oneOf`,`anyOf`,`allOf`,`enum`,`const`,`format`,`minimum`,`maximum`,`minLength`,`maxLength`,`pattern`]);function xs(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null)}function Ss(e){return xs(e)&&Object.keys(e).some(e=>bs.has(e))}function Cs(e){return ps(e)||fs(e)||Ss(e)}function ws(e){if(!xs(e))return!1;let t=Object.keys(e);return t.length>0&&t.every(e=>e===`approve`||e===`reject`)&&t.every(t=>Cs(e[t]))}function Ts(e){let t={};for(let[n,r]of Object.entries(e))t[n]=r;return t}function Es(e){if(ps(e)){let t=fs(e)?Ts(e[`~standard`].jsonSchema.input({target:`draft-2020-12`})):void 0;return{source:e,validator:e,...t!==void 0&&{jsonSchema:t}}}if(Ss(e))return{source:e,jsonSchema:e};throw TypeError(`Expected a supported SchemaInput.`)}function Ds(e){let t={approved:{const:e.approved}},n=[`approved`];return e.approved&&e.inputSchema&&(t.editedArgs=e.inputSchema.jsonSchema??{}),e.payload&&(t.payload=e.payload.jsonSchema??{},n.push(`payload`)),{type:`object`,properties:t,required:n,additionalProperties:!1}}function Os(e,t){let n=t===void 0?null:Es(t),r=null,i=null;if(e!==void 0){if(ps(e)||Ss(e))r=Es(e),i=r;else if(ws(e))r=e.approve===void 0?null:Es(e.approve),i=e.reject===void 0?null:Es(e.reject);else throw TypeError(`approvalSchema must be a SchemaInput or a nonempty map containing approve or reject.`)}let a={oneOf:[Ds({approved:!0,payload:r,inputSchema:n}),Ds({approved:!1,payload:i,inputSchema:null})]},o=os(a),s=os({approve:r?.jsonSchema??null,reject:i?.jsonSchema??null});return{branches:{approve:r,reject:i},responseSchema:a,responseSchemaHash:ss(o),approvalSchemaHash:ss(s)}}function ks(e){return ss(e===void 0?`undefined`:os(Es(e).jsonSchema??{standardValidator:`unserialized`}))}var As=`tanstack:interruptBinding`,js=As;function Ms(e){return e&&typeof e==`object`?e:null}function Q(e,t){return typeof e[t]==`string`?e[t]:void 0}function Ns(e){let t=e.v;return t===void 0||t===1}function Ps(e){let t=Ms(e.metadata),n=t?Ms(t[js]):null;if(!n||Q(n,`interruptId`)!==e.id||!Ns(n))return;let r=Q(n,`kind`),i=Q(n,`interruptId`),a=Q(n,`responseSchemaHash`),o=Q(n,`expiresAt`);if(!i||a===``||o!==void 0&&!Number.isFinite(Date.parse(o)))return;if(r===`generic`){let e=Q(n,`definitionId`),t=Q(n,`key`),s=n.batchIndex,c=Q(n,`payloadSchemaHash`);return(e!==void 0||t!==void 0||s!==void 0||c!==void 0)&&(!e||!t||typeof s!=`number`||!Number.isInteger(s)||s<0)?void 0:{v:1,kind:r,interruptId:i,...a?{responseSchemaHash:a}:{},...o?{expiresAt:o}:{},...e?{definitionId:e}:{},...t?{key:t}:{},...typeof s==`number`?{batchIndex:s}:{},...c?{payloadSchemaHash:c}:{}}}if(!a)return;let s=Q(n,`toolName`),c=Q(n,`toolCallId`);if(s&&c){if(r===`client-tool-execution`){let e=Q(n,`outputSchemaHash`);return e?{v:1,kind:r,interruptId:i,toolName:s,toolCallId:c,outputSchemaHash:e,responseSchemaHash:a,...o?{expiresAt:o}:{}}:void 0}if(r===`tool-approval`){let e=Q(n,`inputSchemaHash`),t=Q(n,`approvalSchemaHash`);return!e||!t?void 0:{v:1,kind:r,interruptId:i,toolName:s,toolCallId:c,originalArgs:n.originalArgs,inputSchemaHash:e,approvalSchemaHash:t,responseSchemaHash:a,...o?{expiresAt:o}:{}}}}}function Fs(e){let t=Ps(e);if(!t)return;let n=Ms(e.metadata),r=n?Ms(n[js]):null;if(!r)return;let i=Q(r,`interruptedRunId`),a=r.generation;if(!(!i||typeof a!=`number`||!Number.isInteger(a)||a<0))return{...t,interruptedRunId:i,generation:a}}var Is=`tanstack:interruptPayload`;function Ls(e,t){if(!fs(e))throw TypeError(`${t} must be a Standard Schema with a JSON Schema converter.`);try{let t=e[`~standard`].jsonSchema.input({target:`draft-07`});if(t===void 0)throw TypeError(`The exported schema is undefined.`);if(typeof t==`function`)throw TypeError(`The exported schema must not be a function.`);if(Array.isArray(t)||!t||typeof t!=`object`||![Object.prototype,null].includes(Object.getPrototypeOf(t)))throw TypeError(`The exported schema must be a plain JSON object.`);let n={};for(let[e,r]of Object.entries(t))e!==`$schema`&&(n[e]=r);return{json:n,canonicalJson:os(n)}}catch(e){throw TypeError(`${t} could not export compatible JSON Schema: ${e instanceof Error?e.message:String(e)}`)}}function Rs(e){return ss(Ls(e,`Interrupt schema`).canonicalJson)}var zs=`tanstack:interruptContinuation`;function Bs(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Vs(e){return{[zs]:e}}function Hs(e){let t=Ps(e);if(t?.kind!==`generic`||t.definitionId===void 0||t.key===void 0||t.batchIndex===void 0)return;let n=Bs(e.metadata)?e.metadata:void 0,r=n!==void 0&&Object.prototype.hasOwnProperty.call(n,`tanstack:interruptPayload`);return{v:1,definitionId:t.definitionId,key:t.key,batchIndex:t.batchIndex,reason:e.reason,message:e.message??``,...e.expiresAt===void 0?{}:{expiresAt:e.expiresAt},...t.responseSchemaHash===void 0?{}:{responseSchemaHash:t.responseSchemaHash},...t.payloadSchemaHash===void 0?{}:{payloadSchemaHash:t.payloadSchemaHash},...r?{payload:n[Is]}:{}}}function Us(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Ws=`subagentInput`;function Gs(e){if(Us(e)&&Us(e.tanstack))return e.tanstack[Ws]}function Ks(e){if(!Us(e)||`parts`in e)return;let t=e.subagentRunId;return typeof t==`string`&&t!==``?t:void 0}function qs(e){if(!Us(e)||!Us(e.metadata))return;let t=e.metadata.tanstack;if(!Us(t)||!Us(t.subagent))return;let{name:n,status:r,error:i,interruptIds:a}=t.subagent;if(typeof n!=`string`||!Js(r))return;let{description:o,parentSubagentRunId:s,parentToolCallId:c,metadata:l,placeholder:u}=t.subagent;return{name:n,status:r,...typeof o==`string`&&{description:o},...Us(i)&&typeof i.message==`string`&&{error:{message:i.message,...typeof i.code==`string`&&{code:i.code}}},...Array.isArray(a)&&{interruptIds:a.filter(e=>typeof e==`string`)},...typeof s==`string`&&{parentSubagentRunId:s},...typeof c==`string`&&{parentToolCallId:c},...Us(l)&&{metadata:l},...u===!0&&{placeholder:!0}}}function Js(e){return e===`running`||e===`finished`||e===`error`||e===`suspended`}function Ys(e){if(!Us(e))return e;let{subagentRunId:t,...n}=e,r=Us(n.metadata)?n.metadata:void 0,i=Us(r?.tanstack)?r.tanstack:void 0;if(!r||!i||!(`subagent`in i))return n;let{subagent:a,...o}=i;return{...n,metadata:{...r,tanstack:o}}}function Xs(e){let t=/* @__PURE__ */ new Map;for(let n of e){let e=Ks(n);e!==void 0&&!t.has(e)&&t.set(e,qs(n)?.parentSubagentRunId)}let n=e=>{let n=e;for(let e=0;e<64;e++){let e=t.get(n);if(e===void 0||!t.has(e))return n;n=e}return n},r=[],i=/* @__PURE__ */ new Map;for(let t of e){let e=Ks(t);if(e===void 0){r.push(t);continue}let a=n(e),o=i.get(a);if(o||(o={id:a,info:{name:`subagent`,status:`finished`},messages:[],hostIndex:r.length-1},i.set(a,o)),e!==a){o.messages.push(t);continue}let s=qs(t);s&&(o.info=s),s?.placeholder||o.messages.push(Ys(t))}return{top:r,groups:[...i.values()]}}function Zs(e){let t=e?.metadata;return typeof t==`object`&&t&&t.providerExecuted===!0?t:null}function Qs(e){return Zs(e)!==null}function $s(e,t){return e?.startsWith(`${t}-segment-`)===!0}var ec=/* @__PURE__ */ new Set([`text`,`image`,`audio`,`video`,`document`]);function tc(e){return e===`cancelled`||e===`denied`}function nc(e){if(typeof e!=`object`||!e)return!1;let t=e;if(typeof t.type!=`string`||!ec.has(t.type))return!1;if(t.type===`text`)return typeof t.content==`string`;let n=t.source;if(typeof n!=`object`||!n)return!1;let r=n;return typeof r.value==`string`?r.type===`file`?r.value.length>0&&(r.provider===void 0||typeof r.provider==`string`):r.type===`data`?typeof r.mimeType==`string`:r.type===`url`:!1}function rc(e){return Array.isArray(e)&&e.length>0&&e.every(nc)}function ic(e){return e&&typeof e==`object`&&`error`in e&&typeof e.error==`string`?e.error:typeof e==`string`?e:`Tool execution failed`}function ac(e){return typeof e==`string`||rc(e)?e:JSON.stringify(e)}function oc(e){let t=[],n=0,r=!0;for(let i of e){let e=t.at(-1);if(i.type===`thinking`)e!==void 0&&e.type!==`thinking`&&(r=!1),t.push({type:`thinking`,index:n++});else if(i.type===`text`){if(i.text===``)continue;if(e?.type===`text`){e.length+=i.text.length;continue}e?.type===`tool-call`&&(r=!1),t.push({type:`text`,length:i.text.length})}else t.push({type:`tool-call`,id:i.id})}return r?void 0:t}function sc(e){let t=e.blockOrder;if(!Array.isArray(t)||t.length===0)return;let n=e.content??``;if(typeof n!=`string`)return;let r=e.thinking??[],i=e.toolCalls??[],a=/* @__PURE__ */ new Set,o=/* @__PURE__ */ new Set,s=[],c=0;for(let e of t){if(typeof e!=`object`||!e)return;if(e.type===`thinking`){let t=Number.isInteger(e.index)?r[e.index]:void 0;if(t===void 0||a.has(e.index))return;a.add(e.index),s.push({type:`thinking`,thinking:t})}else if(e.type===`text`){let t=c+e.length;if(!Number.isInteger(e.length)||e.length<=0||t>n.length)return;s.push({type:`text`,text:n.slice(c,t)}),c=t}else if(e.type===`tool-call`){let t=i.find(t=>t.id===e.id);if(t===void 0||o.has(e.id))return;o.add(e.id),s.push({type:`tool-call`,toolCall:t})}else return}if(c===n.length&&a.size===r.length&&o.size===i.length)return s}function cc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function lc(e){return e.type===`text`||e.type===`image`||e.type===`audio`||e.type===`video`||e.type===`document`}function uc(e){try{return JSON.stringify(e)??``}catch{return``}}function dc(e){return typeof e==`string`&&e!==``?e:void 0}function fc(e){if(`encryptedValue`in e){let t=dc(e.encryptedValue);if(t!==void 0)return t}return dc(Y(e)?.signature)}function pc(e){return`id`in e&&es(e.id)?{redacted:!0}:{}}function mc(e){return e.length===0?null:e.every(e=>e.type===`text`)?e.map(e=>e.content).join(``)||null:e}function hc(e){return e==null?``:typeof e==`string`?e:e.filter(e=>e.type===`text`).map(e=>e.content).join(``)}function gc(e){let t=[];for(let n of e)if(n.type===`text`&&n.content!==``)t.push(n.content);else if(n.type===`structured-output`&&n.status===`complete`&&n.raw!==``)t.push(n.raw);else if(n.type===`subagent`){let e=_c(n);e!==``&&t.push(e)}return t.join(`
124
+ `)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 Na(){return o.isTTY?await Ma(`Paste an organization API key: `):(await pe(o)).trim()}async function Pa(e,t){let n=di(e),{id:r,name:i,slug:a}=await gr({apiKey:e,apiUrl:t});if(r!==n)throw Error(`The API returned a different organization.`);return{id:r,name:i,slug:a}}function Fa(e){return`${e.slice(0,e.indexOf(`_abo_`)+5)}…${e.slice(-4)}`}function Ia(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 ${ci})`}),async e=>{let t=fi(e.apiUrl??n.ASTRALBEAM_API_URL??`https://astralbeam.ai/api`),r=await Na(),i=await Pa(r,t),a=await yi();await vi(async e=>{e.bindings[a]={api_url:t,api_key:r,organization:i},await _i(e)}),Si({apiKey:r,apiUrl:t,organization:i,directory:a}),ii({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 yi(),t=await vi(async t=>{let n=bi(t,e);if(!n)throw Error(`No AstralBeam login covers this directory.`);return delete t.bindings[n.directory],await _i(t),n}),{organization:n}=t.binding;ii({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,organization:r}=await wi(),i=await Pa(e,t);K.context&&(K.context.organization=i);let a=JSON.stringify(i);n&&JSON.stringify(r)!==a&&await vi(async r=>{let o=r.bindings[n];o?.api_key===e&&o.api_url===t&&JSON.stringify(o.organization)!==a&&(o.organization=i,await _i(r))}),ii({organization:i,api_url:t,api_key:Fa(e),source:n??`ASTRALBEAM_API_KEY`},K.json)}}),e.command({command:`list`,describe:`List every directory binding`,handler:async()=>{let{bindings:e}=await gi(),t=Object.entries(e).map(([e,t])=>({directory:e,organization:t.organization,api_url:t.api_url}));if(K.json)return ei({items:t});if(t.length===0)return void a.write(`No bindings.
125
+ `);ai(t.map(({directory:e,organization:t,api_url:n})=>({directory:xi(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 La=new TextEncoder,Ra=new TextDecoder,za=new TextDecoder(`utf-8`,{fatal:!0});function Ba(...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 Va=/[^\x00-\x7f]/;function Ha(e){if(typeof e==`string`&&e.length>=128){if(Va.test(e))throw TypeError(`non-ASCII string encountered in encode()`);return La.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 Ua(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 Wa(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 Ga=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)}},Ka=class extends Ga{static code=`ERR_JOSE_NOT_SUPPORTED`;code=`ERR_JOSE_NOT_SUPPORTED`},qa=class extends Ga{static code=`ERR_JWS_INVALID`;code=`ERR_JWS_INVALID`},Ja=class extends Ga{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`};function Ya(e){try{return Wa(typeof e==`string`?e:Ra.decode(e),!0)}catch(e){throw TypeError(`The input to be decoded is not correctly encoded.`,{cause:e})}}function Xa(e){return Ua(typeof e==`string`?La.encode(e):e,!0)}function Za(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 Qa(...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 $a(e,t){if(e!==void 0)throw TypeError(`${t} can only be called once`)}const eo={__proto__:null,b64:!0};function to(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 no(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 Ka(`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 ro(e,t){if(t.includes(`b64`)){let t=e.b64;if(typeof t!=`boolean`)throw new qa(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);return t}return!0}function io(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(!Za(r))throw new e(`JOSE Header is not a JSON object`);return[r,n]}var ao=Object.defineProperty,oo=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports),so=(e,t)=>{let n=Object.setPrototypeOf({},null);for(var r in e)ao(n,r,{get:e[r],enumerable:!0});return t&1||ao(n,Symbol.toStringTag,{value:`Module`}),t&2?n:Object.preventExtensions(n)};function co(e){if(typeof e!=`string`)throw new Ja(`JWTs must use Compact JWS serialization, JWT must be a string`);let{1:t,length:n}=e.split(`.`);if(n===5)throw new Ja(`Only JWTs using Compact JWS serialization can be decoded`);if(n!==3)throw new Ja(`Invalid JWT`);if(!t)throw new Ja(`JWTs must contain a payload`);let r;try{r=Ya(t)}catch(e){throw new Ja(`Failed to base64url decode the payload`,{cause:e})}let i;try{i=JSON.parse(za.decode(r))}catch(e){throw new Ja(`Failed to parse the decoded payload as JSON`,{cause:e})}if(!Za(i))throw new Ja(`Invalid JWT Claims Set`);return i}/* @__NO_SIDE_EFFECTS__ */
126
+ function lo({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 uo(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 fo=[];let po=0;const{link:mo,unlink:ho,propagate:go,checkDirty:_o,shallowPropagate:vo}=/* @__PURE__ */ lo({update(e){return e._update()},notify(e){fo[bo++]=e,e.flags&=-3},unwatched(e){e.depsTail!==void 0&&(e.depsTail=void 0,e.flags=17,So(e))}});let yo=0,bo=0,xo;function So(e){let t=e.depsTail,n=t===void 0?e.deps:t.nextDep;for(;n!==void 0;)n=ho(n,e)}function Co(){for(;yo<bo;){let e=fo[yo];fo[yo++]=void 0,e.notify()}yo=0,bo=0}function wo(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 xo!==void 0&&mo(i,xo,po),i._snapshot},subscribe(e){let t=uo(e),n={current:!1},r=To(()=>{i.get(),n.current?(xo=void 0,t.next?.(i._snapshot)):n.current=!0});return{unsubscribe:()=>{r.stop()}}},_update(e){let a=xo,o=t?.compare??Object.is;if(n)xo=i,++po,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{xo=a,n&&(i.flags&=-5),So(i)}}};return n?(i.flags=17,i.get=function(){let e=i.flags;if(e&16||e&32&&_o(i.deps,i)){if(i._update()){let e=i.subs;e!==void 0&&vo(e)}}else e&32&&(i.flags=e&-33);return xo!==void 0&&mo(i,xo,po),i._snapshot}):i.set=function(e){if(i._update(e)){let e=i.subs;e!==void 0&&(go(e),vo(e),Co())}},i}function To(e){let t=()=>{let t=xo;xo=n,++po,n.depsTail=void 0,n.flags=6;try{return e()}finally{xo=t,n.flags&=-5,So(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&&_o(this.deps,this)?t():this.flags=2},stop(){this.flags=0,this.depsTail=void 0,So(this)}};return t(),n}function Eo(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Do(e){typeof globalThis.reportError==`function`?globalThis.reportError(e):console.error(e)}function Oo(e){if(Array.isArray(e))return Object.freeze(e.map(Oo));if(!Eo(e))return e;let t={};for(let n of Object.keys(e))t[n]=Oo(e[n]);return Object.freeze(t)}function ko(e,t=/* @__PURE__ */ new WeakMap){let n=e,r={...n};if(Eo(n.source)&&(r.source=Object.freeze({...n.source})),n.type===`tool-call`&&Eo(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?ko(e,t):e))),`input`in n&&(r.input=Oo(n.input)),`output`in n&&(r.output=Oo(n.output)),n.type===`subagent`&&Eo(n.subagent)){let e=n.subagent;r.subagent=Object.freeze(Array.isArray(e.messages)?{...e,messages:jo(t,e.messages)}:{...e})}return Object.freeze(r)}function Ao(e,t,n){let r=e.get(t);return r||(r=n(t),e.set(t,r)),r}function jo(e,t){return Object.freeze(t.map(t=>Ao(e,t,()=>Object.freeze({...t,parts:Object.freeze(t.parts.map(t=>Ao(e,t,()=>ko(t,e))))}))))}function Mo(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 No=8;function Po(e,t){let{unsubscribe:n}=e.subscribe(()=>{let n,r=0;do{n=e.get();try{t()}catch(e){Do(e)}r++}while(e.get()!==n&&r<No)});return n}new TextEncoder,new TextDecoder;var Fo=class extends Error{missingFeature;constructor(e){super(Io(e)),this.name=`UnsupportedResponseStreamError`,this.missingFeature=e}};function Io(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 Lo(e){if(!e.body)throw new Fo(`Response.body`);if(typeof e.body.getReader!=`function`)throw new Fo(`Response.body.getReader`);return e.body.getReader()}function Ro(){if(typeof globalThis.TextDecoder!=`function`)throw new Fo(`TextDecoder`);return new globalThis.TextDecoder}function zo(e){if(!e.startsWith(`data:`))return e;let t=e.slice(5);return t.startsWith(` `)?t.slice(1):t}function Bo(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 Vo(e){let t=Bo(e.createdAt),n=e.parts.map(e=>{if(e.type!==`tool-result`)return e;let t=Bo(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 Ho(e){return e.map(Vo)}function Uo(e){return Object.keys(e).length>0?e:void 0}function Wo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&`promptTokens`in e}function Go(e,t){return Wo(e)?e:Ko(Array.isArray(e)?e:void 0,t)}function Ko(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=Uo({...n?.cachedInputTokens===void 0?{}:{cachedTokens:n.cachedInputTokens},...n?.cacheWriteInputTokens===void 0?{}:{cacheWriteTokens:n.cacheWriteInputTokens},...r}),s=Uo({...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 qo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Jo(e,t){if(t==null)return e;if(e==null)return{...t};let n={...e,...t};return qo(e.tanstack)&&qo(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 Yo(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 Xo(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)=>Xo(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)&&Xo(Reflect.get(e,n),Reflect.get(t,n)))}function Zo(e,t){let n=0,r=()=>{for(;e[n]===` `||e[n]===` `||e[n]===`\r`||e[n]===`
127
+ `;)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 Qo(e,t,n,r){if(n&&Xo(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)=>Qo(e,t,n?.items?.[i],r)??`null`).join(`,`)+`]`;let i=[];for(let a of Object.keys(e)){let o=Qo(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 $o(e,t){if(t===void 0)return e??``;if(e===void 0)return Qo(t,``,void 0,/* @__PURE__ */ new Set)??``;let n;try{n=JSON.parse(e)}catch{return e.trim()===``?Qo(t,``,void 0,/* @__PURE__ */ new Set)??e:e}return Xo(n,t)?e:Qo(t,e,Zo(e,n),/* @__PURE__ */ new Set)??e}function es(e){if(e.trim()===``)return{};try{return JSON.parse(e)??void 0}catch{return}}function ts(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=$o(s,o)}catch{c=s??e}return{args:c,input:es(c)}}var ns=`redacted_thinking-`;function rs(e){return typeof e==`string`&&e.startsWith(`redacted_thinking-`)}var is=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 as(e,t){return e>>>t|e<<32-t}function os(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=as(t,7)^as(t,18)^t>>>3,i=as(n,17)^as(n,19)^n>>>10;h[e]=(h[e-16]??0)+r+(h[e-7]??0)+i>>>0}let t=s,n=c,r=l,i=u,a=d,g=f,_=p,v=m;for(let e=0;e<64;e++){let o=as(a,6)^as(a,11)^as(a,25),s=a&g^~a&_,c=v+o+s+(is[e]??0)+(h[e]??0)>>>0,l=(as(t,2)^as(t,13)^as(t,22))+(t&n^t&r^n&r)>>>0;v=_,_=g,g=a,a=i+c>>>0,i=r,r=n,n=t,t=c+l>>>0}s=s+t>>>0,c=c+n>>>0,l=l+r>>>0,u=u+i>>>0,d=d+a>>>0,f=f+g>>>0,p=p+_>>>0,m=m+v>>>0}let g=e=>(e>>>0).toString(16).padStart(8,`0`);return g(s)+g(c)+g(l)+g(u)+g(d)+g(f)+g(p)+g(m)}function ss(e){return`sha256:${os(e)}`}function cs(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(cs(e[n],t));n=`[${r.join(`,`)}]`}else{let r=e;n=`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${cs(r[e],t)}`).join(`,`)}}`}return t.delete(e),n}function ls(e){return cs(e,/* @__PURE__ */ new WeakSet)}function us(e,t=ss){if(typeof e!=`string`)throw TypeError(`Interrupt digests require canonical JSON text.`);return t(e)}function ds(e){typeof e==`object`&&e&&!Object.isFrozen(e)&&(Object.values(e).forEach(ds),Object.freeze(e))}function Z(e){let t=JSON.parse(ls(e));return ds(t),t}function fs(e){let t=Z([...e].sort((e,t)=>e.interruptId.localeCompare(t.interruptId))),n=ls(t);return Object.freeze({resolutions:t,canonicalResolutions:n,fingerprint:us(n)})}function ps(e){let t={};for(let[n,r]of Object.entries(e))n!==`$schema`&&(t[n]=r);return t}function ms(e){return(typeof e==`object`||typeof e==`function`)&&e!==null}function hs(e){if(!ms(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 gs(e){return ms(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 _s(e){return Object.keys(e).length>0?e:void 0}function vs(e){if(Array.isArray(e)){let t=e.map(e=>ys(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=ys(e,e.required||[]);return{schema:t.schema,itemMap:t.nullWidening}}function ys(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=ys(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=vs(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=vs(n.items);n.items=e.schema,e.itemMap&&(r.items=e.itemMap)}return{schema:n,nullWidening:_s(r)}}function bs(e,t=`input`){if(hs(e)){let n=ps(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(gs(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`?ps(e):e}function xs(e,t={}){if(!e)return;let{forStructuredOutput:n=!1,io:r}=t;if(!n&&!hs(e)&&!gs(e))return e;let i=bs(e,r);return!i||typeof i!=`object`||!n?i:ys(i,i.required||[]).schema}async function Ss(e,t){if(!gs(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 Cs=/* @__PURE__ */ new Set([`$schema`,`$id`,`$ref`,`$defs`,`type`,`properties`,`required`,`additionalProperties`,`items`,`oneOf`,`anyOf`,`allOf`,`enum`,`const`,`format`,`minimum`,`maximum`,`minLength`,`maxLength`,`pattern`]);function ws(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null)}function Ts(e){return ws(e)&&Object.keys(e).some(e=>Cs.has(e))}function Es(e){return gs(e)||hs(e)||Ts(e)}function Ds(e){if(!ws(e))return!1;let t=Object.keys(e);return t.length>0&&t.every(e=>e===`approve`||e===`reject`)&&t.every(t=>Es(e[t]))}function Os(e){let t={};for(let[n,r]of Object.entries(e))t[n]=r;return t}function ks(e){if(gs(e)){let t=hs(e)?Os(e[`~standard`].jsonSchema.input({target:`draft-2020-12`})):void 0;return{source:e,validator:e,...t!==void 0&&{jsonSchema:t}}}if(Ts(e))return{source:e,jsonSchema:e};throw TypeError(`Expected a supported SchemaInput.`)}function As(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 js(e,t){let n=t===void 0?null:ks(t),r=null,i=null;if(e!==void 0){if(gs(e)||Ts(e))r=ks(e),i=r;else if(Ds(e))r=e.approve===void 0?null:ks(e.approve),i=e.reject===void 0?null:ks(e.reject);else throw TypeError(`approvalSchema must be a SchemaInput or a nonempty map containing approve or reject.`)}let a={oneOf:[As({approved:!0,payload:r,inputSchema:n}),As({approved:!1,payload:i,inputSchema:null})]},o=ls(a),s=ls({approve:r?.jsonSchema??null,reject:i?.jsonSchema??null});return{branches:{approve:r,reject:i},responseSchema:a,responseSchemaHash:us(o),approvalSchemaHash:us(s)}}function Ms(e){return us(e===void 0?`undefined`:ls(ks(e).jsonSchema??{standardValidator:`unserialized`}))}var Ns=`tanstack:interruptBinding`,Ps=Ns;function Fs(e){return e&&typeof e==`object`?e:null}function Q(e,t){return typeof e[t]==`string`?e[t]:void 0}function Is(e){let t=e.v;return t===void 0||t===1}function Ls(e){let t=Fs(e.metadata),n=t?Fs(t[Ps]):null;if(!n||Q(n,`interruptId`)!==e.id||!Is(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 Rs(e){let t=Ls(e);if(!t)return;let n=Fs(e.metadata),r=n?Fs(n[Ps]):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 zs=`tanstack:interruptPayload`;function Bs(e,t){if(!hs(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:ls(n)}}catch(e){throw TypeError(`${t} could not export compatible JSON Schema: ${e instanceof Error?e.message:String(e)}`)}}function Vs(e){return us(Bs(e,`Interrupt schema`).canonicalJson)}var Hs=`tanstack:interruptContinuation`;function Us(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ws(e){return{[Hs]:e}}function Gs(e){let t=Ls(e);if(t?.kind!==`generic`||t.definitionId===void 0||t.key===void 0||t.batchIndex===void 0)return;let n=Us(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[zs]}:{}}}function Ks(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var qs=`subagentInput`;function Js(e){if(Ks(e)&&Ks(e.tanstack))return e.tanstack[qs]}function Ys(e){if(!Ks(e)||`parts`in e)return;let t=e.subagentRunId;return typeof t==`string`&&t!==``?t:void 0}function Xs(e){if(!Ks(e)||!Ks(e.metadata))return;let t=e.metadata.tanstack;if(!Ks(t)||!Ks(t.subagent))return;let{name:n,status:r,error:i,interruptIds:a}=t.subagent;if(typeof n!=`string`||!Zs(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},...Ks(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},...Ks(l)&&{metadata:l},...u===!0&&{placeholder:!0}}}function Zs(e){return e===`running`||e===`finished`||e===`error`||e===`suspended`}function Qs(e){if(!Ks(e))return e;let{subagentRunId:t,...n}=e,r=Ks(n.metadata)?n.metadata:void 0,i=Ks(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 $s(e){let t=/* @__PURE__ */ new Map;for(let n of e){let e=Ys(n);e!==void 0&&!t.has(e)&&t.set(e,Xs(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=Ys(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=Xs(t);s&&(o.info=s),s?.placeholder||o.messages.push(Qs(t))}return{top:r,groups:[...i.values()]}}function ec(e){let t=e?.metadata;return typeof t==`object`&&t&&t.providerExecuted===!0?t:null}function tc(e){return ec(e)!==null}function nc(e,t){return e?.startsWith(`${t}-segment-`)===!0}var rc=/* @__PURE__ */ new Set([`text`,`image`,`audio`,`video`,`document`]);function ic(e){return e===`cancelled`||e===`denied`}function ac(e){if(typeof e!=`object`||!e)return!1;let t=e;if(typeof t.type!=`string`||!rc.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 oc(e){return Array.isArray(e)&&e.length>0&&e.every(ac)}function sc(e){return e&&typeof e==`object`&&`error`in e&&typeof e.error==`string`?e.error:typeof e==`string`?e:`Tool execution failed`}function cc(e){return typeof e==`string`||oc(e)?e:JSON.stringify(e)}function lc(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 uc(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 dc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function fc(e){return e.type===`text`||e.type===`image`||e.type===`audio`||e.type===`video`||e.type===`document`}function pc(e){try{return JSON.stringify(e)??``}catch{return``}}function mc(e){return typeof e==`string`&&e!==``?e:void 0}function hc(e){if(`encryptedValue`in e){let t=mc(e.encryptedValue);if(t!==void 0)return t}return mc(Y(e)?.signature)}function gc(e){return`id`in e&&rs(e.id)?{redacted:!0}:{}}function _c(e){return e.length===0?null:e.every(e=>e.type===`text`)?e.map(e=>e.content).join(``)||null:e}function vc(e){return e==null?``:typeof e==`string`?e:e.filter(e=>e.type===`text`).map(e=>e.content).join(``)}function yc(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=bc(n);e!==``&&t.push(e)}return t.join(`
128
128
 
129
- `)}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(`
129
+ `)}function bc(e){let t=[];for(let n of e.subagent.messages){if(!(`parts`in n))continue;let e=yc(n.parts).trim();e!==``&&t.push(e)}return t.length===0?``:`${e.subagent.name}:\n${t.join(`
130
130
 
131
- `)}`}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?`
131
+ `)}`}function xc(e){return Array.isArray(e)?e:vc(e)}function Sc(e){if(!(`role`in e)||e.role!==`tool`)return e;let t=e,n=Y(t)?.toolResult;if(!dc(n)||`content`in n&&!oc(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=Cc(n.createdAt);e&&Reflect.set(r,`createdAt`,e)}oc(n.content)&&Reflect.set(r,`content`,n.content);let i=Reflect.get(t,`metadata`);if(dc(i)){let e=i.tanstack;if(dc(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 Cc(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 wc(e){if(e.type!==`tool-result`)return e;let t=Cc(e.createdAt),{createdAt:n,...r}=e;return t===void 0?r:{...r,createdAt:t}}function Tc(e){return Cc(Y(e)?.createdAt)}function Ec(e){let t=Cc(e.createdAt);return t===void 0?{}:{createdAt:t}}function Dc(e){return e.name===void 0?{}:{name:e.name}}function Oc(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 kc(e){return`${e.toolCallId}\0${e.toolName}\0${e.resource.uri}`}function Ac(e,t){if(t.length===0)return e;let n=new Set(e.parts.filter(Oc).map(e=>kc(e))),r=t.filter(e=>!n.has(kc(e)));return r.length===0?e:{...e,parts:[...e.parts,...r]}}function jc(e){let t=e.parts.filter(Oc),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 Mc(e){return e.role===`system`||e.role===`activity`?[]:e.role===`assistant`?Ic(e):[Nc(e)]}function Nc(e){let t=[];for(let n of e.parts)fc(n)&&t.push(n);return{id:e.id,role:e.role,content:_c(t),...Dc(e),...Ec(e),...e.metadata!==void 0&&{metadata:e.metadata}}}function Pc(){return{contentParts:[],toolCalls:[],order:[]}}function Fc(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 Ic(e){let t=[],n=Pc(),r=[],i=/* @__PURE__ */ new Set,a={id:e.id,...Dc(e),...Ec(e)},o=jc(e),s={...a,...o!==void 0&&{metadata:o}};function c(e=!1){let i=_c(n.contentParts),a=i!==null,o=n.toolCalls.length>0,c=r.length>0,l=Array.isArray(i)?void 0:lc(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=Pc()}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`:Fc(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:Yo(a,{toolResultOutcome:a.outcome}).metadata;t.push({...a.id!==void 0&&{id:a.id},...Ec(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(tc)&&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?``:pc(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?bc(a):``;if(e!==``){let t=`${n.contentParts.length>0?`
132
132
 
133
- `:``}${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&&`
134
- \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}
133
+ `:``}${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:cc(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 Lc(e){return{type:`thinking`,content:e.content,...e.signature&&{signature:e.signature},...e.redacted&&{redacted:!0}}}function Rc(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 zc(e,t){let n=[],r=Cc(e.createdAt);if(e.role===`assistant`&&e.thinking?.length)for(let t of e.thinking)(t.content||t.signature)&&n.push(Lc(t));let i=e.structuredOutput??Hc(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=ic(t)?t:void 0,a=e.error===void 0&&i===void 0?`complete`:`error`;n.push({type:`tool-result`,toolCallId:e.toolCallId,content:xc(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=vc(e.content);t&&n.push({type:`text`,content:t})}if(e.toolCalls&&e.toolCalls.length>0)for(let t of e.toolCalls)n.push(Rc(t));let a=e.role===`assistant`&&i===void 0?uc(e):void 0;a&&n.splice(0,n.length,...a.flatMap(e=>e.type===`text`?[{type:`text`,content:e.text}]:e.type===`tool-call`?[Rc(e.toolCall)]:e.thinking.content||e.thinking.signature?[Lc(e.thinking)]:[]));let o={id:t||Kc(),role:e.role===`tool`?`assistant`:e.role,parts:n,...Dc(e),...r!==void 0&&{createdAt:r},...e.metadata!==void 0&&{metadata:e.metadata}},s=Y(e)?.uiResources;return Ac(o,Array.isArray(s)?s.filter(Oc):[])}function Bc(e){if(`parts`in e)return Vc(e,{...e,id:e.id||Kc()});let t=e.id||Kc();switch(e.role){case`user`:return Vc(e,{id:t,role:`user`,parts:Uc(e.content)});case`assistant`:{let n=Y(e),r=n?.toolCallMetadata,i=Hc(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 Vc(e,zc({role:`assistant`,content:e.content??null,...Dc(e),...a&&{toolCalls:a},...i&&{structuredOutput:i}},t))}case`tool`:{e=Sc(e);let n=Cc(`createdAt`in e?e.createdAt:void 0)??Tc(e);return Vc(e,zc({role:`tool`,content:oc(e.content)?e.content:Wc(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 Vc(e,{id:t,role:`system`,parts:e.content?[{type:`text`,content:e.content}]:[]});case`reasoning`:{let n=hc(e),r=typeof e.content==`string`?e.content:``;return Vc(e,{id:t,role:`assistant`,parts:r||n!==void 0?[{type:`thinking`,content:r,...n===void 0?{}:{signature:n},...gc(e)}]:[]})}case`activity`:return Vc(e,{id:t,role:`activity`,parts:[{type:`activity`,activityType:e.activityType,content:structuredClone(e.content)}]});default:return Vc(e,{id:t,role:`assistant`,parts:[]})}}function Vc(e,t){let n=t.parts.map(e=>wc(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=Cc(i.createdAt)??(a===void 0?void 0:Tc(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(Oc):[];return Ac(i,c)}function Hc(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 Uc(e){let t=Wc(e);return typeof t==`string`?t?[{type:`text`,content:t}]:[]:t}function Wc(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 Gc(e,t){if(`parts`in e){let n=e.parts.map(e=>wc(e));return{...e,parts:n,id:e.id||t(),createdAt:Cc(e.createdAt)??/* @__PURE__ */ new Date}}return{...zc(e,t()),createdAt:Cc(e.createdAt)??/* @__PURE__ */ new Date}}function Kc(){return`msg-${Date.now()}-${Math.random().toString(36).substring(7)}`}function qc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Jc(e,t,n,r,i=!1,a){let o=qc(e)?e:{},s=qc(o.tanstack)?{...o.tanstack}:{};i&&delete s.uiResources;let c=Cc(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 Yc(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=cl(ul(s.id,s.toolCallId,o),r),t=Jc(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:zc(s,s.id),c=e.parts;if(r.add(e.id),s.role===`system`){n.push(Xc(e,`system`,{content:c.length>0?el(c):s.content??``},c,i));continue}if(s.role===`user`){n.push(Xc(e,`user`,{content:c.length>0?rl(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`&&tc(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=cl(t.id??sl(t.toolCallId),r),i=Jc(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`}):cc(t.output),a=typeof i==`string`?i:JSON.stringify(i);n.push({role:`tool`,id:cl(sl(t.id),r),toolCallId:t.id,content:a,metadata:Jc(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:ll(ol(e.id,i),r),content:i.content};i.signature&&(t.encryptedValue=i.signature),n.push(t)}let o=el(t.parts),s=al(t.parts),c=Xc(a===0?e:{...e,id:ll(`${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:{...qc(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(...tl(e,t))}return n}function Xc(e,t,n,r,i){let a=Zc(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 Zc(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=Cc(e.createdAt);a!==void 0&&(i.createdAt=a.toISOString());let o=Qc(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 Qc(e,t){for(let n of e)if(n.type===`structured-output`&&(t||n.status!==`complete`))return $c(n,t)}function $c(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 el(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 tl(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=Yc(n.messages,t),a=i.some(e=>Ys(e)===void 0);return(a?i:[{id:`subagent:${n.id}`,role:`assistant`},...i]).map((e,t)=>{let i=Ys(e);if(i!==void 0){let t=Xs(e);return!t||t.parentSubagentRunId!==void 0?e:nl(e,i,{...t,parentSubagentRunId:n.id})}return nl(e,n.id,!a&&t===0?{...r,placeholder:!0}:r)})}function nl(e,t,n){let r=qc(e.metadata)?e.metadata:{},i=qc(r.tanstack)?r.tanstack:{};return{...e,subagentRunId:t,metadata:{...r,tanstack:{...i,subagent:n}}}}function rl(e){if(!e.some(e=>e.type===`image`||e.type===`audio`||e.type===`video`||e.type===`document`))return el(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 il(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 al(e){let t=[];for(let n of e)if(n.type===`tool-call`){let e=il(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 ol(e,t){let n=`${e}-reasoning-${t.id??dl(t.content)}`;return t.type===`thinking`&&t.redacted?`${ns}${n}`:n}function sl(e){return`tool-${e}`}function cl(e,t){return ll(e,t)}function ll(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 ul(e,t,n){let r=sl(t);return e===void 0||n.has(e)?r:e}function dl(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 fl(e){if((e.type===X.RUN_FINISHED||e.type===X.RUN_ERROR)&&(Array.isArray(e.usage)||Wo(e.usage))){let t=Go(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`?es(t.args):void 0);n!==void 0&&(e.input=n)}return e}function pl(e){fl(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 ml(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 hl(e){return typeof e==`string`&&e!==``?e:void 0}function gl(e){if(`runId`in e){let t=hl(e.runId);if(t!==void 0)return t}return hl(Y(e)?.runId)}var _l=/* @__PURE__ */ oo((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})),vl=(/* @__PURE__ */ oo(((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=_l();Object.defineProperty(e,"Allow",{enumerable:!0,get:function(){return a.Allow}}),i(_l(),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&&`
134
+ \r `.includes(e[r]);)r++};return l()};e.parse=c})))(),yl=new class{parse(e){if(e&&e.trim()!==``)try{return(0,vl.parse)(e)}catch{return}}};function bl(e){return yl.parse(e)}var xl=class{shouldEmit(e,t){return!0}};function Sl(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}
135
135
  /*!
136
136
  * https://github.com/Starcounter-Jack/JSON-Patch
137
137
  * (c) 2017-2022 Joachim Wester
138
138
  * MIT licensed
139
139
  */
140
- 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(`
141
- `)}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}
140
+ var Cl=(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)}})(),wl=Object.prototype.hasOwnProperty;function Tl(e,t){return wl.call(e,t)}function El(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)Tl(e,i)&&r.push(i);return r}function Dl(e){switch(typeof e){case`object`:return JSON.parse(JSON.stringify(e));case`undefined`:return null;default:return e}}function Ol(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 kl(e){return e.indexOf(`/`)===-1&&e.indexOf(`~`)===-1?e:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function Al(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}function jl(e){if(e===void 0)return!0;if(e){if(Array.isArray(e)){for(var t=0,n=e.length;t<n;t++)if(jl(e[t]))return!0}else if(typeof e==`object`){for(var r=El(e),i=r.length,a=0;a<i;a++)if(jl(e[r[a]]))return!0}}return!1}function Ml(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(`
141
+ `)}var Nl=function(e){Cl(t,e);function t(t,n,r,i,a){var o=this.constructor,s=e.call(this,Ml(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=Ml(t,{name:n,index:r,operation:i,tree:a}),s}return t}(Error),Pl=/* @__PURE__ */ so({JsonPatchError:()=>$,_areEquals:()=>Wl,applyOperation:()=>zl,applyPatch:()=>Bl,applyReducer:()=>Vl,deepClone:()=>Fl,getValueByPointer:()=>Rl,validate:()=>Ul,validator:()=>Hl}),$=Nl,Fl=Dl,Il={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=Rl(n,this.path);r&&=Dl(r);var i=zl(n,{op:`remove`,path:this.from}).removed;return zl(n,{op:`add`,path:this.path,value:i}),{newDocument:n,removed:r}},copy:function(e,t,n){var r=Rl(n,this.from);return zl(n,{op:`add`,path:this.path,value:Dl(r)}),{newDocument:n}},test:function(e,t,n){return{newDocument:n,test:Wl(e[t],this.value)}},_get:function(e,t,n){return this.value=e[t],{newDocument:n}}},Ll={add:function(e,t,n){return Ol(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:Il.move,copy:Il.copy,test:Il.test,_get:Il._get};function Rl(e,t){if(t==``)return e;var n={op:`_get`,path:t};return zl(e,n),n.value}function zl(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):Hl(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=Rl(e,t.from),t.op===`move`&&(o.removed=e),o;if(t.op===`test`){if(o.test=Wl(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=Dl(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:Hl;;){if(f=s[l],f&&f.indexOf(`~`)!=-1&&(f=Al(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&&!Ol(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 Ol(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=Ll[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=Il[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 Bl(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=Dl(e));for(var a=Array(t.length),o=0,s=t.length;o<s;o++)a[o]=zl(e,t[o],n,!0,i,o),e=a[o].newDocument;return a.newDocument=e,a}function Vl(e,t,n){var r=zl(e,t);if(r.test===!1)throw new $(`Test operation failed`,`TEST_OPERATION_FAILED`,n,t,e);return r.newDocument}function Hl(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(!Il[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`)&&jl(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=Ul([{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 Ul(e,t,n){try{if(!Array.isArray(e))throw new $(`Patch sequence must be an array`,`SEQUENCE_NOT_AN_ARRAY`);if(t)Bl(Dl(t),Dl(e),n||!0);else{n||=Hl;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 Wl(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(!Wl(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],!Wl(e[o],t[o]))return!1;return!0}return e!==e&&t!==t}
142
142
  /*!
143
143
  * https://github.com/Starcounter-Jack/JSON-Patch
144
144
  * (c) 2017-2021 Joachim Wester
145
145
  * MIT license
146
146
  */
147
- 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=[];handOverAtStreamEnd=!1;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.handOverAtStreamEnd=!1,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);this.handOverAtStreamEnd=this.subagentRunId===void 0;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.handOverAtStreamEnd&&(this.handOverAtStreamEnd=!1,this.hasError||this.handlePendingToolCalls()),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.handOverAtStreamEnd=!1,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(`
148
- `);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(`
149
- `),...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:
150
- `+Object.entries(e).map(([e,{description:t,parameters:n}])=>`- ${e}: ${t} Props schema: ${JSON.stringify(kf(n))}`).join(`
151
- `),inputSchema:{type:`object`,properties:{widget:{type:`string`,enum:Object.keys(e),description:`Name of the widget to render.`},props:{type:`object`,description:`Props for the widget, matching its props schema.`}},required:[`widget`]}}).client((e,n)=>t(e,n?.toolCallId??``))}function Pf(){return dl({name:`ask_questionnaire`,description:`Ask the user a short structured questionnaire rendered inline in the chat. Use it when the next step genuinely depends on their choices instead of asking in prose. The call stays pending until the user submits; their answers arrive as the tool output. Skipped optional questions come back with an empty answers array. An output with skipped: true means the user dismissed the questionnaire by continuing the conversation instead — do not re-ask; address their next message.`,inputSchema:{type:`object`,properties:{items:{type:`array`,minItems:1,description:`Questions shown one at a time, in order.`,items:{type:`object`,properties:{name:{type:`string`,description:`Unique key identifying the question.`},title:{type:`string`,description:`The question itself.`},description:{type:`string`,description:`Optional helper text.`},required:{type:`boolean`,description:`Whether an answer is mandatory.`},multiple:{type:`boolean`,description:`Whether several choices may be selected.`},choices:{type:`array`,minItems:1,items:{type:`object`,properties:{value:{type:`string`},label:{type:`string`},description:{type:`string`}},required:[`value`,`label`]}},input:{type:`object`,description:`Optional free-form alternative to the fixed choices.`,properties:{label:{type:`string`},placeholder:{type:`string`}},required:[`label`,`placeholder`]}},required:[`name`,`title`,`choices`]}}},required:[`items`]}}).client()}function Ff(e,t,n){return Object.entries(e).map(([e,r])=>dl({name:e,description:r.description,inputSchema:kf(r.parameters),...r.metadata?{metadata:r.metadata}:{}}).client(async(i,a)=>{let o=!1;try{let s=n?.(e,r,a?.toolCallId);t?.(`tool`,`executing host tool "${e}"`,{input:i});let c=await Af(r.parameters,i??{});if(c==null)throw t?.(`error`,`input for host tool "${e}" failed schema validation`,{input:i}),Error(`Input for tool "${e}" failed schema validation`);a?.abortSignal?.throwIfAborted();let l=s?.()??r;o=!0;let u=await l.execute(c);try{u=Z(u)}catch{throw Error(`Tool "${e}" ran, but its result is not JSON-compatible. Its changes may already be applied. Read current state before retrying. Return plain JSON values and omit undefined fields.`)}return t?.(`tool`,`host tool "${e}" returned`,{output:u}),u}catch(n){t?.(`error`,`host tool "${e}" threw`,{error:n});let r=n instanceof Error?n:Error(String(n));throw o||Object.assign(r,{[jf]:!0}),r}}))}function If(e){if(e.length>16384)throw Error(`The chat auth token is too large`);let{exp:t,iat:n,user:r}=ao(e);if(!Number.isInteger(t)||Number(t)<=0)throw Error(`The chat auth token has no valid expiry`);let i=Number(t)*1e3,a=n===void 0?3e5:i-n*1e3,o=Math.min(6e4,a*.2),s=r?.admin===!0;return{expiresAt:i,refreshAt:i-o,tenantAdmin:s}}async function Lf(e,t){let{fetchAstralBeamToken:n,fetchClient:r}=e;if(typeof n==`function`)return(await n())?.token;if(!n)throw Error(`Provide fetchAstralBeamToken.`);let{url:i,...a}=n,o=new Headers(a.headers);o.has(`accept`)||o.set(`accept`,`application/json`);let s=await r(i,{method:`POST`,credentials:`include`,cache:`no-store`,...a,headers:o,signal:a.signal?AbortSignal.any([t,a.signal]):t});if(!s.ok)throw Object.assign(/* @__PURE__ */ Error(`Authentication endpoint returned HTTP ${s.status}`),{status:s.status,headers:s.headers});return(await s.json())?.token}const Rf={status:`loading`};function zf(e){return{...e,fetchAstralBeamToken:e.fetchAstralBeamToken,session:{cached:void 0,refreshPromise:void 0,abortController:new AbortController,state:Rf,listeners:/* @__PURE__ */ new Set},fetchClient:globalThis.fetch.bind(globalThis),debug:void 0}}function Bf(e){return e.session.state}function Vf(e,t){let{listeners:n}=e.session;return n.add(t),()=>{n.delete(t)}}function Hf(e,t){e.session.state=t;for(let t of e.session.listeners)t()}function Uf(e,t){e.apiUrl!==t.apiUrl&&(Yf(e),e.session.abortController=new AbortController,Hf(e,{status:`loading`})),e.apiUrl=t.apiUrl,e.fetchAstralBeamToken=t.fetchAstralBeamToken}function Wf(e,t){return JSON.stringify([e.scope,e.organization.id,e.scope===`tenant`?e.tenant.id:null,e.user.id,t===void 0?null:e.scope===`tenant`?t:e.user.role])}async function Gf(e){let{session:t,debug:n,apiUrl:r}=e,{signal:i}=t.abortController,a=typeof e.fetchAstralBeamToken==`function`?`fetchAstralBeamToken`:`Authentication endpoint`;try{for(let o=0;o<2;o++){let s=await Lf(e,i);if(i.throwIfAborted(),typeof s!=`string`||!s)throw Error(`${a} did not return a token`);let{expiresAt:c,refreshAt:l,tenantAdmin:u}=If(s);if(c<=Date.now())throw Error(`${a} returned an expired token`);if(!Number.isFinite(l)||l<=Date.now()||c-Date.now()<5e3)throw Error(`${a} returned a token too close to expiry`);let d;try{d=await Pr({apiUrl:r,astralBeamToken:s,fetchClient:e.fetchClient,signal:i,cache:`no-store`,credentials:`omit`})}catch(t){if(!o&&e.retryUnauthorized!==!1&&or(t)&&t.status===401)continue;throw t}if(i.throwIfAborted(),e.scope&&e.scope!==d.scope)throw Error(`Expected ${e.scope} authentication`);return t.cached={value:s,expiresAt:c,refreshAt:l,synchronizedAt:Date.now(),tenantAdmin:u},Hf(e,{status:`ready`,currentUser:d}),n?.(`auth`,`authentication ready`,{expiresAt:new Date(c)}),s}throw Error(`Authentication failed`)}catch(n){i.throwIfAborted();let r=n instanceof Error?n:/* @__PURE__ */ Error(`Authentication failed`);throw or(r)&&r.status===401&&(r.message=`AstralBeam rejected the chat token after renewal. Check that apiUrl matches the deployment that issued your API key. If the key was revoked or expired, create a replacement in API Keys and update your server's secret.`),t.cached=void 0,Hf(e,{status:`error`,error:r}),r}}async function Kf(e){let{session:t,force:n=!1}=e;if(t.abortController.signal.throwIfAborted(),t.refreshPromise)return await t.refreshPromise;if(!n&&t.cached&&t.cached.refreshAt>Date.now())return t.cached.value;(!t.cached||t.cached.expiresAt<=Date.now())&&Hf(e,{status:`loading`});let r=Gf(e);t.refreshPromise=r;try{return await r}finally{t.refreshPromise===r&&(t.refreshPromise=void 0)}}function qf(e,t){let n=!t||e.session.cached?.value===t;return n&&(e.session.cached=void 0),Kf({...e,force:n,retryUnauthorized:!1})}async function Jf(e){e.session.abortController.signal.aborted&&(e.session.abortController=new AbortController),await Kf(e)}function Yf({session:e}){e.abortController.abort(),e.refreshPromise=void 0,e.cached=void 0,e.state=Rf}async function Xf(e){let{input:t,init:n,session:r,fetchClient:i,debug:a}=e,o=Bf(e),s=await i(t,n);if(s.status!==401||r.abortController.signal.aborted)return s;let c=new Headers(n?.headers),l=c.get(`authorization`),u=l?.startsWith(`Bearer `)?l.slice(7):void 0;a?.(`auth`,`chat auth token was rejected; refreshing once`),await s.body?.cancel();let d=await qf(e,u),f=Bf(e);if(o.status!==`ready`||f.status!==`ready`||Wf(o.currentUser)!==Wf(f.currentUser))throw new DOMException(`Identity changed`,`AbortError`);return n?.signal?.throwIfAborted(),c.set(`authorization`,`Bearer ${d}`),await i(t,{...n,headers:c})}function Zf(e){let t,n=new AbortController,r=0,i=()=>typeof document>`u`||document.visibilityState!==`hidden`&&globalThis.navigator?.onLine!==!1,a=()=>{!n.signal.aborted&&i()&&Kf({...e,force:!0}).catch(()=>{})},o=()=>{if(clearTimeout(t),n.signal.aborted||typeof document>`u`||!i())return;let o=Bf(e);if(o.status===`ready`)r=0,t=setTimeout(a,Math.max(1e3,e.session.cached.refreshAt-Date.now()));else if(o.status===`error`&&r<3){let e=o.error;if(e.status!==void 0&&e.status!==429&&e.status<500||e.status===void 0&&!(e instanceof TypeError))return;let n=e.headers?.get(`retry-after`),i=n?/^\d+$/.test(n)?Number(n)*1e3:Date.parse(n)-Date.now():0;t=setTimeout(a,Math.max(1e3*2**r++,Number.isFinite(i)?i:0))}},s=()=>{if(!i()){clearTimeout(t);return}let n=e.session.cached;!n||Date.now()-n.synchronizedAt>=6e4||n.refreshAt<=Date.now()?a():o()},c=Vf(e,o);if(typeof document<`u`){for(let e of[`focus`,`online`,`offline`])globalThis.addEventListener(e,s,{signal:n.signal});document.addEventListener(`visibilitychange`,s,{signal:n.signal})}return Jf(e).catch(()=>{}),o(),()=>{n.abort(),clearTimeout(t),c()}}async function Qf(e,t){switch(e.action){case`connect`:case`headers`:{let n=await Rr({mcp_server_id:e.mcpServerId},t);return e.action===`connect`?n:(await Br(n.id,{lock_version:n.lock_version,headers:e.headers},t),{id:n.id})}case`disconnect`:return Hr(e.id,t);case`test`:return Wr(e.id,t)}}async function $f(e,t){let n=window.open(`about:blank`,`_blank`,`popup,width=600,height=720`);if(!n)throw Error(`Allow popups to authorize this connection.`);try{let r=e.id??(await Rr({mcp_server_id:e.mcpServerId},await t())).id,i=await Kr(r,await t()),a={organizationId:i.attempt.organization_id,tenantId:i.attempt.tenant_id,connectionId:i.attempt.connection_id,id:i.attempt.id},o=new URL(i.popup_url);o.searchParams.set(`origin`,window.location.origin);let{promise:s,resolve:c,reject:l}=Promise.withResolvers(),u={state:`waiting`},d=new AbortController,f=!1,p=e=>l(e instanceof Error?e:/* @__PURE__ */ Error(`Authorization failed.`)),m=async()=>{let e=await t();return d.signal.throwIfAborted(),{...e,signal:AbortSignal.any([d.signal,...e.signal?[e.signal]:[]])}},h=async()=>{if(!(f||d.signal.aborted)){f=!0;try{if(u.state===`binding`&&(await Jr(r,{attempt_id:a.id,challenge:u.challenge},await m()),d.signal.throwIfAborted(),u={state:`completing`}),u.state===`completing`){let e=await Xr(r,{attempt_id:a.id},await m());if(d.signal.throwIfAborted(),e){c();return}}n.closed&&p(/* @__PURE__ */ Error(`Authorization window closed.`))}catch(e){let t=e instanceof Error?e.status:void 0;!(e instanceof TypeError)&&t!==429&&(t??0)<500&&p(e)}finally{f=!1}}},g=e=>{if(e.source!==n||e.origin!==o.origin)return;let t=e.data;t?.attempt&&t.attempt.id===a.id&&t.attempt.organizationId===a.organizationId&&t.attempt.tenantId===a.tenantId&&t.attempt.connectionId===a.connectionId&&t.type===`mcp-browser-challenge`&&u.state===`waiting`&&typeof t.challenge==`string`&&(u={state:`binding`,challenge:t.challenge},h())},_=setInterval(()=>void h(),5e3),v=setTimeout(()=>p(/* @__PURE__ */ Error(`Authorization expired. Try connecting again.`)),6e5);try{window.addEventListener(`message`,g),n.location.replace(o.href),await s}finally{d.abort(),window.removeEventListener(`message`,g),clearInterval(_),clearTimeout(v)}return r}finally{n.close()}}function ep(e){return e.state===`complete`||e.state===`error`||e.output!==void 0}function tp(e){return e.metadata??{}}function np(e,t){return typeof e==`object`&&e&&t in e?e[t]:void 0}function rp(e,t){let n=np(e,t);return typeof n==`string`?n:void 0}function ip(e,t){let n=np(e,t);return typeof n==`number`?n:void 0}function ap(e){return rp(e.output,`refusal`)}function op(e){if(e.name!==`sandbox_write_file`)return;let t=rp(e.output,`path`)??rp(e.input,`path`);if(t===void 0)return;let n=rp(e.input,`content`)??``;return{toolCallId:e.id,path:t,label:sp(e)??t,content:n,lines:n.length===0?0:n.split(`
152
- `).length,written:e.output!=null&&ap(e)===void 0}}function sp(e){let t=rp(e.output,`relativePath`);return t!==void 0&&t!==`.`?t:rp(e.output,`path`)??rp(e.input,`path`)}function cp(e){if(e.name!==`sandbox_run_command`)return;let t=rp(e.input,`command`);if(t===void 0)return;let n=e.output;return{toolCallId:e.id,command:t,cwd:rp(e.input,`cwd`),exitCode:ip(n,`exitCode`),stdout:rp(n,`stdout`)??``,stderr:rp(n,`stderr`)??``,durationMs:ip(n,`durationMs`),timedOut:np(n,`timedOut`)===!0,truncated:np(n,`truncated`)===!0,finished:n!=null}}function lp(e){let t=/* @__PURE__ */ new Map,n=[];for(let r of e)for(let e of r.parts){if(e.type!==`tool-call`)continue;let r=op(e);r?.written&&t.set(r.path,r);let i=cp(e);i&&ap(e)===void 0&&n.push(i)}return{files:[...t.values()],commands:n}}const up=`Reopen this conversation or start a new one before sending.`;function dp(e,t){return e.length===t.length&&e.every((e,n)=>e.name===t[n]?.name&&e.title===t[n]?.title)}function fp(e,t=!1){let n={...e},r=gf(n.debug),i=/* @__PURE__ */ new Set,a,o=()=>a?.options??n,s={messages:[],status:`ready`,error:void 0,auth:{status:`loading`},capabilities:{attachments:!0},agentTools:[],sandboxStatus:void 0,usageLimitReached:void 0,sandbox:{files:[],commands:[]},thread:void 0,history:`idle`,messagesCursor:void 0,olderMessagesLoading:!1,submission:void 0,activeToolCallIds:[],pendingInteractions:[]},c,l=/* @__PURE__ */ new Map,u,d=`ready`,f,p=e=>{let t=f||c?.phase===`submitting`?d===`streaming`||s.status===`streaming`?`streaming`:`submitted`:d;s={...s,...e,status:t,history:u?.phase??`idle`};for(let e of i)e()},m=e=>e.client===N&&e.selection===w,h=e=>f===e&&m(e),g=e=>{h(e)&&(f=void 0,p({}))},_=({id:e,content:t,phase:n,error:r})=>({id:e,content:t,phase:n,...r?{error:r}:{}}),v={submitting:[`accepted`,`failed`,`refused`],failed:[`submitting`],accepted:[],refused:[]},ee=(e,t,n)=>v[e.phase].includes(t)?(e.phase=t,e.error=n,e===c&&p({submission:_(e)}),!0):!1,y=e=>e.submission===c&&h(e),te=e=>y(e)&&e.submission.phase===`submitting`,ne=(e,t)=>e.delivery.state===`undispatched`?ee(e,`refused`,t):ee(e,`failed`,t??/* @__PURE__ */ Error(`This message may not have been sent. Retry to send it.`)),re=e=>{let t=c;return t?.phase===`submitting`&&ne(t,t.delivery.state===`uncertain`?void 0:Error(e)),t?.phase===`refused`&&t.onRefused?.(),c=void 0,t},b=zf({apiUrl:n.apiUrl,scope:`tenant`,fetchAstralBeamToken:n.fetchAstralBeamToken??{url:`/api/astralbeam/token`}}),x,ie,S,C=!1,w=0,ae=0,oe=async e=>{for(;m(e);){let e=u;try{await e?.completion}catch(t){if(e===u)throw t}if(e===u)return}},se=async e=>{if(await oe(e).catch(()=>void 0),!te(e))return!1;if(s.history===`failed`)throw Error(up);return!0},ce=new AbortController,T,le=!1,ue=[],E=/* @__PURE__ */ new Map,de=0,D=/* @__PURE__ */ new WeakMap,fe=e=>{for(let t of e){if(t.role!==`user`||E.get(t.id)?.attachmentParts||!t.parts.some(e=>`fileId`in e))continue;let e=t.parts.map(e=>Object.freeze({...e}));Object.freeze(e),E.set(t.id,{...E.get(t.id),attachmentParts:e}),de++}},pe=_f(),me=()=>{c&&ee(c,`accepted`)&&(s.thread&&p({thread:{...s.thread,hasMessages:!0}}),c.callbacks?.onAccepted?.())},he=e=>{let t=[...N.getSnapshot().messages],n=t.findLastIndex(e=>e.role===`user`);n!==-1&&(t[n]=xf([e])[0],fe([t[n]]),N.setMessagesManually(t),P&&Ue())},ge=/* @__PURE__ */ new Set,O=/* @__PURE__ */ new Map,_e=/* @__PURE__ */ new Map,k=/* @__PURE__ */ new Map,A=/* @__PURE__ */ new Map,ve=e=>{let t=O.get(e);return t?`live:${t}:${e}`:e},ye=e=>{let t=/* @__PURE__ */ new Map;for(let n of e.pending_interactions){let e=`live:${n.source_message_id}:${n.tool_call_id}`,r=yf(n.source_message_id,n.source_part_id,n.response_target_id),i=k.get(e)??k.get(r);i&&(t.set(r,i),O.get(n.tool_call_id)===n.source_message_id&&t.set(e,i))}k.clear();for(let[e,n]of t)k.set(e,n)},be=e=>{(s.auth.status!==`error`||s.auth.error!==e)&&n.streamCallbacks?.onError?.(e)},xe=e=>{if(e instanceof Error&&e.name===`AbortError`)return;let t=e instanceof Error?e:Error(String(e));p({error:t}),be(t)},Se=e=>{p({unavailableMcpConnections:s.unavailableMcpConnections?.filter(t=>t!==e)??[]})},j=async(e=!0)=>{let t=w,n=b.session.abortController.signal,r=await Kf(b);if(n.throwIfAborted(),e&&t!==w)throw new DOMException(`Conversation changed`,`AbortError`);return{apiUrl:b.apiUrl,astralBeamToken:r,cache:`no-store`,signal:e?AbortSignal.any([ce.signal,n]):n,fetchClient:(e,t)=>Xf({...b,input:e,init:t})}},Ce=0,we,Te=async()=>{let e=++Ce,t=w;if(s.thread?.agentId===null){p({capabilities:{attachments:!1}});return}let i=s.thread?s.thread.agentId:n.agentId;try{let n=await j();if(e!==Ce||t!==w)return;let a=await xr(i?{agentId:i}:{},n);if(e!==Ce||t!==w)return;let o=a.capabilities?.attachments!==!1;p({capabilities:{attachments:o}}),r?.(`mount`,`agent capabilities resolved`,{attachments:o})}catch(e){r?.(`error`,`agent capabilities could not be resolved; keeping the defaults`,e)}},Ee=/* @__PURE__ */ new Map,M=/* @__PURE__ */ new Set,De=/* @__PURE__ */ new Set,Oe=0,ke=()=>{Oe++;for(let e of Ee.values())e();Ee.clear(),M.clear(),De.clear()},Ae=async(e,t)=>{if(!o().onRenderWidget)return{widget:e.widget,rendered:!1};let n=w,r=Oe,i=o().widgets??{};if(!Object.hasOwn(i,e.widget))throw Error(`Unknown widget "${e.widget}"`);let a=i[e.widget],c=await Af(a?.parameters,e.props??{});if(n!==w||r!==Oe||s.thread?.role===`viewer`)return{widget:e.widget,rendered:!1};if(a!==o().widgets?.[e.widget])return Ae(e,t);if(c==null)throw Error(`Props for widget "${e.widget}" failed validation`);let l=o().onRenderWidget;if(!l)return{widget:e.widget,rendered:!1};Ee.get(t)?.(),Ee.delete(t);let u,d=l({widget:e.widget,props:c,toolCallId:t,release:()=>{Ee.get(t)===u&&Ee.delete(t)}});return d&&(u=d,Ee.set(t,d)),M.add(t),{widget:e.widget,rendered:!0}},je=e=>Object.freeze(e.map(e=>{let t=E.get(e.id),n=D.get(e);if(n&&n.presentation===t)return n.message;let r=t?.attachmentParts??e.parts,i=t?.renderIds,a=r.map(t=>{if(t.type!==`tool-call`||t.name!==`render_widget`||t.state!==`complete`||!t.input)return t;let n=t,r=yf(e.id,t.id),a=n.applicationPartId?yf(e.id,n.applicationPartId,n.responseTargetId):r,o=n.upstreamToolCallId,s=n.widgetRenderId??i?.get(r)??i?.get(a)??(o&&O.get(o)===e.id&&M.has(o)?o:t.id);return(i?.get(r)!==s||i.get(a)!==s)&&(i=new Map(i).set(r,s).set(a,s)),n.widgetRenderId===s?t:Object.freeze({...t,widgetRenderId:s})});a.some((e,t)=>e!==r[t])&&(Object.freeze(a),r=a),i&&i!==t?.renderIds&&(t={...t,renderIds:i},E.set(e.id,t),de++);let o=r===e.parts?e:Object.freeze({...e,parts:r});return D.set(e,{presentation:t,message:o}),o})),Me=e=>{if(s.thread?.role!==`viewer`)for(let t of e)for(let e of t.parts){if(e.type!==`tool-call`||e.name!==`render_widget`||e.state!==`complete`||!e.input)continue;let t=e.widgetRenderId??e.id;if(M.has(t)||De.has(t))continue;De.add(t);let n=w,i=Oe,{widgets:a,onRenderWidget:c}=o();Ae(e.input,t).catch(e=>r?.(`error`,`Saved widget could not be rendered`,e)).finally(()=>{n===w&&i===Oe&&(De.delete(t),(a!==o().widgets||c!==o().onRenderWidget)&&Me(s.messages))})}},Ne=()=>{let e=w;return Mf(o().widgets??{},n.tools??{},Ae,r,(t,r,i)=>{let a=ae,o=N,c=S,l=b.apiUrl;return()=>{let u=n.tools&&Object.hasOwn(n.tools,t)?n.tools[t]:void 0;if(e!==w||a!==ae||o!==N||c!==S||l!==b.apiUrl||s.thread?.role===`viewer`||!i||!ge.has(i)||!u||u.parameters!==r.parameters)throw new DOMException(`Host tool authority changed`,`AbortError`);return u}}).map(e=>{if(!e.execute)return e;let t=e.execute;return{...e,execute:async(e,n)=>{let r=n?.toolCallId;if(!r||!ge.has(r))throw Error(`A saved tool call cannot execute again. Send a new message to request it.`);let i=k,a=ve(r),o=S,s=b.apiUrl;try{let r=await t(e,n);return S===o&&b.apiUrl===s&&i.set(a,{outcome:`succeeded`,output:r??null}),r}catch(e){throw!(e instanceof Error&&jf in e)&&S===o&&b.apiUrl===s&&i.set(a,{outcome:`unknown`,output:{error:e instanceof Error?e.message:String(e)}}),e}}}})},Pe=()=>{let e=Ne(),t=e.map(e=>{let t=e.metadata?.title;return{name:e.name,title:typeof t==`string`&&t.length>0?t:void 0}});return dp(s.agentTools,t)||p({agentTools:t}),e},Fe=()=>n.debug?{debug:!0}:{},Ie=async(e,t,n)=>{if(!h(n))throw new DOMException(`Request cancelled`,`AbortError`);let r=s.thread;if(!r||typeof e.body!=`string`)throw Error(`Open a conversation before sending.`);let i=JSON.parse(e.body),a=yr(),o,c=i.messages.at(-1)?.role===`user`&&n.kind===`submission`&&te(n)?n.submission:void 0,l=c?.delivery;if(c)o={...i,threadId:r.id,resume:void 0,parentRunId:void 0,messages:[i.messages.at(-1)],tools:l?.state===`uncertain`?l.tools:i.tools,forwardedProps:{...i.forwardedProps,clientId:pe}};else{Ke();let e=await bf(r.id,t,void 0,O);if(!h(n))throw new DOMException(`Request cancelled`,`AbortError`);p({thread:vf(e.thread,e.messages.length>0)}),ye(e);let s=e.pendingInteractions.filter(e=>k.has(ve(e.toolCallId))),c=s.find(e=>e.toolCallId===i.messages.at(-1)?.toolCallId)??s[0],l=e.pendingInteractions.flatMap(e=>{let t=k.get(ve(e.toolCallId));return t&&e.sourceMessageId===c?.sourceMessageId?[{source_message_id:e.sourceMessageId,source_part_id:e.sourcePartId,response_target_id:e.responseTargetId,...t}]:[]});if(l.length===0)return new Response(``,{headers:{"Content-Type":`text/event-stream`}});a=Mr(r.id),o={client_id:pe,run_id:i.runId,...i.parentRunId?{parent_run_id:i.parentRunId}:{},results:l}}ge.clear(),p({activeToolCallIds:[]});let u=new Headers(e.headers);if(c&&u.set(`Idempotency-Key`,c.key),!h(n))throw new DOMException(`Request cancelled`,`AbortError`);c&&c.delivery.state===`undispatched`&&(c.delivery={state:`uncertain`,tools:i.tools});let d=await fr(a,{...t,...e,headers:u,body:JSON.stringify(o)}).catch(e=>{if(!h(n))throw e;c&&l?.state===`undispatched`&&or(e)&&(e.status===400||e.status===413||e.status===429)&&(c.delivery={state:`undispatched`});let t=or(e)?e.body?.usage_limit:void 0;throw t&&p({usageLimitReached:{name:t.name,resetsAt:t.resets_at}}),e});if(!h(n))throw new DOMException(`Request cancelled`,`AbortError`);if(d.headers.get(`Content-Type`)?.includes(`application/json`)){let e=await d.json();if(!h(n))throw new DOMException(`Request cancelled`,`AbortError`);if(p({thread:{...s.thread,version:e.thread_version},...e.usage_limit?{usageLimitReached:{name:e.usage_limit.name,resetsAt:e.usage_limit.resets_at}}:{}}),c){let i=await bf(r.id,t,void 0,O);if(!h(n))throw new DOMException(`Request cancelled`,`AbortError`);let a=i.messages.find(t=>t.id===e.accepted_message_id);a&&he(a),me()}return new Response(``,{headers:{"Content-Type":`text/event-stream`}})}return d},Le=rd(()=>sr(yr(),b.apiUrl),async()=>{let e=f;if(!e||!h(e))throw new DOMException(`Request cancelled`,`AbortError`);let t=await j();if(!h(e))throw new DOMException(`Request cancelled`,`AbortError`);return{fetchClient:(n,r)=>Ie(r??{},{...t,signal:r?.signal??t.signal},e)}}),Re=Le.connect;Le.connect=async function*(...e){try{for await(let t of Re(...e)){if(t.type===X.TOOL_CALL_START&&t.parentMessageId&&O.set(t.toolCallId,t.parentMessageId),t.type!==X.MESSAGES_SNAPSHOT){yield t;continue}let e;yield{...t,messages:t.messages.map(t=>t.role===`assistant`?(e=_e.get(t.id),e&&t.toolCalls?{...t,toolCalls:t.toolCalls.map(t=>({...t,id:e?.get(t.id)??t.id}))}:t):t.role===`tool`?{...t,toolCallId:e?.get(t.toolCallId)??t.toolCallId}:(e=void 0,t))}}}catch(e){throw e instanceof Error&&or(e.cause)?e.cause:e}};let ze=()=>{let e=new ff({connection:{...Le,hydrate:(t,n)=>{let r=Be;if(!r)return Promise.resolve({messages:[],activeRun:null,interrupts:null,page:{truncated:!1}});let i=n?.before!==void 0,a=i?u?.owner:{client:e,selection:w},o=()=>a!==void 0&&u?.owner===a&&m(a),c=(async()=>{let t=await bf(r,await j(),n?.before,O);for(;n?.before&&t.messages.every(e=>e.role===`tool`)&&t.page_after;){let e=await bf(r,await j(),t.page_after,O);t={...e,messages:[...e.messages,...t.messages]}}if(!o())throw new DOMException(`Conversation changed`,`AbortError`);i||ye(t),ue=i?[...t.messages,...ue]:t.messages;let a=new Set(t.messages.map(e=>e.id)),c=xf(ue,i?s.pendingInteractions:t.pendingInteractions,O).filter(e=>a.has(e.id));if(fe(c),i)p({messagesCursor:t.page_after??void 0});else{t.thread.role===`viewer`&&ke();let n=s.thread?.agentId!==t.thread.agent_id;p({thread:vf(t.thread,t.messages.length>0),messagesCursor:t.page_after??void 0,pendingInteractions:t.pendingInteractions}),n&&Te(),c.length===0&&e.setMessagesManually([])}return{messages:c,activeRun:null,interrupts:null,page:t.page_after?{truncated:!0,cursor:t.page_after}:{truncated:!1}}})();if(!i&&a){let e=c.then(()=>`idle`,()=>`failed`).then(e=>(u&&o()&&(u.phase=e,P&&Ue(),p({})),c));u={owner:a,phase:s.messages.length>0||s.thread?.hasMessages===!1?`refreshing`:`loading`,completion:e},e.catch(()=>void 0),p({olderMessagesLoading:!1})}return c}},threadId:Be??pe,persistence:!0,history:{pageSize:100},queue:`drop`,tools:Pe(),forwardedProps:Fe(),onInterruptStateChange:t=>{N===e&&r?.(`tool`,`interrupt state changed`,t)},onCustomEvent:(t,n)=>{if(N!==e)return;if(t===`astralbeam_thread`){let e=n;if(s.thread?.id===e.threadId){if(e.acceptedMessage&&c?.phase===`submitting`&&he(e.acceptedMessage),e.acceptedMessageId&&me(),e.saved)for(let t of e.executableToolCallIds??[])ge.has(t)||k.delete(ve(t)),ge.add(t);p({thread:{...s.thread,version:e.version},activeToolCallIds:[...ge]})}return}if(t===`astralbeam_mcp_tools`){let e=n,t={};for(let n of e.tools??[])typeof n.name==`string`&&typeof n.title==`string`&&(t[n.name]=n.title);p({serverToolTitles:t,unavailableMcpConnections:e.unavailable??[]});return}let i=n;if(t===`astralbeam.usage_limit.reached`&&typeof i?.name==`string`&&typeof i.resetsAt==`string`){p({usageLimitReached:{name:i.name,resetsAt:i.resetsAt}});return}let a=n?.state;t===`astralbeam.sandbox.status`&&(a===`starting`||a===`ready`||a===`error`)?(r?.(`sandbox`,`sandbox ${a}`),p({sandboxStatus:a})):r?.(`stream`,`custom event "${t}"`,n)},onChunk:t=>{N===e&&(t.type===X.RUN_STARTED&&p({serverToolTitles:{},unavailableMcpConnections:[]}),n.streamCallbacks?.onChunk?.(t))},onResponse:t=>{N===e&&n.streamCallbacks?.onResponse?.(t)},onFinish:t=>{N===e&&n.streamCallbacks?.onFinish?.(t)},onError:t=>{N===e&&(c?.phase!==`submitting`&&t.name!==`AbortError`&&p({error:t}),be(t))}});return e},Be,N=ze(),P,Ve,He=-1,Ue=()=>{let e=N.getSnapshot(),t=Ve!==e.messages||He!==de;if(!t&&d===e.status)return;let n={};d!==e.status&&e.status===`submitted`&&(n.usageLimitReached=void 0),d=e.status,t&&(n.messages=je(e.messages),n.sandbox=lp(n.messages),Ve=e.messages,He=de),p(n),t&&Me(s.messages)},We=()=>{if(!P){let e=N,t=w;P=e.subscribeSnapshot(()=>{N===e&&t===w&&Ue()}),Ue(),Me(s.messages)}N.attach()},Ge=e=>{let t=N;f=void 0,u=void 0,P?.(),P=void 0,Ve=void 0,N=ze(),e&&N.setMessagesManually(e),d=`ready`,t.stop(),t.detach(),ge.clear(),p({activeToolCallIds:[]}),C&&We(),t.dispose()},Ke=()=>{_e.clear(),N.setMessagesManually(N.getSnapshot().messages.map(e=>{let t=/* @__PURE__ */ new Map,n=e.parts.map(n=>{if(n.type!==`tool-call`||tp(n).providerExecuted)return n;let r=n,i=r.upstreamToolCallId??n.id;if(O.get(i)===e.id&&!ep(n))return n;let a=yf(e.id,r.applicationPartId??i,r.responseTargetId);return t.set(i,a),{...n,upstreamToolCallId:i,id:a,...n.name===`render_widget`?{widgetRenderId:r.widgetRenderId??E.get(e.id)?.renderIds?.get(yf(e.id,n.id))??n.id}:{}}});return t.size&&_e.set(e.id,t),{...e,parts:n}}))},qe=e=>{let t=s.thread?.id,n=re(`The conversation changed before this was sent.`);t&&(n?.phase===`failed`?l.set(t,n):l.delete(t),A.set(t,k)),w++,u=void 0,Be=e,ce.abort(),ce=new AbortController,k=A.get(e??``)??/* @__PURE__ */ new Map,_e.clear(),O.clear(),ue=[],E.clear(),D=/* @__PURE__ */ new WeakMap,de++,ke(),p({thread:void 0,messages:[],submission:void 0,error:void 0,sandbox:{files:[],commands:[]},sandboxStatus:void 0,usageLimitReached:void 0,pendingInteractions:[],serverToolTitles:{},unavailableMcpConnections:[],messagesCursor:void 0,olderMessagesLoading:!1}),Ge()},Je=async(e,t=!1)=>{qe(e);let r=w;c=l.get(e),c&&p({submission:_(c)});try{if(C||We(),await oe({client:N,selection:r}),r!==w)return;T&&Cf(T,e)}catch(e){if(r!==w)return;t&&(n.threadId===void 0||n.threadId===`auto`)&&or(e)&&e.status===404?Ye():xe(e)}},Ye=()=>{qe(),C&&Te(),T?Cf(T,null):le=!0},Xe=(e=!1)=>{let t=n.threadId;if(t===void 0||t===`auto`){if(!T)return;t=Cf(T)}t&&t!==`new`?t===s.thread?.id&&T?Cf(T,t):Je(t,e):e||Ye()},Ze=async e=>{if(s.thread)return;let t=await j();if(!te(e))throw new DOMException(`Send cancelled`,`AbortError`);let r=await Cr(n.agentId?{agent_id:n.agentId}:{},t);if(!te(e))throw new DOMException(`Send cancelled`,`AbortError`);Be=r.id,p({thread:vf(r,!1)}),Te(),T&&Cf(T,r.id)},Qe=async(e=!0)=>{if(!s.thread)return;let t=w;try{N.detach(),We(),await oe({client:N,selection:t}),e&&t===w&&p({error:void 0})}catch(e){if(t!==w)return;or(e)&&e.status===404?Ye():xe(e)}},F=async()=>{if(!N.getHasOlderMessages()||s.olderMessagesLoading||s.history!==`idle`||c?.phase===`submitting`)return;let e=w;p({olderMessagesLoading:!0});try{await N.loadOlderMessages(),e===w&&P&&Ue()}catch(t){e===w&&xe(t)}finally{e===w&&p({olderMessagesLoading:!1})}},$e=async e=>{let t=s.thread;if(!t||t.role!==`manager`)return!1;let n=w;try{let r=await Dr(t.id,{title:e,expected_version:t.version},await j());if(n!==w)return!1;let i=vf(r,t.hasMessages);return p({thread:i}),!0}catch(e){return n===w&&xe(e),!1}},et=async(e=s.thread)=>{if(!e||e.role!==`manager`)return!1;let t=w;try{return await kr(e.id,{expected_version:String(e.version)},await j()),t===w&&s.thread?.id===e.id&&Ye(),!0}catch(e){return t===w&&xe(e),!1}},I=async e=>{let t=w;if(f||c?.phase===`submitting`||N.getIsLoading()){xe(/* @__PURE__ */ Error(`Wait for this client's current request to finish before responding.`));return}let n=Bf(b),r=ve(e.toolCallId),i=s.pendingInteractions.find(t=>t.toolCallId===e.toolCallId),a=!(`tool`in e)&&i&&(s.thread?.role===`manager`||n.status===`ready`&&i.targetTenantUserId===n.currentUser.user.id),o=`tool`in e&&e.tool===`ask_questionnaire`&&n.status===`ready`&&i?.targetTenantUserId===n.currentUser.user.id;if(s.thread?.role===`viewer`||!ge.has(e.toolCallId)&&!o&&!a&&!k.has(r)){xe(/* @__PURE__ */ Error(`This tool call belongs to another session and cannot be executed here.`));return}if(!k.has(r)){if(a)k.set(r,{outcome:`unknown`,output:null});else if(`tool`in e){let t=e.output;k.set(r,{outcome:e.state===`output-error`?`failed`:`succeeded`,output:t??null})}}let l={kind:`tool-result`,client:N,selection:t};f=l;try{if(p({}),!h(l)||(Ke(),!h(l)))return;if(i){if(l.client.stop(),await Qe(!1),!h(l))return;await l.client.append({role:`tool`,toolCallId:e.toolCallId,content:JSON.stringify(k.get(ve(e.toolCallId)))})}else`tool`in e&&await l.client.addToolResult(e);h(l)&&await Qe(!1)}finally{g(l)}},tt=e=>I({toolCallId:e}),nt=async e=>{if(e!==c||e.phase!==`submitting`)return _(e);let t={kind:`submission`,submission:e,client:N,selection:w};f=t;try{if(await Kf(b),!await se(t)||(await Ze(t),!te(t))||(e.callbacks?.onThreadReady?.(s.thread.id),!te(t))||(Ke(),!await se(t))||(await t.client.sendMessage(e.content),!y(t)))return _(e);ne(e,t.client.getError()),y(t)&&await Qe(!1)}catch(n){if(!y(t))return _(e);let r=n instanceof Error?n:Error(String(n));r.name===`AbortError`?ne(e):ne(e,r)&&be(r)}finally{g(t)}return _(e)},rt=async(e,t)=>{let n=f||c?.phase===`submitting`||N.getIsLoading()?`Wait for this client's current request to finish before sending.`:s.history===`loading`?`Wait for this conversation to load before sending.`:s.history===`failed`?up:s.thread?.agentId===null?`This conversation’s agent is unavailable. Start a new conversation to continue.`:s.thread?.role===`viewer`?`You have read-only access to this conversation.`:c?.phase===`failed`?`The previous message’s acceptance is unconfirmed. Retry that message before sending different text, or start a new conversation.`:void 0;if(n)return{id:_f(),content:e,phase:`refused`,error:Error(n)};let r={id:_f(),content:e,phase:`submitting`,key:_f(),delivery:{state:`undispatched`},callbacks:t};c=r,p({submission:_(r),error:void 0,olderMessagesLoading:!1}),N.stop(),ge.clear(),Ke(),O.clear(),p({activeToolCallIds:[]});let i=new Promise(e=>r.onRefused=e);return Promise.race([nt(r),i.then(()=>_(r))])},it=async()=>{let e=c;if(!f&&!N.getIsLoading()&&e&&ee(e,`submitting`))return p({error:void 0}),nt(e)},at=()=>{let e=Bf(b),t=s.auth;if(e.status===`ready`){let t=Wf(e.currentUser);S!==void 0&&S!==t&&(re(`The account changed before this was sent.`),l.clear(),A.clear(),k.clear(),qe(),T=void 0),S=t;let r=JSON.stringify(Sf(n)),i=`astralbeam:thread:${n.apiUrl??`https://astralbeam.ai/api`}:${t}:session:${r}`;T!==i&&(T!==void 0&&qe(),T=i,le?(Cf(i,null),le=!1):Xe(!0)),we!==t&&(we=t,Te())}p({auth:e}),e.status===`error`&&(t.status!==`error`||t.error!==e.error)&&n.streamCallbacks?.onError?.(e.error)},ot=()=>{if(C)return;C=!0;let e=ce.signal.aborted&&N.getIsHydrating();N.updateOptions({tools:Pe()}),ce.signal.aborted&&(ce=new AbortController),ie=Vf(b,at),at(),x=Zf(b),e?Ge(N.getSnapshot().messages):We()};return t||ot(),{start:ot,getState:()=>s,getOptions:()=>n,attachView:e=>{if(a)throw Error(`This chat session already has a view attached`);let t={options:e},n=()=>{N.updateOptions({tools:Pe()}),Me(s.messages)};return ke(),a=t,n(),{update:e=>{if(a!==t)return;let r=t.options;t.options=e,(r.widgets!==e.widgets||r.onRenderWidget!==e.onRenderWidget)&&n()},dispose:()=>{a===t&&(ke(),a=void 0,n())}}},subscribe:e=>(i.add(e),()=>i.delete(e)),updateOptions:e=>{let t=n.agentId,i=n.apiUrl,a=n.threadId,o=Sf(n),{widgets:c,onRenderWidget:u}=n;n={...n,...e};let d=Sf(n)!==o;r=gf(n.debug),Uf(b,{apiUrl:n.apiUrl,fetchAstralBeamToken:n.fetchAstralBeamToken??{url:`/api/astralbeam/token`}}),b.debug=r,N.updateOptions({tools:Pe(),forwardedProps:Fe()}),n.apiUrl===i?d?(le=!1,s.thread&&n.threadId===s.thread.id||qe(),T=void 0,at()):n.threadId!==a&&Xe():(re(`The chat service changed before this was sent.`),l.clear(),A.clear(),k.clear(),qe(),T=void 0,at()),(c!==n.widgets||u!==n.onRenderWidget)&&Me(s.messages),C&&(n.agentId!==t||n.apiUrl!==i||d)&&Te()},sendMessage:rt,retry:it,addToolResult:I,stop:()=>{ae++;let e=c,t=f;e?.phase===`submitting`&&ne(e),N.stop(),t&&g(t),e?.phase===`refused`&&e.onRefused?.()},retryAuthentication:()=>{Kf({...b,force:!0}).catch(()=>void 0)},reload:async()=>{let e=w;if(await Qe(),e!==w||s.error)return;let t=/* @__PURE__ */ new Set;for(;e===w;){let e=s.pendingInteractions.find(e=>!t.has(e.sourceMessageId)&&k.has(ve(e.toolCallId)));if(!e||(t.add(e.sourceMessageId),await I({toolCallId:e.toolCallId}),s.error))return}},searchThreads:async(e=``,t,n)=>{let r=await j(),i=await Tr({q:e,page_size:50,...t?{page_after:t}:{}},{...r,signal:AbortSignal.any([r.signal,...n?[n]:[]])});return{items:i.items.map(e=>vf(e)),page_after:i.page_after}},openThread:Je,renameThread:$e,deleteThread:et,refreshThread:()=>Qe(),loadOlderMessages:F,uploadAttachment:async({data:e,filename:t,mimeType:r})=>{let i=s.thread?s.thread.agentId:n.agentId,[a,o]=await Promise.all([e,j(!1)]);return gr({...i?{agentId:i}:{},type:r.startsWith(`image/`)?`image`:`document`,source:{type:`data`,value:a,mimeType:r},metadata:{filename:t}},o)},getThreadAttachment:async(e,t)=>{if(!e.threadId&&!t?.preview)throw Error(`A conversation ID is required to download files.`);return(await vr({...e,delivery:`direct`},{...await j(!!e.threadId||!t?.preview),headers:t?.preview?{"X-File-Preview":`true`}:{}})).blob()},getMcpCatalog:async()=>Ir(await j(!1)),manageMcpConnection:async e=>{let t=await Qf(e,await j(!1));return`id`in e?Se(e.id):t&&`id`in t&&Se(t.id),t},authorizeMcpConnection:async e=>{let t=await $f(e,()=>j(!1));Se(t)},abandonToolCall:tt,reset:()=>{if(r?.(`status`,`conversation reset`),Ye(),s.auth.status===`ready`){let e=JSON.stringify([S,Sf(n)]),t=n.apiUrl??`https://astralbeam.ai/api`;Df(t,e,``,``),Df(t,e,``,``,`sent`),Of({apiUrl:t,identity:e,threadId:``,update:()=>[]}).catch(e=>r?.(`error`,`Draft could not be cleared`,e))}a?.options.onReset()},dispose:()=>{re(`The chat closed before this was sent.`),f=void 0,u=void 0,P?.(),P=void 0,N.detach(),ke(),N.stop(),ce.abort(),w++,Ce++,we=void 0,x?.(),ie?.(),Yf(b),C=!1,queueMicrotask(()=>{C||(N.dispose(),T=void 0,E.clear(),D=/* @__PURE__ */ new WeakMap)}),i.clear()}}}const pp=e=>e[Symbol.toStringTag],mp=(e,t,n)=>{let{alg:r}=e;if(t.use!==void 0){let e=n===`sign`||n===`verify`?`sig`:`enc`;if(t.use!==e)throw TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(t.alg!==void 0&&t.alg!==r)throw TypeError(`Invalid key for this operation, its "alg" must be "${r}" when present`);if(Array.isArray(t.key_ops)){let r=n===`encrypt`||n===`decrypt`?e.ops?.[n===`encrypt`?0:1]:n;if(r&&!t.key_ops.includes(r))throw TypeError(`Invalid key for this operation, its "key_ops" must include "${r}" when present`)}};async function hp(e,t,n){let{alg:r,secret:i}=e,a=n===`decrypt`||n===`sign`;if(i&&t instanceof Uint8Array)return t;let o,s;if(Ja(t)){if(o=Op(t),typeof o.kty!=`string`)throw Sp(r,t,i);if(!(i?o.kty===`oct`&&typeof o.k==`string`:o.kty!==`oct`&&(a?o.kty===`AKP`&&typeof o.priv==`string`||typeof o.d==`string`:o.d===void 0&&o.priv===void 0)))throw TypeError(i?`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`:`JSON Web Key for this operation must be a ${a?`private`:`public`} JWK`);if(mp(e,o,n),o.kty===`oct`)return Ka(o.k);if(!Object.isFrozen(t)){let{key_ops:e}=t;Array.isArray(e)&&Object.freeze(e),Object.freeze(t)}}else{if(!bp(t))throw Sp(r,t,i);let e=i?`secret`:a?`private`:`public`;if(t.type!==e&&(i||[`secret`,`public`,`private`].includes(t.type)))throw TypeError(`${pp(t)} instances must be of type "${e}" for the ${r} algorithm`);if(vp(t))return t;if(s=t,s.type===`secret`)return s.export()}gp||=/* @__PURE__ */ new WeakMap;let c=t,l=gp.get(c);if(l?.[r])return l[r];if(l||gp.set(c,l={}),s&&typeof s.toCryptoKey==`function`){let t=s.type===`public`,n=_p[s.asymmetricKeyDetails?.namedCurve],i=e.resolve?.({crv:n,asymmetricKeyType:s.asymmetricKeyType})??e.subtle;return l[r]=s.toCryptoKey(i,t,e.usages[+!t])}return o??=s.export({format:`jwk`}),o.alg=r,l[r]=await kp(e,o)}let gp;const _p={__proto__:null,prime256v1:`P-256`,secp384r1:`P-384`,secp521r1:`P-521`},vp=e=>{if(e?.[Symbol.toStringTag]===`CryptoKey`)return!0;try{return e instanceof CryptoKey}catch{return!1}},yp=e=>e?.[Symbol.toStringTag]===`KeyObject`,bp=e=>vp(e)||yp(e);function xp(e,t,...n){if(n.length>2){let t=n.pop();e+=`one of type ${n.join(`, `)}, or ${t}.`}else n.length===2?e+=`one of type ${n[0]} or ${n[1]}.`:e+=`of type ${n[0]}.`;return t==null?e+=` Received ${t}`:typeof t==`function`&&t.name?e+=` Received function ${t.name}`:typeof t==`object`&&t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}function Sp(e,t,n){let r=[`CryptoKey`,`KeyObject`,`JSON Web Key`];return n&&r.push(`Uint8Array`),TypeError(xp(`Key for the ${e} algorithm must be `,t,...r))}const Cp=(e,t=`algorithm.name`)=>/* @__PURE__ */ TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function wp(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function Tp(e,t){let{modulusLength:n}=t.algorithm;if(typeof n!=`number`||n<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}function Ep(e,t,n){let r=e.algorithm;if(r.name!==t.name)throw Cp(t.name);if(t.hash&&r.hash?.name!==t.hash)throw Cp(t.hash,`algorithm.hash`);if(t.namedCurve&&r.namedCurve!==t.namedCurve)throw Cp(t.namedCurve,`algorithm.namedCurve`);if(t.length!==void 0&&r.length!==t.length)throw Cp(t.length,`algorithm.length`);wp(e,n)}function Dp(e){return{__proto__:null,...e}}function Op(e){let t=Dp(e);if(t.ext!==void 0&&typeof t.ext!=`boolean`)throw TypeError(`"ext" (Extractable) Parameter must be a boolean`);if(t.key_ops!==void 0){let e=t.key_ops,n=Array.isArray(e)?[...e]:void 0;if(!n||n.some(e=>typeof e!=`string`)||new Set(n).size!==n.length)throw TypeError(`"key_ops" (Key Operations) Parameter must be an array of unique strings`);t.key_ops=n}return t}async function kp(e,t,n){if(!e.kty.includes(t.kty))throw new Ua(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`);let r=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,i=!!(t.d||t.priv),a={...t,ext:n??t.ext};return a.kty!==`AKP`&&delete a.alg,delete a.use,crypto.subtle.importKey(`jwk`,a,r,a.ext??!i,t.key_ops??e.usages[+!!i])}async function Ap(e,t,n,r=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey(`raw`,e,t,r,[n])),Ep(e,t,n),e}function jp(e){let t={__proto__:null};for(let n in e)t[n]={...e[n],alg:n};return t}const Mp=[[`verify`],[`sign`]];function Np(e){let t={name:`HMAC`,hash:`SHA-${e}`};return{kty:[`oct`],secret:!0,subtle:t,signing:t,usages:Mp}}function Pp(e,t){let n={name:t?`RSA-PSS`:`RSASSA-PKCS1-v1_5`,hash:`SHA-${e}`};return{kty:[`RSA`],subtle:n,signing:t?{...n,saltLength:t}:n,usages:Mp,minRsaBits:2048}}function Fp(e,t){return{kty:[`EC`],crv:e,subtle:{name:`ECDSA`,namedCurve:e},signing:{name:`ECDSA`,hash:`SHA-${t}`},usages:Mp}}function Ip(){let e={name:`Ed25519`};return{kty:[`OKP`],crv:`Ed25519`,subtle:e,signing:e,usages:Mp}}function Lp(e){let t={name:`ML-DSA-${e}`};return{kty:[`AKP`],subtle:t,signing:t,usages:Mp}}const Rp=jp({HS256:Np(256),HS384:Np(384),HS512:Np(512),RS256:Pp(256),RS384:Pp(384),RS512:Pp(512),PS256:Pp(256,32),PS384:Pp(384,48),PS512:Pp(512,64),ES256:Fp(`P-256`,256),ES384:Fp(`P-384`,384),ES512:Fp(`P-521`,512),EdDSA:Ip(),Ed25519:Ip(),"ML-DSA-44":Lp(44),"ML-DSA-65":Lp(65),"ML-DSA-87":Lp(87)});function zp(e){let t=typeof e==`string`?Rp[e]:void 0;if(!t)throw new Ua(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}const Bp=e=>Math.floor(e.getTime()/1e3),Vp={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},Hp=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function Up(){throw TypeError(`Invalid time period format`)}function Wp(e){typeof e!=`string`&&Up();let t=Hp.exec(e);(!t||t[4]&&t[1])&&Up();let n=parseFloat(t[2]),r=Math.round(n*Vp[t[3][0].toLowerCase()]);return Number.isFinite(r)||Up(),t[1]===`-`||t[4]===`ago`?-r:r}function Gp(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}function Kp(e,t){if(typeof t!=`string`)throw TypeError(`"${e}" claim must be a string`)}function qp(e){if(typeof e!=`string`&&(!Array.isArray(e)||Array.from(e).some(e=>typeof e!=`string`)))throw TypeError(`"aud" claim must be a string or an array of strings`)}function Jp(e,t){return typeof e==`number`?Gp(t,e):e instanceof Date?Gp(t,Bp(e)):Bp(/* @__PURE__ */ new Date)+Wp(e)}let Yp;function Xp(e){return Yp.get(e)}function Zp(e){let t=Xp(e);for(let e of[`iat`,`nbf`,`exp`]){let n=t[e];if(typeof n==`number`&&!Number.isFinite(n))throw TypeError(`"${e}" claim must be a finite number`)}return Pa.encode(JSON.stringify(t))}var Qp=class{constructor(e={}){if(!Ja(e))throw TypeError(`JWT Claims Set MUST be an object`);(Yp||=/* @__PURE__ */ new WeakMap).set(this,structuredClone(e))}setIssuer(e){return Kp(`iss`,e),Xp(this).iss=e,this}setSubject(e){return Kp(`sub`,e),Xp(this).sub=e,this}setAudience(e){return qp(e),Xp(this).aud=e,this}setJti(e){return Kp(`jti`,e),Xp(this).jti=e,this}setNotBefore(e){return Xp(this).nbf=Jp(e,`setNotBefore`),this}setExpirationTime(e){return Xp(this).exp=Jp(e,`setExpirationTime`),this}setIssuedAt(e){let t=Xp(this);return t.iat=e===void 0?Bp(/* @__PURE__ */ new Date):typeof e==`string`?Gp(`setIssuedAt`,Bp(/* @__PURE__ */ new Date)+Wp(e)):Jp(e,`setIssuedAt`),this}};async function $p(e,t,n){let[r,i,a,o]=e,s=``;if(i!==void 0){let e=to(Wa,i);i=e[0],s=qa(e[1])}if(a!==void 0&&(a=to(Wa,a)[0]),!i&&!a)throw new Wa(`either setProtectedHeader or setUnprotectedHeader must be called before #sign()`);if(!Ya(i,a))throw new Wa(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let c={...i,...a};Qa(Wa,i);let l=eo(i,$a(Wa,Za,o,i,c));l||n?.();let{alg:u}=c;if(typeof u!=`string`||!u)throw new Wa(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);let d=zp(u),f=``,p=r,m;if(l){let t=e[4];t?(f=t[0]??=qa(r),p=t[1]??=za(f)):(f=qa(r),m=Pa.encode(`${s}.${f}`))}m??=La(za(s),za(`.`),p);let h=await Ap(await hp(d,t,`sign`),d.subtle,`sign`);d.minRsaBits&&Tp(d.alg,h);let g={signature:qa(new Uint8Array(await crypto.subtle.sign(d.signing,h,m))),payload:f};return i&&(g.protected=s),a&&(g.header=a),[g,l]}async function em(e,t,n,r,i){let[a]=await $p([e,t,void 0,n],r,i);return`${a.protected}.${a.payload}.${a.signature}`}const tm=Qp;var nm=class extends tm{#e;setProtectedHeader(e){return Xa(this.#e,`setProtectedHeader`),this.#e=e,this}async sign(e,t){return em(Zp(this),this.#e,t?.crit,e,()=>{throw new Ga(`JWTs MUST NOT use unencoded payload`)})}};const rm=`astralbeam`,im=16384,am=8192,om=/^key_[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}_[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}_abo_[A-Za-z]{64}$/,sm=/^limit_[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}_[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,cm=[`id`,`name`,`metadata`],lm=[`id`,`name`,`admin`,`metadata`],um=new TextEncoder;function dm(e){if(!om.test(e))throw Error(`apiKey must match key_<organizationId>_<id>_abo_<secret>`);let t=e.lastIndexOf(`_abo_`),n=e.slice(0,t),r=e.slice(t+1);return{keyId:n,organizationId:n.slice(4,n.indexOf(`_`,4)),keySecret:r}}function fm(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function pm(e){return e===null||typeof e==`string`||typeof e==`boolean`?!0:typeof e==`number`?Number.isFinite(e):Array.isArray(e)?e.every(pm):fm(e)&&Object.values(e).every(pm)}function mm(e,t,n){if(!fm(t))throw Error(`${e} must be an object`);let r=n?lm:cm;for(let n of Object.keys(t))if(!r.includes(n))throw Error(`${e} has an unknown field "${n}"`);let{id:i,name:a,admin:o,metadata:s}=t;if(typeof i!=`string`||i.length<1||i.length>255)throw Error(`${e}.id must be a 1-255 character string`);if(a!==void 0&&typeof a!=`string`)throw Error(`${e}.name must be a string`);if(n&&o!==void 0&&typeof o!=`boolean`)throw Error(`${e}.admin must be a boolean`);if(s!==void 0&&!(fm(s)&&pm(s)))throw Error(`${e}.metadata must be a JSON object`)}function hm(e,t){mm(`user`,e,!0),mm(`tenant`,t,!1);let n=JSON.stringify({user:e,tenant:t});if(um.encode(n).byteLength>am)throw Error(`user and tenant must not exceed ${am} bytes`);return JSON.parse(n)}async function gm(e){let t=await crypto.subtle.digest(`SHA-256`,um.encode(e));return um.encode(qa(new Uint8Array(t)))}async function _m({apiKey:e,email:t,organizationId:n,expiresInSeconds:r=300}){if(typeof t!=`string`||t.length>320||t.includes(`\0`)||!/^[^\s@]+@[^\s@]+$/.test(t))throw Error(`email must be an email address of at most 320 characters`);if(!Number.isInteger(r)||r<60||r>600)throw Error(`organization auth tokens must live for 60-600 seconds`);let{keyId:i,organizationId:a,keySecret:o}=dm(e);if(n!==a)throw Error(`organizationId must match the API key organization`);let s=Math.floor(Date.now()/1e3);return await new nm({ver:1,email:t,organization_id:n}).setProtectedHeader({alg:`HS256`,typ:`astralbeam-organization+jwt`,kid:i}).setIssuer(n).setAudience(rm).setIssuedAt(s).setExpirationTime(s+r).sign(await gm(o))}async function vm({apiKey:e,user:t,tenant:n,usageLimits:r,expiresInSeconds:i=300}){if(!Number.isInteger(i)||i<60||i>600)throw Error(`chat auth tokens must live for 60-600 seconds`);let{keyId:a,organizationId:o,keySecret:s}=dm(e),c=hm(t,n);if(r!==void 0&&(!Array.isArray(r)||r.length>20||!r.every(e=>typeof e==`string`&&sm.test(e))))throw Error(`usageLimits must list at most 20 IDs of the form limit_<organizationId>_<id>`);let l=Math.floor(Date.now()/1e3),u=await new nm({ver:4,user:c.user,tenant:c.tenant,...r?.length?{usage_limits:[...new Set(r)]}:{}}).setProtectedHeader({alg:`HS256`,typ:`astralbeam+jwt`,kid:a}).setIssuer(o).setAudience(rm).setIssuedAt(l).setExpirationTime(l+i).sign(await gm(s));if(um.encode(u).byteLength>im)throw Error(`chat auth tokens must not exceed ${im} bytes`);return u}function ym(e){return e.string([`tenant`,`user`,`tenant-name`,`user-name`]).demandOption([`tenant`,`user`]).boolean(`admin`).number(`expires-in`).coerce(`expires-in`,tr).describe({tenant:`Tenant external ID, signed as tenant.id`,user:`TenantUser external ID, signed as user.id`,"tenant-name":`Tenant display name`,"user-name":`TenantUser display name`,admin:`sign user.admin: true, granting Tenant admin API access`,"expires-in":`token lifetime, 60-600 (default 300)`})}function bm(e){return{tenant:{id:e.tenant,...e.tenantName===void 0?{}:{name:e.tenantName}},user:{id:e.user,...e.userName===void 0?{}:{name:e.userName},...e.admin?{admin:!0}:{}}}}function xm(e,t,n){let r=new Date(Date.now()+t*1e3).toISOString();n?Qr({token:e,expires_at:r}):s.write(`${e}\n`)}function Sm(e){return e.command(`chat`,`Mint a chat JWT for a Tenant's user, as a token endpoint would`,ym,async e=>{let{apiKey:t}=await xi(),n=e.expiresIn??300;xm(await vm({apiKey:t,expiresInSeconds:n,...bm(e)}),n,K.json)}),e.command(`organization`,`Mint an organization-management JWT delegating a member's current role`,e=>e.string(`email`).demandOption(`email`).number(`expires-in`).coerce(`expires-in`,tr).describe({email:`email of an existing member of the organization`,"expires-in":`token lifetime, 60-600 (default 300)`}),async e=>{let{apiKey:t}=await xi(),n=e.expiresIn??300;xm(await _m({apiKey:t,email:e.email,organizationId:li(t),expiresInSeconds:n}),n,K.json)}),e.demandCommand(1)}function Cm(e){return e.filter(e=>e.role===`assistant`).map(e=>e.parts.map(e=>e.type===`text`?e.content:``).join(``)).filter(Boolean).join(`
153
-
154
- `)}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),`
155
- `)),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(`
147
+ var Gl=/* @__PURE__ */ so({compare:()=>nu,generate:()=>eu,observe:()=>$l,unobserve:()=>Ql}),Kl=/* @__PURE__ */ new WeakMap,ql=function(){function e(e){this.observers=/* @__PURE__ */ new Map,this.obj=e}return e}(),Jl=function(){function e(e,t){this.callback=e,this.observer=t}return e}();function Yl(e){return Kl.get(e)}function Xl(e,t){return e.observers.get(t)}function Zl(e,t){e.observers.delete(t.callback)}function Ql(e,t){t.unobserve()}function $l(e,t){var n=[],r,i=Yl(e);if(!i)i=new ql(e),Kl.set(e,i);else{var a=Xl(i,t);r=a&&a.observer}if(r)return r;if(r={},i.value=Dl(e),t){r.callback=t,r.next=null;var o=function(){eu(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(){eu(r),clearTimeout(r.next),Zl(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 Jl(t,r)),r}function eu(e,t){t===void 0&&(t=!1);var n=Kl.get(e.object);tu(n.value,e.object,e.patches,``,t),e.patches.length&&Bl(n.value,e.patches);var r=e.patches;return r.length>0&&(e.patches=[],e.callback&&e.callback(r)),r}function tu(e,t,n,r,i){if(t!==e){typeof t.toJSON==`function`&&(t=t.toJSON());for(var a=El(t),o=El(e),s=!1,c=o.length-1;c>=0;c--){var l=o[c],u=e[l];if(Tl(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)?tu(u,d,n,r+`/`+kl(l),i):u!==d&&(i&&n.push({op:`test`,path:r+`/`+kl(l),value:Dl(u)}),n.push({op:`replace`,path:r+`/`+kl(l),value:Dl(d)}))}else Array.isArray(e)===Array.isArray(t)?(i&&n.push({op:`test`,path:r+`/`+kl(l),value:Dl(u)}),n.push({op:`remove`,path:r+`/`+kl(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];!Tl(e,l)&&t[l]!==void 0&&n.push({op:`add`,path:r+`/`+kl(l),value:Dl(t[l])})}}}function nu(e,t,n){n===void 0&&(n=!1);var r=[];return tu(e,t,r,``,n),r}var ru=Object.assign({},Pl,Gl,{JsonPatchError:Nl,deepClone:Dl,escapePathComponent:kl,unescapePathComponent:Al});function iu(e){return e.type===`activity`}function au(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ou(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=Jo(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 su(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(iu);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=ru.applyPatch(c,i??[],!0,!1);if(!au(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=Jo(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 cu(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 lu(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 uu(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 du(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 fu(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 pu(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 mu(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=bl(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 hu(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 gu(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 _u(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=rs(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 vu=12,yu=/* @__PURE__ */ new Set([`RAW`,`ACTIVITY_SNAPSHOT`,`ACTIVITY_DELTA`,`REASONING_ENCRYPTED_VALUE`,`SUBAGENT_STARTED`,`SUBAGENT_FINISHED`,`SUBAGENT_ERROR`]),bu=/* @__PURE__ */ new Set([`RUN_STARTED`,`RUN_FINISHED`,`RUN_ERROR`,`MESSAGES_SNAPSHOT`]);function xu(e){return e.some(e=>{let t=e.metadata;if(!t||typeof t!=`object`||Array.isArray(t))return!1;let n=t[Ns];return typeof n==`object`&&!!n&&!Array.isArray(n)&&n.kind===`generic`})}var Su=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=[];handOverAtStreamEnd=!1;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 xl,this.events=e.events||{},this.jsonParser=e.jsonParser||yl,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??Kc(),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=fu(this.messages,e,t,n?`error`:void 0,n),a=cc(t),o=n?`error`:`complete`;i=uu(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=pu(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(...Mc(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)||tc(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&&!yu.has(e.type)?this.closeChunk():[];return bu.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=gl(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=_u(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||Kc(),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=Jo(r.metadata,o),c=Cc(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}=$s(e.messages),a=this.mergeReasoningFanOut(r.map(Bc)),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:Kc(),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`&&nc(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`?sc(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=mu(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=lu(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=Jo(i.metadata,e.metadata)),i.arguments+=e.delta||``,a&&e.delta&&(i.state=`input-streaming`),i.parsedArguments=this.jsonParser.parse(i.arguments),this.messages=lu(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=ts(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=ic(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=fu(this.messages,e.toolCallId,o,a?`error`:void 0);let s=a?`error`:`complete`;this.messages=uu(this.messages,t,e.toolCallId,oc(o)?o:Wc(e.content),s,s===`error`?sc(o):void 0,i),this.emitMessagesChange()}handleRunStartedEvent(e){this.activeRuns.size===0&&(this.runToolCallIds=[],this.toolCallsSentToClient.clear(),this.handOverAtStreamEnd=!1,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,Yo(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);this.handOverAtStreamEnd=this.subagentRunId===void 0;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||tc(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??es(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=xu(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=du(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=gl(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)??Kc(),!1).messageId,i=new Set(n);r!==void 0&&i.add(r);for(let t of i)this.mergeMessageMetadata(t,Yo(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=gu(this.messages,r,a),this.structuredMessageIds.delete(r),this.emitStructuredOutputChange(r,`error`),this.emitMessagesChange()),this.events.onError?.(Sl(e))}handleActivitySnapshotEvent(e){this.messages=ou(this.messages,e),this.emitMessagesChange()}handleActivityDeltaEvent(e){this.messages=su(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=_u(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=_u(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=hu(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=lu(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=cu(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>=vu&&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.handOverAtStreamEnd&&(this.handOverAtStreamEnd=!1,this.hasError||this.handlePendingToolCalls()),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=gu(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.handOverAtStreamEnd=!1,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(Cu(t))}};function Cu(e){return{async*[Symbol.asyncIterator](){for(let{chunk:t}of e.chunks)yield t}}}var wu=class extends Error{provider;constructor(e){super(`Missing ${e} API key`),this.name=`ByokMissingError`,this.provider=e}},Tu=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}},Eu=class extends Error{constructor(){super(`BYOK is enabled but no provider slug was resolved. Pass byokProvider or forwardedProps.provider.`),this.name=`ByokUnresolvedProviderError`}},Du=/^[a-z][a-z0-9-]{0,63}$/;function Ou(e){return typeof e==`string`&&Du.test(e)}function ku(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`||!Ou(t.provider)||!(`message`in t)||typeof t.message!=`string`)}var Au=/* @__PURE__ */ new WeakMap;function ju(e){return Au.get(e)??gl(e)}var Mu=class extends Error{constructor(){super(`Stream ended with unterminated trailing data — connection was likely cut short.`),this.name=`StreamTruncatedError`}},Nu=class extends Error{constructor(e){super(`Stream response body read failed`,{cause:e}),this.name=`StreamReadError`}},Pu=class extends Error{constructor(){super(`Durable run ended without a terminal event and could not resume — the run did not complete.`),this.name=`DurableStreamIncompleteError`}},Fu=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`}},Iu=/* @__PURE__ */ new Set([408,429,502,503,504]),Lu=class extends Error{status;retryAfterMs;constructor(e,t,n){super(e),this.status=t,this.name=`StreamHttpError`,this.retryAfterMs=Ru(n)}};function Ru(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 zu(e){return e instanceof Lu&&Iu.has(e.status)}function Bu(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 Vu(e){let t=Bu(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 Fu(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 Fu(i-1,t.budgetMs);await Hu(s,n)}}}function Hu(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 Uu(e){if(!e)return{};if(e instanceof Headers){let t={};return e.forEach((e,n)=>{t[n]=e}),t}return e}var Wu=`X-Run-Id`;function Gu(e){return{[Wu]:e}}function Ku(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*qu(e,t){try{let n=Ro(),r=``;for(;!t?.aborted;){let i;try{i=await e.read()}catch(e){if(t?.aborted)return;throw new Nu(e)}let{done:a,value:o}=i;if(a)break;r+=n.decode(o,{stream:!0});let s=r.split(`
148
+ `);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 Mu}finally{try{e.cancel().catch(()=>{})}catch{}e.releaseLock()}}async function*Ju(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=zo(n),r=pl(JSON.parse(e)),i=t;t=void 0,yield{chunk:r,...i===void 0?{}:{id:i}}}}async function Yu(e){if(!e.ok){if(e.status===401){let t=await e.clone().json().catch(()=>null);if(ku(t))throw new wu(t.error.provider)}throw new Lu(`HTTP error! status: ${e.status} ${e.statusText}`,e.status,e.headers.get(`retry-after`))}}function Xu(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 Zu(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 Qu(e,t,n,r,i,a){let o=await e(Ku(t,Xu(i,a)),{method:`GET`,headers:{Accept:`application/json`,...n},credentials:r});await Yu(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)?Ho(s.messages):[],activeRun:c,interrupts:l,page:Zu(s.page)}}async function $u(e,t,n,r,i){let a=await e(Ku(t,{threadId:i}),{method:`GET`,headers:{Accept:`application/json`,...n},credentials:r});await Yu(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*ed(e,t){await Yu(e),yield*Ju(qu(Lo(e),t))}async function*td(e,t){for await(let{chunk:n}of ed(e,t))yield n}function nd(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 Nu(e)}yield*r(o,a)}}async function*rd(e,t,n){let r=Vu(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 Mu||e instanceof Nu||zu(e))&&r.lastEventId!==void 0){await r.waitBeforeReconnect(a,t,zu(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 Pu}return}}function id(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&&Au.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(Yo({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 ad(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=Yc(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 od(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`,...Uu(s.headers),...Uu(a.headers),...Gu(a.runId)},l=ad(n,r,a,s),u=s.fetchClient??fetch,d=i||s.signal;yield*rd(nd(u,o,{method:`POST`,headers:c,body:JSON.stringify(l),credentials:s.credentials||`same-origin`},ed),d,s.reconnect)},async*joinRun(n,r){let i=typeof e==`function`?e():e,a=typeof t==`function`?await t():t,o=Ku(i,{offset:`-1`,runId:n}),s={...Uu(a.headers)},c=a.fetchClient??fetch,l=r||a.signal;yield*rd(nd(c,o,{method:`GET`,headers:s,credentials:a.credentials||`same-origin`},ed),l,a.reconnect)},async hydrate(n,r){let i=typeof e==`function`?e():e,a=typeof t==`function`?await t():t;return Qu(a.fetchClient??fetch,i,Uu(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 $u(i.fetchClient??fetch,r,Uu(i.headers),i.credentials||`same-origin`,n)}}}function sd(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*td(a,r):yield*cd(a,r)}}}async function*cd(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 ld(e){return e.resumable}function ud(e,t){let n=Gs(e.descriptor);return n?{...t,metadata:Ws(n)}:t}function dd(e){return`cancel`in e&&`clearResolution`in e}var fd=/* @__PURE__ */ new Set([`invalid-payload`,`invalid-edited-args`,`invalid-tool-output`,`invalid-response-schema`,`unknown-interrupt`,`expired`,`stale`,`conflict`]),pd=/* @__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 md(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function hd(e){return Rs(e)}function gd(e){if(!md(e.metadata))return!1;let t=e.metadata[Ns];return!md(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 _d(e){if(!md(e.metadata))return!1;let t=e.metadata[Ns];return!md(t)||t.kind!==`generic`?!1:`definitionId`in t||`key`in t||`batchIndex`in t||`payloadSchemaHash`in t}function vd(e){return e.metadata?.[`tanstack:interruptPayload`]}function yd(e){if(e.responseSchema!==void 0)try{return us(ls(e.responseSchema))}catch{return}}function bd(e){if(e!==void 0)try{return Vs(e)}catch{return}}function xd(e){return e!==null&&(typeof e==`object`||typeof e==`function`)&&`then`in e&&typeof e.then==`function`}function Sd(e,t,n){if(e===void 0)return{valid:!0,payload:t};if(gs(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 xd(r)?Promise.resolve(r).then(i):i(r)}return{valid:!0,payload:t}}function Cd(e){for(let t of fd)if(t===e)return!0;return!1}function wd(e){for(let t of pd)if(t===e)return!0;return!1}function Td(e){if(!md(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`?Cd(n)&&typeof e.interruptId==`string`&&(e.source===`client`||e.source===`server`):t===`batch`&&wd(n)&&Array.isArray(e.interruptIds)&&e.interruptIds.every(e=>typeof e==`string`)&&(e.source===`client`||e.source===`server`||e.source===`transport`)}function Ed(e){return Td(e)?[e]:!md(e)||!Array.isArray(e.errors)?[]:e.errors.every(Td)?e.errors:[]}function Dd(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 Od(e,t){return e.threadId===t.threadId&&e.interruptedRunId===t.interruptedRunId&&e.generation===t.generation&&Dd(e.interruptIds,t.interruptIds)}function kd(e,t,n){let r=n.filter(e=>e.source!==`transport`),i=e=>t.includes(e)&&r.some(t=>Od(e,t)),a=e.filter(e=>!i(e)),o=t.filter(e=>!r.some(t=>Od(e,t)));return Object.freeze({rootErrors:Object.freeze([...a,...n]),submissionRootErrors:Object.freeze([...o,...r])})}function Ad(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):Dd(e.interruptIds,n)}function jd(e,t,n){let r=yd(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 Md(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 Nd=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=hd(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)ld(e)&&(e.validationGeneration++,e.resolution=Object.freeze(ud(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(Yo(ud(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=hd(r);if(i===void 0)return gd(r)?{descriptor:r,binding:jd(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&&yd(r)===i.responseSchemaHash,o=i.interruptId===r.id&&i.interruptedRunId===t.interruptedRunId&&i.generation===t.generation&&i.responseSchemaHash===(yd(r)??i.responseSchemaHash);if(_d(r)&&(!o||i.kind!==`generic`||i.definitionId===void 0||i.key===void 0||i.batchIndex===void 0))return{descriptor:r,binding:jd(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=js(e.approvalSchema,e.inputSchema);if(Ms(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(Ms(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&&bd(e.responseSchema)===i.responseSchemaHash&&(e.payloadSchema===void 0?i.payloadSchemaHash===void 0:i.payloadSchemaHash===bd(e.payloadSchema))){let t=vd(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`||yd(r)===void 0||i.responseSchemaHash===yd(r));return{descriptor:r,binding:jd(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=Md(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=md(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);xd(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(ud(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=>ld(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=fs(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(ud(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=Sd(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 xd(n)?Promise.resolve(n).then(r):r(n)}if(e.kind===`client-tool-execution`){let n=Sd(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 xd(n)?Promise.resolve(n).then(r):r(n)}return this.validateApprovalCandidate(e,t)}validateApprovalCandidate(e,t){if(!md(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=Sd(e.tool?.inputSchema,r,`invalid-edited-args`);return xd(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=Sd(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 xd(o)?Promise.resolve(o).then(s):s(o)}approvalBranchSchema(e,t){let n=e?.approvalSchema;return!md(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=>ld(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(dd),i;try{for(let t of r){let n=e(t);if(n!==void 0){i={code:xd(n)?`async-resolver`:`inactive-transaction`,message:xd(n)?`Interrupt transaction resolvers must be synchronous.`:`Interrupt transaction resolvers must return literal undefined.`};break}}i===void 0&&this.items.some(e=>ld(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)ld(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=Ed(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)ld(e)&&(e.status=`error`);return}let r=n.filter(e=>Ad(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=>ld(t)&&t.descriptor.id===e.interruptId);t&&(t.status=`error`,t.error=Z(e))}else o.push(Z(e));let s=kd(this.rootErrors,this.submissionRootErrors,o);this.rootErrors=s.rootErrors,this.submissionRootErrors=s.submissionRootErrors;for(let e of this.items)ld(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(ld).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})}},Pd=/* @__PURE__ */ new WeakMap;function Fd(e){let t=Object.entries(e.keys()).filter(e=>!!e[1]).map(e=>e[0]).filter(Ou);if(t.length===1)return t[0];let n=Pd.get(e)??[];if(n.length===1)return n[0]}function Id(e,...t){let n=e?.();if(Ou(n))return n;for(let e of t)if(Ou(e))return e}async function Ld(e,t){if(!t)throw new Eu;return await e.prepare(t),e.headers(t)}var Rd=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})}},zd=class extends Rd{emitEvent(){}},Bd=class{events;constructor(e){this.events=new zd(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){}},Vd=e=>new Bd(e);function Hd(e){return`toolCallId`in e&&typeof e.toolCallId==`string`?e.toolCallId:void 0}function Ud(e){return`messageId`in e&&typeof e.messageId==`string`?e.messageId:void 0}function Wd(e){return`parentMessageId`in e&&typeof e.parentMessageId==`string`?e.parentMessageId:void 0}var Gd=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=ju(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=Hd(e);if(n&&this.clearedToolCallIds.has(n))return!0;let r=Wd(e);if(r&&this.clearedMessageIds.has(r))return n&&this.clearedToolCallIds.add(n),!0;let i=Ud(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=Ud(e);t&&this.clearedMessageIds.add(t);let n=Hd(e);n&&this.clearedToolCallIds.add(n)}isRunlessChunkFromIgnoredRun(e){return ju(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 Kd(e){return`toolCallId`in e&&typeof e.toolCallId==`string`?e.toolCallId:void 0}function qd(e){return`messageId`in e&&typeof e.messageId==`string`?e.messageId:void 0}function Jd(e){return`parentMessageId`in e&&typeof e.parentMessageId==`string`?e.parentMessageId:void 0}var Yd=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=ju(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=Kd(e);if(n&&this.clearedToolCallIds.has(n))return!0;let r=Jd(e);if(r&&this.clearedMessageIds.has(r))return n&&this.clearedToolCallIds.add(n),!0;let i=qd(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=qd(e);t&&this.clearedMessageIds.add(t);let n=Kd(e);n&&this.clearedToolCallIds.add(n)}isRunlessChunkFromIgnoredRun(e){return ju(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`}},Xd=8;function Zd(){let{scheduler:e}=globalThis;return e?.yield?e.yield():new Promise(e=>setTimeout(e,0))}function Qd(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 $d(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 sd(n);throw Error("ChatClient: either `connection` or `fetcher` is required.")}function ef(e){return`connect`in e}function tf(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 nf(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 rf(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(`
149
+ `),...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=Jo(i,t.content.metadata));return{content:{content:r,...i===void 0?{}:{metadata:i}},...t===void 0?{}:{body:t}}}function af(e){if(typeof e==`object`&&e&&!Array.isArray(e)&&`approved`in e&&typeof e.approved==`boolean`)return e.approved}function of(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 sf=2e3,cf=/* @__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 lf(e){return e.type===`REASONING_ENCRYPTED_VALUE`?e.subtype===`message`&&typeof e.encryptedValue==`string`&&e.encryptedValue.length>0:cf.has(e.type)}function uf(e){return e.map(e=>({...e,parts:e.parts.map(e=>Object.isFrozen(e)?e.type===`subagent`?{...e,subagent:{...e.subagent,messages:uf(e.subagent.messages)}}:{...e}:e)}))}function df(e){let t=[];for(let n of e)for(let e of n.parts)e.type===`subagent`&&(t.push(e),t.push(...df(e.subagent.messages)));return t}function ff(e){if(`subagentRunId`in e&&typeof e.subagentRunId==`string`)return e.subagentRunId}var pf=64;function mf(e){if(Array.isArray(e))return e.map(mf);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]=mf(r));return t}var hf=class{processor;subagentHandles=/* @__PURE__ */ new Map;stoppedSubagentIds=/* @__PURE__ */ new Set;connection;threadId;persistor;clearedStreamTracker=new Yd;snapshotAtom=wo({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(Qd(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 Gd(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=nf(e.queue);let n=$d(e);if(this.connectionDrainsOnSend=ef(n),this.connection=id(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??Vd)(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 Nd({...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&&uf(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 Su({...e.streamProcessor?.chunkStrategy?{chunkStrategy:e.streamProcessor.chunkStrategy}:{},...a?{initialMessages:a}:{},events:{onMessagesChange:e=>{this.syncSubagentHandles(),this.persistor?.notifyMessagesChanged(e),Mo(this.snapshotAtom,{messages:jo(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=of(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=Ho(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 wu&&this.byok?.request(t.provider,`missing`),t instanceof Tu&&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=ju(e)??this.clearedStreamTracker.takeRunlessRunId();t&&(this.activeRunIds.delete(t),this.setSessionGenerating(this.activeRunIds.size>0),ju(e)||this.resolveProcessing())}updateRunLifecycle(e,t){if(e.type===`RUN_STARTED`){let t=ju(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=ju(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`&&tf(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=ju(e),n=`threadId`in e&&typeof e.threadId==`string`?e.threadId:this.activeResumeThreadId;if(t&&!tf(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<pf;){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&&(Mo(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=af(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=>ko(e))):e.content.content;return Object.freeze({...e,content:Object.freeze({...e.content,content:t})})}))}readSnapshot(e){return Object.freeze({...this.snapshotAtom.get(),messages:jo(this.frozenMessages,this.processor.getMessages()),queue:this.freezeSnapshotQueue(this.getQueue()),isHydrating:e,interruptState:this.interruptManager.getState()})}subscribeSnapshot=e=>Po(this.snapshotAtom,e);getSnapshot=()=>this.snapshotAtom.get();setIsLoading(e){Mo(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){Mo(this.snapshotAtom,{status:e}),this.callbacksRef.current.onStatusChange(e),this.devtoolsBridge.emitSnapshot()}setIsSubscribed(e){Mo(this.snapshotAtom,{isSubscribed:e}),this.callbacksRef.current.onSubscriptionChange(e),this.devtoolsBridge.emitSnapshot()}setConnectionStatus(e){Mo(this.snapshotAtom,{connectionStatus:e}),this.callbacksRef.current.onConnectionStatusChange(e),this.devtoolsBridge.emitSnapshot()}syncIsHydrating(){let e=this.hydrationInFlight!==void 0||this.storeHydrating;this.isHydrating!==e&&(Mo(this.snapshotAtom,{isHydrating:e}),this.callbacksRef.current.onHydratingChange(e))}setSessionGenerating(e){this.sessionGenerating!==e&&(Mo(this.snapshotAtom,{sessionGenerating:e}),this.callbacksRef.current.onSessionGeneratingChange(e),this.devtoolsBridge.emitSnapshot())}notifyResumeStateChange(e){let t=this.getResumeState(),n=this.interruptManager.getState();Mo(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){Mo(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:mf(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<Xd||(n=0,typeof document<`u`&&document.hidden||await Zd())}}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()},sf);try{for await(let a of t(e,n.signal)){if(n.signal.aborted)break;i||(i=!0,clearTimeout(o)),!r&&lf(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=pl(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`)&&(ju(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=ff(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=ju(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=ju(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=Gc(e,Kc);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=Id(this.byokProvider,f.provider,Fd(this.byok));m=await Ld(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?xs(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 wu&&this.byok?.request(n.provider,`missing`),n instanceof Tu&&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 wu||n instanceof Tu||n instanceof Eu))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&&gs(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 Ss(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=Js(n.metadata);return r===void 0?n:{...n,input:r}},t=df(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=Ho(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){Mo(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=rf(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();Mo(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(uf(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=$d({connection:e.connection,fetcher:e.fetcher});this.connectionDrainsOnSend=ef(n),this.connection=id(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=nf(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 gf=e=>`background:${e};color:#fff;border-radius:3px;padding:1px 5px`,_f=`${gf(`#7c3aed`)};font-weight:600`,vf={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 yf(e){if(e)return(e,t,n)=>{console.log(`%cAstralBeam%c ${(/* @__PURE__ */ new Date()).toISOString().slice(11,19)} %c${e}%c ${t}`,_f,`color:#94a3b8;font-weight:400`,gf(vf[e]),``,...n===void 0?[]:[n])}}function bf(){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 xf(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 Sf(e,t,n){return`saved:${e}:${t}${n?`:${n}`:``}`}async function Cf(e,t,n,r=/* @__PURE__ */ new Map){let i=await Nr(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:Sf(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 wf(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(Sf(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=Sf(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,clientMessageId:a.client_message_id}}})}return r}function Tf(e){return e.placementKey??e.agentId??`default`}function Ef(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 Df;function Of(e,t){return JSON.stringify([e,Tf(t)])}function kf(e,t,n){if(!n){if(!Df)try{let e=`astralbeam:draft-session`;Df=globalThis.sessionStorage?.getItem(e)??bf(),globalThis.sessionStorage?.setItem(e,Df)}catch{Df??=bf()}n=`new:${Df}`}return JSON.stringify([e.replace(/\/+$/,``),t,n])}function Af(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 jf(e,t,n,r,i=`draft`){if(!t)return``;let a=`astralbeam:${i}:${kf(e,t,n)}`;try{let e=i===`sent`?globalThis.sessionStorage:void 0;if(r===void 0)return e?.getItem(a)??globalThis.localStorage?.getItem(a)??``;r?(e??globalThis.localStorage)?.setItem(a,r):e?.removeItem(a),(e||!r)&&globalThis.localStorage?.removeItem(a)}catch{}return``}function Mf(e){return typeof e==`string`||typeof e.content==`string`||Array.isArray(e.content)&&e.content.every(e=>e?.type===`text`?typeof e.content==`string`:[`image`,`document`,`audio`,`video`].includes(e?.type)&&e.source?.type===`file`&&typeof e.source.value==`string`)}function Nf(e,t){if(!e.identity||!e.threadId)return;let n=`astralbeam:pending:${kf(e.apiUrl,e.identity,e.threadId)}`;try{let e=globalThis.sessionStorage;if(!e)return;if(t&&`save`in t)return Mf(t.save.content)?(e.setItem(n,JSON.stringify(t.save)),t.save):void 0;let r=JSON.parse(e.getItem(n)??`null`);if(t){r?.key===t.clearKey&&e.removeItem(n);return}return!r||typeof r.id!=`string`||typeof r.key!=`string`||typeof r.clientId!=`string`||!r.content||!Mf(r.content)||!Number.isFinite(r.dispatchedAt)||!Array.isArray(r.tools)||r.draftFileIds!==void 0&&(!Array.isArray(r.draftFileIds)||!r.draftFileIds.every(e=>typeof e==`string`))?void 0:r}catch{}}function Pf({apiUrl:e,identity:t,threadId:n,update:r,moveTo:i}){let a=()=>{if(!t)return[];let a=`astralbeam:attachments:${kf(e,t,n)}`,o=e=>{let t=JSON.parse(globalThis.localStorage?.getItem(e)??`[]`);if(!Array.isArray(t)||!t.every(Af))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:${kf(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 Ff(e){return e?`~standard`in e?`jsonSchema`in e[`~standard`]?xs(e):{type:`object`}:e:{type:`object`,properties:{}}}async function If(e,t){let n=await Ss(e,t);return n.success?n.data??{}:null}const Lf=Symbol(`Host tool was not executed`);function Rf(e,t,n,r,i){return[...Object.keys(e).length>0?[zf(e,n)]:[],Bf(),...Vf(t,r,i)]}function zf(e,t){return ml({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:
150
+ `+Object.entries(e).map(([e,{description:t,parameters:n}])=>`- ${e}: ${t} Props schema: ${JSON.stringify(Ff(n))}`).join(`
151
+ `),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 Bf(){return ml({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 Vf(e,t,n){return Object.entries(e).map(([e,r])=>ml({name:e,description:r.description,inputSchema:Ff(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 If(r.parameters,i??{});if(c==null)throw t?.(`error`,`input for host tool "${e}" failed schema validation`,{input:i}),Error(`Input for tool "${e}" failed schema validation`);a?.abortSignal?.throwIfAborted();let l=s?.()??r;o=!0;let u=await l.execute(c);try{u=Z(u)}catch{throw Error(`Tool "${e}" ran, but its result is not JSON-compatible. Its changes may already be applied. Read current state before retrying. Return plain JSON values and omit undefined fields.`)}return t?.(`tool`,`host tool "${e}" returned`,{output:u}),u}catch(n){t?.(`error`,`host tool "${e}" threw`,{error:n});let r=n instanceof Error?n:Error(String(n));throw o||Object.assign(r,{[Lf]:!0}),r}}))}function Hf(e){if(e.length>16384)throw Error(`The chat auth token is too large`);let{exp:t,iat:n,user:r}=co(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 Uf(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 Wf={status:`loading`};function Gf(e){return{...e,fetchAstralBeamToken:e.fetchAstralBeamToken,session:{cached:void 0,refreshPromise:void 0,abortController:new AbortController,state:Wf,listeners:/* @__PURE__ */ new Set},fetchClient:globalThis.fetch.bind(globalThis),debug:void 0}}function Kf(e){return e.session.state}function qf(e,t){let{listeners:n}=e.session;return n.add(t),()=>{n.delete(t)}}function Jf(e,t){e.session.state=t;for(let t of e.session.listeners)t()}function Yf(e,t){e.apiUrl!==t.apiUrl&&(tp(e),e.session.abortController=new AbortController,Jf(e,{status:`loading`})),e.apiUrl=t.apiUrl,e.fetchAstralBeamToken=t.fetchAstralBeamToken}function Xf(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 Zf(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 Uf(e,i);if(i.throwIfAborted(),typeof s!=`string`||!s)throw Error(`${a} did not return a token`);let{expiresAt:c,refreshAt:l,tenantAdmin:u}=Hf(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 Ir({apiUrl:r,astralBeamToken:s,fetchClient:e.fetchClient,signal:i,cache:`no-store`,credentials:`omit`})}catch(t){if(!o&&e.retryUnauthorized!==!1&&cr(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},Jf(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 cr(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,Jf(e,{status:`error`,error:r}),r}}async function Qf(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())&&Jf(e,{status:`loading`});let r=Zf(e);t.refreshPromise=r;try{return await r}finally{t.refreshPromise===r&&(t.refreshPromise=void 0)}}function $f(e,t){let n=!t||e.session.cached?.value===t;return n&&(e.session.cached=void 0),Qf({...e,force:n,retryUnauthorized:!1})}async function ep(e){e.session.abortController.signal.aborted&&(e.session.abortController=new AbortController),await Qf(e)}function tp({session:e}){e.abortController.abort(),e.refreshPromise=void 0,e.cached=void 0,e.state=Wf}async function np(e){let{input:t,init:n,session:r,fetchClient:i,debug:a}=e,o=Kf(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 $f(e,u),f=Kf(e);if(o.status!==`ready`||f.status!==`ready`||Xf(o.currentUser)!==Xf(f.currentUser))throw new DOMException(`Identity changed`,`AbortError`);return n?.signal?.throwIfAborted(),c.set(`authorization`,`Bearer ${d}`),await i(t,{...n,headers:c})}function rp(e){let t,n=new AbortController,r=0,i=()=>typeof document>`u`||document.visibilityState!==`hidden`&&globalThis.navigator?.onLine!==!1,a=()=>{!n.signal.aborted&&i()&&Qf({...e,force:!0}).catch(()=>{})},o=()=>{if(clearTimeout(t),n.signal.aborted||typeof document>`u`||!i())return;let o=Kf(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=qf(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 ep(e).catch(()=>{}),o(),()=>{n.abort(),clearTimeout(t),c()}}async function ip(e,t){switch(e.action){case`connect`:case`headers`:{let n=await Br({mcp_server_id:e.mcpServerId},t);return e.action===`connect`?n:(await Hr(n.id,{lock_version:n.lock_version,headers:e.headers},t),{id:n.id})}case`disconnect`:return Wr(e.id,t);case`test`:return Kr(e.id,t)}}async function ap(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 Br({mcp_server_id:e.mcpServerId},await t())).id,i=await Jr(r,await t()),a={organizationId:i.attempt.organization_id,tenantId:i.attempt.tenant_id,connectionId:i.attempt.connection_id,id:i.attempt.id},o=new URL(i.popup_url);o.searchParams.set(`origin`,window.location.origin);let{promise:s,resolve:c,reject:l}=Promise.withResolvers(),u={state:`waiting`},d=new AbortController,f=!1,p=e=>l(e instanceof Error?e:/* @__PURE__ */ Error(`Authorization failed.`)),m=async()=>{let e=await t();return d.signal.throwIfAborted(),{...e,signal:AbortSignal.any([d.signal,...e.signal?[e.signal]:[]])}},h=async()=>{if(!(f||d.signal.aborted)){f=!0;try{if(u.state===`binding`&&(await Xr(r,{attempt_id:a.id,challenge:u.challenge},await m()),d.signal.throwIfAborted(),u={state:`completing`}),u.state===`completing`){let e=await Qr(r,{attempt_id:a.id},await m());if(d.signal.throwIfAborted(),e){c();return}}n.closed&&p(/* @__PURE__ */ Error(`Authorization window closed.`))}catch(e){let t=e instanceof Error?e.status:void 0;!(e instanceof TypeError)&&t!==429&&(t??0)<500&&p(e)}finally{f=!1}}},g=e=>{if(e.source!==n||e.origin!==o.origin)return;let t=e.data;t?.attempt&&t.attempt.id===a.id&&t.attempt.organizationId===a.organizationId&&t.attempt.tenantId===a.tenantId&&t.attempt.connectionId===a.connectionId&&t.type===`mcp-browser-challenge`&&u.state===`waiting`&&typeof t.challenge==`string`&&(u={state:`binding`,challenge:t.challenge},h())},_=setInterval(()=>void h(),5e3),v=setTimeout(()=>p(/* @__PURE__ */ Error(`Authorization expired. Try connecting again.`)),6e5);try{window.addEventListener(`message`,g),n.location.replace(o.href),await s}finally{d.abort(),window.removeEventListener(`message`,g),clearInterval(_),clearTimeout(v)}return r}finally{n.close()}}function op(e){return e.state===`complete`||e.state===`error`||e.output!==void 0}function sp(e){return e.metadata??{}}function cp(e,t){return typeof e==`object`&&e&&t in e?e[t]:void 0}function lp(e,t){let n=cp(e,t);return typeof n==`string`?n:void 0}function up(e,t){let n=cp(e,t);return typeof n==`number`?n:void 0}function dp(e){return lp(e.output,`refusal`)}function fp(e){if(e.name!==`sandbox_write_file`)return;let t=lp(e.output,`path`)??lp(e.input,`path`);if(t===void 0)return;let n=lp(e.input,`content`)??``;return{toolCallId:e.id,path:t,label:pp(e)??t,content:n,lines:n.length===0?0:n.split(`
152
+ `).length,written:e.output!=null&&dp(e)===void 0}}function pp(e){let t=lp(e.output,`relativePath`);return t!==void 0&&t!==`.`?t:lp(e.output,`path`)??lp(e.input,`path`)}function mp(e){if(e.name!==`sandbox_run_command`)return;let t=lp(e.input,`command`);if(t===void 0)return;let n=e.output;return{toolCallId:e.id,command:t,cwd:lp(e.input,`cwd`),exitCode:up(n,`exitCode`),stdout:lp(n,`stdout`)??``,stderr:lp(n,`stderr`)??``,durationMs:up(n,`durationMs`),timedOut:cp(n,`timedOut`)===!0,truncated:cp(n,`truncated`)===!0,finished:n!=null}}function hp(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=fp(e);r?.written&&t.set(r.path,r);let i=mp(e);i&&dp(e)===void 0&&n.push(i)}return{files:[...t.values()],commands:n}}const gp=`Refresh this conversation or start a new one before sending.`,_p=`This message may not have been sent. Retry to send it.`,vp=`This message could not be confirmed within 24 hours. Check the saved conversation before sending it again.`;function yp(e,t){return e.length===t.length&&e.every((e,n)=>e.name===t[n]?.name&&e.title===t[n]?.title)}function bp(e,t=!1){let n={...e},r=yf(n.debug),i=/* @__PURE__ */ new Set,a,o=()=>a?.options??n,s={messages:[],status:`ready`,error:void 0,auth:{status:`loading`},capabilities:{attachments:!0},agentTools:[],sandboxStatus:void 0,usageLimitReached:void 0,sandbox:{files:[],commands:[]},thread:void 0,history:`idle`,messagesCursor:void 0,olderMessagesLoading:!1,submission:void 0,activeToolCallIds:[],pendingInteractions:[]},c,l=/* @__PURE__ */ new Map,u,d=`ready`,f,p=e=>{let t=f||c?.phase===`submitting`?d===`streaming`||s.status===`streaming`?`streaming`:`submitted`:d;s={...s,...e,status:t,history:u?.phase??`idle`};for(let e of i)e()},m=e=>e.client===N&&e.selection===C,h=e=>f===e&&m(e),g=e=>{h(e)&&(f=void 0,p({}))},_=e=>e!==void 0&&Date.now()-e.dispatchedAt>=864e5,v=({id:e,content:t,phase:n,error:r,delivery:i})=>({id:e,content:t,phase:n,...r?{error:r}:{},...n===`failed`&&_(i)?{retryExpired:!0}:{}}),ee={submitting:[`accepted`,`failed`,`refused`],failed:[`submitting`,`accepted`],accepted:[],refused:[]},y=(e,t,n)=>ee[e.phase].includes(t)?(e.phase=t,e.error=n,e===c&&p({submission:v(e)}),!0):!1,te=e=>e.submission===c&&h(e),ne=e=>te(e)&&e.submission.phase===`submitting`,re=(e,t)=>e.delivery?y(e,`failed`,t??/* @__PURE__ */ Error(_p)):y(e,`refused`,t),b=e=>{let t=c;return t?.phase===`submitting`&&re(t,t.delivery?void 0:Error(e)),t?.phase===`refused`&&t.onRefused?.(),c=void 0,t},x=Gf({apiUrl:n.apiUrl,scope:`tenant`,fetchAstralBeamToken:n.fetchAstralBeamToken??{url:`/api/astralbeam/token`}}),ie,ae,S,oe=e=>{let t=Kf(x);if(t.status===`ready`)return{apiUrl:n.apiUrl??`https://astralbeam.ai/api`,identity:Of(Xf(t.currentUser),n),threadId:e}},se=e=>{let t=oe(e),n=t&&Nf(t);if(!t||!n)return;let{id:r,key:i,content:a,...o}=n,s={...o,scope:t};return{id:r,key:i,content:a,phase:`failed`,error:/* @__PURE__ */ Error(_(s)?vp:_p),delivery:s}},ce=!1,C=0,le=0,ue=async e=>{for(;m(e);){let e=u;try{await e?.completion}catch(t){if(e===u)throw t}if(e===u)return}},de=async e=>{if(await ue(e).catch(()=>void 0),!ne(e))return!1;if(s.history===`failed`)throw Error(gp);return!0},fe=new AbortController,w,pe=!1,T=[],me=/* @__PURE__ */ new Map,he=0,ge=/* @__PURE__ */ new WeakMap,_e=e=>{for(let t of e){if(t.role!==`user`||me.get(t.id)?.attachmentParts||!t.parts.some(e=>`fileId`in e))continue;let e=t.parts.map(e=>Object.freeze({...e}));Object.freeze(e),me.set(t.id,{...me.get(t.id),attachmentParts:e}),he++}},ve=bf(),ye=e=>{if(!e.delivery?.scope)return;let{scope:t,draftFileIds:n}=e.delivery,i=()=>Nf(t,{clearKey:e.key});if(n&&jf(t.apiUrl,t.identity,t.threadId,``,`sent`),!n?.length)return void i();let a=new Set(n);Pf({...t,update:e=>e.filter(e=>!a.has(e.id))}).then(i,e=>r?.(`error`,`Accepted draft files could not be cleared`,e))},be=()=>{let e=c;e&&y(e,`accepted`)&&(ye(e),s.thread&&p({thread:{...s.thread,hasMessages:!0}}),e.callbacks?.onAccepted?.())},xe=e=>{let t=[...N.getSnapshot().messages],n=t.findLastIndex(e=>e.role===`user`&&e.metadata?.astralbeamSubmissionId===c?.id);if(n!==-1){let r=wf([e])[0];t.some((t,r)=>r!==n&&t.id===e.id)?t.splice(n,1):t[n]=r,_e([r]),N.setMessagesManually(t),P&&qe()}},E=/* @__PURE__ */ new Set,Se=/* @__PURE__ */ new Map,D=/* @__PURE__ */ new Map,O=/* @__PURE__ */ new Map,Ce=/* @__PURE__ */ new Map,we=e=>{let t=Se.get(e);return t?`live:${t}:${e}`:e},Te=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=Sf(n.source_message_id,n.source_part_id,n.response_target_id),i=O.get(e)??O.get(r);i&&(t.set(r,i),Se.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)},Ee=e=>{(s.auth.status!==`error`||s.auth.error!==e)&&n.streamCallbacks?.onError?.(e)},De=e=>{if(e instanceof Error&&e.name===`AbortError`)return;let t=e instanceof Error?e:Error(String(e));p({error:t}),Ee(t)},Oe=e=>{p({unavailableMcpConnections:s.unavailableMcpConnections?.filter(t=>t!==e)??[]})},k=async(e=!0)=>{let t=C,n=x.session.abortController.signal,r=await Qf(x);if(n.throwIfAborted(),e&&t!==C)throw new DOMException(`Conversation changed`,`AbortError`);return{apiUrl:x.apiUrl,astralBeamToken:r,cache:`no-store`,signal:e?AbortSignal.any([fe.signal,n]):n,fetchClient:(e,t)=>np({...x,input:e,init:t})}},ke=0,Ae,A=async()=>{let e=++ke,t=C;if(s.thread?.agentId===null){p({capabilities:{attachments:!1}});return}let i=s.thread?s.thread.agentId:n.agentId;try{let n=await k();if(e!==ke||t!==C)return;let a=await Cr(i?{agentId:i}:{},n);if(e!==ke||t!==C)return;let o=a.capabilities?.attachments!==!1;p({capabilities:{attachments:o}}),r?.(`mount`,`agent capabilities resolved`,{attachments:o})}catch(e){r?.(`error`,`agent capabilities could not be resolved; keeping the defaults`,e)}},j=/* @__PURE__ */ new Map,je=/* @__PURE__ */ new Set,Me=/* @__PURE__ */ new Set,Ne=0,Pe=()=>{Ne++;for(let e of j.values())e();j.clear(),je.clear(),Me.clear()},Fe=async(e,t)=>{if(!o().onRenderWidget)return{widget:e.widget,rendered:!1};let n=C,r=Ne,i=o().widgets??{};if(!Object.hasOwn(i,e.widget))throw Error(`Unknown widget "${e.widget}"`);let a=i[e.widget],c=await If(a?.parameters,e.props??{});if(n!==C||r!==Ne||s.thread?.role===`viewer`)return{widget:e.widget,rendered:!1};if(a!==o().widgets?.[e.widget])return Fe(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};j.get(t)?.(),j.delete(t);let u,d=l({widget:e.widget,props:c,toolCallId:t,release:()=>{j.get(t)===u&&j.delete(t)}});return d&&(u=d,j.set(t,d)),je.add(t),{widget:e.widget,rendered:!0}},Ie=e=>Object.freeze(e.map(e=>{let t=me.get(e.id),n=ge.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=Sf(e.id,t.id),a=n.applicationPartId?Sf(e.id,n.applicationPartId,n.responseTargetId):r,o=n.upstreamToolCallId,s=n.widgetRenderId??i?.get(r)??i?.get(a)??(o&&Se.get(o)===e.id&&je.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},me.set(e.id,t),he++);let o=r===e.parts?e:Object.freeze({...e,parts:r});return ge.set(e,{presentation:t,message:o}),o})),Le=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(je.has(t)||Me.has(t))continue;Me.add(t);let n=C,i=Ne,{widgets:a,onRenderWidget:c}=o();Fe(e.input,t).catch(e=>r?.(`error`,`Saved widget could not be rendered`,e)).finally(()=>{n===C&&i===Ne&&(Me.delete(t),(a!==o().widgets||c!==o().onRenderWidget)&&Le(s.messages))})}},Re=()=>{let e=C;return Rf(o().widgets??{},n.tools??{},Fe,r,(t,r,i)=>{let a=le,o=N,c=S,l=x.apiUrl;return()=>{let u=n.tools&&Object.hasOwn(n.tools,t)?n.tools[t]:void 0;if(e!==C||a!==le||o!==N||c!==S||l!==x.apiUrl||s.thread?.role===`viewer`||!i||!E.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||!E.has(r))throw Error(`A saved tool call cannot execute again. Send a new message to request it.`);let i=O,a=we(r),o=f?.clientId,s=S,c=x.apiUrl;try{let r=await t(e,n);return S===s&&x.apiUrl===c&&i.set(a,{outcome:`succeeded`,output:r??null,clientId:o}),r}catch(e){throw!(e instanceof Error&&Lf in e)&&S===s&&x.apiUrl===c&&i.set(a,{outcome:`unknown`,output:{error:e instanceof Error?e.message:String(e)},clientId:o}),e}}}})},ze=()=>{let e=Re(),t=e.map(e=>{let t=e.metadata?.title;return{name:e.name,title:typeof t==`string`&&t.length>0?t:void 0}});return yp(s.agentTools,t)||p({agentTools:t}),e},Be=()=>n.debug?{debug:!0}:{},Ve=async(e,t,n)=>{if(!h(n))throw new DOMException(`Request cancelled`,`AbortError`);let r=s.thread;if(!r||typeof e.body!=`string`)throw Error(`Open a conversation before sending.`);let i=JSON.parse(e.body),a=xr(),o,c=i.messages.at(-1)?.role===`user`&&n.kind===`submission`&&ne(n)?n.submission:void 0,l=c?.delivery;if(c){if(_(c.delivery))throw Error(vp);n.clientId=l?.clientId??ve,o={...i,threadId:r.id,resume:void 0,parentRunId:void 0,messages:[i.messages.at(-1)],tools:l?.tools??i.tools,forwardedProps:{...i.forwardedProps,clientId:n.clientId,clientMessageId:c.id}}}else{Xe();let e=await Cf(r.id,t,void 0,Se);if(!h(n))throw new DOMException(`Request cancelled`,`AbortError`);p({thread:xf(e.thread,e.messages.length>0)}),Te(e);let s=e.pendingInteractions.filter(e=>O.has(we(e.toolCallId))),c=s.find(e=>e.toolCallId===i.messages.at(-1)?.toolCallId)??s[0];n.clientId=(c&&O.get(we(c.toolCallId))?.clientId)??ve;let l=e.pendingInteractions.flatMap(e=>{let t=O.get(we(e.toolCallId));return t&&e.sourceMessageId===c?.sourceMessageId?[{source_message_id:e.sourceMessageId,source_part_id:e.sourcePartId,response_target_id:e.responseTargetId,outcome:t.outcome,output:t.output}]:[]});if(l.length===0)return new Response(``,{headers:{"Content-Type":`text/event-stream`}});a=Pr(r.id),o={client_id:n.clientId,run_id:i.runId,...i.parentRunId?{parent_run_id:i.parentRunId}:{},results:l}}E.clear(),p({activeToolCallIds:[]});let u=new Headers(e.headers);if(c&&u.set(`Idempotency-Key`,c.key),!h(n))throw new DOMException(`Request cancelled`,`AbortError`);if(c&&!l){let e=oe(r.id),t={tools:i.tools,clientId:ve,dispatchedAt:Date.now(),draftFileIds:c.callbacks?.draftFileIds};if(c.delivery={...t,scope:e},e){let{id:n,key:r,content:i}=c;Nf(e,{save:{id:n,key:r,content:i,...t}})&&t.draftFileIds&&jf(e.apiUrl,e.identity,e.threadId,``,`sent`)}}let d=await mr(a,{...t,...e,headers:u,body:JSON.stringify(o)}).catch(e=>{if(!h(n))throw e;c&&!l&&cr(e)&&(e.status===400||e.status===413||e.status===429)&&(c.delivery?.scope&&Nf(c.delivery.scope,{clearKey:c.key}),c.delivery=void 0);let t=cr(e)?e.body?.usage_limit:void 0;throw t&&p({usageLimitReached:{name:t.name,resetsAt:t.resets_at}}),e});if(!h(n))throw new DOMException(`Request cancelled`,`AbortError`);if(d.headers.get(`Content-Type`)?.includes(`application/json`)){let e=await d.json();if(!h(n))throw new DOMException(`Request cancelled`,`AbortError`);if(p({thread:{...s.thread,version:e.thread_version},...e.usage_limit?{usageLimitReached:{name:e.usage_limit.name,resetsAt:e.usage_limit.resets_at}}:{}}),c){let i=await Cf(r.id,t,void 0,Se);if(!h(n))throw new DOMException(`Request cancelled`,`AbortError`);let a=i.messages.find(t=>t.id===e.accepted_message_id);a&&xe(a),be()}return new Response(``,{headers:{"Content-Type":`text/event-stream`}})}return d},He=od(()=>lr(xr(),x.apiUrl),async()=>{let e=f;if(!e||!h(e))throw new DOMException(`Request cancelled`,`AbortError`);let t=await k();if(!h(e))throw new DOMException(`Request cancelled`,`AbortError`);return{fetchClient:(n,r)=>Ve(r??{},{...t,signal:r?.signal??t.signal},e)}}),Ue=He.connect;He.connect=async function*(...e){try{for await(let t of Ue(...e)){if(t.type===X.TOOL_CALL_START&&t.parentMessageId&&Se.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=D.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&&cr(e.cause)?e.cause:e}};let We=()=>{let e=new hf({connection:{...He,hydrate:(t,n)=>{let r=M;if(!r)return Promise.resolve({messages:[],activeRun:null,interrupts:null,page:{truncated:!1}});let i=n?.before!==void 0,a=i?u?.owner:{client:e,selection:C},o=()=>a!==void 0&&u?.owner===a&&m(a),l=(async()=>{let t=await Cf(r,await k(),n?.before,Se);for(;n?.before&&t.messages.every(e=>e.role===`tool`)&&t.page_after;){let e=await Cf(r,await k(),t.page_after,Se);t={...e,messages:[...e.messages,...t.messages]}}if(!o())throw new DOMException(`Conversation changed`,`AbortError`);i||Te(t),T=i?[...t.messages,...T]:t.messages;let a=new Set(t.messages.map(e=>e.id)),l=wf(T,i?s.pendingInteractions:t.pendingInteractions,Se).filter(e=>a.has(e.id));if(_e(l),i)p({messagesCursor:t.page_after??void 0});else{t.thread.role===`viewer`&&Pe();let n=s.thread?.agentId!==t.thread.agent_id;c??=se(r),p({thread:xf(t.thread,t.messages.length>0),messagesCursor:t.page_after??void 0,pendingInteractions:t.pendingInteractions,submission:c&&v(c)}),n&&A(),l.length===0&&e.setMessagesManually([]);let i=c,{auth:a}=s;i?.phase===`failed`&&a.status===`ready`&&o()&&t.messages.some(e=>e.role===`user`&&e.client_message_id===i.id&&e.author_tenant_user_id===a.currentUser.user.id)&&be()}return{messages:l,activeRun:null,interrupts:null,page:t.page_after?{truncated:!0,cursor:t.page_after}:{truncated:!1}}})();if(!i&&a){let e=l.then(()=>`idle`,()=>`failed`).then(e=>(u&&o()&&(u.phase=e,P&&qe(),p({})),l));u={owner:a,phase:s.messages.length>0||s.thread?.hasMessages===!1?`refreshing`:`loading`,completion:e},e.catch(()=>void 0),p({olderMessagesLoading:!1})}return l}},threadId:M??ve,persistence:!0,history:{pageSize:100},queue:`drop`,tools:ze(),forwardedProps:Be(),onInterruptStateChange:t=>{N===e&&r?.(`tool`,`interrupt state changed`,t)},onCustomEvent:(t,n)=>{if(N!==e)return;if(t===`astralbeam_thread`){let e=n;if(s.thread?.id===e.threadId){if(c?.phase===`submitting`&&(e.acceptedMessage&&xe(e.acceptedMessage),e.acceptedMessageId&&be()),e.saved)for(let t of e.executableToolCallIds??[])E.has(t)||O.delete(we(t)),E.add(t);p({thread:{...s.thread,version:e.version},activeToolCallIds:[...E]})}return}if(t===`astralbeam_mcp_tools`){let e=n,t={};for(let n of e.tools??[])typeof n.name==`string`&&typeof n.title==`string`&&(t[n.name]=n.title);p({serverToolTitles:t,unavailableMcpConnections:e.unavailable??[]});return}let i=n;if(t===`astralbeam.usage_limit.reached`&&typeof i?.name==`string`&&typeof i.resetsAt==`string`){p({usageLimitReached:{name:i.name,resetsAt:i.resetsAt}});return}let a=n?.state;t===`astralbeam.sandbox.status`&&(a===`starting`||a===`ready`||a===`error`)?(r?.(`sandbox`,`sandbox ${a}`),p({sandboxStatus:a})):r?.(`stream`,`custom event "${t}"`,n)},onChunk:t=>{N===e&&(t.type===X.RUN_STARTED&&p({serverToolTitles:{},unavailableMcpConnections:[]}),n.streamCallbacks?.onChunk?.(t))},onResponse:t=>{N===e&&n.streamCallbacks?.onResponse?.(t)},onFinish:t=>{N===e&&n.streamCallbacks?.onFinish?.(t)},onError:t=>{N===e&&(c?.phase!==`submitting`&&t.name!==`AbortError`&&p({error:t}),Ee(t))}});return e},M,N=We(),P,Ge,Ke=-1,qe=()=>{let e=N.getSnapshot(),t=Ge!==e.messages||Ke!==he;if(!t&&d===e.status)return;let n={};d!==e.status&&e.status===`submitted`&&(n.usageLimitReached=void 0),d=e.status,t&&(n.messages=Ie(e.messages),n.sandbox=hp(n.messages),Ge=e.messages,Ke=he),p(n),t&&Le(s.messages)},Je=()=>{if(!P){let e=N,t=C;P=e.subscribeSnapshot(()=>{N===e&&t===C&&qe()}),qe(),Le(s.messages)}N.attach()},Ye=e=>{let t=N;f=void 0,u=void 0,P?.(),P=void 0,Ge=void 0,N=We(),e&&N.setMessagesManually(e),d=`ready`,t.stop(),t.detach(),E.clear(),p({activeToolCallIds:[]}),ce&&Je(),t.dispose()},Xe=()=>{D.clear(),N.setMessagesManually(N.getSnapshot().messages.map(e=>{let t=/* @__PURE__ */ new Map,n=e.parts.map(n=>{if(n.type!==`tool-call`||sp(n).providerExecuted)return n;let r=n,i=r.upstreamToolCallId??n.id;if(Se.get(i)===e.id&&!op(n))return n;let a=Sf(e.id,r.applicationPartId??i,r.responseTargetId);return t.set(i,a),{...n,upstreamToolCallId:i,id:a,...n.name===`render_widget`?{widgetRenderId:r.widgetRenderId??me.get(e.id)?.renderIds?.get(Sf(e.id,n.id))??n.id}:{}}});return t.size&&D.set(e.id,t),{...e,parts:n}}))},Ze=e=>{let t=s.thread?.id,n=b(`The conversation changed before this was sent.`);t&&(n?.phase===`failed`?l.set(t,n):l.delete(t),Ce.set(t,O)),C++,u=void 0,M=e,fe.abort(),fe=new AbortController,O=Ce.get(e??``)??/* @__PURE__ */ new Map,D.clear(),Se.clear(),T=[],me.clear(),ge=/* @__PURE__ */ new WeakMap,he++,Pe(),p({thread:void 0,messages:[],submission:void 0,error:void 0,sandbox:{files:[],commands:[]},sandboxStatus:void 0,usageLimitReached:void 0,pendingInteractions:[],serverToolTitles:{},unavailableMcpConnections:[],messagesCursor:void 0,olderMessagesLoading:!1}),Ye()},Qe=async(e,t=!1)=>{Ze(e);let r=C;c=l.get(e),c&&p({submission:v(c)});try{if(ce||Je(),await ue({client:N,selection:r}),r!==C)return;w&&Ef(w,e)}catch(e){if(r!==C)return;t&&(n.threadId===void 0||n.threadId===`auto`)&&cr(e)&&e.status===404?$e():De(e)}},$e=()=>{Ze(),ce&&A(),w?Ef(w,null):pe=!0},et=(e=!1)=>{let t=n.threadId;if(t===void 0||t===`auto`){if(!w)return;t=Ef(w)}t&&t!==`new`?t===s.thread?.id&&w?Ef(w,t):Qe(t,e):e||$e()},F=async e=>{if(s.thread)return;let t=await k();if(!ne(e))throw new DOMException(`Send cancelled`,`AbortError`);let r=await Tr(n.agentId?{agent_id:n.agentId}:{},t);if(!ne(e))throw new DOMException(`Send cancelled`,`AbortError`);M=r.id,p({thread:xf(r,!1)}),A(),w&&Ef(w,r.id)},tt=async(e=!0)=>{if(!M||N.getIsLoading())return;let t=C;try{N.detach(),Je(),await ue({client:N,selection:t}),e&&t===C&&p({error:void 0})}catch(e){if(t!==C)return;cr(e)&&e.status===404?$e():De(e)}},nt=async()=>{if(!N.getHasOlderMessages()||s.olderMessagesLoading||s.history!==`idle`||c?.phase===`submitting`)return;let e=C;p({olderMessagesLoading:!0});try{await N.loadOlderMessages(),e===C&&P&&qe()}catch(t){e===C&&De(t)}finally{e===C&&p({olderMessagesLoading:!1})}},I=async e=>{let t=s.thread;if(!t||t.role!==`manager`)return!1;let n=C;try{let r=await kr(t.id,{title:e,expected_version:t.version},await k());if(n!==C)return!1;let i=xf(r,t.hasMessages);return p({thread:i}),!0}catch(e){return n===C&&De(e),!1}},rt=async(e=s.thread)=>{if(!e||e.role!==`manager`)return!1;let t=C;try{return await jr(e.id,{expected_version:String(e.version)},await k()),t===C&&s.thread?.id===e.id&&$e(),!0}catch(e){return t===C&&De(e),!1}},it=async e=>{let t=C;if(f||c?.phase===`submitting`||N.getIsLoading()){De(/* @__PURE__ */ Error(`Wait for this client's current request to finish before responding.`));return}let n=Kf(x),r=we(e.toolCallId),i=s.pendingInteractions.find(t=>t.toolCallId===e.toolCallId),a=!(`tool`in e)&&i&&(s.thread?.role===`manager`||n.status===`ready`&&i.targetTenantUserId===n.currentUser.user.id),o=`tool`in e&&e.tool===`ask_questionnaire`&&n.status===`ready`&&i?.targetTenantUserId===n.currentUser.user.id;if(s.thread?.role===`viewer`||!E.has(e.toolCallId)&&!o&&!a&&!O.has(r)){De(/* @__PURE__ */ Error(`This tool call belongs to another session and cannot be executed here.`));return}if(!O.has(r)){if(a)O.set(r,{outcome:`unknown`,output:null});else if(`tool`in e){let t=e.output;O.set(r,{outcome:e.state===`output-error`?`failed`:`succeeded`,output:t??null})}}let l={kind:`tool-result`,client:N,selection:t};f=l;try{if(p({}),!h(l)||(Xe(),!h(l)))return;if(i){if(l.client.stop(),await tt(!1),!h(l))return;await l.client.append({role:`tool`,toolCallId:e.toolCallId,content:JSON.stringify(O.get(we(e.toolCallId)))})}else`tool`in e&&await l.client.addToolResult(e);h(l)&&await tt(!1)}finally{g(l)}},at=e=>it({toolCallId:e}),ot=async e=>{if(e!==c||e.phase!==`submitting`)return v(e);let t={kind:`submission`,submission:e,client:N,selection:C};f=t;try{if(await Qf(x),!await de(t)||(await F(t),!ne(t))||(e.callbacks?.onThreadReady?.(s.thread.id),!ne(t))||(Xe(),!await de(t)))return v(e);if(typeof e.content!=`string`||e.content.trim()){let n=typeof e.content==`string`?{content:e.content}:e.content;await t.client.sendMessage({...n,metadata:{...n.metadata,astralbeamSubmissionId:e.id}})}if(!te(t))return v(e);re(e,t.client.getError()),te(t)&&await tt(!1)}catch(n){if(!te(t))return v(e);let r=n instanceof Error?n:Error(String(n));r.name===`AbortError`?re(e):re(e,r)&&Ee(r)}finally{g(t)}return v(e)},st=async(e,t)=>{let n=f||c?.phase===`submitting`||N.getIsLoading()?`Wait for this client's current request to finish before sending.`:s.history===`loading`?`Wait for this conversation to load before sending.`:s.history===`failed`?gp: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:bf(),content:e,phase:`refused`,error:Error(n)};let r={id:bf(),content:e,phase:`submitting`,key:bf(),callbacks:t};c=r,p({submission:v(r),error:void 0,olderMessagesLoading:!1}),N.stop(),E.clear(),Xe(),Se.clear(),p({activeToolCallIds:[]});let i=new Promise(e=>r.onRefused=e);return Promise.race([ot(r),i.then(()=>v(r))])},ct=async()=>{let e=c;if(!(f||N.getIsLoading()||e?.phase!==`failed`)){if(_(e.delivery)){e.error=/* @__PURE__ */ Error(vp);let t=v(e);return p({submission:t}),t}if(y(e,`submitting`))return p({error:void 0}),ot(e)}},lt=()=>{let e=Kf(x),t=s.auth;if(e.status===`ready`){let t=Xf(e.currentUser);S!==void 0&&S!==t&&(b(`The account changed before this was sent.`),l.clear(),Ce.clear(),O.clear(),Ze(),w=void 0),S=t;let r=JSON.stringify(Tf(n)),i=`astralbeam:thread:${n.apiUrl??`https://astralbeam.ai/api`}:${t}:session:${r}`;w!==i&&(w!==void 0&&Ze(),w=i,pe?(Ef(i,null),pe=!1):et(!0)),Ae!==t&&(Ae=t,A())}p({auth:e}),e.status===`error`&&(t.status!==`error`||t.error!==e.error)&&n.streamCallbacks?.onError?.(e.error)},ut=()=>{if(ce)return;ce=!0;let e=fe.signal.aborted&&N.getIsHydrating();N.updateOptions({tools:ze()}),fe.signal.aborted&&(fe=new AbortController),ae=qf(x,lt),lt(),ie=rp(x),e?Ye(N.getSnapshot().messages):Je()};return t||ut(),{start:ut,getState:()=>s,getOptions:()=>n,attachView:e=>{if(a)throw Error(`This chat session already has a view attached`);let t={options:e},n=()=>{N.updateOptions({tools:ze()}),Le(s.messages)};return Pe(),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&&(Pe(),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=Tf(n),{widgets:c,onRenderWidget:u}=n;n={...n,...e};let d=Tf(n)!==o;r=yf(n.debug),Yf(x,{apiUrl:n.apiUrl,fetchAstralBeamToken:n.fetchAstralBeamToken??{url:`/api/astralbeam/token`}}),x.debug=r,N.updateOptions({tools:ze(),forwardedProps:Be()}),n.apiUrl===i?d?(pe=!1,s.thread&&n.threadId===s.thread.id||Ze(),w=void 0,lt()):n.threadId!==a&&et():(b(`The chat service changed before this was sent.`),l.clear(),Ce.clear(),O.clear(),Ze(),w=void 0,lt()),(c!==n.widgets||u!==n.onRenderWidget)&&Le(s.messages),ce&&(n.agentId!==t||n.apiUrl!==i||d)&&A()},sendMessage:st,retry:ct,addToolResult:it,stop:()=>{le++;let e=c,t=f;e?.phase===`submitting`&&re(e),N.stop(),t&&g(t),e?.phase===`refused`&&e.onRefused?.()},retryAuthentication:()=>{Qf({...x,force:!0}).catch(()=>void 0)},reload:async()=>{if(N.getIsLoading())return;let e=C;if(await tt(),e!==C||s.error)return;let t=/* @__PURE__ */ new Set;for(;e===C;){let e=s.pendingInteractions.find(e=>!t.has(e.sourceMessageId)&&O.has(we(e.toolCallId)));if(!e||(t.add(e.sourceMessageId),await it({toolCallId:e.toolCallId}),s.error))return}},searchThreads:async(e=``,t,n)=>{let r=await k(),i=await Dr({q:e,page_size:50,...t?{page_after:t}:{}},{...r,signal:AbortSignal.any([r.signal,...n?[n]:[]])});return{items:i.items.map(e=>xf(e)),page_after:i.page_after}},openThread:Qe,renameThread:I,deleteThread:rt,refreshThread:()=>tt(),loadOlderMessages:nt,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 vr({...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 br({...e,delivery:`direct`},{...await k(!!e.threadId||!t?.preview),headers:t?.preview?{"X-File-Preview":`true`}:{}})).blob()},getMcpCatalog:async()=>Rr(await k(!1)),manageMcpConnection:async e=>{let t=await ip(e,await k(!1));return`id`in e?Oe(e.id):t&&`id`in t&&Oe(t.id),t},authorizeMcpConnection:async e=>{let t=await ap(e,()=>k(!1));Oe(t)},abandonToolCall:at,reset:()=>{if(r?.(`status`,`conversation reset`),$e(),s.auth.status===`ready`){let e=Of(Xf(s.auth.currentUser),n),t=n.apiUrl??`https://astralbeam.ai/api`;jf(t,e,``,``),jf(t,e,``,``,`sent`),Pf({apiUrl:t,identity:e,threadId:``,update:()=>[]}).catch(e=>r?.(`error`,`Draft could not be cleared`,e))}a?.options.onReset()},dispose:()=>{b(`The chat closed before this was sent.`),f=void 0,u=void 0,P?.(),P=void 0,N.detach(),Pe(),N.stop(),fe.abort(),C++,ke++,Ae=void 0,ie?.(),ae?.(),tp(x),ce=!1,queueMicrotask(()=>{ce||(N.dispose(),w=void 0,me.clear(),ge=/* @__PURE__ */ new WeakMap)}),i.clear()}}}const xp=e=>e[Symbol.toStringTag],Sp=(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 Cp(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(Za(t)){if(o=Ip(t),typeof o.kty!=`string`)throw Ap(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(Sp(e,o,n),o.kty===`oct`)return Ya(o.k);if(!Object.isFrozen(t)){let{key_ops:e}=t;Array.isArray(e)&&Object.freeze(e),Object.freeze(t)}}else{if(!Op(t))throw Ap(r,t,i);let e=i?`secret`:a?`private`:`public`;if(t.type!==e&&(i||[`secret`,`public`,`private`].includes(t.type)))throw TypeError(`${xp(t)} instances must be of type "${e}" for the ${r} algorithm`);if(Ep(t))return t;if(s=t,s.type===`secret`)return s.export()}wp||=/* @__PURE__ */ new WeakMap;let c=t,l=wp.get(c);if(l?.[r])return l[r];if(l||wp.set(c,l={}),s&&typeof s.toCryptoKey==`function`){let t=s.type===`public`,n=Tp[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 Lp(e,o)}let wp;const Tp={__proto__:null,prime256v1:`P-256`,secp384r1:`P-384`,secp521r1:`P-521`},Ep=e=>{if(e?.[Symbol.toStringTag]===`CryptoKey`)return!0;try{return e instanceof CryptoKey}catch{return!1}},Dp=e=>e?.[Symbol.toStringTag]===`KeyObject`,Op=e=>Ep(e)||Dp(e);function kp(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 Ap(e,t,n){let r=[`CryptoKey`,`KeyObject`,`JSON Web Key`];return n&&r.push(`Uint8Array`),TypeError(kp(`Key for the ${e} algorithm must be `,t,...r))}const jp=(e,t=`algorithm.name`)=>/* @__PURE__ */ TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function Mp(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function Np(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 Pp(e,t,n){let r=e.algorithm;if(r.name!==t.name)throw jp(t.name);if(t.hash&&r.hash?.name!==t.hash)throw jp(t.hash,`algorithm.hash`);if(t.namedCurve&&r.namedCurve!==t.namedCurve)throw jp(t.namedCurve,`algorithm.namedCurve`);if(t.length!==void 0&&r.length!==t.length)throw jp(t.length,`algorithm.length`);Mp(e,n)}function Fp(e){return{__proto__:null,...e}}function Ip(e){let t=Fp(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 Lp(e,t,n){if(!e.kty.includes(t.kty))throw new Ka(`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 Rp(e,t,n,r=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey(`raw`,e,t,r,[n])),Pp(e,t,n),e}function zp(e){let t={__proto__:null};for(let n in e)t[n]={...e[n],alg:n};return t}const Bp=[[`verify`],[`sign`]];function Vp(e){let t={name:`HMAC`,hash:`SHA-${e}`};return{kty:[`oct`],secret:!0,subtle:t,signing:t,usages:Bp}}function Hp(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:Bp,minRsaBits:2048}}function Up(e,t){return{kty:[`EC`],crv:e,subtle:{name:`ECDSA`,namedCurve:e},signing:{name:`ECDSA`,hash:`SHA-${t}`},usages:Bp}}function Wp(){let e={name:`Ed25519`};return{kty:[`OKP`],crv:`Ed25519`,subtle:e,signing:e,usages:Bp}}function Gp(e){let t={name:`ML-DSA-${e}`};return{kty:[`AKP`],subtle:t,signing:t,usages:Bp}}const Kp=zp({HS256:Vp(256),HS384:Vp(384),HS512:Vp(512),RS256:Hp(256),RS384:Hp(384),RS512:Hp(512),PS256:Hp(256,32),PS384:Hp(384,48),PS512:Hp(512,64),ES256:Up(`P-256`,256),ES384:Up(`P-384`,384),ES512:Up(`P-521`,512),EdDSA:Wp(),Ed25519:Wp(),"ML-DSA-44":Gp(44),"ML-DSA-65":Gp(65),"ML-DSA-87":Gp(87)});function qp(e){let t=typeof e==`string`?Kp[e]:void 0;if(!t)throw new Ka(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}const Jp=e=>Math.floor(e.getTime()/1e3),Yp={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},Xp=/^(\+|\-)? ?(\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 Qp(e){typeof e!=`string`&&Zp();let t=Xp.exec(e);(!t||t[4]&&t[1])&&Zp();let n=parseFloat(t[2]),r=Math.round(n*Yp[t[3][0].toLowerCase()]);return Number.isFinite(r)||Zp(),t[1]===`-`||t[4]===`ago`?-r:r}function $p(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}function em(e,t){if(typeof t!=`string`)throw TypeError(`"${e}" claim must be a string`)}function tm(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 nm(e,t){return typeof e==`number`?$p(t,e):e instanceof Date?$p(t,Jp(e)):Jp(/* @__PURE__ */ new Date)+Qp(e)}let rm;function im(e){return rm.get(e)}function am(e){let t=im(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 La.encode(JSON.stringify(t))}var om=class{constructor(e={}){if(!Za(e))throw TypeError(`JWT Claims Set MUST be an object`);(rm||=/* @__PURE__ */ new WeakMap).set(this,structuredClone(e))}setIssuer(e){return em(`iss`,e),im(this).iss=e,this}setSubject(e){return em(`sub`,e),im(this).sub=e,this}setAudience(e){return tm(e),im(this).aud=e,this}setJti(e){return em(`jti`,e),im(this).jti=e,this}setNotBefore(e){return im(this).nbf=nm(e,`setNotBefore`),this}setExpirationTime(e){return im(this).exp=nm(e,`setExpirationTime`),this}setIssuedAt(e){let t=im(this);return t.iat=e===void 0?Jp(/* @__PURE__ */ new Date):typeof e==`string`?$p(`setIssuedAt`,Jp(/* @__PURE__ */ new Date)+Qp(e)):nm(e,`setIssuedAt`),this}};async function sm(e,t,n){let[r,i,a,o]=e,s=``;if(i!==void 0){let e=io(qa,i);i=e[0],s=Xa(e[1])}if(a!==void 0&&(a=io(qa,a)[0]),!i&&!a)throw new qa(`either setProtectedHeader or setUnprotectedHeader must be called before #sign()`);if(!Qa(i,a))throw new qa(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let c={...i,...a};to(qa,i);let l=ro(i,no(qa,eo,o,i,c));l||n?.();let{alg:u}=c;if(typeof u!=`string`||!u)throw new qa(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);let d=qp(u),f=``,p=r,m;if(l){let t=e[4];t?(f=t[0]??=Xa(r),p=t[1]??=Ha(f)):(f=Xa(r),m=La.encode(`${s}.${f}`))}m??=Ba(Ha(s),Ha(`.`),p);let h=await Rp(await Cp(d,t,`sign`),d.subtle,`sign`);d.minRsaBits&&Np(d.alg,h);let g={signature:Xa(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 cm(e,t,n,r,i){let[a]=await sm([e,t,void 0,n],r,i);return`${a.protected}.${a.payload}.${a.signature}`}const lm=om;var um=class extends lm{#e;setProtectedHeader(e){return $a(this.#e,`setProtectedHeader`),this.#e=e,this}async sign(e,t){return cm(am(this),this.#e,t?.crit,e,()=>{throw new Ja(`JWTs MUST NOT use unencoded payload`)})}};const dm=`astralbeam`,fm=16384,pm=8192,mm=/^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}$/,hm=/^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}$/,gm=[`id`,`name`,`metadata`],_m=[`id`,`name`,`admin`,`metadata`],vm=new TextEncoder;function ym(e){if(!mm.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 bm(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function xm(e){return e===null||typeof e==`string`||typeof e==`boolean`?!0:typeof e==`number`?Number.isFinite(e):Array.isArray(e)?e.every(xm):bm(e)&&Object.values(e).every(xm)}function Sm(e,t,n){if(!bm(t))throw Error(`${e} must be an object`);let r=n?_m:gm;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&&!(bm(s)&&xm(s)))throw Error(`${e}.metadata must be a JSON object`)}function Cm(e,t){Sm(`user`,e,!0),Sm(`tenant`,t,!1);let n=JSON.stringify({user:e,tenant:t});if(vm.encode(n).byteLength>pm)throw Error(`user and tenant must not exceed ${pm} bytes`);return JSON.parse(n)}async function wm(e){let t=await crypto.subtle.digest(`SHA-256`,vm.encode(e));return vm.encode(Xa(new Uint8Array(t)))}async function Tm({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}=ym(e);if(n!==a)throw Error(`organizationId must match the API key organization`);let s=Math.floor(Date.now()/1e3);return await new um({ver:1,email:t,organization_id:n}).setProtectedHeader({alg:`HS256`,typ:`astralbeam-organization+jwt`,kid:i}).setIssuer(n).setAudience(dm).setIssuedAt(s).setExpirationTime(s+r).sign(await wm(o))}async function Em({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}=ym(e),c=Cm(t,n);if(r!==void 0&&(!Array.isArray(r)||r.length>20||!r.every(e=>typeof e==`string`&&hm.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 um({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(dm).setIssuedAt(l).setExpirationTime(l+i).sign(await wm(s));if(vm.encode(u).byteLength>fm)throw Error(`chat auth tokens must not exceed ${fm} bytes`);return u}function Dm(e){return e.string([`tenant`,`user`,`tenant-name`,`user-name`]).demandOption([`tenant`,`user`]).boolean(`admin`).number(`expires-in`).coerce(`expires-in`,rr).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 Om(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 km(e,t,n){let r=new Date(Date.now()+t*1e3).toISOString();n?ei({token:e,expires_at:r}):s.write(`${e}\n`)}function Am(e){return e.command(`chat`,`Mint a chat JWT for a Tenant's user, as a token endpoint would`,Dm,async e=>{let{apiKey:t}=await wi(),n=e.expiresIn??300;km(await Em({apiKey:t,expiresInSeconds:n,...Om(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`,rr).describe({email:`email of an existing member of the organization`,"expires-in":`token lifetime, 60-600 (default 300)`}),async e=>{let{apiKey:t}=await wi(),n=e.expiresIn??300;km(await Tm({apiKey:t,email:e.email,organizationId:di(t),expiresInSeconds:n}),n,K.json)}),e.demandCommand(1)}function jm(e){return e.filter(e=>e.role===`assistant`).map(e=>e.parts.map(e=>e.type===`text`?e.content:``).join(``)).filter(Boolean).join(`
153
+
154
+ `)}async function Mm(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=jm(t);c.startsWith(i)&&(s.write(ti(c.slice(i.length),`
155
+ `)),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 ${ti(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?ei({messages:u.slice(r)}):i.endsWith(`
156
156
  `)||s.write(`
157
- `)}async function Tm(e){let t=E({input:o,output:s});a.write(`Type a message, or /exit to quit.
158
- `);try{for(;;){let n=(await t.question(`> `).catch(()=>`/exit`)).trim();if(n===`/exit`)return;n&&await wm(e,n,!1)}}finally{t.close()}}function Em(e){e.command(`chat [message]`,`Chat with an agent as one of a Tenant's users, like the embedded widget`,e=>ym(e).positional(`message`,{type:`string`,description:`message to send (default: stdin when piped, else an interactive prompt)`}).option(`agent`,{type:`string`,description:`public agent ID (default: the organization's default agent)`}),async e=>{let{json:t,message:n}=e,{apiKey:r,apiUrl:i}=await xi(),a=e.expiresIn??300,s=bm(e),c=fp({apiUrl:i,...e.agent===void 0?{}:{agentId:e.agent},fetchAstralBeamToken:async()=>({token:await vm({apiKey:r,expiresInSeconds:a,...s})})});try{if(n!==void 0)await wm(c,n,t);else if(!o.isTTY)await wm(c,(await ue(o)).trim(),t);else if(t)throw new er(`Pass a message or pipe one on stdin with --json.`);else await Tm(c)}finally{c.dispose()}})}const Dm=new URL(`skills/astralbeam/SKILL.md`,import.meta.url);function Om(e){return e.command({command:`$0`,describe:!1,handler:async()=>{let e=await b(Dm,`utf8`);K.json?ni({content:e},!0):s.write(e)}}),e.command(`install`,`Write the skill to <dir>/astralbeam/SKILL.md`,e=>e.option(`dir`,{type:`string`,default:`.agents/skills`,description:`skills directory relative to the current directory, or an absolute path`}),async e=>{let t=ce(e.dir,`astralbeam`);await re(t,{recursive:!0});let n=se(t,`SKILL.md`);await C(n,await b(Dm,`utf8`)),K.json||a.write(`Restart your agent session to load the skill.
159
- `),ni({path:n},K.json)}),e}const km=`
157
+ `)}async function Nm(e){let t=T({input:o,output:s});a.write(`Type a message, or /exit to quit.
158
+ `);try{for(;;){let n=(await t.question(`> `).catch(()=>`/exit`)).trim();if(n===`/exit`)return;n&&await Mm(e,n,!1)}}finally{t.close()}}function Pm(e){e.command(`chat [message]`,`Chat with an agent as one of a Tenant's users, like the embedded widget`,e=>Dm(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 wi(),a=e.expiresIn??300,s=Om(e),c=bp({apiUrl:i,...e.agent===void 0?{}:{agentId:e.agent},fetchAstralBeamToken:async()=>({token:await Em({apiKey:r,expiresInSeconds:a,...s})})});try{if(n!==void 0)await Mm(c,n,t);else if(!o.isTTY)await Mm(c,(await pe(o)).trim(),t);else if(t)throw new nr(`Pass a message or pipe one on stdin with --json.`);else await Nm(c)}finally{c.dispose()}})}const Fm=new URL(`skills/astralbeam/SKILL.md`,import.meta.url);function Im(e){return e.command({command:`$0`,describe:!1,handler:async()=>{let e=await b(Fm,`utf8`);K.json?ii({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=ue(e.dir,`astralbeam`);await re(t,{recursive:!0});let n=le(t,`SKILL.md`);await oe(n,await b(Fm,`utf8`)),K.json||a.write(`Restart your agent session to load the skill.
159
+ `),ii({path:n},K.json)}),e}const Lm=`
160
160
  Environment:
161
161
  ASTRALBEAM_API_KEY organization API key, used instead of directory logins
162
- ASTRALBEAM_API_URL override the saved API URL (default ${oi})
162
+ ASTRALBEAM_API_URL override the saved API URL (default ${ci})
163
163
  ASTRALBEAM_CONFIG_DIR directory holding config.json
164
164
 
165
165
  Exit codes: 0 success, 1 API or runtime failure, 2 parser usage errors.
166
- Docs: https://astralbeam.ai/docs/cli/getting-started`;async function Am(e){let t=e.includes(`--debug`),n=$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).middleware(e=>{K.json=e.json},!0).fail((e,t,n)=>{throw n.parsed&&(K.json=n.parsed.argv.json===!0),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(n),Object.assign(K,{json:!1,context:void 0,failedRequest:void 0});let r=globalThis.fetch;globalThis.fetch=jm(r,t);try{return(await n.parseAsync()).json&&a.write(`${JSON.stringify({context:K.context??null})}\n`),0}catch(e){return t&&e instanceof Error&&a.write(`[debug] ${e.stack}\n`),ai(e,K.json,K.context,K.failedRequest),e instanceof er?2:1}finally{globalThis.fetch=r}}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};
166
+ Docs: https://astralbeam.ai/docs/cli/getting-started`;async function Rm(e){let t=e.includes(`--debug`),n=tr(e.slice(2)).scriptName(`astralbeam`).version($r).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).middleware(e=>{K.json=e.json},!0).fail((e,t,n)=>{throw n.parsed&&(K.json=n.parsed.argv.json===!0),new nr(e||t?.message||`Invalid command.`)}).epilog(Lm).alias(`q`,`search`).command(Object.values(ja)).command(`auth`,`Bind organization API keys to directories, and check them`,Ia).command(`token`,`Mint short-lived JWTs offline with the organization API key`,Am).command(`skill`,`Print or install the AstralBeam integration skill`,Im);Pm(n),Object.assign(K,{json:!1,context:void 0,failedRequest:void 0});let r=globalThis.fetch;globalThis.fetch=zm(r,t);try{return(await n.parseAsync()).json&&a.write(`${JSON.stringify({context:K.context??null})}\n`),0}catch(e){return t&&e instanceof Error&&a.write(`[debug] ${e.stack}\n`),si(e,K.json,K.context,K.failedRequest),e instanceof nr?2:1}finally{globalThis.fetch=r}}function zm(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{Rm as run};