@astralbeam/cli 0.30.7 → 0.31.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/astralbeam.js +1 -1
- package/dist/program-Bt_1l2HJ.js +166 -0
- package/package.json +5 -6
- package/dist/program-CN-qLnwE.js +0 -166
|
@@ -0,0 +1,166 @@
|
|
|
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:D};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&&O.stringWidth(e[0])>n&&(n=Math.min(Math.floor(this.width*.5),O.stringWidth(e[0])))}),t.forEach(e=>{this.div(...e.map((t,r)=>({text:t.trim(),padding:this.measurePadding(t),width:r===0&&e.length>1?n:void 0})))}),this.rows[this.rows.length-1]}colFromString(e){return{text:e,padding:this.measurePadding(e)}}measurePadding(e){let t=O.stripAnsi(e);return[0,t.match(/\s*$/)[0].length,0,t.match(/^\s*/)[0].length]}toString(){let e=[];return this.rows.forEach(t=>{this.rowToString(t,e)}),e.filter(e=>!e.hidden).map(e=>e.text).join(`
|
|
3
|
+
`)}rowToString(e,t){return this.rasterize(e).forEach((n,r)=>{let i=``;n.forEach((n,a)=>{let{width:o}=e[a],s=this.negatePadding(e[a]),c=n;if(s>O.stringWidth(n)&&(c+=` `.repeat(s-O.stringWidth(n))),e[a].align&&e[a].align!==`left`&&this.wrap){let t=_e[e[a].align];c=t(c,s),O.stringWidth(c)<s&&(c+=` `.repeat((o||0)-O.stringWidth(c)-1))}let l=e[a].padding||[0,0,0,0];l[3]&&(i+=` `.repeat(l[3])),i+=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=O.stringWidth(i.trimRight());return t.span?this.wrap?r<a?e:(t.hidden=!0,i.trimRight()+` `.repeat(r-a)+e.trimLeft()):(t.hidden=!0,i+e):e}rasterize(e){let t=[],n=this.columnWidths(e),r;return e.forEach((e,i)=>{e.width=n[i],r=this.wrap?O.wrap(e.text,this.negatePadding(e),{hard:!0}).split(`
|
|
4
|
+
`):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||O.stringWidth(e.text));let t=e.length,n=this.width,r=e.map(e=>{if(e.width)return t--,n-=e.width,e.width}),i=t?Math.floor(n/t):0;return r.map((t,n)=>t===void 0?Math.max(i,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=O.stringWidth(e);return n<t?` `.repeat(t-n)+e:e}function D(e,t){e=e.trim();let n=O.stringWidth(e);return n>=t?e:` `.repeat(t-n>>1)+e}let O;function k(e,t){return O=t,new ve({width:e?.width||xe(),wrap:e?.wrap})}const Se=/* @__PURE__ */ RegExp(`\x1B(?:\\[(?:\\d+[ABCDEFGJKSTm]|\\d+;\\d+[Hfm]|\\d+;\\d+;\\d+m|6n|s|u|\\?25[lh])|\\w)`,`g`);function Ce(e){return e.replace(Se,``)}function we(e,t){let[n,r]=e.match(Se)||[``,``];e=Ce(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 Te(e){return k(e,{stringWidth:e=>[...e].length,stripAnsi:Ce,wrap:we})}function Ee(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
|
+
/**
|
|
8
|
+
* @license
|
|
9
|
+
* Copyright (c) 2016, Contributors
|
|
10
|
+
* SPDX-License-Identifier: ISC
|
|
11
|
+
*/
|
|
12
|
+
function De(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 A(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 Oe(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
|
+
/**
|
|
14
|
+
* @license
|
|
15
|
+
* Copyright (c) 2016, Contributors
|
|
16
|
+
* SPDX-License-Identifier: ISC
|
|
17
|
+
*/
|
|
18
|
+
function ke(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
|
+
/**
|
|
20
|
+
* @license
|
|
21
|
+
* Copyright (c) 2016, Contributors
|
|
22
|
+
* SPDX-License-Identifier: ISC
|
|
23
|
+
*/
|
|
24
|
+
var j;(function(e){e.BOOLEAN=`boolean`,e.STRING=`string`,e.NUMBER=`number`,e.ARRAY=`array`})(j||={});
|
|
25
|
+
/**
|
|
26
|
+
* @license
|
|
27
|
+
* Copyright (c) 2016, Contributors
|
|
28
|
+
* SPDX-License-Identifier: ISC
|
|
29
|
+
*/
|
|
30
|
+
let M;var Ae=class{constructor(e){M=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=ke(e),i=typeof e==`string`,a=je(Object.assign(Object.create(null),n.alias)),o=Object.assign({"boolean-negation":!0,"camel-case-expansion":!0,"combine-arrays":!1,"dot-notation":!0,"duplicate-arguments-array":!0,"flatten-duplicate-arrays":!0,"greedy-arrays":!0,"halt-at-non-option":!1,"nargs-eats-options":!1,"negation-prefix":`no-`,"parse-numbers":!0,"parse-positional-numbers":!0,"populate--":!1,"set-placeholder-key":!1,"short-option-groups":!0,"strip-aliased":!1,"strip-dashed":!1,"unknown-options-as-args":!1},n.configuration),s=Object.assign(Object.create(null),n.default),c=n.configObjects||[],l=n.envPrefix,u=o[`populate--`],d=u?`--`:`_`,f=Object.create(null),p=Object.create(null),m=n.__||M.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;D();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=>De(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 De(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`?M.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=Pe(t)),(T(e,h.bools)||T(e,h.counts))&&typeof t==`string`&&(t=t===`true`);let r=Array.isArray(t)?t.map(function(t){return S(e,t)}):S(e,t);return T(e,h.counts)&&(E(r)||typeof r==`boolean`)&&(r=Me()),T(e,h.normalize)&&T(e,h.arrays)&&(r=Array.isArray(t)?t.map(e=>M.normalize(e)):M.normalize(t)),r}function S(e,t){return!o[`parse-positional-numbers`]&&e===`_`||!T(e,h.strings)&&!T(e,h.bools)&&!Array.isArray(t)&&(Oe(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=M.resolve(M.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=M.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=M.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)),De(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=Ne(e),typeof r==`object`&&r[e]===void 0&&(r[e]={}),typeof r[e]!=`object`||Array.isArray(r[e])?(Array.isArray(r[e])?r[e].push({}):r[e]=[r[e],{}],r=r[e][r[e].length-1]):r=r[e]});let i=Ne(t[t.length-1]),a=T(t.join(`.`),h.arrays),s=Array.isArray(n),c=o[`duplicate-arguments-array`];!c&&T(i,h.nargs)&&(c=!0,(!E(r[i])&&h.nargs[i]===1||Array.isArray(r[i])&&r[i].length===h.nargs[i])&&(r[i]=void 0)),n===Me()?r[i]=Me(r[i]):Array.isArray(r[i])?c&&a&&s?r[i]=o[`flatten-duplicate-arrays`]?r[i].concat(n):(Array.isArray(r[i][0])?r[i]:[r[i]]).concat([n]):!c&&!!a==!!s?r[i]=n:r[i]=r[i].concat([n]):r[i]===void 0&&a?r[i]=s?n:[n]:c&&!(r[i]===void 0||T(i,h.counts)||T(i,h.bools))?r[i]=[r[i],n]:r[i]=n}function pe(...e){e.forEach(function(e){Object.keys(e||{}).forEach(function(e){h.aliases[e]||(h.aliases[e]=[].concat(a[e]||[]),h.aliases[e].concat(e).forEach(function(t){if(/-/.test(t)&&o[`camel-case-expansion`]){let n=De(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=A(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{[j.BOOLEAN]:!0,[j.STRING]:``,[j.NUMBER]:void 0,[j.ARRAY]:[]}[e]}function xe(e){let t=j.BOOLEAN;return T(e,h.strings)?t=j.STRING:T(e,h.numbers)?t=j.NUMBER:T(e,h.bools)?t=j.BOOLEAN:T(e,h.arrays)&&(t=j.ARRAY),t}function E(e){return e===void 0}function D(){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 je(e){let t=[],n=Object.create(null),r=!0;for(Object.keys(e).forEach(function(n){t.push([].concat(e[n],n))});r;){r=!1;for(let e=0;e<t.length;e++)for(let n=e+1;n<t.length;n++)if(t[e].filter(function(e){return t[n].indexOf(e)!==-1}).length){t[e]=t[e].concat(t[n]),t.splice(n,1),r=!0;break}}return t.forEach(function(e){e=e.filter(function(e,t,n){return n.indexOf(e)===t});let t=e.pop();t!==void 0&&typeof t==`string`&&(n[t]=e)}),n}function Me(e){return e===void 0?1:e+1}function Ne(e){return e===`__proto__`?`___proto___`:e}function Pe(e){return typeof e==`string`&&(e[0]===`'`||e[0]===`"`)&&e[e.length-1]===e[0]?e.substring(1,e.length-1):e}
|
|
31
|
+
/**
|
|
32
|
+
* @fileoverview Main entrypoint for libraries using yargs-parser in Node.js
|
|
33
|
+
* CJS and ESM environments.
|
|
34
|
+
*
|
|
35
|
+
* @license
|
|
36
|
+
* Copyright (c) 2016, Contributors
|
|
37
|
+
* SPDX-License-Identifier: ISC
|
|
38
|
+
*/
|
|
39
|
+
const Fe=process&&process.env&&process.env.YARGS_MIN_NODE_VERSION?Number(process.env.YARGS_MIN_NODE_VERSION):12,Ie=(process==null?void 0:process.versions)?.node??(process==null?void 0:process.version)?.slice(1);if(Ie&&Number(Ie.match(/^([^.]+)/)[1])<Fe)throw Error(`yargs parser supports a minimum Node.js version of ${Fe}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`);const Le=process?process.env:{},Re=new Ae({cwd:process.cwd,env:()=>Le,format: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`)}}),ze=function(e,t){return Re.parse(e.slice(),t).argv};ze.detailed=function(e,t){return Re.parse(e.slice(),t)},ze.camelCase=De,ze.decamelize=A,ze.looksLikeNumber=Oe;function Be(){return+!Ve()}function Ve(){return He()&&!process.defaultApp}function He(){return!!process.versions.electron}function Ue(){return process.argv[Be()]}var N=class e extends Error{constructor(t){super(t||`yargs error`),this.name=`YError`,Error.captureStackTrace&&Error.captureStackTrace(this,e)}},P={fs:{readFileSync:g,writeFile:ee},format:y,resolve:h,exists:e=>{try{return v(e).isFile()}catch{return!1}}};let F;var We=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(),F.format.apply(F.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),F.format.apply(F.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);F.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{F.fs.readFileSync&&(e=JSON.parse(F.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=F.resolve(e,`./`,t+`.json`);if(this.fallbackToLanguage&&!this._fileExistsSync(n)&&~t.lastIndexOf(`_`)){let r=F.resolve(e,`./`,t.split(`_`)[0]+`.json`);this._fileExistsSync(r)&&(n=r)}return n}_fileExistsSync(e){return F.exists(e)}};function Ge(e,t){F=t;let n=new We(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 Ke=e=>Ge(e,P),qe=`loading a directory of commands is not supported yet for ESM`;let Je;try{Je=ne(import.meta.url)}catch{Je=process.cwd()}const Ye=Je.substring(0,Je.lastIndexOf(`node_modules`));var Xe={assert:{notStrictEqual:c,strictEqual:l},cliui:Te,findUp:Ee,getEnv:e=>process.env[e],inspect:te,getCallerFile:()=>{throw new N(qe)},getProcessArgvBin:Ue,mainFilename:Ye||process.cwd(),Parser:ze,path:{basename:u,dirname:d,extname:f,relative:m,resolve:h},process:{argv:()=>process.argv,cwd:process.cwd,emitWarning:(e,t)=>process.emitWarning(e,t),execPath:()=>process.execPath,exit:process.exit,nextTick:process.nextTick,stdColumns:process.stdout.columns===void 0?null:process.stdout.columns},readFileSync:g,require:()=>{throw new N(`require is not supported by ESM`)},requireDirectory:()=>{throw new N(qe)},stringWidth:e=>[...e].length,y18n:Ke({directory:h(Je,`../../../locales`),updateFiles:!1})};function Ze(e,t,n,r){n.assert.notStrictEqual(e,t,r)}function Qe(e,t){t.assert.strictEqual(typeof e,`string`)}function $e(e){return Object.keys(e)}function I(e){return!!e&&!!e.then&&typeof e.then==`function`}function et(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 tt=[`first`,`second`,`third`,`fourth`,`fifth`,`sixth`];function L(e,t,n){function r(){return typeof e==`object`?[{demanded:[],optional:[]},e,t]:[et(`cmd ${e}`),t,n]}try{let e=0,[t,n,i]=r(),a=[].slice.call(n);for(;a.length&&a[a.length-1]===void 0;)a.pop();let o=i||a.length;if(o<t.demanded.length)throw new N(`Not enough arguments provided. Expected ${t.demanded.length} but received ${a.length}.`);let s=t.demanded.length+t.optional.length;if(o>s)throw new N(`Too many arguments provided. Expected max ${s} but received ${o}.`);t.demanded.forEach(t=>{let n=nt(a.shift());t.cmd.filter(e=>e===n||e===`*`).length===0&&rt(n,t.cmd,e),e+=1}),t.optional.forEach(t=>{if(a.length===0)return;let n=nt(a.shift());t.cmd.filter(e=>e===n||e===`*`).length===0&&rt(n,t.cmd,e),e+=1})}catch(e){console.warn(e.stack)}}function nt(e){return Array.isArray(e)?`array`:e===null?`null`:typeof e}function rt(e,t,n){throw new N(`Invalid ${tt[n]||`manyith`} argument. Expected ${t.join(` or `)} but received ${e}.`)}var it=class{constructor(e){this.globalMiddleware=[],this.frozens=[],this.yargs=e}addMiddleware(e,t,n=!0,r=!1){if(L(`<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 at(e){return e?e.map(e=>(e.applyBeforeValidation=!1,e)):[]}function ot(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(I(e))return e.then(e=>Promise.all([e,n(e,t)])).then(([e,t])=>Object.assign(e,t));{let r=n(e,t);return I(r)?r.then(t=>Object.assign(e,t)):Object.assign(e,r)}},e)}function st(e,t,n=e=>{throw e}){try{let n=ct(e)?e():e;return I(n)?n.then(e=>t(e)):t(n)}catch(e){return n(e)}}function ct(e){return typeof e==`function`}function lt(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 ut=/(^\*)|(^\$0)/;var dt=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=at(i);if(r||=(()=>{}),Array.isArray(e)){if(mt(e))[e,...o]=e;else for(let t of e)this.addHandler(t)}else if(_t(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(pt(n)){this.addHandler([e].concat(o),t,n.builder,n.handler,n.middlewares,n.deprecated);return}if(typeof e==`string`){let i=et(e);o=o.map(e=>et(e).cmd);let c=!1,l=[i.cmd].concat(o).filter(e=>!ut.test(e)||(c=!0,!1));l.length===0&&c&&l.push(`$0`),c&&(i.cmd=l[0],o=l.slice(1),e=e.replace(ut,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 I(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(ht(c)){n.getInternalMethods().getUsageInstance().freeze();let u=c(n.getInternalMethods().reset(r),s);if(I(u))return u.then(r=>(l=$n(r)?r:n,this.parseAndUpdateUsage(e,t,l,i,a,o)))}else gt(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 I(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=ut.test(t.original)?t.original.replace(ut,``).trim():t.original,r=e.filter(e=>!ut.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=st(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=ot(n,a,o,!1),n=st(n,e=>{let n=t.handler(e);return I(n)?n.then(()=>e):e}),e||a.getInternalMethods().getUsageInstance().cacheHelpMessage(),I(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=ot(n,o,c,!0);return I(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=et(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=ut.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(ht(t))return t(e,!0);pt(t)||Object.keys(t).forEach(n=>{e.option(n,t[n])})}moduleName(e){let t=lt(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;Ze(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();Ze(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 ft(e,t,n,r){return new dt(e,t,n,r)}function pt(e){return typeof e==`object`&&!!e.builder&&typeof e.handler==`function`}function mt(e){return e.every(e=>typeof e==`string`)}function ht(e){return typeof e==`function`}function gt(e){return typeof e==`object`}function _t(e){return typeof e==`object`&&!Array.isArray(e)}function vt(e={},t=()=>!0){let n={};return $e(e).forEach(r=>{t(r,e[r])&&(n[r]=e[r])}),n}function yt(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 bt(e){return typeof e==`boolean`}function xt(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(bt(a)){if(n)throw n;if(t)throw Error(t)}else a(t,n,r)}else{if(e.getExitProcess()&&yt(!0),!c){c=!0,s&&(e.showHelp(`error`),l.error()),(t||n)&&l.error(t||n);let r=a||o;r&&((t||n)&&l.error(``),l.error(r))}if(n||=new N(t),e.getExitProcess())return e.exit(1);if(e.getInternalMethods().hasParseCallback())return e.exit(1,n);throw n}};let l=[],u=!1;r.usage=(e,t)=>e===null?(u=!0,l=[],r):(u=!1,l.push([e,t||``]),r),r.getUsage=()=>l,r.getUsageDisabled=()=>u,r.getPositionalGroupName=()=>n(`Positionals:`);let d=[];r.example=(e,t)=>{d.push([e,t||``])};let f=[];r.command=function(e,t,n,r,i=!1){n&&(f=f.map(e=>(e[2]=!1,e))),f.push([e,t||``,n,r,i])},r.getCommands=()=>f;let p={};r.describe=function(e,t){Array.isArray(e)?e.forEach(e=>{r.describe(e,t)}):typeof e==`object`?Object.keys(e).forEach(t=>{r.describe(t,e[t])}):p[e]=t},r.getDescriptions=()=>p;let m=[];r.epilog=e=>{m.push(e)};let h=!1,g;r.wrap=e=>{h=!0,g=e},r.getWrap=()=>t.getEnv(`YARGS_DISABLE_WRAP`)?null:(h||=(g=b(),!0),g);let _=`__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(Tt(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]=Ct(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:Tt(i),padding:[0,2,0,2+wt(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} ${Tt(e[0])}`:Tt(e[0]))+wt(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=vt(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 St(e){return typeof e==`object`}function Ct(e,t){return St(e)?{text:e.text,indentation:e.indentation+t}:{text:e,indentation:t}}function wt(e){return St(e)?e.indentation:0}function Tt(e){return St(e)?e.text:e}var Et=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(ht(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=et(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(Ze(this.customCompletionFunction,null,this.shim),Ot(this.customCompletionFunction)){let e=this.customCompletionFunction(n,t);return I(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 kt(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 I(r)?r.then(i):i(r)}generateCompletionScript(e,t){let n=this.zshShell?`#compdef {{app_name}}
|
|
41
|
+
###-begin-{{app_name}}-completions-###
|
|
42
|
+
#
|
|
43
|
+
# yargs command completion script
|
|
44
|
+
#
|
|
45
|
+
# Installation: {{app_path}} {{completion_command}} >> ~/.zshrc
|
|
46
|
+
# or {{app_path}} {{completion_command}} >> ~/.zprofile on OSX.
|
|
47
|
+
#
|
|
48
|
+
_{{app_name}}_yargs_completions()
|
|
49
|
+
{
|
|
50
|
+
local reply
|
|
51
|
+
local si=$IFS
|
|
52
|
+
IFS=$'
|
|
53
|
+
' reply=($(COMP_CWORD="$((CURRENT-1))" COMP_LINE="$BUFFER" COMP_POINT="$CURSOR" {{app_path}} --get-yargs-completions "\${words[@]}"))
|
|
54
|
+
IFS=$si
|
|
55
|
+
_describe 'values' reply
|
|
56
|
+
}
|
|
57
|
+
compdef _{{app_name}}_yargs_completions {{app_name}}
|
|
58
|
+
###-end-{{app_name}}-completions-###
|
|
59
|
+
`:`###-begin-{{app_name}}-completions-###
|
|
60
|
+
#
|
|
61
|
+
# yargs command completion script
|
|
62
|
+
#
|
|
63
|
+
# Installation: {{app_path}} {{completion_command}} >> ~/.bashrc
|
|
64
|
+
# or {{app_path}} {{completion_command}} >> ~/.bash_profile on OSX.
|
|
65
|
+
#
|
|
66
|
+
_{{app_name}}_yargs_completions()
|
|
67
|
+
{
|
|
68
|
+
local cur_word args type_list
|
|
69
|
+
|
|
70
|
+
cur_word="\${COMP_WORDS[COMP_CWORD]}"
|
|
71
|
+
args=("\${COMP_WORDS[@]}")
|
|
72
|
+
|
|
73
|
+
# ask yargs to generate completions.
|
|
74
|
+
type_list=$({{app_path}} --get-yargs-completions "\${args[@]}")
|
|
75
|
+
|
|
76
|
+
COMPREPLY=( $(compgen -W "\${type_list}" -- \${cur_word}) )
|
|
77
|
+
|
|
78
|
+
# if no match was found, fall back to filename completion
|
|
79
|
+
if [ \${#COMPREPLY[@]} -eq 0 ]; then
|
|
80
|
+
COMPREPLY=()
|
|
81
|
+
fi
|
|
82
|
+
|
|
83
|
+
return 0
|
|
84
|
+
}
|
|
85
|
+
complete -o bashdefault -o default -F _{{app_name}}_yargs_completions {{app_name}}
|
|
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 Dt(e,t,n,r){return new Et(e,t,n,r)}function Ot(e){return e.length<3}function kt(e){return e.length>3}function At(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 jt=[`$0`,`--`,`_`];function Mt(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=>{jt.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=>{jt.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){L(`<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)):(Ze(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){L(`<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=At(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=vt(o,t=>!e[t]),c=vt(c,t=>!e[t]),a};let l=[];return a.freeze=function(){l.push({implied:o,conflicting:c})},a.unfreeze=function(){let e=l.pop();Ze(e,void 0,n),{implied:o,conflicting:c}=e},a}let Nt=[],Pt;function Ft(e,t,n,r){Pt=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=Lt(t,e.extends);else try{a=ge.resolve(e.extends)}catch{return e}It(a),Nt.push(a),i=r?JSON.parse(Pt.readFileSync(a,`utf8`)):ge(e.extends),delete e.extends,i=Ft(i,Pt.path.dirname(a),n,Pt)}return Nt=[],n?Rt(i,e):Object.assign({},i,e)}function It(e){if(Nt.indexOf(e)>-1)throw new N(`Circular extended configurations: '${e}'.`)}function Lt(e,t){return Pt.path.resolve(e,t)}function Rt(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])?Rt(e[i],t[i]):t[i];return n}var R=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},z=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)},B,zt,Bt,Vt,Ht,Ut,Wt,Gt,Kt,qt,Jt,Yt,Xt,Zt,Qt,$t,en,V,H,tn,nn,rn,an,on,sn,cn,ln,U,un,dn,fn,W,pn,mn,G;function hn(e){return(t=[],n=e.process.cwd(),r)=>{let i=new Qn(t,n,r,e);return Object.defineProperty(i,"argv",{get:()=>i.parse(),enumerable:!0}),i.help(),i.version(),i}}const gn=Symbol(`copyDoubleDash`),_n=Symbol(`copyDoubleDash`),vn=Symbol(`deleteFromParserHintObject`),yn=Symbol(`emitWarning`),bn=Symbol(`freeze`),xn=Symbol(`getDollarZero`),Sn=Symbol(`getParserConfiguration`),Cn=Symbol(`getUsageConfiguration`),wn=Symbol(`guessLocale`),Tn=Symbol(`guessVersion`),En=Symbol(`parsePositionalNumbers`),Dn=Symbol(`pkgUp`),On=Symbol(`populateParserHintArray`),kn=Symbol(`populateParserHintSingleValueDictionary`),An=Symbol(`populateParserHintArrayDictionary`),jn=Symbol(`populateParserHintDictionary`),Mn=Symbol(`sanitizeKey`),Nn=Symbol(`setKey`),Pn=Symbol(`unfreeze`),Fn=Symbol(`validateAsync`),In=Symbol(`getCommandInstance`),Ln=Symbol(`getContext`),Rn=Symbol(`getHasOutput`),zn=Symbol(`getLoggerInstance`),Bn=Symbol(`getParseContext`),Vn=Symbol(`getUsageInstance`),Hn=Symbol(`getValidationInstance`),Un=Symbol(`hasParseCallback`),Wn=Symbol(`isGlobalContext`),Gn=Symbol(`postProcess`),Kn=Symbol(`rebase`),qn=Symbol(`reset`),Jn=Symbol(`runYargsParserAndExecuteCommands`),Yn=Symbol(`runValidation`),Xn=Symbol(`setHasOutput`),Zn=Symbol(`kTrackManuallySetKeys`);var Qn=class{constructor(e=[],t,n,r){this.customScriptName=!1,this.parsed=!1,B.set(this,void 0),zt.set(this,void 0),Bt.set(this,{commands:[],fullCommands:[]}),Vt.set(this,null),Ht.set(this,null),Ut.set(this,`show-hidden`),Wt.set(this,null),Gt.set(this,!0),Kt.set(this,{}),qt.set(this,!0),Jt.set(this,[]),Yt.set(this,void 0),Xt.set(this,{}),Zt.set(this,!1),Qt.set(this,null),$t.set(this,!0),en.set(this,void 0),V.set(this,``),H.set(this,void 0),tn.set(this,void 0),nn.set(this,{}),rn.set(this,null),an.set(this,null),on.set(this,{}),sn.set(this,{}),cn.set(this,void 0),ln.set(this,!1),U.set(this,void 0),un.set(this,!1),dn.set(this,!1),fn.set(this,!1),W.set(this,void 0),pn.set(this,{}),mn.set(this,null),G.set(this,void 0),R(this,U,r,`f`),R(this,cn,e,`f`),R(this,zt,t,`f`),R(this,tn,n,`f`),R(this,Yt,new it(this),`f`),this.$0=this[xn](),this[qn](),R(this,B,z(this,B,`f`),`f`),R(this,W,z(this,W,`f`),`f`),R(this,G,z(this,G,`f`),`f`),R(this,H,z(this,H,`f`),`f`),z(this,H,`f`).showHiddenOpt=z(this,Ut,`f`),R(this,en,this[_n](),`f`)}addHelpOpt(e,t){return L(`[string|boolean] [string]`,[e,t],arguments.length),z(this,Qt,`f`)&&(this[vn](z(this,Qt,`f`)),R(this,Qt,null,`f`)),e===!1&&t===void 0||(R(this,Qt,typeof e==`string`?e:`help`,`f`),this.boolean(z(this,Qt,`f`)),this.describe(z(this,Qt,`f`),t||z(this,W,`f`).deferY18nLookup(`Show help`))),this}help(e,t){return this.addHelpOpt(e,t)}addShowHiddenOpt(e,t){if(L(`[string|boolean] [string]`,[e,t],arguments.length),e===!1&&t===void 0)return this;let n=typeof e==`string`?e:z(this,Ut,`f`);return this.boolean(n),this.describe(n,t||z(this,W,`f`).deferY18nLookup(`Show hidden options`)),z(this,H,`f`).showHiddenOpt=n,this}showHidden(e,t){return this.addShowHiddenOpt(e,t)}alias(e,t){return L(`<object|string|array> [string|array]`,[e,t],arguments.length),this[An](this.alias.bind(this),`alias`,e,t),this}array(e){return L(`<array|string>`,[e],arguments.length),this[On](`array`,e),this[Zn](e),this}boolean(e){return L(`<array|string>`,[e],arguments.length),this[On](`boolean`,e),this[Zn](e),this}check(e,t){return L(`<function> [boolean]`,[e,t],arguments.length),this.middleware((t,n)=>st(()=>e(t,n.getOptions()),n=>(n?(typeof n==`string`||n instanceof Error)&&z(this,W,`f`).fail(n.toString(),n):z(this,W,`f`).fail(z(this,U,`f`).y18n.__(`Argument check failed: %s`,e.toString())),t),e=>(z(this,W,`f`).fail(e.message?e.message:e.toString(),e),t)),!1,t),this}choices(e,t){return L(`<object|string|array> [string|array]`,[e,t],arguments.length),this[An](this.choices.bind(this),`choices`,e,t),this}coerce(e,t){if(L(`<object|string|array> [function]`,[e,t],arguments.length),Array.isArray(e)){if(!t)throw new N(`coerce callback must be provided`);for(let n of e)this.coerce(n,t);return this}if(typeof e==`object`){for(let t of Object.keys(e))this.coerce(t,e[t]);return this}if(!t)throw new N(`coerce callback must be provided`);return z(this,H,`f`).key[e]=!0,z(this,Yt,`f`).addCoerceMiddleware((n,r)=>{let i;return Object.prototype.hasOwnProperty.call(n,e)?st(()=>(i=r.getAliases(),t(n[e])),t=>{n[e]=t;let a=r.getInternalMethods().getParserConfiguration()[`strip-aliased`];if(i[e]&&a!==!0)for(let r of i[e])n[r]=t;return n},e=>{throw new N(e.message)}):n},e),this}conflicts(e,t){return L(`<string|object> [string|array]`,[e,t],arguments.length),z(this,G,`f`).conflicts(e,t),this}config(e=`config`,t,n){return L(`[object|string] [string|function] [function]`,[e,t,n],arguments.length),typeof e==`object`&&!Array.isArray(e)?(e=Ft(e,z(this,zt,`f`),this[Sn]()[`deep-merge-config`]||!1,z(this,U,`f`)),z(this,H,`f`).configObjects=(z(this,H,`f`).configObjects||[]).concat(e),this):(typeof t==`function`&&(n=t,t=void 0),this.describe(e,t||z(this,W,`f`).deferY18nLookup(`Path to JSON config file`)),(Array.isArray(e)?e:[e]).forEach(e=>{z(this,H,`f`).config[e]=n||!0}),this)}completion(e,t,n){return L(`[string] [string|boolean|function] [function]`,[e,t,n],arguments.length),typeof t==`function`&&(n=t,t=void 0),R(this,Ht,e||z(this,Ht,`f`)||`completion`,`f`),!t&&t!==!1&&(t=`generate completion script`),this.command(z(this,Ht,`f`),t),n&&z(this,Vt,`f`).registerFunction(n),this}command(e,t,n,r,i,a){return L(`<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]`,[e,t,n,r,i,a],arguments.length),z(this,B,`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){L(`<string> [object]`,[e,t],arguments.length);let n=z(this,tn,`f`)||z(this,U,`f`).require;return z(this,B,`f`).addDirectory(e,n,z(this,U,`f`).getCallerFile(),t),this}count(e){return L(`<array|string>`,[e],arguments.length),this[On](`count`,e),this[Zn](e),this}default(e,t,n){return L(`<object|string|array> [*] [string]`,[e,t,n],arguments.length),n&&(Qe(e,z(this,U,`f`)),z(this,H,`f`).defaultDescription[e]=n),typeof t==`function`&&(Qe(e,z(this,U,`f`)),z(this,H,`f`).defaultDescription[e]||(z(this,H,`f`).defaultDescription[e]=z(this,W,`f`).functionDescription(t)),t=t.call()),this[kn](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 L(`[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),z(this,H,`f`).demandedCommands._={min:e,max:t,minMsg:n,maxMsg:r},this}demand(e,t,n){return Array.isArray(t)?(t.forEach(e=>{Ze(n,!0,z(this,U,`f`)),this.demandOption(e,n)}),t=1/0):typeof t!=`number`&&(n=t,t=1/0),typeof e==`number`?(Ze(n,!0,z(this,U,`f`)),this.demandCommand(e,t,n,n)):Array.isArray(e)?e.forEach(e=>{Ze(n,!0,z(this,U,`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 L(`<object|string|array> [string]`,[e,t],arguments.length),this[kn](this.demandOption.bind(this),`demandedOptions`,e,t),this}deprecateOption(e,t){return L(`<string> [string|boolean]`,[e,t],arguments.length),z(this,H,`f`).deprecatedOptions[e]=t,this}describe(e,t){return L(`<object|string|array> [string]`,[e,t],arguments.length),this[Nn](e,!0),z(this,W,`f`).describe(e,t),this}detectLocale(e){return L(`<boolean>`,[e],arguments.length),R(this,Gt,e,`f`),this}env(e){return L(`[string|boolean]`,[e],arguments.length),e===!1?delete z(this,H,`f`).envPrefix:z(this,H,`f`).envPrefix=e||``,this}epilogue(e){return L(`<string>`,[e],arguments.length),z(this,W,`f`).epilog(e),this}epilog(e){return this.epilogue(e)}example(e,t){return L(`<string|array> [string]`,[e,t],arguments.length),Array.isArray(e)?e.forEach(e=>this.example(...e)):z(this,W,`f`).example(e,t),this}exit(e,t){R(this,Zt,!0,`f`),R(this,Wt,t,`f`),z(this,qt,`f`)&&z(this,U,`f`).process.exit(e)}exitProcess(e=!0){return L(`[boolean]`,[e],arguments.length),R(this,qt,e,`f`),this}fail(e){if(L(`<function|boolean>`,[e],arguments.length),typeof e==`boolean`&&e!==!1)throw new N(`Invalid first argument. Expected function or boolean 'false'`);return z(this,W,`f`).failFn(e),this}getAliases(){return this.parsed?this.parsed.aliases:{}}async getCompletion(e,t){return L(`<array> [function]`,[e,t],arguments.length),t?z(this,Vt,`f`).getCompletion(e,t):new Promise((t,n)=>{z(this,Vt,`f`).getCompletion(e,(e,r)=>{e?n(e):t(r)})})}getDemandedOptions(){return L([],0),z(this,H,`f`).demandedOptions}getDemandedCommands(){return L([],0),z(this,H,`f`).demandedCommands}getDeprecatedOptions(){return L([],0),z(this,H,`f`).deprecatedOptions}getDetectLocale(){return z(this,Gt,`f`)}getExitProcess(){return z(this,qt,`f`)}getGroups(){return Object.assign({},z(this,Xt,`f`),z(this,sn,`f`))}getHelp(){if(R(this,Zt,!0,`f`),!z(this,W,`f`).hasCachedHelpMessage()){if(!this.parsed){let e=this[Jn](z(this,cn,`f`),void 0,void 0,0,!0);if(I(e))return e.then(()=>z(this,W,`f`).help())}let e=z(this,B,`f`).runDefaultBuilderOn(this);if(I(e))return e.then(()=>z(this,W,`f`).help())}return Promise.resolve(z(this,W,`f`).help())}getOptions(){return z(this,H,`f`)}getStrict(){return z(this,un,`f`)}getStrictCommands(){return z(this,dn,`f`)}getStrictOptions(){return z(this,fn,`f`)}global(e,t){return L(`<string|array> [boolean]`,[e,t],arguments.length),e=[].concat(e),t===!1?e.forEach(e=>{z(this,H,`f`).local.includes(e)||z(this,H,`f`).local.push(e)}):z(this,H,`f`).local=z(this,H,`f`).local.filter(t=>e.indexOf(t)===-1),this}group(e,t){L(`<string|array> <string>`,[e,t],arguments.length);let n=z(this,sn,`f`)[t]||z(this,Xt,`f`)[t];z(this,sn,`f`)[t]&&delete z(this,sn,`f`)[t];let r={};return z(this,Xt,`f`)[t]=(n||[]).concat(e).filter(e=>r[e]?!1:r[e]=!0),this}hide(e){return L(`<string>`,[e],arguments.length),z(this,H,`f`).hiddenOptions.push(e),this}implies(e,t){return L(`<string|object> [number|string|array]`,[e,t],arguments.length),z(this,G,`f`).implies(e,t),this}locale(e){return L(`[string]`,[e],arguments.length),e===void 0?(this[wn](),z(this,U,`f`).y18n.getLocale()):(R(this,Gt,!1,`f`),z(this,U,`f`).y18n.setLocale(e),this)}middleware(e,t,n){return z(this,Yt,`f`).addMiddleware(e,!!t,n)}nargs(e,t){return L(`<string|object|array> [number]`,[e,t],arguments.length),this[kn](this.nargs.bind(this),`narg`,e,t),this}normalize(e){return L(`<array|string>`,[e],arguments.length),this[On](`normalize`,e),this}number(e){return L(`<array|string>`,[e],arguments.length),this[On](`number`,e),this[Zn](e),this}option(e,t){if(L(`<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[Zn](e),z(this,mn,`f`)&&(e===`version`||t?.alias===`version`)&&this[yn](`"version" is a reserved word.
|
|
89
|
+
Please do one of the following:
|
|
90
|
+
- Disable version with \`yargs.version(false)\` if using "version" as an option
|
|
91
|
+
- Use the built-in \`yargs.version\` method instead (if applicable)
|
|
92
|
+
- Use a different option key
|
|
93
|
+
https://yargs.js.org/docs/#api-reference-version`,void 0,`versionWarning`),z(this,H,`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&&(z(this,H,`f`).defaultDescription[e]=t.defaultDescription),t.skipValidation&&this.skipValidation(e);let i=t.describe||t.description||t.desc,a=z(this,W,`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){L(`[string|array] [function|boolean|object] [function]`,[e,t,n],arguments.length),this[bn](),e===void 0&&(e=z(this,cn,`f`)),typeof t==`object`&&(R(this,an,t,`f`),t=n),typeof t==`function`&&(R(this,rn,t,`f`),t=!1),t||R(this,cn,e,`f`),z(this,rn,`f`)&&R(this,qt,!1,`f`);let r=this[Jn](e,!!t),i=this.parsed;return z(this,Vt,`f`).setParsed(this.parsed),I(r)?r.then(e=>(z(this,rn,`f`)&&z(this,rn,`f`).call(this,z(this,Wt,`f`),e,z(this,V,`f`)),e)).catch(e=>{throw z(this,rn,`f`)&&z(this,rn,`f`)(e,this.parsed.argv,z(this,V,`f`)),e}).finally(()=>{this[Pn](),this.parsed=i}):(z(this,rn,`f`)&&z(this,rn,`f`).call(this,z(this,Wt,`f`),r,z(this,V,`f`)),this[Pn](),this.parsed=i,r)}parseAsync(e,t,n){let r=this.parse(e,t,n);return I(r)?r:Promise.resolve(r)}parseSync(e,t,n){let r=this.parse(e,t,n);if(I(r))throw new N(`.parseSync() must not be used with asynchronous builders, handlers, or middleware`);return r}parserConfiguration(e){return L(`<object>`,[e],arguments.length),R(this,nn,e,`f`),this}pkgConf(e,t){L(`<string> [string]`,[e,t],arguments.length);let n=null,r=this[Dn](t||z(this,zt,`f`));return r[e]&&typeof r[e]==`object`&&(n=Ft(r[e],t||z(this,zt,`f`),this[Sn]()[`deep-merge-config`]||!1,z(this,U,`f`)),z(this,H,`f`).configObjects=(z(this,H,`f`).configObjects||[]).concat(n)),this}positional(e,t){L(`<string> <object>`,[e,t],arguments.length);let n=[`default`,`defaultDescription`,`implies`,`normalize`,`choices`,`conflicts`,`coerce`,`type`,`describe`,`desc`,`description`,`alias`];t=vt(t,(e,t)=>e===`type`&&![`string`,`number`,`boolean`].includes(t)?!1:n.includes(e));let r=z(this,Bt,`f`).fullCommands[z(this,Bt,`f`).fullCommands.length-1],i=r?z(this,B,`f`).cmdToParseOptions(r):{array:[],alias:{},default:{},demand:{}};return $e(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,z(this,W,`f`).getPositionalGroupName()),this.option(e,t)}recommendCommands(e=!0){return L(`[boolean]`,[e],arguments.length),R(this,ln,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 L(`<array|string|object> [number]`,[e],arguments.length),typeof e==`string`&&z(this,H,`f`).narg[e]||this[kn](this.requiresArg.bind(this),`narg`,e,NaN),this}showCompletionScript(e,t){return L(`[string] [string]`,[e,t],arguments.length),e||=this.$0,z(this,en,`f`).log(z(this,Vt,`f`).generateCompletionScript(e,t||z(this,Ht,`f`)||`completion`)),this}showHelp(e){if(L(`[string|function]`,[e],arguments.length),R(this,Zt,!0,`f`),!z(this,W,`f`).hasCachedHelpMessage()){if(!this.parsed){let t=this[Jn](z(this,cn,`f`),void 0,void 0,0,!0);if(I(t))return t.then(()=>{z(this,W,`f`).showHelp(e)}),this}let t=z(this,B,`f`).runDefaultBuilderOn(this);if(I(t))return t.then(()=>{z(this,W,`f`).showHelp(e)}),this}return z(this,W,`f`).showHelp(e),this}scriptName(e){return this.customScriptName=!0,this.$0=e,this}showHelpOnFail(e,t){return L(`[boolean|string] [string]`,[e,t],arguments.length),z(this,W,`f`).showHelpOnFail(e,t),this}showVersion(e){return L(`[string|function]`,[e],arguments.length),z(this,W,`f`).showVersion(e),this}skipValidation(e){return L(`<array|string>`,[e],arguments.length),this[On](`skipValidation`,e),this}strict(e){return L(`[boolean]`,[e],arguments.length),R(this,un,e!==!1,`f`),this}strictCommands(e){return L(`[boolean]`,[e],arguments.length),R(this,dn,e!==!1,`f`),this}strictOptions(e){return L(`[boolean]`,[e],arguments.length),R(this,fn,e!==!1,`f`),this}string(e){return L(`<array|string>`,[e],arguments.length),this[On](`string`,e),this[Zn](e),this}terminalWidth(){return L([],0),z(this,U,`f`).process.stdColumns}updateLocale(e){return this.updateStrings(e)}updateStrings(e){return L(`<object>`,[e],arguments.length),R(this,Gt,!1,`f`),z(this,U,`f`).y18n.updateLocale(e),this}usage(e,t,n,r){if(L(`<string|null|undefined> [string|boolean] [function|object] [function]`,[e,t,n,r],arguments.length),t!==void 0){if(Ze(e,null,z(this,U,`f`)),(e||``).match(/^\$0( |$)/))return this.command(e,t,n,r);throw new N(`.usage() description must start with $0 if being used as alias for .command()`)}return z(this,W,`f`).usage(e),this}usageConfiguration(e){return L(`<object>`,[e],arguments.length),R(this,pn,e,`f`),this}version(e,t,n){let r=`version`;if(L(`[boolean|string] [string] [string]`,[e,t,n],arguments.length),z(this,mn,`f`)&&(this[vn](z(this,mn,`f`)),z(this,W,`f`).version(void 0),R(this,mn,null,`f`)),arguments.length===0)n=this[Tn](),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 R(this,mn,typeof e==`string`?e:r,`f`),t||=z(this,W,`f`).deferY18nLookup(`Show version number`),z(this,W,`f`).version(n||void 0),this.boolean(z(this,mn,`f`)),this.describe(z(this,mn,`f`),t),this}wrap(e){return L(`<number|null|undefined>`,[e],arguments.length),z(this,W,`f`).wrap(e),this}[(B=/* @__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,en=/* @__PURE__ */ new WeakMap,V=/* @__PURE__ */ new WeakMap,H=/* @__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,ln=/* @__PURE__ */ new WeakMap,U=/* @__PURE__ */ new WeakMap,un=/* @__PURE__ */ new WeakMap,dn=/* @__PURE__ */ new WeakMap,fn=/* @__PURE__ */ new WeakMap,W=/* @__PURE__ */ new WeakMap,pn=/* @__PURE__ */ new WeakMap,mn=/* @__PURE__ */ new WeakMap,G=/* @__PURE__ */ new WeakMap,gn)](e){if(!e._||!e[`--`])return e;e._.push.apply(e._,e[`--`]);try{delete e[`--`]}catch{}return e}[_n](){return{log:(...e)=>{this[Un]()||console.log(...e),R(this,Zt,!0,`f`),z(this,V,`f`).length&&R(this,V,z(this,V,`f`)+`
|
|
94
|
+
`,`f`),R(this,V,z(this,V,`f`)+e.join(` `),`f`)},error:(...e)=>{this[Un]()||console.error(...e),R(this,Zt,!0,`f`),z(this,V,`f`).length&&R(this,V,z(this,V,`f`)+`
|
|
95
|
+
`,`f`),R(this,V,z(this,V,`f`)+e.join(` `),`f`)}}}[vn](e){$e(z(this,H,`f`)).forEach(t=>{if((e=>e===`configObjects`)(t))return;let n=z(this,H,`f`)[t];Array.isArray(n)?n.includes(e)&&n.splice(n.indexOf(e),1):typeof n==`object`&&delete n[e]}),delete z(this,W,`f`).getDescriptions()[e]}[yn](e,t,n){z(this,Kt,`f`)[n]||(z(this,U,`f`).process.emitWarning(e,t),z(this,Kt,`f`)[n]=!0)}[bn](){z(this,Jt,`f`).push({options:z(this,H,`f`),configObjects:z(this,H,`f`).configObjects.slice(0),exitProcess:z(this,qt,`f`),groups:z(this,Xt,`f`),strict:z(this,un,`f`),strictCommands:z(this,dn,`f`),strictOptions:z(this,fn,`f`),completionCommand:z(this,Ht,`f`),output:z(this,V,`f`),exitError:z(this,Wt,`f`),hasOutput:z(this,Zt,`f`),parsed:this.parsed,parseFn:z(this,rn,`f`),parseContext:z(this,an,`f`)}),z(this,W,`f`).freeze(),z(this,G,`f`).freeze(),z(this,B,`f`).freeze(),z(this,Yt,`f`).freeze()}[xn](){let e=``,t;return t=/\b(node|iojs|electron)(\.exe)?$/.test(z(this,U,`f`).process.argv()[0])?z(this,U,`f`).process.argv().slice(1,2):z(this,U,`f`).process.argv().slice(0,1),e=t.map(e=>{let t=this[Kn](z(this,zt,`f`),e);return e.match(/^(\/|([a-zA-Z]:)?\\)/)&&t.length<e.length?t:e}).join(` `).trim(),z(this,U,`f`).getEnv(`_`)&&z(this,U,`f`).getProcessArgvBin()===z(this,U,`f`).getEnv(`_`)&&(e=z(this,U,`f`).getEnv(`_`).replace(`${z(this,U,`f`).path.dirname(z(this,U,`f`).process.execPath())}/`,``)),e}[Sn](){return z(this,nn,`f`)}[Cn](){return z(this,pn,`f`)}[wn](){if(!z(this,Gt,`f`))return;let e=z(this,U,`f`).getEnv(`LC_ALL`)||z(this,U,`f`).getEnv(`LC_MESSAGES`)||z(this,U,`f`).getEnv(`LANG`)||z(this,U,`f`).getEnv(`LANGUAGE`)||`en_US`;this.locale(e.replace(/[.:].*/,``))}[Tn](){return this[Dn]().version||`unknown`}[En](e){let t=e[`--`]?e[`--`]:e._;for(let e=0,n;(n=t[e])!==void 0;e++)z(this,U,`f`).Parser.looksLikeNumber(n)&&Number.isSafeInteger(Math.floor(parseFloat(`${n}`)))&&(t[e]=Number(n));return e}[Dn](e){let t=e||`*`;if(z(this,on,`f`)[t])return z(this,on,`f`)[t];let n={};try{let t=e||z(this,U,`f`).mainFilename;!e&&z(this,U,`f`).path.extname(t)&&(t=z(this,U,`f`).path.dirname(t));let r=z(this,U,`f`).findUp(t,(e,t)=>{if(t.includes(`package.json`))return`package.json`});Ze(r,void 0,z(this,U,`f`)),n=JSON.parse(z(this,U,`f`).readFileSync(r,`utf8`))}catch{}return z(this,on,`f`)[t]=n||{},z(this,on,`f`)[t]}[On](e,t){t=[].concat(t),t.forEach(t=>{t=this[Mn](t),z(this,H,`f`)[e].push(t)})}[kn](e,t,n,r){this[jn](e,t,n,r,(e,t,n)=>{z(this,H,`f`)[e][t]=n})}[An](e,t,n,r){this[jn](e,t,n,r,(e,t,n)=>{z(this,H,`f`)[e][t]=(z(this,H,`f`)[e][t]||[]).concat(n)})}[jn](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 $e(n))e(t,n[t]);else i(t,this[Mn](n),r)}[Mn](e){return e===`__proto__`?`___proto___`:e}[Nn](e,t){return this[kn](this[Nn].bind(this),`key`,e,t),this}[Pn](){var e,t,n,r,i,a,o,s,c,l,u,d;let f=z(this,Jt,`f`).pop();Ze(f,void 0,z(this,U,`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){R(e,H,t,`f`)}}.value,configObjects:p,exitProcess:{set value(e){R(t,qt,e,`f`)}}.value,groups:{set value(e){R(n,Xt,e,`f`)}}.value,output:{set value(e){R(r,V,e,`f`)}}.value,exitError:{set value(e){R(i,Wt,e,`f`)}}.value,hasOutput:{set value(e){R(a,Zt,e,`f`)}}.value,parsed:this.parsed,strict:{set value(e){R(o,un,e,`f`)}}.value,strictCommands:{set value(e){R(s,dn,e,`f`)}}.value,strictOptions:{set value(e){R(c,fn,e,`f`)}}.value,completionCommand:{set value(e){R(l,Ht,e,`f`)}}.value,parseFn:{set value(e){R(u,rn,e,`f`)}}.value,parseContext:{set value(e){R(d,an,e,`f`)}}.value}=f,z(this,H,`f`).configObjects=p,z(this,W,`f`).unfreeze(),z(this,G,`f`).unfreeze(),z(this,B,`f`).unfreeze(),z(this,Yt,`f`).unfreeze()}[Fn](e,t){return st(t,t=>(e(t),t))}getInternalMethods(){return{getCommandInstance:this[In].bind(this),getContext:this[Ln].bind(this),getHasOutput:this[Rn].bind(this),getLoggerInstance:this[zn].bind(this),getParseContext:this[Bn].bind(this),getParserConfiguration:this[Sn].bind(this),getUsageConfiguration:this[Cn].bind(this),getUsageInstance:this[Vn].bind(this),getValidationInstance:this[Hn].bind(this),hasParseCallback:this[Un].bind(this),isGlobalContext:this[Wn].bind(this),postProcess:this[Gn].bind(this),reset:this[qn].bind(this),runValidation:this[Yn].bind(this),runYargsParserAndExecuteCommands:this[Jn].bind(this),setHasOutput:this[Xn].bind(this)}}[In](){return z(this,B,`f`)}[Ln](){return z(this,Bt,`f`)}[Rn](){return z(this,Zt,`f`)}[zn](){return z(this,en,`f`)}[Bn](){return z(this,an,`f`)||{}}[Vn](){return z(this,W,`f`)}[Hn](){return z(this,G,`f`)}[Un](){return!!z(this,rn,`f`)}[Wn](){return z(this,$t,`f`)}[Gn](e,t,n,r){return n||I(e)||(t||(e=this[gn](e)),(this[Sn]()[`parse-positional-numbers`]||this[Sn]()[`parse-positional-numbers`]===void 0)&&(e=this[En](e)),r&&(e=ot(e,this,z(this,Yt,`f`).getMiddleware(),!1))),e}[qn](e={}){R(this,H,z(this,H,`f`)||{},`f`);let t={};t.local=z(this,H,`f`).local||[],t.configObjects=z(this,H,`f`).configObjects||[];let n={};return t.local.forEach(t=>{n[t]=!0,(e[t]||[]).forEach(e=>{n[e]=!0})}),Object.assign(z(this,sn,`f`),Object.keys(z(this,Xt,`f`)).reduce((e,t)=>{let r=z(this,Xt,`f`)[t].filter(e=>!(e in n));return r.length>0&&(e[t]=r),e},{})),R(this,Xt,{},`f`),[`array`,`boolean`,`string`,`skipValidation`,`count`,`normalize`,`number`,`hiddenOptions`].forEach(e=>{t[e]=(z(this,H,`f`)[e]||[]).filter(e=>!n[e])}),[`narg`,`key`,`alias`,`default`,`defaultDescription`,`config`,`choices`,`demandedOptions`,`demandedCommands`,`deprecatedOptions`].forEach(e=>{t[e]=vt(z(this,H,`f`)[e],e=>!n[e])}),t.envPrefix=z(this,H,`f`).envPrefix,R(this,H,t,`f`),R(this,W,z(this,W,`f`)?z(this,W,`f`).reset(n):xt(this,z(this,U,`f`)),`f`),R(this,G,z(this,G,`f`)?z(this,G,`f`).reset(n):Mt(this,z(this,W,`f`),z(this,U,`f`)),`f`),R(this,B,z(this,B,`f`)?z(this,B,`f`).reset():ft(z(this,W,`f`),z(this,G,`f`),z(this,Yt,`f`),z(this,U,`f`)),`f`),z(this,Vt,`f`)||R(this,Vt,Dt(this,z(this,W,`f`),z(this,B,`f`),z(this,U,`f`)),`f`),z(this,Yt,`f`).reset(),R(this,Ht,null,`f`),R(this,V,``,`f`),R(this,Wt,null,`f`),R(this,Zt,!1,`f`),this.parsed=!1,this}[Kn](e,t){return z(this,U,`f`).path.relative(e,t)}[Jn](e,t,n,r=0,i=!1){let a=!!n||i;e||=z(this,cn,`f`),z(this,H,`f`).__=z(this,U,`f`).y18n.__,z(this,H,`f`).configuration=this[Sn]();let o=!!z(this,H,`f`).configuration[`populate--`],s=Object.assign({},z(this,H,`f`).configuration,{"populate--":!0}),c=z(this,U,`f`).Parser.detailed(e,Object.assign({},z(this,H,`f`),{configuration:{"parse-positional-numbers":!1,...s}})),l=Object.assign(c.argv,z(this,an,`f`)),u,d=c.aliases,f=!1,p=!1;Object.keys(l).forEach(e=>{e===z(this,Qt,`f`)&&l[e]?f=!0:e===z(this,mn,`f`)&&l[e]&&(p=!0)}),l.$0=this.$0,this.parsed=c,r===0&&z(this,W,`f`).clearCachedHelpMessage();try{if(this[wn](),t)return this[Gn](l,o,!!n,!1);z(this,Qt,`f`)&&[z(this,Qt,`f`)].concat(d[z(this,Qt,`f`)]||[]).filter(e=>e.length>1).includes(``+l._[l._.length-1])&&(l._.pop(),f=!0),R(this,$t,!1,`f`);let s=z(this,B,`f`).getCommands(),m=z(this,Vt,`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!==z(this,Ht,`f`)){let e=z(this,B,`f`).runCommand(a,this,c,t+1,i,f||p||i);return this[Gn](e,o,!!n,!1)}if(!e&&a!==z(this,Ht,`f`)){e=a;break}}!z(this,B,`f`).hasDefaultCommand()&&z(this,ln,`f`)&&e&&!h&&z(this,G,`f`).recommendCommands(e,s)}z(this,Ht,`f`)&&l._.includes(z(this,Ht,`f`))&&!m&&(z(this,qt,`f`)&&yt(!0),this.showCompletionScript(),this.exit(0))}if(z(this,B,`f`).hasDefaultCommand()&&!h){let e=z(this,B,`f`).runCommand(null,this,c,0,i,f||p||i);return this[Gn](e,o,!!n,!1)}if(m){z(this,qt,`f`)&&yt(!0),e=[].concat(e);let t=e.slice(e.indexOf(`--${z(this,Vt,`f`).completionKey}`)+1);return z(this,Vt,`f`).getCompletion(t,(e,t)=>{if(e)throw new N(e.message);(t||[]).forEach(e=>{z(this,en,`f`).log(e)}),this.exit(0)}),this[Gn](l,!o,!!n,!1)}if(z(this,Zt,`f`)||(f?(z(this,qt,`f`)&&yt(!0),a=!0,this.showHelp(`log`),this.exit(0)):p&&(z(this,qt,`f`)&&yt(!0),a=!0,z(this,W,`f`).showVersion(`log`),this.exit(0))),!a&&z(this,H,`f`).skipValidation.length>0&&(a=Object.keys(l).some(e=>z(this,H,`f`).skipValidation.indexOf(e)>=0&&l[e]===!0)),!a){if(c.error)throw new N(c.error.message);if(!m){let e=this[Yn](d,{},c.error);n||(u=ot(l,this,z(this,Yt,`f`).getMiddleware(),!0)),u=this[Fn](e,u??l),I(u)&&!n&&(u=u.then(()=>ot(l,this,z(this,Yt,`f`).getMiddleware(),!1)))}}}catch(e){if(e instanceof N)z(this,W,`f`).fail(e.message,e);else throw e}return this[Gn](u??l,o,!!n,!0)}[Yn](e,t,n,r){let i={...this.getDemandedOptions()};return a=>{if(n)throw new N(n.message);z(this,G,`f`).nonOptionCount(a),z(this,G,`f`).requiredArguments(a,i);let o=!1;z(this,dn,`f`)&&(o=z(this,G,`f`).unknownCommands(a)),z(this,un,`f`)&&!o?z(this,G,`f`).unknownArguments(a,e,t,!!r):z(this,fn,`f`)&&z(this,G,`f`).unknownArguments(a,e,{},!1,!1),z(this,G,`f`).limitedChoices(a),z(this,G,`f`).implications(a),z(this,G,`f`).conflicting(a)}}[Xn](){R(this,Zt,!0,`f`)}[Zn](e){if(typeof e==`string`)z(this,H,`f`).key[e]=!0;else for(let t of e)z(this,H,`f`).key[t]=!0}};function $n(e){return!!e&&typeof e.getInternalMethods==`function`}const er=hn(Xe);var tr=class extends Error{};function nr(e){if(!Number.isInteger(e)||e<60||e>600)throw new tr(`Expected a whole number of seconds from 60 to 600.`);return e}function rr(e,t=`https://astralbeam.ai/api`){return`${t.replace(/\/+$/,``)}${e.replace(/^\/api(?=\/)/,``)}`}function ir(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 ar(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(rr(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=ir(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 or(e,t){let n=await ar(e,t);if(n.status!==204)return await n.json()}function sr(e){return e instanceof Error&&e.name===`AstralBeamApiError`&&`status`in e&&typeof e.status==`number`}function cr(e,t=`https://astralbeam.ai/api`){return`${t.replace(/\/+$/,``)}${e.replace(/^\/api(?=\/)/,``)}`}function lr(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 ur(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(cr(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=lr(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 dr(e,t){let n=await ur(e,t);if(n.status!==204)return await n.json()}function K(e,t){return dr(e,t)}async function fr(e,t){let n=await ur(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 pr(e,t){return ur(e,t)}const mr=()=>`/api/v1/organization`,hr=e=>dr(mr(),{...e,method:`GET`}),gr=()=>`/api/v1/chat/files`,_r=(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 K(gr(),{...t,method:`POST`,headers:{"Content-Type":`application/json`,...n(t?.headers)},body:JSON.stringify(e)})},vr=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`},yr=(e,t)=>fr(vr(e),{...t,method:`GET`}),br=()=>`/api/v1/chat`,xr=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`},Sr=(e,t)=>K(xr(e),{...t,method:`GET`}),Cr=()=>`/api/v1/chat/threads`,wr=(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 K(Cr(),{...t,method:`POST`,headers:{"Content-Type":`application/json`,...n(t?.headers)},body:JSON.stringify(e)})},Tr=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`},Er=(e,t)=>K(Tr(e),{...t,method:`GET`}),Dr=e=>`/api/v1/chat/threads/${encodeURIComponent(String(e))}`,Or=(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 K(Dr(e),{...n,method:`PATCH`,headers:{"Content-Type":`application/json`,...r(n?.headers)},body:JSON.stringify(t)})},kr=(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))}`},Ar=(e,t,n)=>K(kr(e,t),{...n,method:`DELETE`}),jr=(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`},Mr=(e,t,n)=>K(jr(e,t),{...n,method:`GET`}),Nr=e=>`/api/v1/chat/threads/${encodeURIComponent(String(e))}/tool-results`,Pr=()=>`/api/v1/me`,Fr=e=>K(Pr(),{...e,method:`POST`}),Ir=()=>`/api/v1/me/mcp/catalog`,Lr=e=>K(Ir(),{...e,method:`GET`}),Rr=()=>`/api/v1/me/mcp/connections`,zr=(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 K(Rr(),{...t,method:`POST`,headers:{"Content-Type":`application/json`,...n(t?.headers)},body:JSON.stringify(e)})},Br=e=>`/api/v1/me/mcp/connections/${encodeURIComponent(String(e))}/headers`,Vr=(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 K(Br(e),{...n,method:`POST`,headers:{"Content-Type":`application/json`,...r(n?.headers)},body:JSON.stringify(t)})},Hr=e=>`/api/v1/me/mcp/connections/${encodeURIComponent(String(e))}`,Ur=(e,t)=>K(Hr(e),{...t,method:`DELETE`}),Wr=e=>`/api/v1/me/mcp/connections/${encodeURIComponent(String(e))}/test`,Gr=(e,t)=>K(Wr(e),{...t,method:`POST`}),Kr=e=>`/api/v1/me/mcp/connections/${encodeURIComponent(String(e))}/authorize`,qr=(e,t)=>K(Kr(e),{...t,method:`POST`}),Jr=e=>`/api/v1/me/mcp/connections/${encodeURIComponent(String(e))}/oauth/bind`,Yr=(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 K(Jr(e),{...n,method:`POST`,headers:{"Content-Type":`application/json`,...r(n?.headers)},body:JSON.stringify(t)})},Xr=e=>`/api/v1/me/mcp/connections/${encodeURIComponent(String(e))}/oauth/complete`,Zr=(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 K(Xr(e),{...n,method:`POST`,headers:{"Content-Type":`application/json`,...r(n?.headers)},body:JSON.stringify(t)})};var Qr=`0.31.0`;function $r(e){s.write(`${JSON.stringify(e,null,2)}\n`)}function ei(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 ti(e){return e==null?``:ei(typeof e==`string`?e:JSON.stringify(e))}function ni(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)} ${ti(r)}\n`)}function ri(e,t){t?$r(e):ni(e)}function ii(e,t){let n=e.map(e=>t.map(t=>ti(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 ai(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 (${Qr}).`;if(e.status===429)return`The API rate limit was reached. Wait a few minutes and retry.`}function oi(e,t,n,r){let i=e instanceof Error?e.message:String(e);if(t){let t=sr(e)?e.body??{status:e.status,detail:i}:{detail:i};a.write(`${JSON.stringify({error:t,context:n??null})}\n`);return}if(!sr(e))return void a.write(`Error: ${ei(i)}\n`);let o=r?` from ${r}`:``;a.write(`Error: ${ei(i)} (HTTP ${e.status}${o})\n`);for(let t of e.body?.issues??[])a.write(` ${ei(t.path)}: ${ei(t.message)}\n`);let s=ai(e);s&&a.write(`${s}\n`)}const si=`https://astralbeam.ai/api`,ci=/^key_([0-9a-f-]{36})_[0-9a-f-]{36}_abo_[A-Za-z]{64}$/;function li(){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 ui(e){let t=ci.exec(e)?.[1];if(!t)throw Error(`The API key must match key_<organizationId>_<id>_abo_<secret>.`);return t}function di(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 fi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function pi(e){return fi(e)&&Object.values(e).every(e=>fi(e)&&typeof e.api_url==`string`&&typeof e.api_key==`string`&&fi(e.organization)&&typeof e.organization.id==`string`&&typeof e.organization.name==`string`&&typeof e.organization.slug==`string`)}function mi(e){try{let t=JSON.parse(e);if(fi(t)){let e=t.bindings===void 0?{}:t.bindings;if(pi(e))return{bindings:e}}}catch{}throw Error(`Invalid AstralBeam login bindings in ${li()}`)}async function hi(){try{return mi(await b(li(),`utf8`))}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return{bindings:{}};throw e}}async function gi(e){let t=li();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 _i(e){let t=`${li()}.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 hi())}finally{await S(t)}}async function vi(){return await x(t())}function yi(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 bi(e){let t=ce();return e===t||e.startsWith(t+de)?`~${e.slice(t.length)}`:e}const q={json:!1,context:void 0,failedRequest:void 0};function xi(e){q.context={organization:e.organization,bound_directory:e.directory??null},q.json||a.write(Si(e))}function Si(e){let{organization:t,directory:n}=e,r=t.name?`${ei(t.name)} (${ei(t.slug??``)}) · `:``,i=n?`bound at ${bi(n)}`:`from ASTRALBEAM_API_KEY`;return`▸ ${r}org ${t.id} · ${i}\n`}async function Ci(){let e=n.ASTRALBEAM_API_KEY,t;if(e)t={apiKey:e,apiUrl:di(n.ASTRALBEAM_API_URL??`https://astralbeam.ai/api`),organization:{id:ui(e)}};else{let e=await vi(),r=yi(await hi(),e);if(!r)throw Error(`No AstralBeam login covers ${bi(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:di(n.ASTRALBEAM_API_URL??i.api_url),organization:i.organization,directory:r.directory}}return xi(t),t}function wi(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 Ti(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 Ei(e,t=[]){let n=Ti(e,`body`);for(let{path:e,flag:r}of t){let t=n;for(let n of e)t=Di(t)&&Object.hasOwn(t,n)?t[n]:void 0;if(!Di(t))throw Error(`--body must include a JSON object at ${e.join(`.`)} (for --${r}).`)}return n}function Di(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Oi(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=Ti(e,t);if(!Di(i))throw Error(`${r} must be a JSON object.`);return i}function ki(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 Ai(e){return e.replace(/^filter_(.+)$/,`filter[$1]`)}async function ji(e){let{apiKey:t,apiUrl:n}=await Ci();return{send(e,r={}){let i=new URLSearchParams;for(let t of e.query??[]){let e=r[t];e!==void 0&&i.set(Ai(t),typeof e==`string`?e:JSON.stringify(e))}return or(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 J(e,t){if(e!==void 0){if(q.json||typeof e!=`object`||!e)return $r(e);if(`items`in e&&Array.isArray(e.items)){let t=e.items;t.length?ii(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 ${ei(e.page_after)}\n`)}else ri(e,!1)}}function Y(e,t){return t()}let Mi=``;async function Ni(e,t,n){return t.dryRun&&(Mi=(await Ci()).apiUrl),n()}function Pi(e){e.query&&=Object.fromEntries(Object.entries(e.query).map(([e,t])=>[Ai(e),t])),$r({...e,note:`Local request preview only. No HTTP request or server-side validation is performed.`,command:e.command.replace(/^cf /,`astralbeam `),url:rr(new URL(e.url).pathname.replace(/^\/client\/v4/,``),Mi)})}function Fi(e,t){throw Error(`Missing required option --${e} (or pass --body).`)}var Ii={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 Li(e){return e.usage(`$0 docs search
|
|
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 Ri={command:`search`,describe:`Search documentation`,builder:Li,handler:async e=>Ni({command:`docs search`,classification:{safeFlags:[`dry-run`]}},e,async()=>{let t={q:e.q};if(e.dryRun){Pi({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 ji(e);J(await Y(`Loading`,async()=>n.send(Ii,t)),{successLabel:`Loaded`})})},zi={command:`docs`,describe:`docs`,builder:e=>e.command(Ri).demandCommand(1,`Please specify a subcommand`),handler:()=>{}};var Bi={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 Vi(e){return e.usage(`$0 organization get
|
|
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 Hi={command:`get`,describe:`Get the current Organization`,builder:Vi,handler:async e=>Ni({command:`organization get`,classification:{safeFlags:[`dry-run`]}},e,async()=>{if(e.dryRun){Pi({command:`cf organization get`,method:`GET`,url:`https://api.cloudflare.com/client/v4/api/v1/organization`,pathParams:{},bodyKind:`none`});return}let t=await ji(e);J(await Y(`Loading`,async()=>t.send(Bi)),{successLabel:`Loaded`})})},Ui={command:`organization`,describe:`organization`,builder:e=>e.command(Hi).demandCommand(1,`Please specify a subcommand`),handler:()=>{}};function Wi(e,...t){let n=e[0]??``;for(let[r,i]of t.entries())n+=encodeURIComponent(String(i))+(e[r+1]??``);return n}var Gi={method:`POST`,path:e=>Wi`/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 Ki(e){return e.usage(`$0 tenant-users create <tenant-id>
|
|
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 qi={command:`create <tenant-id>`,describe:`Create a TenantUser`,builder:Ki,handler:async e=>Ni({command:`tenant-users create`,classification:{safeFlags:[`admin`,`dry-run`]}},e,async()=>{if(e.dryRun){Pi({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?wi({external_id:ki(e[`external-id`],`external-id`,`text`),name:ki(e.name,`name`,`text`),metadata:Oi(e.metadata,`metadata`),admin:e.admin},[[`metadata`]]):Ei(e.body)});return}let t=await ji(e);if(e.body){let n=Ei(e.body);J(await Y(`Creating`,async()=>t.send(Gi,{body:n,tenant_id:e[`tenant-id`]})),{successLabel:`Created`});return}e[`external-id`]===void 0&&(e[`external-id`]=await Fi(`external-id`,`Your stable external identity. Exact and case-sensitive; whitespace is preserved. Immutable after creation.`));let n=wi({external_id:ki(e[`external-id`],`external-id`,`text`),name:ki(e.name,`name`,`text`),metadata:Oi(e.metadata,`metadata`),admin:e.admin},[[`metadata`]]);J(await Y(`Creating`,async()=>t.send(Gi,{body:n,tenant_id:e[`tenant-id`]})),{successLabel:`Created`})})};var Ji={method:`GET`,path:e=>Wi`/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 Yi(e){return e.usage(`$0 tenant-users get <id>
|
|
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 Xi={command:`get <id>`,describe:`Get a TenantUser`,builder:Yi,handler:async e=>Ni({command:`tenant-users get`,classification:{safeFlags:[`dry-run`]}},e,async()=>{if(e.dryRun){Pi({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 ji(e);J(await Y(`Loading`,async()=>t.send(Ji,{tenant_id:e[`tenant-id`],id:e.id})),{successLabel:`Loaded`})})};var Zi={method:`GET`,path:e=>Wi`/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 Qi(e){return e.usage(`$0 tenant-users list
|
|
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 $i={command:`list`,describe:`List TenantUsers`,builder:Qi,handler:async e=>Ni({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){Pi({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 ji(e);J(await Y(`Loading`,async()=>n.send(Zi,{tenant_id:e[`tenant-id`],...t})),{successLabel:`Loaded`})})};var ea={method:`PATCH`,path:e=>Wi`/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 ta(e){return e.usage(`$0 tenant-users update <id>
|
|
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 na={command:`update <id>`,describe:`Update a TenantUser`,builder:ta,handler:async e=>Ni({command:`tenant-users update`,classification:{safeFlags:[`admin`,`dry-run`]}},e,async()=>{if(e.dryRun){Pi({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?wi({name:ki(e.name,`name`,`text`),metadata:Oi(e.metadata,`metadata`),admin:e.admin},[[`metadata`]]):Ei(e.body)});return}let t=await ji(e);if(e.body){let n=Ei(e.body);J(await Y(`Updating`,async()=>t.send(ea,{body:n,tenant_id:e[`tenant-id`],id:e.id})),{successLabel:`Updated`});return}let n=wi({name:ki(e.name,`name`,`text`),metadata:Oi(e.metadata,`metadata`),admin:e.admin},[[`metadata`]]);J(await Y(`Updating`,async()=>t.send(ea,{body:n,tenant_id:e[`tenant-id`],id:e.id})),{successLabel:`Updated`})})};var ra={method:`GET`,path:e=>Wi`/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 ia(e){return e.usage(`$0 tenant-users usage get <tenant-id>
|
|
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 aa={command:`get <tenant-id>`,describe:`Get TenantUser usage`,builder:ia,handler:async e=>Ni({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){Pi({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 ji(e);J(await Y(`Loading`,async()=>n.send(ra,{tenant_id:e[`tenant-id`],...t})),{successLabel:`Loaded`})})},oa={command:`usage`,describe:`Operations for usage`,builder:e=>e.command(aa).demandCommand(1,`Please specify a subcommand`),handler:()=>{}},sa={command:`tenant-users`,describe:`tenant-users`,builder:e=>e.command(qi).command(Xi).command($i).command(na).command(oa).demandCommand(1,`Please specify a subcommand`),handler:()=>{}};var ca={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 la(e){return e.usage(`$0 tenants create
|
|
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 ua={command:`create`,describe:`Create a Tenant`,builder:la,handler:async e=>Ni({command:`tenants create`,classification:{safeFlags:[`dry-run`]}},e,async()=>{if(e.dryRun){Pi({command:`cf tenants create`,method:`POST`,url:`https://api.cloudflare.com/client/v4/api/v1/tenants`,pathParams:{},bodyKind:`json`,body:e.body===void 0?wi({external_id:ki(e[`external-id`],`external-id`,`text`),name:ki(e.name,`name`,`text`),metadata:Oi(e.metadata,`metadata`)},[[`metadata`]]):Ei(e.body)});return}let t=await ji(e);if(e.body){let n=Ei(e.body);J(await Y(`Creating`,async()=>t.send(ca,{body:n})),{successLabel:`Created`});return}e[`external-id`]===void 0&&(e[`external-id`]=await Fi(`external-id`,`Your stable external identity. Exact and case-sensitive; whitespace is preserved. Immutable after creation.`));let n=wi({external_id:ki(e[`external-id`],`external-id`,`text`),name:ki(e.name,`name`,`text`),metadata:Oi(e.metadata,`metadata`)},[[`metadata`]]);J(await Y(`Creating`,async()=>t.send(ca,{body:n})),{successLabel:`Created`})})};var da={method:`GET`,path:e=>Wi`/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 fa(e){return e.usage(`$0 tenants get <id>
|
|
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 pa={command:`get <id>`,describe:`Get a Tenant`,builder:fa,handler:async e=>Ni({command:`tenants get`,classification:{safeFlags:[`dry-run`]}},e,async()=>{if(e.dryRun){Pi({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 ji(e);J(await Y(`Loading`,async()=>t.send(da,{id:e.id})),{successLabel:`Loaded`})})};var ma={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 ha(e){return e.usage(`$0 tenants list
|
|
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 ga={command:`list`,describe:`List Tenants`,builder:ha,handler:async e=>Ni({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){Pi({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 ji(e);J(await Y(`Loading`,async()=>n.send(ma,t)),{successLabel:`Loaded`})})};var _a={method:`PATCH`,path:e=>Wi`/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 va(e){return e.usage(`$0 tenants update <id>
|
|
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 ya={command:`update <id>`,describe:`Update a Tenant`,builder:va,handler:async e=>Ni({command:`tenants update`,classification:{safeFlags:[`dry-run`]}},e,async()=>{if(e.dryRun){Pi({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?wi({name:ki(e.name,`name`,`text`),metadata:Oi(e.metadata,`metadata`)},[[`metadata`]]):Ei(e.body)});return}let t=await ji(e);if(e.body){let n=Ei(e.body);J(await Y(`Updating`,async()=>t.send(_a,{body:n,id:e.id})),{successLabel:`Updated`});return}let n=wi({name:ki(e.name,`name`,`text`),metadata:Oi(e.metadata,`metadata`)},[[`metadata`]]);J(await Y(`Updating`,async()=>t.send(_a,{body:n,id:e.id})),{successLabel:`Updated`})})};var ba={method:`GET`,path:e=>Wi`/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 xa(e){return e.usage(`$0 tenants threads messages list
|
|
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 Sa={command:`list`,describe:`Read conversation history for administration`,builder:xa,handler:async e=>Ni({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){Pi({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 ji(e);J(await Y(`Loading`,async()=>n.send(ba,{tenantId:e[`tenant-id`],id:e.id,...t})),{successLabel:`Loaded`})})},Ca={command:`messages`,describe:`Operations for threads.messages`,builder:e=>e.command(Sa).demandCommand(1,`Please specify a subcommand`),handler:()=>{}},wa={command:`threads`,describe:`Operations for threads`,builder:e=>e.command(Ca).demandCommand(1,`Please specify a subcommand`),handler:()=>{}},Ta={command:`tenants`,describe:`tenants`,builder:e=>e.command(ua).command(pa).command(ga).command(ya).command(wa).demandCommand(1,`Please specify a subcommand`),handler:()=>{}};var Ea={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 Da(e){return e.usage(`$0 threads list
|
|
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 Oa={command:`list`,describe:`List conversations for administration`,builder:Da,handler:async e=>Ni({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){Pi({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 ji(e);J(await Y(`Loading`,async()=>n.send(Ea,t)),{successLabel:`Loaded`})})},ka={command:`threads`,describe:`threads`,builder:e=>e.command(Oa).demandCommand(1,`Please specify a subcommand`),handler:()=>{}};var Aa=/* @__PURE__ */ he({command0:()=>zi,command1:()=>Ui,command2:()=>sa,command3:()=>Ta,command4:()=>ka});function ja(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
|
+
`)},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 Ma(){return o.isTTY?await ja(`Paste an organization API key: `):(await pe(o)).trim()}async function Na(e,t){let n=ui(e),{id:r,name:i,slug:a}=await hr({apiKey:e,apiUrl:t});if(r!==n)throw Error(`The API returned a different organization.`);return{id:r,name:i,slug:a}}function Pa(e){return`${e.slice(0,e.indexOf(`_abo_`)+5)}…${e.slice(-4)}`}function Fa(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 ${si})`}),async e=>{let t=di(e.apiUrl??n.ASTRALBEAM_API_URL??`https://astralbeam.ai/api`),r=await Ma(),i=await Na(r,t),a=await vi();await _i(async e=>{e.bindings[a]={api_url:t,api_key:r,organization:i},await gi(e)}),xi({apiKey:r,apiUrl:t,organization:i,directory:a}),ri({directory:a,organization:i,api_url:t},q.json)}),e.command({command:`logout`,describe:`Remove the binding that covers this directory`,handler:async()=>{let e=await vi(),t=await _i(async t=>{let n=yi(t,e);if(!n)throw Error(`No AstralBeam login covers this directory.`);return delete t.bindings[n.directory],await gi(t),n}),{organization:n}=t.binding;ri({directory:t.directory,organization:n},q.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 Ci(),i=await Na(e,t);q.context&&(q.context.organization=i);let a=JSON.stringify(i);n&&JSON.stringify(r)!==a&&await _i(async r=>{let o=r.bindings[n];o?.api_key===e&&o.api_url===t&&JSON.stringify(o.organization)!==a&&(o.organization=i,await gi(r))}),ri({organization:i,api_url:t,api_key:Pa(e),source:n??`ASTRALBEAM_API_KEY`},q.json)}}),e.command({command:`list`,describe:`List every directory binding`,handler:async()=>{let{bindings:e}=await hi(),t=Object.entries(e).map(([e,t])=>({directory:e,organization:t.organization,api_url:t.api_url}));if(q.json)return $r({items:t});if(t.length===0)return void a.write(`No bindings.
|
|
125
|
+
`);ii(t.map(({directory:e,organization:t,api_url:n})=>({directory:bi(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 Ia=new TextEncoder,La=new TextDecoder,Ra=new TextDecoder(`utf-8`,{fatal:!0});function za(...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 Ba=/[^\x00-\x7f]/;function Va(e){if(typeof e==`string`&&e.length>=128){if(Ba.test(e))throw TypeError(`non-ASCII string encountered in encode()`);return Ia.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 Ha(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 Ua(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 Wa=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)}},Ga=class extends Wa{static code=`ERR_JOSE_NOT_SUPPORTED`;code=`ERR_JOSE_NOT_SUPPORTED`},Ka=class extends Wa{static code=`ERR_JWS_INVALID`;code=`ERR_JWS_INVALID`},qa=class extends Wa{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`};function Ja(e){try{return Ua(typeof e==`string`?e:La.decode(e),!0)}catch(e){throw TypeError(`The input to be decoded is not correctly encoded.`,{cause:e})}}function Ya(e){return Ha(typeof e==`string`?Ia.encode(e):e,!0)}function Xa(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 Za(...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 Qa(e,t){if(e!==void 0)throw TypeError(`${t} can only be called once`)}const $a={__proto__:null,b64:!0};function eo(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 to(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 Ga(`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 no(e,t){if(t.includes(`b64`)){let t=e.b64;if(typeof t!=`boolean`)throw new Ka(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);return t}return!0}function ro(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(!Xa(r))throw new e(`JOSE Header is not a JSON object`);return[r,n]}var io=Object.defineProperty,ao=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports),oo=(e,t)=>{let n=Object.setPrototypeOf({},null);for(var r in e)io(n,r,{get:e[r],enumerable:!0});return t&1||io(n,Symbol.toStringTag,{value:`Module`}),t&2?n:Object.preventExtensions(n)};function so(e){if(typeof e!=`string`)throw new qa(`JWTs must use Compact JWS serialization, JWT must be a string`);let{1:t,length:n}=e.split(`.`);if(n===5)throw new qa(`Only JWTs using Compact JWS serialization can be decoded`);if(n!==3)throw new qa(`Invalid JWT`);if(!t)throw new qa(`JWTs must contain a payload`);let r;try{r=Ja(t)}catch(e){throw new qa(`Failed to base64url decode the payload`,{cause:e})}let i;try{i=JSON.parse(Ra.decode(r))}catch(e){throw new qa(`Failed to parse the decoded payload as JSON`,{cause:e})}if(!Xa(i))throw new qa(`Invalid JWT Claims Set`);return i}/* @__NO_SIDE_EFFECTS__ */
|
|
126
|
+
function co({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 lo(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 uo=[];let fo=0;const{link:po,unlink:mo,propagate:ho,checkDirty:go,shallowPropagate:_o}=/* @__PURE__ */ co({update(e){return e._update()},notify(e){uo[yo++]=e,e.flags&=-3},unwatched(e){e.depsTail!==void 0&&(e.depsTail=void 0,e.flags=17,xo(e))}});let vo=0,yo=0,bo;function xo(e){let t=e.depsTail,n=t===void 0?e.deps:t.nextDep;for(;n!==void 0;)n=mo(n,e)}function So(){for(;vo<yo;){let e=uo[vo];uo[vo++]=void 0,e.notify()}vo=0,yo=0}function Co(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 bo!==void 0&&po(i,bo,fo),i._snapshot},subscribe(e){let t=lo(e),n={current:!1},r=wo(()=>{i.get(),n.current?(bo=void 0,t.next?.(i._snapshot)):n.current=!0});return{unsubscribe:()=>{r.stop()}}},_update(e){let a=bo,o=t?.compare??Object.is;if(n)bo=i,++fo,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{bo=a,n&&(i.flags&=-5),xo(i)}}};return n?(i.flags=17,i.get=function(){let e=i.flags;if(e&16||e&32&&go(i.deps,i)){if(i._update()){let e=i.subs;e!==void 0&&_o(e)}}else e&32&&(i.flags=e&-33);return bo!==void 0&&po(i,bo,fo),i._snapshot}):i.set=function(e){if(i._update(e)){let e=i.subs;e!==void 0&&(ho(e),_o(e),So())}},i}function wo(e){let t=()=>{let t=bo;bo=n,++fo,n.depsTail=void 0,n.flags=6;try{return e()}finally{bo=t,n.flags&=-5,xo(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&&go(this.deps,this)?t():this.flags=2},stop(){this.flags=0,this.depsTail=void 0,xo(this)}};return t(),n}function To(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Eo(e){typeof globalThis.reportError==`function`?globalThis.reportError(e):console.error(e)}function Do(e){if(Array.isArray(e))return Object.freeze(e.map(Do));if(!To(e))return e;let t={};for(let n of Object.keys(e))t[n]=Do(e[n]);return Object.freeze(t)}function Oo(e,t=/* @__PURE__ */ new WeakMap){let n=e,r={...n};if(To(n.source)&&(r.source=Object.freeze({...n.source})),n.type===`tool-call`&&To(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?Oo(e,t):e))),`input`in n&&(r.input=Do(n.input)),`output`in n&&(r.output=Do(n.output)),n.type===`subagent`&&To(n.subagent)){let e=n.subagent;r.subagent=Object.freeze(Array.isArray(e.messages)?{...e,messages:Ao(t,e.messages)}:{...e})}return Object.freeze(r)}function ko(e,t,n){let r=e.get(t);return r||(r=n(t),e.set(t,r)),r}function Ao(e,t){return Object.freeze(t.map(t=>ko(e,t,()=>Object.freeze({...t,parts:Object.freeze(t.parts.map(t=>ko(e,t,()=>Oo(t,e))))}))))}function jo(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 Mo=8;function No(e,t){let{unsubscribe:n}=e.subscribe(()=>{let n,r=0;do{n=e.get();try{t()}catch(e){Eo(e)}r++}while(e.get()!==n&&r<Mo)});return n}var Po=/^[a-z][a-z0-9-]{0,63}$/;function Fo(e){return typeof e==`string`&&Po.test(e)}function Io(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`||!Fo(t.provider)||!(`message`in t)||typeof t.message!=`string`)}var Lo=class extends Error{provider;constructor(e){super(`Missing ${e} API key`),this.name=`ByokMissingError`,this.provider=e}},Ro=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}},zo=class extends Error{constructor(){super(`BYOK is enabled but no provider slug was resolved. Pass byokProvider or forwardedProps.provider.`),this.name=`ByokUnresolvedProviderError`}},Bo=/* @__PURE__ */ new WeakMap;function Vo(e){let t=Object.entries(e.keys()).filter(e=>!!e[1]).map(e=>e[0]).filter(Fo);if(t.length===1)return t[0];let n=Bo.get(e)??[];if(n.length===1)return n[0]}function Ho(e,...t){let n=e?.();if(Fo(n))return n;for(let e of t)if(Fo(e))return e}async function Uo(e,t){if(!t)throw new zo;return await e.prepare(t),e.headers(t)}var Wo=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})}},Go=class extends Wo{emitEvent(){}},Ko=class{events;constructor(e){this.events=new Go(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){}},qo=e=>new Ko(e),Jo=class extends Error{missingFeature;constructor(e){super(Yo(e)),this.name=`UnsupportedResponseStreamError`,this.missingFeature=e}};function Yo(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 Xo(e){if(!e.body)throw new Jo(`Response.body`);if(typeof e.body.getReader!=`function`)throw new Jo(`Response.body.getReader`);return e.body.getReader()}function Zo(){if(typeof globalThis.TextDecoder!=`function`)throw new Jo(`TextDecoder`);return new globalThis.TextDecoder}function Qo(e){if(!e.startsWith(`data:`))return e;let t=e.slice(5);return t.startsWith(` `)?t.slice(1):t}function $o(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 es(e){let t=$o(e.createdAt),n=e.parts.map(e=>{if(e.type!==`tool-result`)return e;let t=$o(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 ts(e){return e.map(es)}function ns(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}}}}}var rs=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 is(e,t){return e>>>t|e<<32-t}function as(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=is(t,7)^is(t,18)^t>>>3,i=is(n,17)^is(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=is(a,6)^is(a,11)^is(a,25),s=a&g^~a&_,c=v+o+s+(rs[e]??0)+(h[e]??0)>>>0,l=(is(t,2)^is(t,13)^is(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 os(e){return`sha256:${as(e)}`}function ss(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(ss(e[n],t));n=`[${r.join(`,`)}]`}else{let r=e;n=`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${ss(r[e],t)}`).join(`,`)}}`}return t.delete(e),n}function cs(e){return ss(e,/* @__PURE__ */ new WeakSet)}function ls(e,t=os){if(typeof e!=`string`)throw TypeError(`Interrupt digests require canonical JSON text.`);return t(e)}function us(e){typeof e==`object`&&e&&!Object.isFrozen(e)&&(Object.values(e).forEach(us),Object.freeze(e))}function X(e){let t=JSON.parse(cs(e));return us(t),t}function ds(e){let t={};for(let[n,r]of Object.entries(e))n!==`$schema`&&(t[n]=r);return t}function fs(e){return(typeof e==`object`||typeof e==`function`)&&e!==null}function ps(e){if(!fs(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 ms(e){return fs(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 hs(e){return Object.keys(e).length>0?e:void 0}function gs(e){if(Array.isArray(e)){let t=e.map(e=>_s(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=_s(e,e.required||[]);return{schema:t.schema,itemMap:t.nullWidening}}function _s(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=_s(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=gs(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=gs(n.items);n.items=e.schema,e.itemMap&&(r.items=e.itemMap)}return{schema:n,nullWidening:hs(r)}}function vs(e,t=`input`){if(ps(e)){let n=ds(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(ms(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`?ds(e):e}function ys(e,t={}){if(!e)return;let{forStructuredOutput:n=!1,io:r}=t;if(!n&&!ps(e)&&!ms(e))return e;let i=vs(e,r);return!i||typeof i!=`object`||!n?i:_s(i,i.required||[]).schema}async function bs(e,t){if(!ms(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 xs=/* @__PURE__ */ new Set([`$schema`,`$id`,`$ref`,`$defs`,`type`,`properties`,`required`,`additionalProperties`,`items`,`oneOf`,`anyOf`,`allOf`,`enum`,`const`,`format`,`minimum`,`maximum`,`minLength`,`maxLength`,`pattern`]);function Ss(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null)}function Cs(e){return Ss(e)&&Object.keys(e).some(e=>xs.has(e))}function ws(e){return ms(e)||ps(e)||Cs(e)}function Ts(e){if(!Ss(e))return!1;let t=Object.keys(e);return t.length>0&&t.every(e=>e===`approve`||e===`reject`)&&t.every(t=>ws(e[t]))}function Es(e){let t={};for(let[n,r]of Object.entries(e))t[n]=r;return t}function Ds(e){if(ms(e)){let t=ps(e)?Es(e[`~standard`].jsonSchema.input({target:`draft-2020-12`})):void 0;return{source:e,validator:e,...t!==void 0&&{jsonSchema:t}}}if(Cs(e))return{source:e,jsonSchema:e};throw TypeError(`Expected a supported SchemaInput.`)}function Os(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 ks(e,t){let n=t===void 0?null:Ds(t),r=null,i=null;if(e!==void 0){if(ms(e)||Cs(e))r=Ds(e),i=r;else if(Ts(e))r=e.approve===void 0?null:Ds(e.approve),i=e.reject===void 0?null:Ds(e.reject);else throw TypeError(`approvalSchema must be a SchemaInput or a nonempty map containing approve or reject.`)}let a={oneOf:[Os({approved:!0,payload:r,inputSchema:n}),Os({approved:!1,payload:i,inputSchema:null})]},o=cs(a),s=cs({approve:r?.jsonSchema??null,reject:i?.jsonSchema??null});return{branches:{approve:r,reject:i},responseSchema:a,responseSchemaHash:ls(o),approvalSchemaHash:ls(s)}}function As(e){return ls(e===void 0?`undefined`:cs(Ds(e).jsonSchema??{standardValidator:`unserialized`}))}function js(e){let t=e?.metadata;return typeof t==`object`&&t&&t.providerExecuted===!0?t:null}function Ms(e){return js(e)!==null}function Ns(e,t){return e?.startsWith(`${t}-segment-`)===!0}var Ps=/* @__PURE__ */ new Set([`text`,`image`,`audio`,`video`,`document`]);function Fs(e){return e===`cancelled`||e===`denied`}function Is(e){if(typeof e!=`object`||!e)return!1;let t=e;if(typeof t.type!=`string`||!Ps.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 Ls(e){return Array.isArray(e)&&e.length>0&&e.every(Is)}function Rs(e){return e&&typeof e==`object`&&`error`in e&&typeof e.error==`string`?e.error:typeof e==`string`?e:`Tool execution failed`}function zs(e){return typeof e==`string`||Ls(e)?e:JSON.stringify(e)}function Bs(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Vs(e,t){if(t==null)return e;if(e==null)return{...t};let n={...e,...t};return Bs(e.tanstack)&&Bs(t.tanstack)&&(n.tanstack={...e.tanstack,...t.tanstack}),n}function Z(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 Hs(e,t){let n=e.metadata,r=Z(e)??{};return{...e,metadata:{...n??{},tanstack:{...r,...t}}}}let Q=/* @__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}({});var Us=`redacted_thinking-`;function Ws(e){return typeof e==`string`&&e.startsWith(`redacted_thinking-`)}function Gs(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 Ks(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 qs(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Js=`subagentInput`;function Ys(e){if(qs(e)&&qs(e.tanstack))return e.tanstack[Js]}function Xs(e){if(!qs(e)||`parts`in e)return;let t=e.subagentRunId;return typeof t==`string`&&t!==``?t:void 0}function Zs(e){if(!qs(e)||!qs(e.metadata))return;let t=e.metadata.tanstack;if(!qs(t)||!qs(t.subagent))return;let{name:n,status:r,error:i,interruptIds:a}=t.subagent;if(typeof n!=`string`||!Qs(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},...qs(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},...qs(l)&&{metadata:l},...u===!0&&{placeholder:!0}}}function Qs(e){return e===`running`||e===`finished`||e===`error`||e===`suspended`}function $s(e){if(!qs(e))return e;let{subagentRunId:t,...n}=e,r=qs(n.metadata)?n.metadata:void 0,i=qs(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 ec(e){let t=/* @__PURE__ */ new Map;for(let n of e){let e=Xs(n);e!==void 0&&!t.has(e)&&t.set(e,Zs(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=Xs(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=Zs(t);s&&(o.info=s),s?.placeholder||o.messages.push($s(t))}return{top:r,groups:[...i.values()]}}function tc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function nc(e){return e.type===`text`||e.type===`image`||e.type===`audio`||e.type===`video`||e.type===`document`}function rc(e){try{return JSON.stringify(e)??``}catch{return``}}function ic(e){return typeof e==`string`&&e!==``?e:void 0}function ac(e){if(`encryptedValue`in e){let t=ic(e.encryptedValue);if(t!==void 0)return t}return ic(Z(e)?.signature)}function oc(e){return`id`in e&&Ws(e.id)?{redacted:!0}:{}}function sc(e){return e.length===0?null:e.every(e=>e.type===`text`)?e.map(e=>e.content).join(``)||null:e}function cc(e){return e==null?``:typeof e==`string`?e:e.filter(e=>e.type===`text`).map(e=>e.content).join(``)}function lc(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=uc(n);e!==``&&t.push(e)}return t.join(`
|
|
127
|
+
|
|
128
|
+
`)}function uc(e){let t=[];for(let n of e.subagent.messages){if(!(`parts`in n))continue;let e=lc(n.parts).trim();e!==``&&t.push(e)}return t.length===0?``:`${e.subagent.name}:\n${t.join(`
|
|
129
|
+
|
|
130
|
+
`)}`}function dc(e){return Array.isArray(e)?e:cc(e)}function fc(e){if(!(`role`in e)||e.role!==`tool`)return e;let t=e,n=Z(t)?.toolResult;if(!tc(n)||`content`in n&&!Ls(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=pc(n.createdAt);e&&Reflect.set(r,`createdAt`,e)}Ls(n.content)&&Reflect.set(r,`content`,n.content);let i=Reflect.get(t,`metadata`);if(tc(i)){let e=i.tanstack;if(tc(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 pc(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 mc(e){if(e.type!==`tool-result`)return e;let t=pc(e.createdAt),{createdAt:n,...r}=e;return t===void 0?r:{...r,createdAt:t}}function hc(e){return pc(Z(e)?.createdAt)}function gc(e){let t=pc(e.createdAt);return t===void 0?{}:{createdAt:t}}function _c(e){return e.name===void 0?{}:{name:e.name}}function vc(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 yc(e){return`${e.toolCallId}\0${e.toolName}\0${e.resource.uri}`}function bc(e,t){if(t.length===0)return e;let n=new Set(e.parts.filter(vc).map(e=>yc(e))),r=t.filter(e=>!n.has(yc(e)));return r.length===0?e:{...e,parts:[...e.parts,...r]}}function xc(e){let t=e.parts.filter(vc),n=e.metadata??{},r={...Z(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 Sc(e){return e.role===`system`||e.role===`activity`?[]:e.role===`assistant`?Ec(e):[Cc(e)]}function Cc(e){let t=[];for(let n of e.parts)nc(n)&&t.push(n);return{id:e.id,role:e.role,content:sc(t),..._c(e),...gc(e),...e.metadata!==void 0&&{metadata:e.metadata}}}function wc(){return{contentParts:[],toolCalls:[],order:[]}}function Tc(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 Ec(e){let t=[],n=wc(),r=[],i=/* @__PURE__ */ new Set,a={id:e.id,..._c(e),...gc(e)},o=xc(e),s={...a,...o!==void 0&&{metadata:o}};function c(e=!1){let i=sc(n.contentParts),a=i!==null,o=n.toolCalls.length>0,c=r.length>0,l=Array.isArray(i)?void 0:Gs(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=wc()}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`:Tc(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:Hs(a,{toolResultOutcome:a.outcome}).metadata;t.push({...a.id!==void 0&&{id:a.id},...gc(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(Ms)&&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?``:rc(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?uc(a):``;if(e!==``){let t=`${n.contentParts.length>0?`
|
|
131
|
+
|
|
132
|
+
`:``}${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:zs(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 Dc(e){return{type:`thinking`,content:e.content,...e.signature&&{signature:e.signature},...e.redacted&&{redacted:!0}}}function Oc(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 kc(e,t){let n=[],r=pc(e.createdAt);if(e.role===`assistant`&&e.thinking?.length)for(let t of e.thinking)(t.content||t.signature)&&n.push(Dc(t));let i=e.structuredOutput??Mc(Z(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=Z(e)?.toolResultOutcome,i=Fs(t)?t:void 0,a=e.error===void 0&&i===void 0?`complete`:`error`;n.push({type:`tool-result`,toolCallId:e.toolCallId,content:dc(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=cc(e.content);t&&n.push({type:`text`,content:t})}if(e.toolCalls&&e.toolCalls.length>0)for(let t of e.toolCalls)n.push(Oc(t));let a=e.role===`assistant`&&i===void 0?Ks(e):void 0;a&&n.splice(0,n.length,...a.flatMap(e=>e.type===`text`?[{type:`text`,content:e.text}]:e.type===`tool-call`?[Oc(e.toolCall)]:e.thinking.content||e.thinking.signature?[Dc(e.thinking)]:[]));let o={id:t||Ic(),role:e.role===`tool`?`assistant`:e.role,parts:n,..._c(e),...r!==void 0&&{createdAt:r},...e.metadata!==void 0&&{metadata:e.metadata}},s=Z(e)?.uiResources;return bc(o,Array.isArray(s)?s.filter(vc):[])}function Ac(e){if(`parts`in e)return jc(e,{...e,id:e.id||Ic()});let t=e.id||Ic();switch(e.role){case`user`:return jc(e,{id:t,role:`user`,parts:Nc(e.content)});case`assistant`:{let n=Z(e),r=n?.toolCallMetadata,i=Mc(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 jc(e,kc({role:`assistant`,content:e.content??null,..._c(e),...a&&{toolCalls:a},...i&&{structuredOutput:i}},t))}case`tool`:{e=fc(e);let n=pc(`createdAt`in e?e.createdAt:void 0)??hc(e);return jc(e,kc({role:`tool`,content:Ls(e.content)?e.content:Pc(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 jc(e,{id:t,role:`system`,parts:e.content?[{type:`text`,content:e.content}]:[]});case`reasoning`:{let n=ac(e),r=typeof e.content==`string`?e.content:``;return jc(e,{id:t,role:`assistant`,parts:r||n!==void 0?[{type:`thinking`,content:r,...n===void 0?{}:{signature:n},...oc(e)}]:[]})}case`activity`:return jc(e,{id:t,role:`activity`,parts:[{type:`activity`,activityType:e.activityType,content:structuredClone(e.content)}]});default:return jc(e,{id:t,role:`assistant`,parts:[]})}}function jc(e,t){let n=t.parts.map(e=>mc(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=pc(i.createdAt)??(a===void 0?void 0:hc(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=Z(a)?.uiResources,c=Array.isArray(s)?s.filter(vc):[];return bc(i,c)}function Mc(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 Nc(e){let t=Pc(e);return typeof t==`string`?t?[{type:`text`,content:t}]:[]:t}function Pc(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 Fc(e,t){if(`parts`in e){let n=e.parts.map(e=>mc(e));return{...e,parts:n,id:e.id||t(),createdAt:pc(e.createdAt)??/* @__PURE__ */ new Date}}return{...kc(e,t()),createdAt:pc(e.createdAt)??/* @__PURE__ */ new Date}}function Ic(){return`msg-${Date.now()}-${Math.random().toString(36).substring(7)}`}var Lc=class{shouldEmit(e,t){return!0}},Rc=/* @__PURE__ */ ao((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})),zc=(/* @__PURE__ */ ao(((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=Rc();Object.defineProperty(e,"Allow",{enumerable:!0,get:function(){return a.Allow}}),i(Rc(),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&&`
|
|
133
|
+
\r `.includes(e[r]);)r++};return l()};e.parse=c})))(),Bc=new class{parse(e){if(e&&e.trim()!==``)try{return(0,zc.parse)(e)}catch{return}}};function Vc(e){return Bc.parse(e)}function Hc(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}function Uc(e){return typeof e==`string`&&e!==``?e:void 0}function Wc(e){if(`runId`in e){let t=Uc(e.runId);if(t!==void 0)return t}return Uc(Z(e)?.runId)}function Gc(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)=>Gc(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)&&Gc(Reflect.get(e,n),Reflect.get(t,n)))}function Kc(e,t){let n=0,r=()=>{for(;e[n]===` `||e[n]===` `||e[n]===`\r`||e[n]===`
|
|
134
|
+
`;)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 qc(e,t,n,r){if(n&&Gc(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)=>qc(e,t,n?.items?.[i],r)??`null`).join(`,`)+`]`;let i=[];for(let a of Object.keys(e)){let o=qc(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 Jc(e,t){if(t===void 0)return e??``;if(e===void 0)return qc(t,``,void 0,/* @__PURE__ */ new Set)??``;let n;try{n=JSON.parse(e)}catch{return e.trim()===``?qc(t,``,void 0,/* @__PURE__ */ new Set)??e:e}return Gc(n,t)?e:qc(t,e,Kc(e,n),/* @__PURE__ */ new Set)??e}function Yc(e){if(e.trim()===``)return{};try{return JSON.parse(e)??void 0}catch{return}}function Xc(e,t){let n=Z(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=Jc(s,o)}catch{c=s??e}return{args:c,input:Yc(c)}}function Zc(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 Qc(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 $c(e){if(e==null)return;let t=Z({metadata:e});if(t?.toolResultOutcome===void 0)return e;let{toolResultOutcome:n,...r}=t,i={...e};return Object.keys(r).length>0?i.tanstack=r:delete i.tanstack,Object.keys(i).length>0?i:void 0}function el(e,t,n,r,i,a,o,s){return e.map(e=>{if(e.id!==t)return e;let c=[...e.parts],l=c.findIndex(e=>e.type===`tool-result`&&e.toolCallId===n),u=Vs((l>=0?c[l]:void 0)?.metadata,s),d=Z({metadata:s})?.toolResultOutcome!==void 0;i===`complete`&&o===void 0&&!d&&(u=$c(u));let f={type:`tool-result`,toolCallId:n,content:r,state:i,...o!==void 0&&{outcome:o},...a&&{error:a},...u!==void 0&&{metadata:u}};return l>=0?c[l]=f:c.push(f),{...e,parts:c}})}function tl(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 nl(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 rl(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 il(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=Vc(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 al(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 ol(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 sl(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=Ws(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}})}function cl(e){let t=X([...e].sort((e,t)=>e.interruptId.localeCompare(t.interruptId))),n=cs(t);return Object.freeze({resolutions:t,canonicalResolutions:n,fingerprint:ls(n)})}var ll=`tanstack:interruptBinding`,ul=ll;function dl(e){return e&&typeof e==`object`?e:null}function fl(e,t){return typeof e[t]==`string`?e[t]:void 0}function pl(e){let t=e.v;return t===void 0||t===1}function ml(e){let t=dl(e.metadata),n=t?dl(t[ul]):null;if(!n||fl(n,`interruptId`)!==e.id||!pl(n))return;let r=fl(n,`kind`),i=fl(n,`interruptId`),a=fl(n,`responseSchemaHash`),o=fl(n,`expiresAt`);if(!i||a===``||o!==void 0&&!Number.isFinite(Date.parse(o)))return;if(r===`generic`){let e=fl(n,`definitionId`),t=fl(n,`key`),s=n.batchIndex,c=fl(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=fl(n,`toolName`),c=fl(n,`toolCallId`);if(s&&c){if(r===`client-tool-execution`){let e=fl(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=fl(n,`inputSchemaHash`),t=fl(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 hl(e,t){return{...e,metadata:{...e.metadata,[ul]:{...t,v:1,interruptId:e.id}}}}function gl(e){let t=ml(e);if(!t)return;let n=dl(e.metadata),r=n?dl(n[ul]):null;if(!r)return;let i=fl(r,`interruptedRunId`),a=r.generation;if(!(!i||typeof a!=`number`||!Number.isInteger(a)||a<0))return{...t,interruptedRunId:i,generation:a}}
|
|
135
|
+
/*!
|
|
136
|
+
* https://github.com/Starcounter-Jack/JSON-Patch
|
|
137
|
+
* (c) 2017-2022 Joachim Wester
|
|
138
|
+
* MIT licensed
|
|
139
|
+
*/
|
|
140
|
+
var _l=(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)}})(),vl=Object.prototype.hasOwnProperty;function yl(e,t){return vl.call(e,t)}function bl(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)yl(e,i)&&r.push(i);return r}function xl(e){switch(typeof e){case`object`:return JSON.parse(JSON.stringify(e));case`undefined`:return null;default:return e}}function Sl(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 Cl(e){return e.indexOf(`/`)===-1&&e.indexOf(`~`)===-1?e:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function wl(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}function Tl(e){if(e===void 0)return!0;if(e){if(Array.isArray(e)){for(var t=0,n=e.length;t<n;t++)if(Tl(e[t]))return!0}else if(typeof e==`object`){for(var r=bl(e),i=r.length,a=0;a<i;a++)if(Tl(e[r[a]]))return!0}}return!1}function El(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 Dl=function(e){_l(t,e);function t(t,n,r,i,a){var o=this.constructor,s=e.call(this,El(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=El(t,{name:n,index:r,operation:i,tree:a}),s}return t}(Error),Ol=/* @__PURE__ */ oo({JsonPatchError:()=>$,_areEquals:()=>Rl,applyOperation:()=>Nl,applyPatch:()=>Pl,applyReducer:()=>Fl,deepClone:()=>kl,getValueByPointer:()=>Ml,validate:()=>Ll,validator:()=>Il}),$=Dl,kl=xl,Al={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=Ml(n,this.path);r&&=xl(r);var i=Nl(n,{op:`remove`,path:this.from}).removed;return Nl(n,{op:`add`,path:this.path,value:i}),{newDocument:n,removed:r}},copy:function(e,t,n){var r=Ml(n,this.from);return Nl(n,{op:`add`,path:this.path,value:xl(r)}),{newDocument:n}},test:function(e,t,n){return{newDocument:n,test:Rl(e[t],this.value)}},_get:function(e,t,n){return this.value=e[t],{newDocument:n}}},jl={add:function(e,t,n){return Sl(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:Al.move,copy:Al.copy,test:Al.test,_get:Al._get};function Ml(e,t){if(t==``)return e;var n={op:`_get`,path:t};return Nl(e,n),n.value}function Nl(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):Il(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=Ml(e,t.from),t.op===`move`&&(o.removed=e),o;if(t.op===`test`){if(o.test=Rl(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=xl(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:Il;;){if(f=s[l],f&&f.indexOf(`~`)!=-1&&(f=wl(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&&!Sl(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 Sl(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=jl[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=Al[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 Pl(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=xl(e));for(var a=Array(t.length),o=0,s=t.length;o<s;o++)a[o]=Nl(e,t[o],n,!0,i,o),e=a[o].newDocument;return a.newDocument=e,a}function Fl(e,t,n){var r=Nl(e,t);if(r.test===!1)throw new $(`Test operation failed`,`TEST_OPERATION_FAILED`,n,t,e);return r.newDocument}function Il(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(!Al[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`)&&Tl(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=Ll([{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 Ll(e,t,n){try{if(!Array.isArray(e))throw new $(`Patch sequence must be an array`,`SEQUENCE_NOT_AN_ARRAY`);if(t)Pl(xl(t),xl(e),n||!0);else{n||=Il;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 Rl(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(!Rl(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],!Rl(e[o],t[o]))return!1;return!0}return e!==e&&t!==t}
|
|
142
|
+
/*!
|
|
143
|
+
* https://github.com/Starcounter-Jack/JSON-Patch
|
|
144
|
+
* (c) 2017-2021 Joachim Wester
|
|
145
|
+
* MIT license
|
|
146
|
+
*/
|
|
147
|
+
var zl=/* @__PURE__ */ oo({compare:()=>Xl,generate:()=>Jl,observe:()=>ql,unobserve:()=>Kl}),Bl=/* @__PURE__ */ new WeakMap,Vl=function(){function e(e){this.observers=/* @__PURE__ */ new Map,this.obj=e}return e}(),Hl=function(){function e(e,t){this.callback=e,this.observer=t}return e}();function Ul(e){return Bl.get(e)}function Wl(e,t){return e.observers.get(t)}function Gl(e,t){e.observers.delete(t.callback)}function Kl(e,t){t.unobserve()}function ql(e,t){var n=[],r,i=Ul(e);if(!i)i=new Vl(e),Bl.set(e,i);else{var a=Wl(i,t);r=a&&a.observer}if(r)return r;if(r={},i.value=xl(e),t){r.callback=t,r.next=null;var o=function(){Jl(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(){Jl(r),clearTimeout(r.next),Gl(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 Hl(t,r)),r}function Jl(e,t){t===void 0&&(t=!1);var n=Bl.get(e.object);Yl(n.value,e.object,e.patches,``,t),e.patches.length&&Pl(n.value,e.patches);var r=e.patches;return r.length>0&&(e.patches=[],e.callback&&e.callback(r)),r}function Yl(e,t,n,r,i){if(t!==e){typeof t.toJSON==`function`&&(t=t.toJSON());for(var a=bl(t),o=bl(e),s=!1,c=o.length-1;c>=0;c--){var l=o[c],u=e[l];if(yl(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)?Yl(u,d,n,r+`/`+Cl(l),i):u!==d&&(i&&n.push({op:`test`,path:r+`/`+Cl(l),value:xl(u)}),n.push({op:`replace`,path:r+`/`+Cl(l),value:xl(d)}))}else Array.isArray(e)===Array.isArray(t)?(i&&n.push({op:`test`,path:r+`/`+Cl(l),value:xl(u)}),n.push({op:`remove`,path:r+`/`+Cl(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];!yl(e,l)&&t[l]!==void 0&&n.push({op:`add`,path:r+`/`+Cl(l),value:xl(t[l])})}}}function Xl(e,t,n){n===void 0&&(n=!1);var r=[];return Yl(e,t,r,``,n),r}var Zl=Object.assign({},Ol,zl,{JsonPatchError:Dl,deepClone:xl,escapePathComponent:Cl,unescapePathComponent:wl});function Ql(e){return e.type===`activity`}function $l(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function eu(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=Vs(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 tu(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(Ql);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=Zl.applyPatch(c,i??[],!0,!1);if(!$l(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=Vs(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}}var nu=12,ru=/* @__PURE__ */ new Set([`RAW`,`ACTIVITY_SNAPSHOT`,`ACTIVITY_DELTA`,`REASONING_ENCRYPTED_VALUE`,`SUBAGENT_STARTED`,`SUBAGENT_FINISHED`,`SUBAGENT_ERROR`]),iu=/* @__PURE__ */ new Set([`RUN_STARTED`,`RUN_FINISHED`,`RUN_ERROR`,`MESSAGES_SNAPSHOT`]);function au(e){return e.some(e=>{let t=e.metadata;if(!t||typeof t!=`object`||Array.isArray(t))return!1;let n=t[ll];return typeof n==`object`&&!!n&&!Array.isArray(n)&&n.kind===`generic`})}var ou=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 Lc,this.events=e.events||{},this.jsonParser=e.jsonParser||Bc,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??Ic(),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=nl(this.messages,e,t,n?`error`:void 0,n),a=zs(t),o=n?`error`:`complete`;i=el(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=rl(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(...Sc(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)||Ms(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:Q.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:Q.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:Q.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:Q.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:Q.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:Q.REASONING_MESSAGE_CONTENT,messageId:r,delta:e.delta??``,...e.metadata===void 0?{}:{metadata:e.metadata},timestamp:n}),i}default:{let n=t&&!ru.has(e.type)?this.closeChunk():[];return iu.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:Q.TEXT_MESSAGE_END,messageId:e.id,timestamp:t}];case`TOOL_CALL`:return[{type:Q.TOOL_CALL_END,toolCallId:e.id,timestamp:t}];case`REASONING_MESSAGE`:return[{type:Q.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=Wc(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=sl(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||Ic(),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=Z({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=Z(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=Vs(r.metadata,o),c=pc(Z(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}=ec(e.messages),a=this.mergeReasoningFanOut(r.map(Ac)),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:Q.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:Ic(),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`&&Ns(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,r=/* @__PURE__ */ new Map;for(let e of t)for(let t of e.parts)t.type===`tool-call`?n.set(t.id,t):t.type===`tool-result`&&r.set(t.toolCallId,t);let i=/* @__PURE__ */ new Set;for(let t of e)for(let e of t.parts)e.type===`tool-call`&&i.add(e.id);let a=[];for(let t of e){let e=!1,o=t.parts.map(t=>{if(t.type!==`tool-result`||t.metadata!=null)return t;let n=r.get(t.toolCallId);if(n?.metadata==null)return t;let i=t.state===`complete`&&t.outcome===void 0?$c(n.metadata):n.metadata;return i==null?t:(e=!0,{...t,metadata:i})}),s=e?{...t,parts:o}:t,c=o.filter(e=>e.type===`tool-result`),l=t.role===`assistant`&&c.length===1&&o.every(e=>e.type===`tool-result`||e.type===`ui-resource`)?c[0]:void 0;if(!l){a.push(s);continue}let u=a.findLast(e=>e.parts.some(e=>e.type===`tool-call`&&e.id===l.toolCallId))??a.findLast(e=>e.role===`assistant`&&(e.parts.length!==1||e.parts[0]?.type!==`tool-result`));if(!u){i.has(l.toolCallId)||console.warn(`[StreamProcessor] MESSAGES_SNAPSHOT contains a tool-result for "${l.toolCallId}" but no matching tool-call exists in the snapshot, and there is no assistant message to anchor into; addToolResult("${l.toolCallId}") will not be able to locate this call`),a.push(s);continue}let d=[...u.parts];if(!i.has(l.toolCallId)&&!d.some(e=>e.type===`tool-call`&&e.id===l.toolCallId)){let e=n.get(l.toolCallId);e?(d.push({...e}),i.add(e.id)):console.warn(`[StreamProcessor] MESSAGES_SNAPSHOT contains a tool-result for "${l.toolCallId}" but no matching tool-call exists in the snapshot or the pre-snapshot state; addToolResult("${l.toolCallId}") will not be able to locate this call`)}d.push(...o),u.parts=d}return this.enrichSnapshotToolCallsFromResults(a,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`?Rs(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=il(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=Z(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=Qc(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=Vs(i.metadata,e.metadata)),i.arguments+=e.delta||``,a&&e.delta&&(i.state=`input-streaming`),i.parsedArguments=this.jsonParser.parse(i.arguments),this.messages=Qc(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=Xc(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=Z(e)?.toolResultOutcome,i=Fs(r)?r:void 0,a=n.state===`output-error`||Z(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=nl(this.messages,e.toolCallId,o,a?`error`:void 0);let s=a?`error`:`complete`;this.messages=el(this.messages,t,e.toolCallId,Ls(o)?o:Pc(e.content),s,s===`error`?Rs(o):void 0,i,e.metadata),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=Z(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,Hs(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?Z(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`&&Z(e)?.loopStopped!==!0){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||Ms(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??Yc(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=au(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=tl(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=Wc(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)??Ic(),!1).messageId,i=new Set(n);r!==void 0&&i.add(r);for(let t of i)this.mergeMessageMetadata(t,Hs(e,{stopReason:Z(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=ol(this.messages,r,a),this.structuredMessageIds.delete(r),this.emitStructuredOutputChange(r,`error`),this.emitMessagesChange()),this.events.onError?.(Hc(e))}handleActivitySnapshotEvent(e){this.messages=eu(this.messages,e),this.emitMessagesChange()}handleActivityDeltaEvent(e){this.messages=tu(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=sl(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=sl(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=al(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=Qc(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=Zc(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>=nu&&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=ol(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(su(t))}};function su(e){return{async*[Symbol.asyncIterator](){for(let{chunk:t}of e.chunks)yield t}}}function cu(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function lu(e,t,n,r,i=!1,a){let o=cu(e)?e:{},s=cu(o.tanstack)?{...o.tanstack}:{};i&&delete s.uiResources;let c=pc(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 uu(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=Cu(Tu(s.id,s.toolCallId,o),r),t=lu(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:kc(s,s.id),c=e.parts;if(r.add(e.id),s.role===`system`){n.push(du(e,`system`,{content:c.length>0?hu(c):s.content??``},c,i));continue}if(s.role===`user`){n.push(du(e,`user`,{content:c.length>0?vu(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`&&Ms(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=Cu(t.id??Su(t.toolCallId),r),i=lu(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`}):zs(t.output),a=typeof i==`string`?i:JSON.stringify(i);n.push({role:`tool`,id:Cu(Su(t.id),r),toolCallId:t.id,content:a,metadata:lu(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:wu(xu(e.id,i),r),content:i.content};i.signature&&(t.encryptedValue=i.signature),n.push(t)}let o=hu(t.parts),s=bu(t.parts),c=du(a===0?e:{...e,id:wu(`${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:{...cu(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(...gu(e,t))}return n}function du(e,t,n,r,i){let a=fu(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 fu(e,t,n){let r={...e.metadata??{}},i={...Z(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=pc(e.createdAt);a!==void 0&&(i.createdAt=a.toISOString());let o=pu(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 pu(e,t){for(let n of e)if(n.type===`structured-output`&&(t||n.status!==`complete`))return mu(n,t)}function mu(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 hu(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 gu(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=uu(n.messages,t),a=i.some(e=>Xs(e)===void 0);return(a?i:[{id:`subagent:${n.id}`,role:`assistant`},...i]).map((e,t)=>{let i=Xs(e);if(i!==void 0){let t=Zs(e);return!t||t.parentSubagentRunId!==void 0?e:_u(e,i,{...t,parentSubagentRunId:n.id})}return _u(e,n.id,!a&&t===0?{...r,placeholder:!0}:r)})}function _u(e,t,n){let r=cu(e.metadata)?e.metadata:{},i=cu(r.tanstack)?r.tanstack:{};return{...e,subagentRunId:t,metadata:{...r,tanstack:{...i,subagent:n}}}}function vu(e){if(!e.some(e=>e.type===`image`||e.type===`audio`||e.type===`video`||e.type===`document`))return hu(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 yu(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 bu(e){let t=[];for(let n of e)if(n.type===`tool-call`){let e=yu(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 xu(e,t){let n=`${e}-reasoning-${t.id??Eu(t.content)}`;return t.type===`thinking`&&t.redacted?`${Us}${n}`:n}function Su(e){return`tool-${e}`}function Cu(e,t){return wu(e,t)}function wu(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 Tu(e,t,n){let r=Su(t);return e===void 0||n.has(e)?r:e}function Eu(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 Du(e){return Object.keys(e).length>0?e:void 0}function Ou(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&`promptTokens`in e}function ku(e,t){return Ou(e)?e:Au(Array.isArray(e)?e:void 0,t)}function Au(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=Du({...n?.cachedInputTokens===void 0?{}:{cachedTokens:n.cachedInputTokens},...n?.cacheWriteInputTokens===void 0?{}:{cacheWriteTokens:n.cacheWriteInputTokens},...r}),s=Du({...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 ju(e){if((e.type===Q.RUN_FINISHED||e.type===Q.RUN_ERROR)&&(Array.isArray(e.usage)||Ou(e.usage))){let t=ku(e.usage,Z(e)?.usage);t!==void 0&&(e.usage=t)}if(e.type===Q.TOOL_CALL_END&&e.input===void 0){let t=Z(e),n=t?.input??(typeof t?.args==`string`?Yc(t.args):void 0);n!==void 0&&(e.input=n)}return e}function Mu(e){ju(e);let t=Z(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}var Nu=`tanstack:interruptPayload`;function Pu(e,t){if(!ps(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:cs(n)}}catch(e){throw TypeError(`${t} could not export compatible JSON Schema: ${e instanceof Error?e.message:String(e)}`)}}function Fu(e){return ls(Pu(e,`Interrupt schema`).canonicalJson)}var Iu=`tanstack:interruptContinuation`;function Lu(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ru(e){return{[Iu]:e}}function zu(e){let t=ml(e);if(t?.kind!==`generic`||t.definitionId===void 0||t.key===void 0||t.batchIndex===void 0)return;let n=Lu(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[Nu]}:{}}}var Bu=/* @__PURE__ */ new WeakMap;function Vu(e){return Bu.get(e)??Wc(e)}var Hu=class extends Error{constructor(){super(`Stream ended with unterminated trailing data — connection was likely cut short.`),this.name=`StreamTruncatedError`}},Uu=class extends Error{constructor(e){super(`Stream response body read failed`,{cause:e}),this.name=`StreamReadError`}},Wu=class extends Error{constructor(){super(`Durable run ended without a terminal event and could not resume — the run did not complete.`),this.name=`DurableStreamIncompleteError`}},Gu=class extends Error{constructor(e,t){super(t===void 0?`Durable run exceeded its reconnect ceiling of ${e} attempts — giving up.`:`Durable run did not reconnect within its budget of ${t} ms (${e} attempts) — giving up.`),this.name=`StreamReconnectLimitError`}},Ku=/* @__PURE__ */ new Set([408,429,502,503,504]),qu=class extends Error{status;retryAfterMs;constructor(e,t,n){super(e),this.status=t,this.name=`StreamHttpError`,this.retryAfterMs=Ju(n)}};function Ju(e){if(!e)return;let t=Number(e);if(Number.isFinite(t))return t>=0?t*1e3:void 0;let n=Date.parse(e);return Number.isNaN(n)?void 0:Math.max(0,n-Date.now())}function Yu(e){return e instanceof qu&&Ku.has(e.status)}function Xu(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 Zu(e){let t=Xu(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 Gu(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 Gu(i-1,t.budgetMs);await td(s,n)}}}function Qu(e,t){if(!e||!t)return e??t;let n=e.aborted?e:t.aborted?t:ed(e,t);return $u.set(e,n),n}var $u=/* @__PURE__ */ new WeakMap;function ed(e,t){if(typeof AbortSignal.any==`function`)return AbortSignal.any([e,t]);let n=new AbortController;return e.addEventListener(`abort`,()=>n.abort(e.reason),{once:!0}),t.addEventListener(`abort`,()=>n.abort(t.reason),{once:!0}),n.signal}function td(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 nd(e){if(!e)return{};if(e instanceof Headers){let t={};return e.forEach((e,n)=>{t[n]=e}),t}return e}var rd=`X-Run-Id`;function id(e){return{[rd]:e}}function ad(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*od(e,t){try{let n=Zo(),r=``;for(;!t?.aborted;){let i;try{i=await e.read()}catch(e){if(t?.aborted)return;throw new Uu(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 Hu}finally{try{e.cancel().catch(()=>{})}catch{}e.releaseLock()}}async function*sd(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=Qo(n),r=Mu(JSON.parse(e)),i=t;t=void 0,yield{chunk:r,...i===void 0?{}:{id:i}}}}async function cd(e){if(!e.ok){if(e.status===401){let t=await e.clone().json().catch(()=>null);if(Io(t))throw new Lo(t.error.provider)}throw new qu(`HTTP error! status: ${e.status} ${e.statusText}`,e.status,e.headers.get(`retry-after`))}}function ld(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 ud(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 dd(e,t,n,r,i,a){let o=await e(ad(t,ld(i,a)),{method:`GET`,headers:{Accept:`application/json`,...n},credentials:r});await cd(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)?ts(s.messages):[],activeRun:c,interrupts:l,page:ud(s.page)}}async function fd(e,t,n,r,i){let a=await e(ad(t,{threadId:i}),{method:`GET`,headers:{Accept:`application/json`,...n},credentials:r});await cd(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*pd(e,t){await cd(e),yield*sd(od(Xo(e),t))}async function*md(e,t){for await(let{chunk:n}of pd(e,t))yield n}function hd(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 Uu(e)}yield*r(o,a)}}async function*gd(e,t,n){let r=Zu(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 Hu||e instanceof Uu||Yu(e))&&r.lastEventId!==void 0){await r.waitBeforeReconnect(a,t,Yu(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 Wu}return}}function _d(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),r=e.cancelRun?.bind(e);return{subscribe:e.subscribe.bind(e),send:e.send.bind(e),...t?{joinRun:t}:{},...n?{hydrate:n}:{},...r?{cancelRun:r}:{}}}if(!t)throw Error(`Connection adapter must provide either connect or both subscribe and send`);let i=[],a=[],o;function s(e,t){t&&Bu.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,u=()=>r?.aborted===!0||r!==void 0&&$u.get(r)?.aborted===!0;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);if(u()&&!r?.aborted)throw Object.assign(/* @__PURE__ */ Error(`Aborted`),{name:`AbortError`});!u()&&!a&&s(Hs({type:Q.RUN_FINISHED,threadId:o??i.threadId,runId:l??i.runId,timestamp:Date.now()},{finishReason:`stop`,model:`connect-wrapper`}),i.runId)}catch(e){if(!u()&&!a){let t=e instanceof Error?e.message:`Unknown error in connect()`;s({type:Q.RUN_ERROR,threadId:o??i.threadId,runId:l??i.runId,timestamp:Date.now(),message:t},i.runId)}throw e}await c(r)},...e.cancelRun?{cancelRun:e.cancelRun.bind(e)}:{},...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)}:{}})()}}var vd=1e4;function yd(e){return typeof e!=`function`&&e.cancelUrl===void 0?{}:{async cancelRun({runId:t,threadId:n}){let r=typeof e==`function`?await e():e,{cancelUrl:i}=r;if(i===void 0)return;let a=await(r.fetchClient??fetch)(typeof i==`function`?i():i,{method:`POST`,headers:{"Content-Type":`application/json`,...nd(r.headers)},body:JSON.stringify({runId:t,threadId:n}),credentials:r.credentials||`same-origin`,signal:AbortSignal.timeout(vd)});if(!a.ok)throw Error(`Run cancel failed with status ${a.status}`)}}}function bd(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=uu(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 xd(e,t={}){return{...yd(t),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`,...nd(s.headers),...nd(a.headers),...id(a.runId)},l=bd(n,r,a,s),u=s.fetchClient??fetch,d=Qu(i,s.signal);yield*gd(hd(u,o,{method:`POST`,headers:c,body:JSON.stringify(l),credentials:s.credentials||`same-origin`},pd),d,s.reconnect)},async*joinRun(n,r){let i=typeof e==`function`?e():e,a=typeof t==`function`?await t():t,o=ad(i,{offset:`-1`,runId:n}),s={...nd(a.headers)},c=a.fetchClient??fetch,l=Qu(r,a.signal);yield*gd(hd(c,o,{method:`GET`,headers:s,credentials:a.credentials||`same-origin`},pd),l,a.reconnect)},async hydrate(n,r){let i=typeof e==`function`?e():e,a=typeof t==`function`?await t():t;return dd(a.fetchClient??fetch,i,nd(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 fd(i.fetchClient??fetch,r,nd(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*md(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{let e=n.return?.();t.aborted?Promise.resolve(e).catch(()=>{}):await e}}function wd(e){return`toolCallId`in e&&typeof e.toolCallId==`string`?e.toolCallId:void 0}function Td(e){return`messageId`in e&&typeof e.messageId==`string`?e.messageId:void 0}function Ed(e){return`parentMessageId`in e&&typeof e.parentMessageId==`string`?e.parentMessageId:void 0}var Dd=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=Vu(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=wd(e);if(n&&this.clearedToolCallIds.has(n))return!0;let r=Ed(e);if(r&&this.clearedMessageIds.has(r))return n&&this.clearedToolCallIds.add(n),!0;let i=Td(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=Td(e);t&&this.clearedMessageIds.add(t);let n=wd(e);n&&this.clearedToolCallIds.add(n)}isRunlessChunkFromIgnoredRun(e){return Vu(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 Od(e){return`toolCallId`in e&&typeof e.toolCallId==`string`?e.toolCallId:void 0}function kd(e){return`messageId`in e&&typeof e.messageId==`string`?e.messageId:void 0}function Ad(e){return`parentMessageId`in e&&typeof e.parentMessageId==`string`?e.parentMessageId:void 0}var jd=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=Vu(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=Od(e);if(n&&this.clearedToolCallIds.has(n))return!0;let r=Ad(e);if(r&&this.clearedMessageIds.has(r))return n&&this.clearedToolCallIds.add(n),!0;let i=kd(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=kd(e);t&&this.clearedMessageIds.add(t);let n=Od(e);n&&this.clearedToolCallIds.add(n)}isRunlessChunkFromIgnoredRun(e){return Vu(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 Md(e){return e.resumable}function Nd(e,t){let n=zu(e.descriptor);return n?{...t,metadata:Ru(n)}:t}function Pd(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`]),Id=/* @__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 Ld(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Rd(e){return gl(e)}function zd(e){if(!Ld(e.metadata))return!1;let t=e.metadata[ll];return!Ld(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 Bd(e){if(!Ld(e.metadata))return!1;let t=e.metadata[ll];return!Ld(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 Hd(e){if(e.responseSchema!==void 0)try{return ls(cs(e.responseSchema))}catch{return}}function Ud(e){if(e!==void 0)try{return Fu(e)}catch{return}}function Wd(e){return e!==null&&(typeof e==`object`||typeof e==`function`)&&`then`in e&&typeof e.then==`function`}function Gd(e,t,n){if(e===void 0)return{valid:!0,payload:t};if(ms(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 Wd(r)?Promise.resolve(r).then(i):i(r)}return{valid:!0,payload:t}}function Kd(e){for(let t of Fd)if(t===e)return!0;return!1}function qd(e){for(let t of Id)if(t===e)return!0;return!1}function Jd(e){if(!Ld(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`?Kd(n)&&typeof e.interruptId==`string`&&(e.source===`client`||e.source===`server`):t===`batch`&&qd(n)&&Array.isArray(e.interruptIds)&&e.interruptIds.every(e=>typeof e==`string`)&&(e.source===`client`||e.source===`server`||e.source===`transport`)}function Yd(e){return Jd(e)?[e]:!Ld(e)||!Array.isArray(e.errors)?[]:e.errors.every(Jd)?e.errors:[]}function Xd(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 Zd(e,t){return e.threadId===t.threadId&&e.interruptedRunId===t.interruptedRunId&&e.generation===t.generation&&Xd(e.interruptIds,t.interruptIds)}function Qd(e,t,n){let r=n.filter(e=>e.source!==`transport`),i=e=>t.includes(e)&&r.some(t=>Zd(e,t)),a=e.filter(e=>!i(e)),o=t.filter(e=>!r.some(t=>Zd(e,t)));return Object.freeze({rootErrors:Object.freeze([...a,...n]),submissionRootErrors:Object.freeze([...o,...r])})}function $d(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):Xd(e.interruptIds,n)}function ef(e,t,n){let r=Hd(e)??n?.responseSchemaHash;return X({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 tf(e,t){let n=X(e.descriptor),r=e.error===void 0?Object.freeze([]):Object.freeze([X(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 nf=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:X(e.interrupts)};let n=/* @__PURE__ */ new Map;for(let t of e.interrupts){let e=Rd(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)Md(e)&&(e.validationGeneration++,e.resolution=Object.freeze(Nd(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=X(Hs(Nd(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=X(e),i=Rd(r);if(i===void 0)return zd(r)?{descriptor:r,binding:ef(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&&Hd(r)===i.responseSchemaHash,o=i.interruptId===r.id&&i.interruptedRunId===t.interruptedRunId&&i.generation===t.generation&&i.responseSchemaHash===(Hd(r)??i.responseSchemaHash);if(Bd(r)&&(!o||i.kind!==`generic`||i.definitionId===void 0||i.key===void 0||i.batchIndex===void 0))return{descriptor:r,binding:ef(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=ks(e.approvalSchema,e.inputSchema);if(As(e.inputSchema)===i.inputSchemaHash&&t.approvalSchemaHash===i.approvalSchemaHash&&t.responseSchemaHash===i.responseSchemaHash)return{descriptor:r,binding:X(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(As(e.outputSchema)===i.outputSchemaHash)return{descriptor:r,binding:X(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:X(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&&Ud(e.responseSchema)===i.responseSchemaHash&&(e.payloadSchema===void 0?i.payloadSchemaHash===void 0:i.payloadSchemaHash===Ud(e.payloadSchema))){let t=Vd(r);return{descriptor:r,binding:X(i),definition:e,kind:`generic`,status:`pending`,canResolve:!0,resumable:!0,...t===void 0?{}:{payload:X(t)},validationGeneration:0}}}let s=i.interruptId===r.id&&i.interruptedRunId===t.interruptedRunId&&i.generation===t.generation&&(i.kind!==`generic`||Hd(r)===void 0||i.responseSchemaHash===Hd(r));return{descriptor:r,binding:ef(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=tf(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=X(n.binding),i={...r,kind:`tool-approval`,binding:t,toolName:n.binding.toolName,toolCallId:n.binding.toolCallId,originalArgs:X(n.binding.originalArgs),cancel:()=>this.cancelItem(n.descriptor.id,e),clearResolution:()=>this.clearItem(n.descriptor.id,e),resolveInterrupt:(t,r)=>{let i=Ld(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`?X(n.binding):X({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);Wd(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(Nd(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=>Md(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=cl(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=X(Nd(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=Gd(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 Wd(n)?Promise.resolve(n).then(r):r(n)}if(e.kind===`client-tool-execution`){let n=Gd(e.tool?.outputSchema,t,`invalid-tool-output`),r=e=>{if(!(`valid`in e))return e;try{return{valid:!0,payload:X(e.payload)}}catch(e){return{code:`invalid-tool-output`,message:e instanceof Error?e.message:String(e)}}};return Wd(n)?Promise.resolve(n).then(r):r(n)}return this.validateApprovalCandidate(e,t)}validateApprovalCandidate(e,t){if(!Ld(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=Gd(e.tool?.inputSchema,r,`invalid-edited-args`);return Wd(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=Gd(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 Wd(o)?Promise.resolve(o).then(s):s(o)}approvalBranchSchema(e,t){let n=e?.approvalSchema;return!Ld(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=>Md(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=X({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(Pd),i;try{for(let t of r){let n=e(t);if(n!==void 0){i={code:Wd(n)?`async-resolver`:`inactive-transaction`,message:Wd(n)?`Interrupt transaction resolvers must be synchronous.`:`Interrupt transaction resolvers must return literal undefined.`};break}}i===void 0&&this.items.some(e=>Md(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)Md(e)&&(e.status=`submitting`);this.publish(),this.performSubmission(t)}async performSubmission(e){try{await this.options.submit(e.submission)}catch(t){if(this.activeSubmissionOperation!==e)return;this.handleSubmissionFailure(t,e.submission)}finally{this.activeSubmissionOperation===e&&(this.activeSubmissionOperation=void 0,this.resuming=!1,this.publish())}}handleSubmissionFailure(e,t){let n=Yd(e);if(n.length===0){let n=e instanceof Error?e.message:String(e);this.addRootError(`transport`,n,!0,`transport`),this.retrySubmission=t;for(let e of this.items)Md(e)&&(e.status=`error`);return}let r=n.filter(e=>$d(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=>Md(t)&&t.descriptor.id===e.interruptId);t&&(t.status=`error`,t.error=X(e))}else o.push(X(e));let s=Qd(this.rootErrors,this.submissionRootErrors,o);this.rootErrors=s.rootErrors,this.submissionRootErrors=s.submissionRootErrors;for(let e of this.items)Md(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(Md).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})}},rf=8;function af(e,t){return new Promise((n,r)=>{let i=()=>r(Object.assign(/* @__PURE__ */ Error(`Aborted`),{name:`AbortError`}));if(t.aborted)return i();t.addEventListener(`abort`,i,{once:!0}),e.then(n,r).finally(()=>{t.removeEventListener(`abort`,i)})})}function of(){let{scheduler:e}=globalThis;return e?.yield?e.yield():new Promise(e=>setTimeout(e,0))}function sf(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 cf(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 lf(e){return`connect`in e}function uf(e){if(e.type!==`RUN_FINISHED`||e.outcome?.type===`interrupt`||Z(e)?.loopStopped===!0)return!1;let t=e;return t.finishReason===void 0?Z(e)?.finishReason===`tool_calls`:t.finishReason===`tool_calls`}function df(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 ff(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=Vs(i,t.content.metadata));return{content:{content:r,...i===void 0?{}:{metadata:i}},...t===void 0?{}:{body:t}}}function pf(e){if(typeof e==`object`&&e&&!Array.isArray(e)&&`approved`in e&&typeof e.approved==`boolean`)return e.approved}function mf(e,t,n){let r=ks(n.tool.approvalSchema,n.tool.inputSchema);return hl({id:e,reason:`tool_call`,message:`Approval required to run ${n.toolName}`,toolCallId:n.toolCallId,responseSchema:r.responseSchema,metadata:{kind:`approval`,toolName:n.toolName,input:n.input}},{v:1,kind:`tool-approval`,interruptId:e,interruptedRunId:t,generation:0,toolName:n.toolName,toolCallId:n.toolCallId,originalArgs:n.input,inputSchemaHash:As(n.tool.inputSchema),approvalSchemaHash:r.approvalSchemaHash,responseSchemaHash:r.responseSchemaHash})}function hf(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 gf=2e3,_f=/* @__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 vf(e){return e.type===`REASONING_ENCRYPTED_VALUE`?e.subtype===`message`&&typeof e.encryptedValue==`string`&&e.encryptedValue.length>0:_f.has(e.type)}function yf(e){return e.map(e=>({...e,parts:e.parts.map(e=>Object.isFrozen(e)?e.type===`subagent`?{...e,subagent:{...e.subagent,messages:yf(e.subagent.messages)}}:{...e}:e)}))}function bf(e){let t=[];for(let n of e)for(let e of n.parts)e.type===`subagent`&&(t.push(e),t.push(...bf(e.subagent.messages)));return t}function xf(e){if(`subagentRunId`in e&&typeof e.subagentRunId==`string`)return e.subagentRunId}var Sf=64;function Cf(e){if(Array.isArray(e))return e.map(Cf);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]=Cf(r));return t}var wf=class{processor;subagentHandles=/* @__PURE__ */ new Map;stoppedSubagentIds=/* @__PURE__ */ new Set;connection;threadId;persistor;clearedStreamTracker=new jd;snapshotAtom=Co({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;pendingLocalApprovals=[];localApprovals=null;activeClientTools=null;activeContext=void 0;continuationPending=!1;subscriptionAbortController=null;clientToolAbortController=new AbortController;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(sf(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 Dd(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=df(e.queue);let n=cf(e);if(this.connectionDrainsOnSend=lf(n),this.connection=_d(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??qo)(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 nf({...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&&yf(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 ou({...e.streamProcessor?.chunkStrategy?{chunkStrategy:e.streamProcessor.chunkStrategy}:{},...a?{initialMessages:a}:{},events:{onMessagesChange:e=>{this.syncSubagentHandles(),this.persistor?.notifyMessagesChanged(e),jo(this.snapshotAtom,{messages:Ao(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,n)=>{this.currentStreamId&&this.events.thinkingUpdated(this.currentStreamId,e,n,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);this.handingOverPendingToolCalls&&t?.needsApproval===!0?this.pendingLocalApprovals.push({...e,tool:t}):t&&this.runClientTool(e,t)},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=hf(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=ts(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 Lo&&this.byok?.request(t.provider,`missing`),t instanceof Ro&&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=Vu(e)??this.clearedStreamTracker.takeRunlessRunId();t&&(this.activeRunIds.delete(t),this.setSessionGenerating(this.activeRunIds.size>0),Vu(e)||this.resolveProcessing())}updateRunLifecycle(e,t){if(e.type===`RUN_STARTED`){let t=Vu(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=Vu(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`&&uf(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=Vu(e),n=`threadId`in e&&typeof e.threadId==`string`?e.threadId:this.activeResumeThreadId;if(t&&!uf(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<Sf;){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&&(jo(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.localApprovals;if(t?.runId===e.interruptedRunId){this.localApprovals=null,this.interruptManager.reset();for(let n of e.resolutions){let e=t.calls.get(n.interruptId);e&&this.answerLocalApproval(e,n.payload)}return}let n=this.continuationGeneration;this.activeInterruptSubmission=e,this.interruptSubmissionFailure=void 0;for(let t of e.resolutions){let e=pf(t.payload);if(e===void 0)continue;let n=t.interruptId;this.processor.addToolApprovalResponse(n,e)}let r=await this.resumeInterruptsUnsafeForGeneration([...e.resolutions],{threadId:e.threadId,runId:e.interruptedRunId},n).finally(()=>{this.activeInterruptSubmission===e&&(this.activeInterruptSubmission=void 0)});if(n!==this.continuationGeneration)return;let i=this.takeInterruptSubmissionFailure();if(i!==void 0)throw{errors:i.errors};if(!r)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=>Oo(e))):e.content.content;return Object.freeze({...e,content:Object.freeze({...e.content,content:t})})}))}readSnapshot(e){return Object.freeze({...this.snapshotAtom.get(),messages:Ao(this.frozenMessages,this.processor.getMessages()),queue:this.freezeSnapshotQueue(this.getQueue()),isHydrating:e,interruptState:this.interruptManager.getState()})}subscribeSnapshot=e=>No(this.snapshotAtom,e);getSnapshot=()=>this.snapshotAtom.get();setIsLoading(e){jo(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){jo(this.snapshotAtom,{status:e}),this.callbacksRef.current.onStatusChange(e),this.devtoolsBridge.emitSnapshot()}setIsSubscribed(e){jo(this.snapshotAtom,{isSubscribed:e}),this.callbacksRef.current.onSubscriptionChange(e),this.devtoolsBridge.emitSnapshot()}setConnectionStatus(e){jo(this.snapshotAtom,{connectionStatus:e}),this.callbacksRef.current.onConnectionStatusChange(e),this.devtoolsBridge.emitSnapshot()}syncIsHydrating(){let e=this.hydrationInFlight!==void 0||this.storeHydrating;this.isHydrating!==e&&(jo(this.snapshotAtom,{isHydrating:e}),this.callbacksRef.current.onHydratingChange(e))}setSessionGenerating(e){this.sessionGenerating!==e&&(jo(this.snapshotAtom,{sessionGenerating:e}),this.callbacksRef.current.onSessionGeneratingChange(e),this.devtoolsBridge.emitSnapshot())}notifyResumeStateChange(e){let t=this.getResumeState(),n=this.interruptManager.getState();jo(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){jo(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:Cf(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<rf||(n=0,typeof document<`u`&&document.hidden||await of())}}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()},gf);try{for await(let a of t(e,n.signal)){if(n.signal.aborted)break;i||(i=!0,clearTimeout(o)),!r&&vf(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=Mu(e),e.type===`RUN_ERROR`&&this.isActiveInterruptSubmissionFailure(e)){let t=Z(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`)&&(Vu(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=xf(e);if(t&&e.type===Q.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.raiseLocalApprovals(),this.resolveJoinedRun(e)}}raiseLocalApprovals(){if(this.pendingLocalApprovals.length===0)return;let e=this.generateUniqueId(`local-approval`),t=new Map(this.pendingLocalApprovals.map(e=>[`local_approval_${e.toolCallId}`,e]));this.pendingLocalApprovals=[],this.localApprovals={runId:e,calls:t},this.interruptManager.hydrate({threadId:this.threadId,interruptedRunId:e,generation:0,interrupts:Array.from(t,([t,n])=>mf(t,e,n))})}answerLocalApproval(e,t){let n=e=>typeof t==`object`&&t?Reflect.get(t,e):void 0;pf(t)===!0?this.runClientTool({...e,input:n(`editedArgs`)??e.input},e.tool):this.addToolResultForClientTool({toolCallId:e.toolCallId,tool:e.toolName,output:n(`payload`)??{error:`User declined tool execution`},state:`output-error`,errorText:`User declined tool execution`},e.tool,this.continuationGeneration)}isActiveInterruptSubmissionFailure(e){let t=this.activeInterruptSubmission,n=Z(e)?.interruptErrors;if(!t||!Array.isArray(n)||n.length===0)return!1;let r=Vu(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=Vu(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=Fc(e,Ic);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=Ho(this.byokProvider,f.provider,Vo(this.byok));m=await Uo(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?ys(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 af(Promise.all(this.pendingToolExecutions.values()),a),this.handingOverPendingToolCalls=!0;try{this.processor.finalizeStream()}finally{this.handingOverPendingToolCalls=!1}this.raiseLocalApprovals(),this.pendingToolExecutions.size>0&&await af(Promise.all(this.pendingToolExecutions.values()),a),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),!a.aborted&&e===this.streamGeneration&&this.stop(),!1;if(n instanceof Lo&&this.byok?.request(n.provider,`missing`),n instanceof Ro&&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 Lo||n instanceof Ro||n instanceof zo))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,t=e?this.currentRunId:null;if(t){let e={runId:t,threadId:this.threadId};(async()=>this.connection.cancelRun?.(e))().catch(()=>{})}this.cancelInFlightStream({setReadyStatus:!0}),this.clientToolAbortController.abort(),this.clientToolAbortController=new AbortController,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)}runClientTool(e,t){let n=t.execute;if(!n)return;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,abortSignal:this.clientToolAbortController.signal,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)}async addToolResultForClientTool(e,t,n,r){if(e.state!==`output-error`)try{let n=t?.outputSchema&&ms(t.outputSchema)?await this.validateClientToolOutput(t,e.output):e.output;this.interruptManager.getDescriptors().some(t=>t.toolCallId===e.toolCallId)&&(n=X(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 bs(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=Ys(n.metadata);return r===void 0?n:{...n,input:r}},t=bf(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:Q.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=ts(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){jo(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||this.hasOpenInterrupts()}hasOpenInterrupts(){return this.interruptManager.getInterrupts().length>0}async drainQueue(){if(!(this.messageQueueDraining||this.isLoading||this.hasOpenInterrupts()||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=ff(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();jo(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(yf(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=cf({connection:e.connection,fetcher:e.fetcher});this.connectionDrainsOnSend=lf(n),this.connection=_d(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=df(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 Tf=e=>`background:${e};color:#fff;border-radius:3px;padding:1px 5px`,Ef=`${Tf(`#7c3aed`)};font-weight:600`,Df={mount:`#7c3aed`,auth:`#be185d`,theme:`#8b5cf6`,send:`#2563eb`,run:`#0891b2`,stream:`#0e7490`,text:`#16a34a`,reasoning:`#64748b`,tool:`#d97706`,widget:`#db2777`,attachment:`#0d9488`,sandbox:`#0369a1`,questionnaire:`#9333ea`,status:`#475569`,error:`#dc2626`};function Of(e){if(e)return(e,t,n)=>{console.log(`%cAstralBeam%c ${(/* @__PURE__ */ new Date()).toISOString().slice(11,19)} %c${e}%c ${t}`,Ef,`color:#94a3b8;font-weight:400`,Tf(Df[e]),``,...n===void 0?[]:[n])}}function kf(){let e=crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16)),t=Date.now(),n=new DataView(e.buffer);n.setUint16(0,Math.floor(t/4294967296)),n.setUint32(2,t),e[6]=e[6]&15|112,e[8]=e[8]&63|128;let r=Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``);return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}function Af(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 jf(e,t,n){return`saved:${e}:${t}${n?`:${n}`:``}`}async function Mf(e,t,n,r=/* @__PURE__ */ new Map){let i=await Mr(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:jf(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 Nf(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(jf(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=jf(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 Pf(e){return e.placementKey??e.agentId??`default`}function Ff(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 If;function Lf(e,t){return JSON.stringify([e,Pf(t)])}function Rf(e,t,n){if(!n){if(!If)try{let e=`astralbeam:draft-session`;If=globalThis.sessionStorage?.getItem(e)??kf(),globalThis.sessionStorage?.setItem(e,If)}catch{If??=kf()}n=`new:${If}`}return JSON.stringify([e.replace(/\/+$/,``),t,n])}function zf(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 Bf(e,t,n,r,i=`draft`){if(!t)return``;let a=`astralbeam:${i}:${Rf(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 Vf(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 Hf(e,t){if(!e.identity||!e.threadId)return;let n=`astralbeam:pending:${Rf(e.apiUrl,e.identity,e.threadId)}`;try{let e=globalThis.sessionStorage;if(!e)return;if(t&&`save`in t)return Vf(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||!Vf(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 Uf({apiUrl:e,identity:t,threadId:n,update:r,moveTo:i}){let a=()=>{if(!t)return[];let a=`astralbeam:attachments:${Rf(e,t,n)}`,o=e=>{let t=JSON.parse(globalThis.localStorage?.getItem(e)??`[]`);if(!Array.isArray(t)||!t.every(zf))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:${Rf(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 Wf(e){return e?`~standard`in e?`jsonSchema`in e[`~standard`]?ys(e):{type:`object`}:e:{type:`object`,properties:{}}}async function Gf(e,t){let n=await bs(e,t);return n.success?n.data??{}:null}const Kf=Symbol(`Host tool was not executed`);function qf(e,t,n,r,i){return[...Object.keys(e).length>0?[Jf(e,n)]:[],Yf(),...Xf(t,r,i)]}function Jf(e,t){return ns({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(Wf(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 Yf(){return ns({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 Xf(e,t,n){return Object.entries(e).map(([e,r])=>ns({name:e,description:r.description,inputSchema:Wf(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 Gf(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=X(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,{[Kf]:!0}),r}}))}function Zf(e){if(e.length>16384)throw Error(`The chat auth token is too large`);let{exp:t,iat:n,user:r}=so(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 Qf(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 $f={status:`loading`};function ep(e){return{...e,fetchAstralBeamToken:e.fetchAstralBeamToken,session:{cached:void 0,refreshPromise:void 0,abortController:new AbortController,state:$f,listeners:/* @__PURE__ */ new Set},fetchClient:globalThis.fetch.bind(globalThis),debug:void 0}}function tp(e){return e.session.state}function np(e,t){let{listeners:n}=e.session;return n.add(t),()=>{n.delete(t)}}function rp(e,t){e.session.state=t;for(let t of e.session.listeners)t()}function ip(e,t){e.apiUrl!==t.apiUrl&&(up(e),e.session.abortController=new AbortController,rp(e,{status:`loading`})),e.apiUrl=t.apiUrl,e.fetchAstralBeamToken=t.fetchAstralBeamToken}function ap(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 op(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 Qf(e,i);if(i.throwIfAborted(),typeof s!=`string`||!s)throw Error(`${a} did not return a token`);let{expiresAt:c,refreshAt:l,tenantAdmin:u}=Zf(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 Fr({apiUrl:r,astralBeamToken:s,fetchClient:e.fetchClient,signal:i,cache:`no-store`,credentials:`omit`})}catch(t){if(!o&&e.retryUnauthorized!==!1&&sr(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},rp(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 sr(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,rp(e,{status:`error`,error:r}),r}}async function sp(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())&&rp(e,{status:`loading`});let r=op(e);t.refreshPromise=r;try{return await r}finally{t.refreshPromise===r&&(t.refreshPromise=void 0)}}function cp(e,t){let n=!t||e.session.cached?.value===t;return n&&(e.session.cached=void 0),sp({...e,force:n,retryUnauthorized:!1})}async function lp(e){e.session.abortController.signal.aborted&&(e.session.abortController=new AbortController),await sp(e)}function up({session:e}){e.abortController.abort(),e.refreshPromise=void 0,e.cached=void 0,e.state=$f}async function dp(e){let{input:t,init:n,session:r,fetchClient:i,debug:a}=e,o=tp(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 cp(e,u),f=tp(e);if(o.status!==`ready`||f.status!==`ready`||ap(o.currentUser)!==ap(f.currentUser))throw new DOMException(`Identity changed`,`AbortError`);return n?.signal?.throwIfAborted(),c.set(`authorization`,`Bearer ${d}`),await i(t,{...n,headers:c})}function fp(e){let t,n=new AbortController,r=0,i=()=>typeof document>`u`||document.visibilityState!==`hidden`&&globalThis.navigator?.onLine!==!1,a=()=>{!n.signal.aborted&&i()&&sp({...e,force:!0}).catch(()=>{})},o=()=>{if(clearTimeout(t),n.signal.aborted||typeof document>`u`||!i())return;let o=tp(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=np(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 lp(e).catch(()=>{}),o(),()=>{n.abort(),clearTimeout(t),c()}}async function pp(e,t){switch(e.action){case`connect`:case`headers`:{let n=await zr({mcp_server_id:e.mcpServerId},t);return e.action===`connect`?n:(await Vr(n.id,{lock_version:n.lock_version,headers:e.headers},t),{id:n.id})}case`disconnect`:return Ur(e.id,t);case`test`:return Gr(e.id,t)}}async function mp(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 zr({mcp_server_id:e.mcpServerId},await t())).id,i=await qr(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 Yr(r,{attempt_id:a.id,challenge:u.challenge},await m()),d.signal.throwIfAborted(),u={state:`completing`}),u.state===`completing`){let e=await Zr(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 hp(e){return e.state===`complete`||e.state===`error`||e.output!==void 0}function gp(e){return e.metadata??{}}function _p(e,t){return typeof e==`object`&&e&&t in e?e[t]:void 0}function vp(e,t){let n=_p(e,t);return typeof n==`string`?n:void 0}function yp(e,t){let n=_p(e,t);return typeof n==`number`?n:void 0}function bp(e){return vp(e.output,`refusal`)}function xp(e){if(e.name!==`sandbox_write_file`)return;let t=vp(e.output,`path`)??vp(e.input,`path`);if(t===void 0)return;let n=vp(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&&bp(e)===void 0}}function Sp(e){let t=vp(e.output,`relativePath`);return t!==void 0&&t!==`.`?t:vp(e.output,`path`)??vp(e.input,`path`)}function Cp(e){if(e.name!==`sandbox_run_command`)return;let t=vp(e.input,`command`);if(t===void 0)return;let n=e.output;return{toolCallId:e.id,command:t,cwd:vp(e.input,`cwd`),exitCode:yp(n,`exitCode`),stdout:vp(n,`stdout`)??``,stderr:vp(n,`stderr`)??``,durationMs:yp(n,`durationMs`),timedOut:_p(n,`timedOut`)===!0,truncated:_p(n,`truncated`)===!0,finished:n!=null}}function wp(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=xp(e);r?.written&&t.set(r.path,r);let i=Cp(e);i&&bp(e)===void 0&&n.push(i)}return{files:[...t.values()],commands:n}}const Tp=`Refresh this conversation or start a new one before sending.`,Ep=`This message may not have been sent. Retry to send it.`,Dp=`This message could not be confirmed within 24 hours. Check the saved conversation before sending it again.`;function Op(e,t){return e.length===t.length&&e.every((e,n)=>e.name===t[n]?.name&&e.title===t[n]?.title)}function kp(e,t=!1){let n={...e},r=Of(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,preparingContext:!1,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===P&&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(Ep)):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=ep({apiUrl:n.apiUrl,scope:`tenant`,fetchAstralBeamToken:n.fetchAstralBeamToken??{url:`/api/astralbeam/token`}}),ie,ae,S,oe=e=>{let t=tp(x);if(t.status===`ready`)return{apiUrl:n.apiUrl??`https://astralbeam.ai/api`,identity:Lf(ap(t.currentUser),n),threadId:e}},se=e=>{let t=oe(e),n=t&&Hf(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)?Dp:Ep),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(Tp);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=kf(),ye=e=>{if(!e.delivery?.scope)return;let{scope:t,draftFileIds:n}=e.delivery,i=()=>Hf(t,{clearKey:e.key});if(n&&Bf(t.apiUrl,t.identity,t.threadId,``,`sent`),!n?.length)return void i();let a=new Set(n);Uf({...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=[...P.getSnapshot().messages],n=t.findLastIndex(e=>e.role===`user`&&e.metadata?.astralbeamSubmissionId===c?.id);if(n!==-1){let r=Nf([e])[0];t.some((t,r)=>r!==n&&t.id===e.id)?t.splice(n,1):t[n]=r,_e([r]),P.setMessagesManually(t),F&&Ke()}},E=/* @__PURE__ */ new Set,D=/* @__PURE__ */ new Map,O=/* @__PURE__ */ new Map,k=/* @__PURE__ */ new Map,Se=/* @__PURE__ */ new Map,Ce=e=>{let t=D.get(e);return t?`live:${t}:${e}`:e},we=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=jf(n.source_message_id,n.source_part_id,n.response_target_id),i=k.get(e)??k.get(r);i&&(t.set(r,i),D.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)},Te=e=>{(s.auth.status!==`error`||s.auth.error!==e)&&n.streamCallbacks?.onError?.(e)},Ee=e=>{if(e instanceof Error&&e.name===`AbortError`)return;let t=e instanceof Error?e:Error(String(e));p({error:t}),Te(t)},De=e=>{p({unavailableMcpConnections:s.unavailableMcpConnections?.filter(t=>t!==e)??[]})},A=async(e=!0)=>{let t=C,n=x.session.abortController.signal,r=await sp(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)=>dp({...x,input:e,init:t})}},Oe=0,ke,j=async()=>{let e=++Oe,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 A();if(e!==Oe||t!==C)return;let a=await Sr(i?{agentId:i}:{},n);if(e!==Oe||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)}},M=/* @__PURE__ */ new Map,Ae=/* @__PURE__ */ new Set,je=/* @__PURE__ */ new Set,Me=0,Ne=()=>{Me++;for(let e of M.values())e();M.clear(),Ae.clear(),je.clear()},Pe=async(e,t)=>{if(!o().onRenderWidget)return{widget:e.widget,rendered:!1};let n=C,r=Me,i=o().widgets??{};if(!Object.hasOwn(i,e.widget))throw Error(`Unknown widget "${e.widget}"`);let a=i[e.widget],c=await Gf(a?.parameters,e.props??{});if(n!==C||r!==Me||s.thread?.role===`viewer`)return{widget:e.widget,rendered:!1};if(a!==o().widgets?.[e.widget])return Pe(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};M.get(t)?.(),M.delete(t);let u,d=l({widget:e.widget,props:c,toolCallId:t,release:()=>{M.get(t)===u&&M.delete(t)}});return d&&(u=d,M.set(t,d)),Ae.add(t),{widget:e.widget,rendered:!0}},Fe=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=jf(e.id,t.id),a=n.applicationPartId?jf(e.id,n.applicationPartId,n.responseTargetId):r,o=n.upstreamToolCallId,s=n.widgetRenderId??i?.get(r)??i?.get(a)??(o&&D.get(o)===e.id&&Ae.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})),Ie=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(Ae.has(t)||je.has(t))continue;je.add(t);let n=C,i=Me,{widgets:a,onRenderWidget:c}=o();Pe(e.input,t).catch(e=>r?.(`error`,`Saved widget could not be rendered`,e)).finally(()=>{n===C&&i===Me&&(je.delete(t),(a!==o().widgets||c!==o().onRenderWidget)&&Ie(s.messages))})}},Le=()=>{let e=C;return qf(o().widgets??{},n.tools??{},Pe,r,(t,r,i)=>{let a=le,o=P,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!==P||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=k,a=Ce(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&&Kf in e)&&S===s&&x.apiUrl===c&&i.set(a,{outcome:`unknown`,output:{error:e instanceof Error?e.message:String(e)},clientId:o}),e}}}})},Re=()=>{let e=Le(),t=e.map(e=>{let t=e.metadata?.title;return{name:e.name,title:typeof t==`string`&&t.length>0?t:void 0}});return Op(s.agentTools,t)||p({agentTools:t}),e},ze=()=>n.debug?{debug:!0}:{},Be=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=br(),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(Dp);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{Ye();let e=await Mf(r.id,t,void 0,D);if(!h(n))throw new DOMException(`Request cancelled`,`AbortError`);p({thread:Af(e.thread,e.messages.length>0)}),we(e);let s=e.pendingInteractions.filter(e=>k.has(Ce(e.toolCallId))),c=s.find(e=>e.toolCallId===i.messages.at(-1)?.toolCallId)??s[0];n.clientId=(c&&k.get(Ce(c.toolCallId))?.clientId)??ve;let l=e.pendingInteractions.flatMap(e=>{let t=k.get(Ce(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=Nr(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;Hf(e,{save:{id:n,key:r,content:i,...t}})&&t.draftFileIds&&Bf(e.apiUrl,e.identity,e.threadId,``,`sent`)}}let d=await pr(a,{...t,...e,headers:u,body:JSON.stringify(o)}).catch(e=>{if(!h(n))throw e;c&&!l&&sr(e)&&(e.status===400||e.status===413||e.status===429)&&(c.delivery?.scope&&Hf(c.delivery.scope,{clearKey:c.key}),c.delivery=void 0);let t=sr(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 Mf(r.id,t,void 0,D);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},Ve=xd(()=>cr(br(),x.apiUrl),async()=>{let e=f;if(!e||!h(e))throw new DOMException(`Request cancelled`,`AbortError`);let t=await A();if(!h(e))throw new DOMException(`Request cancelled`,`AbortError`);return{fetchClient:(n,r)=>Be(r??{},{...t,signal:r?.signal??t.signal},e)}}),He=Ve.connect;Ve.connect=async function*(...e){try{for await(let t of He(...e)){if(t.type===Q.TOOL_CALL_START&&t.parentMessageId&&D.set(t.toolCallId,t.parentMessageId),t.type!==Q.MESSAGES_SNAPSHOT){yield t;continue}let e;yield{...t,messages:t.messages.map(t=>t.role===`assistant`?(e=O.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&&sr(e.cause)?e.cause:e}};let Ue=()=>{let e=new wf({connection:{...Ve,hydrate:(t,n)=>{let r=N;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 Mf(r,await A(),n?.before,D);for(;n?.before&&t.messages.every(e=>e.role===`tool`)&&t.page_after;){let e=await Mf(r,await A(),t.page_after,D);t={...e,messages:[...e.messages,...t.messages]}}if(!o())throw new DOMException(`Conversation changed`,`AbortError`);i||we(t),T=i?[...t.messages,...T]:t.messages;let a=new Set(t.messages.map(e=>e.id)),l=Nf(T,i?s.pendingInteractions:t.pendingInteractions,D).filter(e=>a.has(e.id));if(_e(l),i)p({messagesCursor:t.page_after??void 0});else{t.thread.role===`viewer`&&Ne();let n=s.thread?.agentId!==t.thread.agent_id;c??=se(r),p({thread:Af(t.thread,t.messages.length>0),messagesCursor:t.page_after??void 0,pendingInteractions:t.pendingInteractions,submission:c&&v(c)}),n&&j(),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,F&&Ke(),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:N??ve,persistence:!0,history:{pageSize:100},queue:`drop`,tools:Re(),forwardedProps:ze(),onInterruptStateChange:t=>{P===e&&r?.(`tool`,`interrupt state changed`,t)},onCustomEvent:(t,n)=>{if(P!==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)||k.delete(Ce(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}if(t===`compaction:started`||t===`compaction:ended`){p({preparingContext:t===`compaction:started`});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=>{P===e&&(t.type===Q.RUN_STARTED&&p({serverToolTitles:{},unavailableMcpConnections:[]}),n.streamCallbacks?.onChunk?.(t))},onResponse:t=>{P===e&&n.streamCallbacks?.onResponse?.(t)},onFinish:t=>{P===e&&n.streamCallbacks?.onFinish?.(t)},onError:t=>{P===e&&(c?.phase!==`submitting`&&t.name!==`AbortError`&&p({error:t}),Te(t))}});return e},N,P=Ue(),F,We,Ge=-1,Ke=()=>{let e=P.getSnapshot(),t=We!==e.messages||Ge!==he;if(!t&&d===e.status)return;let n={};(e.status===`ready`||e.status===`error`)&&(n.preparingContext=!1),d!==e.status&&e.status===`submitted`&&(n.usageLimitReached=void 0),d=e.status,t&&(n.messages=Fe(e.messages),n.sandbox=wp(n.messages),We=e.messages,Ge=he),p(n),t&&Ie(s.messages)},qe=()=>{if(!F){let e=P,t=C;F=e.subscribeSnapshot(()=>{P===e&&t===C&&Ke()}),Ke(),Ie(s.messages)}P.attach()},Je=e=>{let t=P;f=void 0,u=void 0,F?.(),F=void 0,We=void 0,P=Ue(),e&&P.setMessagesManually(e),d=`ready`,t.stop(),t.detach(),E.clear(),p({activeToolCallIds:[]}),ce&&qe(),t.dispose()},Ye=()=>{O.clear(),P.setMessagesManually(P.getSnapshot().messages.map(e=>{let t=/* @__PURE__ */ new Map,n=e.parts.map(n=>{if(n.type!==`tool-call`||gp(n).providerExecuted)return n;let r=n,i=r.upstreamToolCallId??n.id;if(D.get(i)===e.id&&!hp(n))return n;let a=jf(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(jf(e.id,n.id))??n.id}:{}}});return t.size&&O.set(e.id,t),{...e,parts:n}}))},Xe=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),Se.set(t,k)),C++,u=void 0,N=e,fe.abort(),fe=new AbortController,k=Se.get(e??``)??/* @__PURE__ */ new Map,O.clear(),D.clear(),T=[],me.clear(),ge=/* @__PURE__ */ new WeakMap,he++,Ne(),p({thread:void 0,messages:[],submission:void 0,error:void 0,sandbox:{files:[],commands:[]},sandboxStatus:void 0,preparingContext:!1,usageLimitReached:void 0,pendingInteractions:[],serverToolTitles:{},unavailableMcpConnections:[],messagesCursor:void 0,olderMessagesLoading:!1}),Je()},Ze=async(e,t=!1)=>{Xe(e);let r=C;c=l.get(e),c&&p({submission:v(c)});try{if(ce||qe(),await ue({client:P,selection:r}),r!==C)return;w&&Ff(w,e)}catch(e){if(r!==C)return;t&&(n.threadId===void 0||n.threadId===`auto`)&&sr(e)&&e.status===404?Qe():Ee(e)}},Qe=()=>{Xe(),ce&&j(),w?Ff(w,null):pe=!0},$e=(e=!1)=>{let t=n.threadId;if(t===void 0||t===`auto`){if(!w)return;t=Ff(w)}t&&t!==`new`?t===s.thread?.id&&w?Ff(w,t):Ze(t,e):e||Qe()},I=async e=>{if(s.thread)return;let t=await A();if(!ne(e))throw new DOMException(`Send cancelled`,`AbortError`);let r=await wr(n.agentId?{agent_id:n.agentId}:{},t);if(!ne(e))throw new DOMException(`Send cancelled`,`AbortError`);N=r.id,p({thread:Af(r,!1)}),j(),w&&Ff(w,r.id)},et=async(e=!0)=>{if(!N||P.getIsLoading())return;let t=C;try{P.detach(),qe(),await ue({client:P,selection:t}),e&&t===C&&p({error:void 0})}catch(e){if(t!==C)return;sr(e)&&e.status===404?Qe():Ee(e)}},tt=async()=>{if(!P.getHasOlderMessages()||s.olderMessagesLoading||s.history!==`idle`||c?.phase===`submitting`)return;let e=C;p({olderMessagesLoading:!0});try{await P.loadOlderMessages(),e===C&&F&&Ke()}catch(t){e===C&&Ee(t)}finally{e===C&&p({olderMessagesLoading:!1})}},L=async e=>{let t=s.thread;if(!t||t.role!==`manager`)return!1;let n=C;try{let r=await Or(t.id,{title:e,expected_version:t.version},await A());if(n!==C)return!1;let i=Af(r,t.hasMessages);return p({thread:i}),!0}catch(e){return n===C&&Ee(e),!1}},nt=async(e=s.thread)=>{if(!e||e.role!==`manager`)return!1;let t=C;try{return await Ar(e.id,{expected_version:String(e.version)},await A()),t===C&&s.thread?.id===e.id&&Qe(),!0}catch(e){return t===C&&Ee(e),!1}},rt=async e=>{let t=C;if(f||c?.phase===`submitting`||P.getIsLoading()){Ee(/* @__PURE__ */ Error(`Wait for this client's current request to finish before responding.`));return}let n=tp(x),r=Ce(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&&!k.has(r)){Ee(/* @__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:P,selection:t};f=l;try{if(p({}),!h(l)||(Ye(),!h(l)))return;if(i){if(l.client.stop(),await et(!1),!h(l))return;await l.client.append({role:`tool`,toolCallId:e.toolCallId,content:JSON.stringify(k.get(Ce(e.toolCallId)))})}else`tool`in e&&await l.client.addToolResult(e);h(l)&&await et(!1)}finally{g(l)}},it=e=>rt({toolCallId:e}),at=async e=>{if(e!==c||e.phase!==`submitting`)return v(e);let t={kind:`submission`,submission:e,client:P,selection:C};f=t;try{if(await sp(x),!await de(t)||(await I(t),!ne(t))||(e.callbacks?.onThreadReady?.(s.thread.id),!ne(t))||(Ye(),!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 et(!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)&&Te(r)}finally{g(t)}return v(e)},ot=async(e,t)=>{let n=f||c?.phase===`submitting`||P.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`?Tp: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:kf(),content:e,phase:`refused`,error:Error(n)};let r={id:kf(),content:e,phase:`submitting`,key:kf(),callbacks:t};c=r,p({submission:v(r),error:void 0,olderMessagesLoading:!1}),P.stop(),E.clear(),Ye(),D.clear(),p({activeToolCallIds:[]});let i=new Promise(e=>r.onRefused=e);return Promise.race([at(r),i.then(()=>v(r))])},st=async()=>{let e=c;if(!(f||P.getIsLoading()||e?.phase!==`failed`)){if(_(e.delivery)){e.error=/* @__PURE__ */ Error(Dp);let t=v(e);return p({submission:t}),t}if(y(e,`submitting`))return p({error:void 0}),at(e)}},ct=()=>{let e=tp(x),t=s.auth;if(e.status===`ready`){let t=ap(e.currentUser);S!==void 0&&S!==t&&(b(`The account changed before this was sent.`),l.clear(),Se.clear(),k.clear(),Xe(),w=void 0),S=t;let r=JSON.stringify(Pf(n)),i=`astralbeam:thread:${n.apiUrl??`https://astralbeam.ai/api`}:${t}:session:${r}`;w!==i&&(w!==void 0&&Xe(),w=i,pe?(Ff(i,null),pe=!1):$e(!0)),ke!==t&&(ke=t,j())}p({auth:e}),e.status===`error`&&(t.status!==`error`||t.error!==e.error)&&n.streamCallbacks?.onError?.(e.error)},lt=()=>{if(ce)return;ce=!0;let e=fe.signal.aborted&&P.getIsHydrating();P.updateOptions({tools:Re()}),fe.signal.aborted&&(fe=new AbortController),ae=np(x,ct),ct(),ie=fp(x),e?Je(P.getSnapshot().messages):qe()};return t||lt(),{start:lt,getState:()=>s,getOptions:()=>n,attachView:e=>{if(a)throw Error(`This chat session already has a view attached`);let t={options:e},n=()=>{P.updateOptions({tools:Re()}),Ie(s.messages)};return Ne(),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&&(Ne(),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=Pf(n),{widgets:c,onRenderWidget:u}=n;n={...n,...e};let d=Pf(n)!==o;r=Of(n.debug),ip(x,{apiUrl:n.apiUrl,fetchAstralBeamToken:n.fetchAstralBeamToken??{url:`/api/astralbeam/token`}}),x.debug=r,P.updateOptions({tools:Re(),forwardedProps:ze()}),n.apiUrl===i?d?(pe=!1,s.thread&&n.threadId===s.thread.id||Xe(),w=void 0,ct()):n.threadId!==a&&$e():(b(`The chat service changed before this was sent.`),l.clear(),Se.clear(),k.clear(),Xe(),w=void 0,ct()),(c!==n.widgets||u!==n.onRenderWidget)&&Ie(s.messages),ce&&(n.agentId!==t||n.apiUrl!==i||d)&&j()},sendMessage:ot,retry:st,addToolResult:rt,stop:()=>{le++;let e=c,t=f;e?.phase===`submitting`&&re(e),P.stop(),t&&g(t),e?.phase===`refused`&&e.onRefused?.()},retryAuthentication:()=>{sp({...x,force:!0}).catch(()=>void 0)},reload:async()=>{if(P.getIsLoading())return;let e=C;if(await et(),e!==C||s.error)return;let t=/* @__PURE__ */ new Set;for(;e===C;){let e=s.pendingInteractions.find(e=>!t.has(e.sourceMessageId)&&k.has(Ce(e.toolCallId)));if(!e||(t.add(e.sourceMessageId),await rt({toolCallId:e.toolCallId}),s.error))return}},searchThreads:async(e=``,t,n)=>{let r=await A(),i=await Er({q:e,page_size:50,...t?{page_after:t}:{}},{...r,signal:AbortSignal.any([r.signal,...n?[n]:[]])});return{items:i.items.map(e=>Af(e)),page_after:i.page_after}},openThread:Ze,renameThread:L,deleteThread:nt,refreshThread:()=>et(),loadOlderMessages:tt,uploadAttachment:async({data:e,filename:t,mimeType:r})=>{let i=s.thread?s.thread.agentId:n.agentId,[a,o]=await Promise.all([e,A(!1)]);return _r({...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 yr({...e,delivery:`direct`},{...await A(!!e.threadId||!t?.preview),headers:t?.preview?{"X-File-Preview":`true`}:{}})).blob()},getMcpCatalog:async()=>Lr(await A(!1)),manageMcpConnection:async e=>{let t=await pp(e,await A(!1));return`id`in e?De(e.id):t&&`id`in t&&De(t.id),t},authorizeMcpConnection:async e=>{let t=await mp(e,()=>A(!1));De(t)},abandonToolCall:it,reset:()=>{if(r?.(`status`,`conversation reset`),Qe(),s.auth.status===`ready`){let e=Lf(ap(s.auth.currentUser),n),t=n.apiUrl??`https://astralbeam.ai/api`;Bf(t,e,``,``),Bf(t,e,``,``,`sent`),Uf({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,F?.(),F=void 0,P.detach(),Ne(),P.stop(),fe.abort(),C++,Oe++,ke=void 0,ie?.(),ae?.(),up(x),ce=!1,queueMicrotask(()=>{ce||(P.dispose(),w=void 0,me.clear(),ge=/* @__PURE__ */ new WeakMap)}),i.clear()}}}const Ap=e=>e[Symbol.toStringTag],jp=(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.kty===`AKP`&&t.alg===void 0)throw TypeError(`missing "alg" (Algorithm) Parameter value`);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 Mp(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(Xa(t)){if(o=Gp(t),typeof o.kty!=`string`)throw zp(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(jp(e,o,n),o.kty===`oct`)return Ja(o.k);if(!Object.isFrozen(t)){let{key_ops:e}=t;Array.isArray(e)&&Object.freeze(e),Object.freeze(t)}}else{if(!Lp(t))throw zp(r,t,i);let e=i?`secret`:a?`private`:`public`;if(t.type!==e&&(i||[`secret`,`public`,`private`].includes(t.type)))throw TypeError(`${Ap(t)} instances must be of type "${e}" for the ${r} algorithm`);if(Fp(t))return t;if(s=t,s.type===`secret`)return s.export()}Np||=/* @__PURE__ */ new WeakMap;let c=t,l=Np.get(c);if(l?.[r])return l[r];if(l||Np.set(c,l={}),s&&typeof s.toCryptoKey==`function`){let t=s.type===`public`,n=Pp[s.asymmetricKeyDetails?.namedCurve],i=e.resolve?.({crv:n,asymmetricKeyType:s.asymmetricKeyType})??e.subtle;return l[r]=s.toCryptoKey(i,t,e.usages[+!t])}return o??=s.export({format:`jwk`}),o.alg=r,l[r]=await Kp(e,o)}let Np;const Pp={__proto__:null,prime256v1:`P-256`,secp384r1:`P-384`,secp521r1:`P-521`},Fp=e=>{if(e?.[Symbol.toStringTag]===`CryptoKey`)return!0;try{return e instanceof CryptoKey}catch{return!1}},Ip=e=>e?.[Symbol.toStringTag]===`KeyObject`,Lp=e=>Fp(e)||Ip(e);function Rp(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 zp(e,t,n){let r=[`CryptoKey`,`KeyObject`,`JSON Web Key`];return n&&r.push(`Uint8Array`),TypeError(Rp(`Key for the ${e} algorithm must be `,t,...r))}const Bp=(e,t=`algorithm.name`)=>/* @__PURE__ */ TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function Vp(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function Hp(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 Up(e,t,n){let r=e.algorithm;if(r.name!==t.name)throw Bp(t.name);if(t.hash&&r.hash?.name!==t.hash)throw Bp(t.hash,`algorithm.hash`);if(t.namedCurve&&r.namedCurve!==t.namedCurve)throw Bp(t.namedCurve,`algorithm.namedCurve`);if(t.length!==void 0&&r.length!==t.length)throw Bp(t.length,`algorithm.length`);Vp(e,n)}function Wp(e){return{__proto__:null,...e}}function Gp(e){let t=Wp(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 Ga(`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 qp(e,t,n,r=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey(`raw`,e,t,r,[n])),Up(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 Yp=[[`verify`],[`sign`]];function Xp(e){let t={name:`HMAC`,hash:`SHA-${e}`};return{kty:[`oct`],secret:!0,subtle:t,signing:t,usages:Yp}}function Zp(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:Yp,minRsaBits:2048}}function Qp(e,t){return{kty:[`EC`],crv:e,subtle:{name:`ECDSA`,namedCurve:e},signing:{name:`ECDSA`,hash:`SHA-${t}`},usages:Yp}}function $p(){let e={name:`Ed25519`};return{kty:[`OKP`],crv:`Ed25519`,subtle:e,signing:e,usages:Yp}}function em(e){let t={name:`ML-DSA-${e}`};return{kty:[`AKP`],subtle:t,signing:t,usages:Yp}}const tm=Jp({HS256:Xp(256),HS384:Xp(384),HS512:Xp(512),RS256:Zp(256),RS384:Zp(384),RS512:Zp(512),PS256:Zp(256,32),PS384:Zp(384,48),PS512:Zp(512,64),ES256:Qp(`P-256`,256),ES384:Qp(`P-384`,384),ES512:Qp(`P-521`,512),EdDSA:$p(),Ed25519:$p(),"ML-DSA-44":em(44),"ML-DSA-65":em(65),"ML-DSA-87":em(87)});function nm(e){let t=typeof e==`string`?tm[e]:void 0;if(!t)throw new Ga(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}const rm=e=>Math.floor(e.getTime()/1e3),im={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},am=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function om(){throw TypeError(`Invalid time period format`)}function sm(e){typeof e!=`string`&&om();let t=am.exec(e);(!t||t[4]&&t[1])&&om();let n=parseFloat(t[2]),r=Math.round(n*im[t[3][0].toLowerCase()]);return Number.isFinite(r)||om(),t[1]===`-`||t[4]?.toLowerCase()===`ago`?-r:r}function cm(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}function lm(e,t){if(typeof t!=`string`)throw TypeError(`"${e}" claim must be a string`)}function um(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 dm(e,t){return typeof e==`number`?cm(t,e):e instanceof Date?cm(t,rm(e)):rm(/* @__PURE__ */ new Date)+sm(e)}let fm;function pm(e){return fm.get(e)}function mm(e){let t=pm(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 Ia.encode(JSON.stringify(t))}var hm=class{constructor(e={}){if(!Xa(e))throw TypeError(`JWT Claims Set MUST be an object`);(fm||=/* @__PURE__ */ new WeakMap).set(this,structuredClone(e))}setIssuer(e){return lm(`iss`,e),pm(this).iss=e,this}setSubject(e){return lm(`sub`,e),pm(this).sub=e,this}setAudience(e){return um(e),pm(this).aud=e,this}setJti(e){return lm(`jti`,e),pm(this).jti=e,this}setNotBefore(e){return pm(this).nbf=dm(e,`setNotBefore`),this}setExpirationTime(e){return pm(this).exp=dm(e,`setExpirationTime`),this}setIssuedAt(e){let t=pm(this);return t.iat=e===void 0?rm(/* @__PURE__ */ new Date):typeof e==`string`?cm(`setIssuedAt`,rm(/* @__PURE__ */ new Date)+sm(e)):dm(e,`setIssuedAt`),this}};async function gm(e,t,n){let[r,i,a,o]=e,s=``;if(i!==void 0){let e=ro(Ka,i);i=e[0],s=Ya(e[1])}if(a!==void 0&&(a=ro(Ka,a)[0]),!i&&!a)throw new Ka(`either setProtectedHeader or setUnprotectedHeader must be called before #sign()`);if(!Za(i,a))throw new Ka(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let c={...i,...a};eo(Ka,i);let l=no(i,to(Ka,$a,o,i,c));l||n?.();let{alg:u}=c;if(typeof u!=`string`||!u)throw new Ka(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);let d=nm(u),f=``,p=r,m;if(l){let t=e[4];t?(f=t[0]??=Ya(r),p=t[1]??=Va(f)):(f=Ya(r),m=Ia.encode(`${s}.${f}`))}m??=za(Va(s),Va(`.`),p);let h=await qp(await Mp(d,t,`sign`),d.subtle,`sign`);d.minRsaBits&&Hp(d.alg,h);let g={signature:Ya(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 _m(e,t,n,r,i){let[a]=await gm([e,t,void 0,n],r,i);return`${a.protected}.${a.payload}.${a.signature}`}const vm=hm;var ym=class extends vm{#e;setProtectedHeader(e){return Qa(this.#e,`setProtectedHeader`),this.#e=e,this}async sign(e,t){return _m(mm(this),this.#e,t?.crit,e,()=>{throw new qa(`JWTs MUST NOT use unencoded payload`)})}};const bm=`astralbeam`,xm=16384,Sm=8192,Cm=/^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}$/,wm=/^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}$/,Tm=[`id`,`name`,`metadata`],Em=[`id`,`name`,`admin`,`metadata`],Dm=new TextEncoder;function Om(e){if(!Cm.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 km(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Am(e){return e===null||typeof e==`string`||typeof e==`boolean`?!0:typeof e==`number`?Number.isFinite(e):Array.isArray(e)?e.every(Am):km(e)&&Object.values(e).every(Am)}function jm(e,t,n){if(!km(t))throw Error(`${e} must be an object`);let r=n?Em:Tm;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&&!(km(s)&&Am(s)))throw Error(`${e}.metadata must be a JSON object`)}function Mm(e,t){jm(`user`,e,!0),jm(`tenant`,t,!1);let n=JSON.stringify({user:e,tenant:t});if(Dm.encode(n).byteLength>Sm)throw Error(`user and tenant must not exceed ${Sm} bytes`);return JSON.parse(n)}async function Nm(e){let t=await crypto.subtle.digest(`SHA-256`,Dm.encode(e));return Dm.encode(Ya(new Uint8Array(t)))}async function Pm({apiKey:e,email:t,organizationId:n,expiresInSeconds:r=300}){if(typeof t!=`string`||t.length>320||t.includes(`\0`)||!/^[^\s@]+@[^\s@]+$/.test(t))throw Error(`email must be an email address of at most 320 characters`);if(!Number.isInteger(r)||r<60||r>600)throw Error(`organization auth tokens must live for 60-600 seconds`);let{keyId:i,organizationId:a,keySecret:o}=Om(e);if(n!==a)throw Error(`organizationId must match the API key organization`);let s=Math.floor(Date.now()/1e3);return await new ym({ver:1,email:t,organization_id:n}).setProtectedHeader({alg:`HS256`,typ:`astralbeam-organization+jwt`,kid:i}).setIssuer(n).setAudience(bm).setIssuedAt(s).setExpirationTime(s+r).sign(await Nm(o))}async function Fm({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}=Om(e),c=Mm(t,n);if(r!==void 0&&(!Array.isArray(r)||r.length>20||!r.every(e=>typeof e==`string`&&wm.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 ym({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(bm).setIssuedAt(l).setExpirationTime(l+i).sign(await Nm(s));if(Dm.encode(u).byteLength>xm)throw Error(`chat auth tokens must not exceed ${xm} bytes`);return u}function Im(e){return e.string([`tenant`,`user`,`tenant-name`,`user-name`]).demandOption([`tenant`,`user`]).boolean(`admin`).number(`expires-in`).coerce(`expires-in`,nr).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 Lm(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 Rm(e,t,n){let r=new Date(Date.now()+t*1e3).toISOString();n?$r({token:e,expires_at:r}):s.write(`${e}\n`)}function zm(e){return e.command(`chat`,`Mint a chat JWT for a Tenant's user, as a token endpoint would`,Im,async e=>{let{apiKey:t}=await Ci(),n=e.expiresIn??300;Rm(await Fm({apiKey:t,expiresInSeconds:n,...Lm(e)}),n,q.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`,nr).describe({email:`email of an existing member of the organization`,"expires-in":`token lifetime, 60-600 (default 300)`}),async e=>{let{apiKey:t}=await Ci(),n=e.expiresIn??300;Rm(await Pm({apiKey:t,email:e.email,organizationId:ui(t),expiresInSeconds:n}),n,q.json)}),e.demandCommand(1)}function Bm(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 Vm(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=Bm(t);c.startsWith(i)&&(s.write(ei(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 ${ei(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?$r({messages:u.slice(r)}):i.endsWith(`
|
|
156
|
+
`)||s.write(`
|
|
157
|
+
`)}async function Hm(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 Vm(e,n,!1)}}finally{t.close()}}function Um(e){e.command(`chat [message]`,`Chat with an agent as one of a Tenant's users, like the embedded widget`,e=>Im(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 Ci(),a=e.expiresIn??300,s=Lm(e),c=kp({apiUrl:i,...e.agent===void 0?{}:{agentId:e.agent},fetchAstralBeamToken:async()=>({token:await Fm({apiKey:r,expiresInSeconds:a,...s})})});try{if(n!==void 0)await Vm(c,n,t);else if(!o.isTTY)await Vm(c,(await pe(o)).trim(),t);else if(t)throw new tr(`Pass a message or pipe one on stdin with --json.`);else await Hm(c)}finally{c.dispose()}})}const Wm=new URL(`skills/astralbeam/SKILL.md`,import.meta.url);function Gm(e){return e.command({command:`$0`,describe:!1,handler:async()=>{let e=await b(Wm,`utf8`);q.json?ri({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(Wm,`utf8`)),q.json||a.write(`Restart your agent session to load the skill.
|
|
159
|
+
`),ri({path:n},q.json)}),e}const Km=`
|
|
160
|
+
Environment:
|
|
161
|
+
ASTRALBEAM_API_KEY organization API key, used instead of directory logins
|
|
162
|
+
ASTRALBEAM_API_URL override the saved API URL (default ${si})
|
|
163
|
+
ASTRALBEAM_CONFIG_DIR directory holding config.json
|
|
164
|
+
|
|
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 qm(e){let t=e.includes(`--debug`),n=er(e.slice(2)).scriptName(`astralbeam`).version(Qr).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=>{q.json=e.json},!0).fail((e,t,n)=>{throw n.parsed&&(q.json=n.parsed.argv.json===!0),new tr(e||t?.message||`Invalid command.`)}).epilog(Km).alias(`q`,`search`).command(Object.values(Aa)).command(`auth`,`Bind organization API keys to directories, and check them`,Fa).command(`token`,`Mint short-lived JWTs offline with the organization API key`,zm).command(`skill`,`Print or install the AstralBeam integration skill`,Gm);Um(n),Object.assign(q,{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:q.context??null})}\n`),0}catch(e){return t&&e instanceof Error&&a.write(`[debug] ${e.stack}\n`),oi(e,q.json,q.context,q.failedRequest),e instanceof tr?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||(q.failedRequest=`${i} ${o}`),c},e)}export{qm as run};
|