@astralbeam/cli 0.30.3 → 0.30.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/astralbeam.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import e from"node:process";e.env.NO_COLOR!==void 0&&delete e.env.FORCE_COLOR;const{run:t}=await import(`./program-
|
|
2
|
+
import e from"node:process";e.env.NO_COLOR!==void 0&&delete e.env.FORCE_COLOR;const{run:t}=await import(`./program-vJMaRQKQ.js`);e.exitCode=await t(e.argv);export{};
|
|
@@ -88,7 +88,7 @@ complete -o bashdefault -o default -F _{{app_name}}_yargs_completions {{app_name
|
|
|
88
88
|
`)}`:``;t.fail(i(`Missing required argument: %s`,`Missing required arguments: %s`,Object.keys(r).length,Object.keys(r).join(`, `)+n))}},a.unknownArguments=function(n,r,o,s,c=!0){let l=e.getInternalMethods().getCommandInstance().getCommands(),u=[],d=e.getInternalMethods().getContext();if(Object.keys(n).forEach(t=>{!At.includes(t)&&!Object.prototype.hasOwnProperty.call(o,t)&&!Object.prototype.hasOwnProperty.call(e.getInternalMethods().getParseContext(),t)&&!a.isValidAndSomeAliasIsNotNew(t,r)&&u.push(t)}),c&&(d.commands.length>0||l.length>0||s)&&n._.slice(d.commands.length).forEach(e=>{l.includes(``+e)||u.push(``+e)}),c){let t=e.getDemandedCommands()._?.max||0,r=d.commands.length+t;r<n._.length&&n._.slice(r).forEach(e=>{e=String(e),!d.commands.includes(e)&&!u.includes(e)&&u.push(e)})}u.length&&t.fail(i(`Unknown argument: %s`,`Unknown arguments: %s`,u.length,u.map(e=>e.trim()?e:`"${e}"`).join(`, `)))},a.unknownCommands=function(n){let r=e.getInternalMethods().getCommandInstance().getCommands(),a=[],o=e.getInternalMethods().getContext();return(o.commands.length>0||r.length>0)&&n._.slice(o.commands.length).forEach(e=>{r.includes(``+e)||a.push(``+e)}),a.length>0&&(t.fail(i(`Unknown command: %s`,`Unknown commands: %s`,a.length,a.join(`, `))),!0)},a.isValidAndSomeAliasIsNotNew=function(t,n){if(!Object.prototype.hasOwnProperty.call(n,t))return!1;let r=e.parsed.newAliases;return[t,...n[t]].some(e=>!Object.prototype.hasOwnProperty.call(r,e)||!r[t])},a.limitedChoices=function(n){let i=e.getOptions(),a={};if(!Object.keys(i.choices).length)return;Object.keys(n).forEach(e=>{At.indexOf(e)===-1&&Object.prototype.hasOwnProperty.call(i.choices,e)&&[].concat(n[e]).forEach(t=>{i.choices[e].indexOf(t)===-1&&t!==void 0&&(a[e]=(a[e]||[]).concat(t))})});let o=Object.keys(a);if(!o.length)return;let s=r(`Invalid values:`);o.forEach(e=>{s+=`\n ${r(`Argument: %s, Given: %s, Choices: %s`,e,t.stringifiedValues(a[e]),t.stringifiedValues(i.choices[e]))}`}),t.fail(s)};let o={};a.implies=function(t,r){I(`<string|object> [array|number|string]`,[t,r],arguments.length),typeof t==`object`?Object.keys(t).forEach(e=>{a.implies(e,t[e])}):(e.global(t),o[t]||(o[t]=[]),Array.isArray(r)?r.forEach(e=>a.implies(t,e)):(Xe(r,void 0,n),o[t].push(r)))},a.getImplied=function(){return o};function s(e,t){let n=Number(t);return t=isNaN(n)?t:n,typeof t==`number`?t=e._.length>=t:t.match(/^--no-.+/)?(t=t.match(/^--no-(.+)/)[1],t=!Object.prototype.hasOwnProperty.call(e,t)):t=Object.prototype.hasOwnProperty.call(e,t),t}a.implications=function(e){let n=[];if(Object.keys(o).forEach(t=>{let r=t;(o[t]||[]).forEach(t=>{let i=r,a=t;i=s(e,i),t=s(e,t),i&&!t&&n.push(` ${r} -> ${a}`)})}),n.length){let e=`${r(`Implications failed:`)}\n`;n.forEach(t=>{e+=t}),t.fail(e)}};let c={};a.conflicts=function(t,n){I(`<string|object> [array|string]`,[t,n],arguments.length),typeof t==`object`?Object.keys(t).forEach(e=>{a.conflicts(e,t[e])}):(e.global(t),c[t]||(c[t]=[]),Array.isArray(n)?n.forEach(e=>a.conflicts(t,e)):c[t].push(n))},a.getConflicting=()=>c,a.conflicting=function(i){Object.keys(i).forEach(e=>{c[e]&&c[e].forEach(n=>{n&&i[e]!==void 0&&i[n]!==void 0&&t.fail(r(`Arguments %s and %s are mutually exclusive`,e,n))})}),e.getInternalMethods().getParserConfiguration()[`strip-dashed`]&&Object.keys(c).forEach(e=>{c[e].forEach(a=>{a&&i[n.Parser.camelCase(e)]!==void 0&&i[n.Parser.camelCase(a)]!==void 0&&t.fail(r(`Arguments %s and %s are mutually exclusive`,e,a))})})},a.recommendCommands=function(e,n){n=n.sort((e,t)=>t.length-e.length);let i=null,a=1/0;for(let t=0,r;(r=n[t])!==void 0;t++){let t=kt(e,r);t<=3&&t<a&&(a=t,i=r)}i&&t.fail(r(`Did you mean %s?`,i))},a.reset=function(e){return o=_t(o,t=>!e[t]),c=_t(c,t=>!e[t]),a};let l=[];return a.freeze=function(){l.push({implied:o,conflicting:c})},a.unfreeze=function(){let e=l.pop();Xe(e,void 0,n),{implied:o,conflicting:c}=e},a}let Mt=[],Nt;function Pt(e,t,n,r){Nt=r;let i={};if(Object.prototype.hasOwnProperty.call(e,`extends`)){if(typeof e.extends!=`string`)return i;let r=/\.json|\..*rc$/.test(e.extends),a=null;if(r)a=It(t,e.extends);else try{a=fe.resolve(e.extends)}catch{return e}Ft(a),Mt.push(a),i=r?JSON.parse(Nt.readFileSync(a,`utf8`)):fe(e.extends),delete e.extends,i=Pt(i,Nt.path.dirname(a),n,Nt)}return Mt=[],n?Lt(i,e):Object.assign({},i,e)}function Ft(e){if(Mt.indexOf(e)>-1)throw new P(`Circular extended configurations: '${e}'.`)}function It(e,t){return Nt.path.resolve(e,t)}function Lt(e,t){let n={};function r(e){return e&&typeof e==`object`&&!Array.isArray(e)}Object.assign(n,e);for(let i of Object.keys(t))n[i]=r(t[i])&&r(n[i])?Lt(e[i],t[i]):t[i];return n}var L=function(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n},R=function(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)},z,Rt,zt,Bt,Vt,Ht,Ut,Wt,Gt,Kt,qt,Jt,Yt,Xt,Zt,Qt,$t,B,V,en,tn,nn,rn,an,on,sn,cn,H,ln,un,dn,U,fn,pn,W;function mn(e){return(t=[],n=e.process.cwd(),r)=>{let i=new Zn(t,n,r,e);return Object.defineProperty(i,"argv",{get:()=>i.parse(),enumerable:!0}),i.help(),i.version(),i}}const hn=Symbol(`copyDoubleDash`),gn=Symbol(`copyDoubleDash`),_n=Symbol(`deleteFromParserHintObject`),vn=Symbol(`emitWarning`),yn=Symbol(`freeze`),bn=Symbol(`getDollarZero`),xn=Symbol(`getParserConfiguration`),Sn=Symbol(`getUsageConfiguration`),Cn=Symbol(`guessLocale`),wn=Symbol(`guessVersion`),Tn=Symbol(`parsePositionalNumbers`),En=Symbol(`pkgUp`),Dn=Symbol(`populateParserHintArray`),On=Symbol(`populateParserHintSingleValueDictionary`),kn=Symbol(`populateParserHintArrayDictionary`),An=Symbol(`populateParserHintDictionary`),jn=Symbol(`sanitizeKey`),Mn=Symbol(`setKey`),Nn=Symbol(`unfreeze`),Pn=Symbol(`validateAsync`),Fn=Symbol(`getCommandInstance`),In=Symbol(`getContext`),Ln=Symbol(`getHasOutput`),Rn=Symbol(`getLoggerInstance`),zn=Symbol(`getParseContext`),Bn=Symbol(`getUsageInstance`),Vn=Symbol(`getValidationInstance`),Hn=Symbol(`hasParseCallback`),Un=Symbol(`isGlobalContext`),Wn=Symbol(`postProcess`),Gn=Symbol(`rebase`),Kn=Symbol(`reset`),qn=Symbol(`runYargsParserAndExecuteCommands`),Jn=Symbol(`runValidation`),Yn=Symbol(`setHasOutput`),Xn=Symbol(`kTrackManuallySetKeys`);var Zn=class{constructor(e=[],t,n,r){this.customScriptName=!1,this.parsed=!1,z.set(this,void 0),Rt.set(this,void 0),zt.set(this,{commands:[],fullCommands:[]}),Bt.set(this,null),Vt.set(this,null),Ht.set(this,`show-hidden`),Ut.set(this,null),Wt.set(this,!0),Gt.set(this,{}),Kt.set(this,!0),qt.set(this,[]),Jt.set(this,void 0),Yt.set(this,{}),Xt.set(this,!1),Zt.set(this,null),Qt.set(this,!0),$t.set(this,void 0),B.set(this,``),V.set(this,void 0),en.set(this,void 0),tn.set(this,{}),nn.set(this,null),rn.set(this,null),an.set(this,{}),on.set(this,{}),sn.set(this,void 0),cn.set(this,!1),H.set(this,void 0),ln.set(this,!1),un.set(this,!1),dn.set(this,!1),U.set(this,void 0),fn.set(this,{}),pn.set(this,null),W.set(this,void 0),L(this,H,r,`f`),L(this,sn,e,`f`),L(this,Rt,t,`f`),L(this,en,n,`f`),L(this,Jt,new rt(this),`f`),this.$0=this[bn](),this[Kn](),L(this,z,R(this,z,`f`),`f`),L(this,U,R(this,U,`f`),`f`),L(this,W,R(this,W,`f`),`f`),L(this,V,R(this,V,`f`),`f`),R(this,V,`f`).showHiddenOpt=R(this,Ht,`f`),L(this,$t,this[gn](),`f`)}addHelpOpt(e,t){return I(`[string|boolean] [string]`,[e,t],arguments.length),R(this,Zt,`f`)&&(this[_n](R(this,Zt,`f`)),L(this,Zt,null,`f`)),e===!1&&t===void 0||(L(this,Zt,typeof e==`string`?e:`help`,`f`),this.boolean(R(this,Zt,`f`)),this.describe(R(this,Zt,`f`),t||R(this,U,`f`).deferY18nLookup(`Show help`))),this}help(e,t){return this.addHelpOpt(e,t)}addShowHiddenOpt(e,t){if(I(`[string|boolean] [string]`,[e,t],arguments.length),e===!1&&t===void 0)return this;let n=typeof e==`string`?e:R(this,Ht,`f`);return this.boolean(n),this.describe(n,t||R(this,U,`f`).deferY18nLookup(`Show hidden options`)),R(this,V,`f`).showHiddenOpt=n,this}showHidden(e,t){return this.addShowHiddenOpt(e,t)}alias(e,t){return I(`<object|string|array> [string|array]`,[e,t],arguments.length),this[kn](this.alias.bind(this),`alias`,e,t),this}array(e){return I(`<array|string>`,[e],arguments.length),this[Dn](`array`,e),this[Xn](e),this}boolean(e){return I(`<array|string>`,[e],arguments.length),this[Dn](`boolean`,e),this[Xn](e),this}check(e,t){return I(`<function> [boolean]`,[e,t],arguments.length),this.middleware((t,n)=>ot(()=>e(t,n.getOptions()),n=>(n?(typeof n==`string`||n instanceof Error)&&R(this,U,`f`).fail(n.toString(),n):R(this,U,`f`).fail(R(this,H,`f`).y18n.__(`Argument check failed: %s`,e.toString())),t),e=>(R(this,U,`f`).fail(e.message?e.message:e.toString(),e),t)),!1,t),this}choices(e,t){return I(`<object|string|array> [string|array]`,[e,t],arguments.length),this[kn](this.choices.bind(this),`choices`,e,t),this}coerce(e,t){if(I(`<object|string|array> [function]`,[e,t],arguments.length),Array.isArray(e)){if(!t)throw new P(`coerce callback must be provided`);for(let n of e)this.coerce(n,t);return this}if(typeof e==`object`){for(let t of Object.keys(e))this.coerce(t,e[t]);return this}if(!t)throw new P(`coerce callback must be provided`);return R(this,V,`f`).key[e]=!0,R(this,Jt,`f`).addCoerceMiddleware((n,r)=>{let i;return Object.prototype.hasOwnProperty.call(n,e)?ot(()=>(i=r.getAliases(),t(n[e])),t=>{n[e]=t;let a=r.getInternalMethods().getParserConfiguration()[`strip-aliased`];if(i[e]&&a!==!0)for(let r of i[e])n[r]=t;return n},e=>{throw new P(e.message)}):n},e),this}conflicts(e,t){return I(`<string|object> [string|array]`,[e,t],arguments.length),R(this,W,`f`).conflicts(e,t),this}config(e=`config`,t,n){return I(`[object|string] [string|function] [function]`,[e,t,n],arguments.length),typeof e==`object`&&!Array.isArray(e)?(e=Pt(e,R(this,Rt,`f`),this[xn]()[`deep-merge-config`]||!1,R(this,H,`f`)),R(this,V,`f`).configObjects=(R(this,V,`f`).configObjects||[]).concat(e),this):(typeof t==`function`&&(n=t,t=void 0),this.describe(e,t||R(this,U,`f`).deferY18nLookup(`Path to JSON config file`)),(Array.isArray(e)?e:[e]).forEach(e=>{R(this,V,`f`).config[e]=n||!0}),this)}completion(e,t,n){return I(`[string] [string|boolean|function] [function]`,[e,t,n],arguments.length),typeof t==`function`&&(n=t,t=void 0),L(this,Vt,e||R(this,Vt,`f`)||`completion`,`f`),!t&&t!==!1&&(t=`generate completion script`),this.command(R(this,Vt,`f`),t),n&&R(this,Bt,`f`).registerFunction(n),this}command(e,t,n,r,i,a){return I(`<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]`,[e,t,n,r,i,a],arguments.length),R(this,z,`f`).addHandler(e,t,n,r,i,a),this}commands(e,t,n,r,i,a){return this.command(e,t,n,r,i,a)}commandDir(e,t){I(`<string> [object]`,[e,t],arguments.length);let n=R(this,en,`f`)||R(this,H,`f`).require;return R(this,z,`f`).addDirectory(e,n,R(this,H,`f`).getCallerFile(),t),this}count(e){return I(`<array|string>`,[e],arguments.length),this[Dn](`count`,e),this[Xn](e),this}default(e,t,n){return I(`<object|string|array> [*] [string]`,[e,t,n],arguments.length),n&&(Ze(e,R(this,H,`f`)),R(this,V,`f`).defaultDescription[e]=n),typeof t==`function`&&(Ze(e,R(this,H,`f`)),R(this,V,`f`).defaultDescription[e]||(R(this,V,`f`).defaultDescription[e]=R(this,U,`f`).functionDescription(t)),t=t.call()),this[On](this.default.bind(this),`default`,e,t),this}defaults(e,t,n){return this.default(e,t,n)}demandCommand(e=1,t,n,r){return I(`[number] [number|string] [string|null|undefined] [string|null|undefined]`,[e,t,n,r],arguments.length),typeof t!=`number`&&(n=t,t=1/0),this.global(`_`,!1),R(this,V,`f`).demandedCommands._={min:e,max:t,minMsg:n,maxMsg:r},this}demand(e,t,n){return Array.isArray(t)?(t.forEach(e=>{Xe(n,!0,R(this,H,`f`)),this.demandOption(e,n)}),t=1/0):typeof t!=`number`&&(n=t,t=1/0),typeof e==`number`?(Xe(n,!0,R(this,H,`f`)),this.demandCommand(e,t,n,n)):Array.isArray(e)?e.forEach(e=>{Xe(n,!0,R(this,H,`f`)),this.demandOption(e,n)}):typeof n==`string`?this.demandOption(e,n):(n===!0||n===void 0)&&this.demandOption(e),this}demandOption(e,t){return I(`<object|string|array> [string]`,[e,t],arguments.length),this[On](this.demandOption.bind(this),`demandedOptions`,e,t),this}deprecateOption(e,t){return I(`<string> [string|boolean]`,[e,t],arguments.length),R(this,V,`f`).deprecatedOptions[e]=t,this}describe(e,t){return I(`<object|string|array> [string]`,[e,t],arguments.length),this[Mn](e,!0),R(this,U,`f`).describe(e,t),this}detectLocale(e){return I(`<boolean>`,[e],arguments.length),L(this,Wt,e,`f`),this}env(e){return I(`[string|boolean]`,[e],arguments.length),e===!1?delete R(this,V,`f`).envPrefix:R(this,V,`f`).envPrefix=e||``,this}epilogue(e){return I(`<string>`,[e],arguments.length),R(this,U,`f`).epilog(e),this}epilog(e){return this.epilogue(e)}example(e,t){return I(`<string|array> [string]`,[e,t],arguments.length),Array.isArray(e)?e.forEach(e=>this.example(...e)):R(this,U,`f`).example(e,t),this}exit(e,t){L(this,Xt,!0,`f`),L(this,Ut,t,`f`),R(this,Kt,`f`)&&R(this,H,`f`).process.exit(e)}exitProcess(e=!0){return I(`[boolean]`,[e],arguments.length),L(this,Kt,e,`f`),this}fail(e){if(I(`<function|boolean>`,[e],arguments.length),typeof e==`boolean`&&e!==!1)throw new P(`Invalid first argument. Expected function or boolean 'false'`);return R(this,U,`f`).failFn(e),this}getAliases(){return this.parsed?this.parsed.aliases:{}}async getCompletion(e,t){return I(`<array> [function]`,[e,t],arguments.length),t?R(this,Bt,`f`).getCompletion(e,t):new Promise((t,n)=>{R(this,Bt,`f`).getCompletion(e,(e,r)=>{e?n(e):t(r)})})}getDemandedOptions(){return I([],0),R(this,V,`f`).demandedOptions}getDemandedCommands(){return I([],0),R(this,V,`f`).demandedCommands}getDeprecatedOptions(){return I([],0),R(this,V,`f`).deprecatedOptions}getDetectLocale(){return R(this,Wt,`f`)}getExitProcess(){return R(this,Kt,`f`)}getGroups(){return Object.assign({},R(this,Yt,`f`),R(this,on,`f`))}getHelp(){if(L(this,Xt,!0,`f`),!R(this,U,`f`).hasCachedHelpMessage()){if(!this.parsed){let e=this[qn](R(this,sn,`f`),void 0,void 0,0,!0);if(F(e))return e.then(()=>R(this,U,`f`).help())}let e=R(this,z,`f`).runDefaultBuilderOn(this);if(F(e))return e.then(()=>R(this,U,`f`).help())}return Promise.resolve(R(this,U,`f`).help())}getOptions(){return R(this,V,`f`)}getStrict(){return R(this,ln,`f`)}getStrictCommands(){return R(this,un,`f`)}getStrictOptions(){return R(this,dn,`f`)}global(e,t){return I(`<string|array> [boolean]`,[e,t],arguments.length),e=[].concat(e),t===!1?e.forEach(e=>{R(this,V,`f`).local.includes(e)||R(this,V,`f`).local.push(e)}):R(this,V,`f`).local=R(this,V,`f`).local.filter(t=>e.indexOf(t)===-1),this}group(e,t){I(`<string|array> <string>`,[e,t],arguments.length);let n=R(this,on,`f`)[t]||R(this,Yt,`f`)[t];R(this,on,`f`)[t]&&delete R(this,on,`f`)[t];let r={};return R(this,Yt,`f`)[t]=(n||[]).concat(e).filter(e=>r[e]?!1:r[e]=!0),this}hide(e){return I(`<string>`,[e],arguments.length),R(this,V,`f`).hiddenOptions.push(e),this}implies(e,t){return I(`<string|object> [number|string|array]`,[e,t],arguments.length),R(this,W,`f`).implies(e,t),this}locale(e){return I(`[string]`,[e],arguments.length),e===void 0?(this[Cn](),R(this,H,`f`).y18n.getLocale()):(L(this,Wt,!1,`f`),R(this,H,`f`).y18n.setLocale(e),this)}middleware(e,t,n){return R(this,Jt,`f`).addMiddleware(e,!!t,n)}nargs(e,t){return I(`<string|object|array> [number]`,[e,t],arguments.length),this[On](this.nargs.bind(this),`narg`,e,t),this}normalize(e){return I(`<array|string>`,[e],arguments.length),this[Dn](`normalize`,e),this}number(e){return I(`<array|string>`,[e],arguments.length),this[Dn](`number`,e),this[Xn](e),this}option(e,t){if(I(`<string|object> [object]`,[e,t],arguments.length),typeof e==`object`)Object.keys(e).forEach(t=>{this.options(t,e[t])});else{typeof t!=`object`&&(t={}),this[Xn](e),R(this,pn,`f`)&&(e===`version`||t?.alias===`version`)&&this[vn]([`"version" is a reserved word.`,`Please do one of the following:`,'- Disable version with `yargs.version(false)` if using "version" as an option',"- Use the built-in `yargs.version` method instead (if applicable)",`- Use a different option key`,`https://yargs.js.org/docs/#api-reference-version`].join(`
|
|
89
89
|
`),void 0,`versionWarning`),R(this,V,`f`).key[e]=!0,t.alias&&this.alias(e,t.alias);let n=t.deprecate||t.deprecated;n&&this.deprecateOption(e,n);let r=t.demand||t.required||t.require;r&&this.demand(e,r),t.demandOption&&this.demandOption(e,typeof t.demandOption==`string`?t.demandOption:void 0),t.conflicts&&this.conflicts(e,t.conflicts),`default`in t&&this.default(e,t.default),t.implies!==void 0&&this.implies(e,t.implies),t.nargs!==void 0&&this.nargs(e,t.nargs),t.config&&this.config(e,t.configParser),t.normalize&&this.normalize(e),t.choices&&this.choices(e,t.choices),t.coerce&&this.coerce(e,t.coerce),t.group&&this.group(e,t.group),(t.boolean||t.type===`boolean`)&&(this.boolean(e),t.alias&&this.boolean(t.alias)),(t.array||t.type===`array`)&&(this.array(e),t.alias&&this.array(t.alias)),(t.number||t.type===`number`)&&(this.number(e),t.alias&&this.number(t.alias)),(t.string||t.type===`string`)&&(this.string(e),t.alias&&this.string(t.alias)),(t.count||t.type===`count`)&&this.count(e),typeof t.global==`boolean`&&this.global(e,t.global),t.defaultDescription&&(R(this,V,`f`).defaultDescription[e]=t.defaultDescription),t.skipValidation&&this.skipValidation(e);let i=t.describe||t.description||t.desc,a=R(this,U,`f`).getDescriptions();(!Object.prototype.hasOwnProperty.call(a,e)||typeof i==`string`)&&this.describe(e,i),t.hidden&&this.hide(e),t.requiresArg&&this.requiresArg(e)}return this}options(e,t){return this.option(e,t)}parse(e,t,n){I(`[string|array] [function|boolean|object] [function]`,[e,t,n],arguments.length),this[yn](),e===void 0&&(e=R(this,sn,`f`)),typeof t==`object`&&(L(this,rn,t,`f`),t=n),typeof t==`function`&&(L(this,nn,t,`f`),t=!1),t||L(this,sn,e,`f`),R(this,nn,`f`)&&L(this,Kt,!1,`f`);let r=this[qn](e,!!t),i=this.parsed;return R(this,Bt,`f`).setParsed(this.parsed),F(r)?r.then(e=>(R(this,nn,`f`)&&R(this,nn,`f`).call(this,R(this,Ut,`f`),e,R(this,B,`f`)),e)).catch(e=>{throw R(this,nn,`f`)&&R(this,nn,`f`)(e,this.parsed.argv,R(this,B,`f`)),e}).finally(()=>{this[Nn](),this.parsed=i}):(R(this,nn,`f`)&&R(this,nn,`f`).call(this,R(this,Ut,`f`),r,R(this,B,`f`)),this[Nn](),this.parsed=i,r)}parseAsync(e,t,n){let r=this.parse(e,t,n);return F(r)?r:Promise.resolve(r)}parseSync(e,t,n){let r=this.parse(e,t,n);if(F(r))throw new P(`.parseSync() must not be used with asynchronous builders, handlers, or middleware`);return r}parserConfiguration(e){return I(`<object>`,[e],arguments.length),L(this,tn,e,`f`),this}pkgConf(e,t){I(`<string> [string]`,[e,t],arguments.length);let n=null,r=this[En](t||R(this,Rt,`f`));return r[e]&&typeof r[e]==`object`&&(n=Pt(r[e],t||R(this,Rt,`f`),this[xn]()[`deep-merge-config`]||!1,R(this,H,`f`)),R(this,V,`f`).configObjects=(R(this,V,`f`).configObjects||[]).concat(n)),this}positional(e,t){I(`<string> <object>`,[e,t],arguments.length);let n=[`default`,`defaultDescription`,`implies`,`normalize`,`choices`,`conflicts`,`coerce`,`type`,`describe`,`desc`,`description`,`alias`];t=_t(t,(e,t)=>e===`type`&&![`string`,`number`,`boolean`].includes(t)?!1:n.includes(e));let r=R(this,zt,`f`).fullCommands[R(this,zt,`f`).fullCommands.length-1],i=r?R(this,z,`f`).cmdToParseOptions(r):{array:[],alias:{},default:{},demand:{}};return Qe(i).forEach(n=>{let r=i[n];Array.isArray(r)?r.indexOf(e)!==-1&&(t[n]=!0):r[e]&&!(n in t)&&(t[n]=r[e])}),this.group(e,R(this,U,`f`).getPositionalGroupName()),this.option(e,t)}recommendCommands(e=!0){return I(`[boolean]`,[e],arguments.length),L(this,cn,e,`f`),this}required(e,t,n){return this.demand(e,t,n)}require(e,t,n){return this.demand(e,t,n)}requiresArg(e){return I(`<array|string|object> [number]`,[e],arguments.length),typeof e==`string`&&R(this,V,`f`).narg[e]||this[On](this.requiresArg.bind(this),`narg`,e,NaN),this}showCompletionScript(e,t){return I(`[string] [string]`,[e,t],arguments.length),e||=this.$0,R(this,$t,`f`).log(R(this,Bt,`f`).generateCompletionScript(e,t||R(this,Vt,`f`)||`completion`)),this}showHelp(e){if(I(`[string|function]`,[e],arguments.length),L(this,Xt,!0,`f`),!R(this,U,`f`).hasCachedHelpMessage()){if(!this.parsed){let t=this[qn](R(this,sn,`f`),void 0,void 0,0,!0);if(F(t))return t.then(()=>{R(this,U,`f`).showHelp(e)}),this}let t=R(this,z,`f`).runDefaultBuilderOn(this);if(F(t))return t.then(()=>{R(this,U,`f`).showHelp(e)}),this}return R(this,U,`f`).showHelp(e),this}scriptName(e){return this.customScriptName=!0,this.$0=e,this}showHelpOnFail(e,t){return I(`[boolean|string] [string]`,[e,t],arguments.length),R(this,U,`f`).showHelpOnFail(e,t),this}showVersion(e){return I(`[string|function]`,[e],arguments.length),R(this,U,`f`).showVersion(e),this}skipValidation(e){return I(`<array|string>`,[e],arguments.length),this[Dn](`skipValidation`,e),this}strict(e){return I(`[boolean]`,[e],arguments.length),L(this,ln,e!==!1,`f`),this}strictCommands(e){return I(`[boolean]`,[e],arguments.length),L(this,un,e!==!1,`f`),this}strictOptions(e){return I(`[boolean]`,[e],arguments.length),L(this,dn,e!==!1,`f`),this}string(e){return I(`<array|string>`,[e],arguments.length),this[Dn](`string`,e),this[Xn](e),this}terminalWidth(){return I([],0),R(this,H,`f`).process.stdColumns}updateLocale(e){return this.updateStrings(e)}updateStrings(e){return I(`<object>`,[e],arguments.length),L(this,Wt,!1,`f`),R(this,H,`f`).y18n.updateLocale(e),this}usage(e,t,n,r){if(I(`<string|null|undefined> [string|boolean] [function|object] [function]`,[e,t,n,r],arguments.length),t!==void 0){if(Xe(e,null,R(this,H,`f`)),(e||``).match(/^\$0( |$)/))return this.command(e,t,n,r);throw new P(`.usage() description must start with $0 if being used as alias for .command()`)}return R(this,U,`f`).usage(e),this}usageConfiguration(e){return I(`<object>`,[e],arguments.length),L(this,fn,e,`f`),this}version(e,t,n){let r=`version`;if(I(`[boolean|string] [string] [string]`,[e,t,n],arguments.length),R(this,pn,`f`)&&(this[_n](R(this,pn,`f`)),R(this,U,`f`).version(void 0),L(this,pn,null,`f`)),arguments.length===0)n=this[wn](),e=r;else if(arguments.length===1){if(e===!1)return this;n=e,e=r}else arguments.length===2&&(n=t,t=void 0);return L(this,pn,typeof e==`string`?e:r,`f`),t||=R(this,U,`f`).deferY18nLookup(`Show version number`),R(this,U,`f`).version(n||void 0),this.boolean(R(this,pn,`f`)),this.describe(R(this,pn,`f`),t),this}wrap(e){return I(`<number|null|undefined>`,[e],arguments.length),R(this,U,`f`).wrap(e),this}[(z=/* @__PURE__ */ new WeakMap,Rt=/* @__PURE__ */ new WeakMap,zt=/* @__PURE__ */ new WeakMap,Bt=/* @__PURE__ */ new WeakMap,Vt=/* @__PURE__ */ new WeakMap,Ht=/* @__PURE__ */ new WeakMap,Ut=/* @__PURE__ */ new WeakMap,Wt=/* @__PURE__ */ new WeakMap,Gt=/* @__PURE__ */ new WeakMap,Kt=/* @__PURE__ */ new WeakMap,qt=/* @__PURE__ */ new WeakMap,Jt=/* @__PURE__ */ new WeakMap,Yt=/* @__PURE__ */ new WeakMap,Xt=/* @__PURE__ */ new WeakMap,Zt=/* @__PURE__ */ new WeakMap,Qt=/* @__PURE__ */ new WeakMap,$t=/* @__PURE__ */ new WeakMap,B=/* @__PURE__ */ new WeakMap,V=/* @__PURE__ */ new WeakMap,en=/* @__PURE__ */ new WeakMap,tn=/* @__PURE__ */ new WeakMap,nn=/* @__PURE__ */ new WeakMap,rn=/* @__PURE__ */ new WeakMap,an=/* @__PURE__ */ new WeakMap,on=/* @__PURE__ */ new WeakMap,sn=/* @__PURE__ */ new WeakMap,cn=/* @__PURE__ */ new WeakMap,H=/* @__PURE__ */ new WeakMap,ln=/* @__PURE__ */ new WeakMap,un=/* @__PURE__ */ new WeakMap,dn=/* @__PURE__ */ new WeakMap,U=/* @__PURE__ */ new WeakMap,fn=/* @__PURE__ */ new WeakMap,pn=/* @__PURE__ */ new WeakMap,W=/* @__PURE__ */ new WeakMap,hn)](e){if(!e._||!e[`--`])return e;e._.push.apply(e._,e[`--`]);try{delete e[`--`]}catch{}return e}[gn](){return{log:(...e)=>{this[Hn]()||console.log(...e),L(this,Xt,!0,`f`),R(this,B,`f`).length&&L(this,B,R(this,B,`f`)+`
|
|
90
90
|
`,`f`),L(this,B,R(this,B,`f`)+e.join(` `),`f`)},error:(...e)=>{this[Hn]()||console.error(...e),L(this,Xt,!0,`f`),R(this,B,`f`).length&&L(this,B,R(this,B,`f`)+`
|
|
91
|
-
`,`f`),L(this,B,R(this,B,`f`)+e.join(` `),`f`)}}}[_n](e){Qe(R(this,V,`f`)).forEach(t=>{if((e=>e===`configObjects`)(t))return;let n=R(this,V,`f`)[t];Array.isArray(n)?n.includes(e)&&n.splice(n.indexOf(e),1):typeof n==`object`&&delete n[e]}),delete R(this,U,`f`).getDescriptions()[e]}[vn](e,t,n){R(this,Gt,`f`)[n]||(R(this,H,`f`).process.emitWarning(e,t),R(this,Gt,`f`)[n]=!0)}[yn](){R(this,qt,`f`).push({options:R(this,V,`f`),configObjects:R(this,V,`f`).configObjects.slice(0),exitProcess:R(this,Kt,`f`),groups:R(this,Yt,`f`),strict:R(this,ln,`f`),strictCommands:R(this,un,`f`),strictOptions:R(this,dn,`f`),completionCommand:R(this,Vt,`f`),output:R(this,B,`f`),exitError:R(this,Ut,`f`),hasOutput:R(this,Xt,`f`),parsed:this.parsed,parseFn:R(this,nn,`f`),parseContext:R(this,rn,`f`)}),R(this,U,`f`).freeze(),R(this,W,`f`).freeze(),R(this,z,`f`).freeze(),R(this,Jt,`f`).freeze()}[bn](){let e=``,t;return t=/\b(node|iojs|electron)(\.exe)?$/.test(R(this,H,`f`).process.argv()[0])?R(this,H,`f`).process.argv().slice(1,2):R(this,H,`f`).process.argv().slice(0,1),e=t.map(e=>{let t=this[Gn](R(this,Rt,`f`),e);return e.match(/^(\/|([a-zA-Z]:)?\\)/)&&t.length<e.length?t:e}).join(` `).trim(),R(this,H,`f`).getEnv(`_`)&&R(this,H,`f`).getProcessArgvBin()===R(this,H,`f`).getEnv(`_`)&&(e=R(this,H,`f`).getEnv(`_`).replace(`${R(this,H,`f`).path.dirname(R(this,H,`f`).process.execPath())}/`,``)),e}[xn](){return R(this,tn,`f`)}[Sn](){return R(this,fn,`f`)}[Cn](){if(!R(this,Wt,`f`))return;let e=R(this,H,`f`).getEnv(`LC_ALL`)||R(this,H,`f`).getEnv(`LC_MESSAGES`)||R(this,H,`f`).getEnv(`LANG`)||R(this,H,`f`).getEnv(`LANGUAGE`)||`en_US`;this.locale(e.replace(/[.:].*/,``))}[wn](){return this[En]().version||`unknown`}[Tn](e){let t=e[`--`]?e[`--`]:e._;for(let e=0,n;(n=t[e])!==void 0;e++)R(this,H,`f`).Parser.looksLikeNumber(n)&&Number.isSafeInteger(Math.floor(parseFloat(`${n}`)))&&(t[e]=Number(n));return e}[En](e){let t=e||`*`;if(R(this,an,`f`)[t])return R(this,an,`f`)[t];let n={};try{let t=e||R(this,H,`f`).mainFilename;!e&&R(this,H,`f`).path.extname(t)&&(t=R(this,H,`f`).path.dirname(t));let r=R(this,H,`f`).findUp(t,(e,t)=>{if(t.includes(`package.json`))return`package.json`});Xe(r,void 0,R(this,H,`f`)),n=JSON.parse(R(this,H,`f`).readFileSync(r,`utf8`))}catch{}return R(this,an,`f`)[t]=n||{},R(this,an,`f`)[t]}[Dn](e,t){t=[].concat(t),t.forEach(t=>{t=this[jn](t),R(this,V,`f`)[e].push(t)})}[On](e,t,n,r){this[An](e,t,n,r,(e,t,n)=>{R(this,V,`f`)[e][t]=n})}[kn](e,t,n,r){this[An](e,t,n,r,(e,t,n)=>{R(this,V,`f`)[e][t]=(R(this,V,`f`)[e][t]||[]).concat(n)})}[An](e,t,n,r,i){if(Array.isArray(n))n.forEach(t=>{e(t,r)});else if((e=>typeof e==`object`)(n))for(let t of Qe(n))e(t,n[t]);else i(t,this[jn](n),r)}[jn](e){return e===`__proto__`?`___proto___`:e}[Mn](e,t){return this[On](this[Mn].bind(this),`key`,e,t),this}[Nn](){var e,t,n,r,i,a,o,s,c,l,u,d;let f=R(this,qt,`f`).pop();Xe(f,void 0,R(this,H,`f`));let p;e=this,t=this,n=this,r=this,i=this,a=this,o=this,s=this,c=this,l=this,u=this,d=this,{options:{set value(t){L(e,V,t,`f`)}}.value,configObjects:p,exitProcess:{set value(e){L(t,Kt,e,`f`)}}.value,groups:{set value(e){L(n,Yt,e,`f`)}}.value,output:{set value(e){L(r,B,e,`f`)}}.value,exitError:{set value(e){L(i,Ut,e,`f`)}}.value,hasOutput:{set value(e){L(a,Xt,e,`f`)}}.value,parsed:this.parsed,strict:{set value(e){L(o,ln,e,`f`)}}.value,strictCommands:{set value(e){L(s,un,e,`f`)}}.value,strictOptions:{set value(e){L(c,dn,e,`f`)}}.value,completionCommand:{set value(e){L(l,Vt,e,`f`)}}.value,parseFn:{set value(e){L(u,nn,e,`f`)}}.value,parseContext:{set value(e){L(d,rn,e,`f`)}}.value}=f,R(this,V,`f`).configObjects=p,R(this,U,`f`).unfreeze(),R(this,W,`f`).unfreeze(),R(this,z,`f`).unfreeze(),R(this,Jt,`f`).unfreeze()}[Pn](e,t){return ot(t,t=>(e(t),t))}getInternalMethods(){return{getCommandInstance:this[Fn].bind(this),getContext:this[In].bind(this),getHasOutput:this[Ln].bind(this),getLoggerInstance:this[Rn].bind(this),getParseContext:this[zn].bind(this),getParserConfiguration:this[xn].bind(this),getUsageConfiguration:this[Sn].bind(this),getUsageInstance:this[Bn].bind(this),getValidationInstance:this[Vn].bind(this),hasParseCallback:this[Hn].bind(this),isGlobalContext:this[Un].bind(this),postProcess:this[Wn].bind(this),reset:this[Kn].bind(this),runValidation:this[Jn].bind(this),runYargsParserAndExecuteCommands:this[qn].bind(this),setHasOutput:this[Yn].bind(this)}}[Fn](){return R(this,z,`f`)}[In](){return R(this,zt,`f`)}[Ln](){return R(this,Xt,`f`)}[Rn](){return R(this,$t,`f`)}[zn](){return R(this,rn,`f`)||{}}[Bn](){return R(this,U,`f`)}[Vn](){return R(this,W,`f`)}[Hn](){return!!R(this,nn,`f`)}[Un](){return R(this,Qt,`f`)}[Wn](e,t,n,r){return n||F(e)||(t||(e=this[hn](e)),(this[xn]()[`parse-positional-numbers`]||this[xn]()[`parse-positional-numbers`]===void 0)&&(e=this[Tn](e)),r&&(e=at(e,this,R(this,Jt,`f`).getMiddleware(),!1))),e}[Kn](e={}){L(this,V,R(this,V,`f`)||{},`f`);let t={};t.local=R(this,V,`f`).local||[],t.configObjects=R(this,V,`f`).configObjects||[];let n={};return t.local.forEach(t=>{n[t]=!0,(e[t]||[]).forEach(e=>{n[e]=!0})}),Object.assign(R(this,on,`f`),Object.keys(R(this,Yt,`f`)).reduce((e,t)=>{let r=R(this,Yt,`f`)[t].filter(e=>!(e in n));return r.length>0&&(e[t]=r),e},{})),L(this,Yt,{},`f`),[`array`,`boolean`,`string`,`skipValidation`,`count`,`normalize`,`number`,`hiddenOptions`].forEach(e=>{t[e]=(R(this,V,`f`)[e]||[]).filter(e=>!n[e])}),[`narg`,`key`,`alias`,`default`,`defaultDescription`,`config`,`choices`,`demandedOptions`,`demandedCommands`,`deprecatedOptions`].forEach(e=>{t[e]=_t(R(this,V,`f`)[e],e=>!n[e])}),t.envPrefix=R(this,V,`f`).envPrefix,L(this,V,t,`f`),L(this,U,R(this,U,`f`)?R(this,U,`f`).reset(n):bt(this,R(this,H,`f`)),`f`),L(this,W,R(this,W,`f`)?R(this,W,`f`).reset(n):jt(this,R(this,U,`f`),R(this,H,`f`)),`f`),L(this,z,R(this,z,`f`)?R(this,z,`f`).reset():dt(R(this,U,`f`),R(this,W,`f`),R(this,Jt,`f`),R(this,H,`f`)),`f`),R(this,Bt,`f`)||L(this,Bt,Et(this,R(this,U,`f`),R(this,z,`f`),R(this,H,`f`)),`f`),R(this,Jt,`f`).reset(),L(this,Vt,null,`f`),L(this,B,``,`f`),L(this,Ut,null,`f`),L(this,Xt,!1,`f`),this.parsed=!1,this}[Gn](e,t){return R(this,H,`f`).path.relative(e,t)}[qn](e,t,n,r=0,i=!1){let a=!!n||i;e||=R(this,sn,`f`),R(this,V,`f`).__=R(this,H,`f`).y18n.__,R(this,V,`f`).configuration=this[xn]();let o=!!R(this,V,`f`).configuration[`populate--`],s=Object.assign({},R(this,V,`f`).configuration,{"populate--":!0}),c=R(this,H,`f`).Parser.detailed(e,Object.assign({},R(this,V,`f`),{configuration:{"parse-positional-numbers":!1,...s}})),l=Object.assign(c.argv,R(this,rn,`f`)),u,d=c.aliases,f=!1,p=!1;Object.keys(l).forEach(e=>{e===R(this,Zt,`f`)&&l[e]?f=!0:e===R(this,pn,`f`)&&l[e]&&(p=!0)}),l.$0=this.$0,this.parsed=c,r===0&&R(this,U,`f`).clearCachedHelpMessage();try{if(this[Cn](),t)return this[Wn](l,o,!!n,!1);R(this,Zt,`f`)&&[R(this,Zt,`f`)].concat(d[R(this,Zt,`f`)]||[]).filter(e=>e.length>1).includes(``+l._[l._.length-1])&&(l._.pop(),f=!0),L(this,Qt,!1,`f`);let s=R(this,z,`f`).getCommands(),m=R(this,Bt,`f`).completionKey in l,h=f||m||i;if(l._.length){if(s.length){let e;for(let t=r||0,a;l._[t]!==void 0;t++){if(a=String(l._[t]),s.includes(a)&&a!==R(this,Vt,`f`)){let e=R(this,z,`f`).runCommand(a,this,c,t+1,i,f||p||i);return this[Wn](e,o,!!n,!1)}if(!e&&a!==R(this,Vt,`f`)){e=a;break}}!R(this,z,`f`).hasDefaultCommand()&&R(this,cn,`f`)&&e&&!h&&R(this,W,`f`).recommendCommands(e,s)}R(this,Vt,`f`)&&l._.includes(R(this,Vt,`f`))&&!m&&(R(this,Kt,`f`)&&vt(!0),this.showCompletionScript(),this.exit(0))}if(R(this,z,`f`).hasDefaultCommand()&&!h){let e=R(this,z,`f`).runCommand(null,this,c,0,i,f||p||i);return this[Wn](e,o,!!n,!1)}if(m){R(this,Kt,`f`)&&vt(!0),e=[].concat(e);let t=e.slice(e.indexOf(`--${R(this,Bt,`f`).completionKey}`)+1);return R(this,Bt,`f`).getCompletion(t,(e,t)=>{if(e)throw new P(e.message);(t||[]).forEach(e=>{R(this,$t,`f`).log(e)}),this.exit(0)}),this[Wn](l,!o,!!n,!1)}if(R(this,Xt,`f`)||(f?(R(this,Kt,`f`)&&vt(!0),a=!0,this.showHelp(`log`),this.exit(0)):p&&(R(this,Kt,`f`)&&vt(!0),a=!0,R(this,U,`f`).showVersion(`log`),this.exit(0))),!a&&R(this,V,`f`).skipValidation.length>0&&(a=Object.keys(l).some(e=>R(this,V,`f`).skipValidation.indexOf(e)>=0&&l[e]===!0)),!a){if(c.error)throw new P(c.error.message);if(!m){let e=this[Jn](d,{},c.error);n||(u=at(l,this,R(this,Jt,`f`).getMiddleware(),!0)),u=this[Pn](e,u??l),F(u)&&!n&&(u=u.then(()=>at(l,this,R(this,Jt,`f`).getMiddleware(),!1)))}}}catch(e){if(e instanceof P)R(this,U,`f`).fail(e.message,e);else throw e}return this[Wn](u??l,o,!!n,!0)}[Jn](e,t,n,r){let i={...this.getDemandedOptions()};return a=>{if(n)throw new P(n.message);R(this,W,`f`).nonOptionCount(a),R(this,W,`f`).requiredArguments(a,i);let o=!1;R(this,un,`f`)&&(o=R(this,W,`f`).unknownCommands(a)),R(this,ln,`f`)&&!o?R(this,W,`f`).unknownArguments(a,e,t,!!r):R(this,dn,`f`)&&R(this,W,`f`).unknownArguments(a,e,{},!1,!1),R(this,W,`f`).limitedChoices(a),R(this,W,`f`).implications(a),R(this,W,`f`).conflicting(a)}}[Yn](){L(this,Xt,!0,`f`)}[Xn](e){if(typeof e==`string`)R(this,V,`f`).key[e]=!0;else for(let t of e)R(this,V,`f`).key[t]=!0}};function Qn(e){return!!e&&typeof e.getInternalMethods==`function`}const $n=mn(Ye);var er=class extends Error{};function tr(e){if(!Number.isInteger(e)||e<60||e>600)throw new er(`Expected a whole number of seconds from 60 to 600.`);return e}function nr(e,t=`https://astralbeam.ai/api`){return`${t.replace(/\/+$/,``)}${e.replace(/^\/api(?=\/)/,``)}`}function rr(e,t){if(!e||typeof e!=`object`)return!1;let n=e;return n.status===t&&typeof n.type==`string`&&typeof n.title==`string`&&typeof n.detail==`string`&&(n.reference===void 0||typeof n.reference==`string`)&&(n.issues===void 0||Array.isArray(n.issues)&&n.issues.every(e=>e&&typeof e.path==`string`&&typeof e.message==`string`))}async function ir(e,t){let{apiUrl:n,apiKey:r,astralBeamToken:i,fetchClient:a=globalThis.fetch,...o}=t,s=new Headers,c=o.headers instanceof Headers?o.headers.entries():Array.isArray(o.headers)?o.headers:Object.entries(o.headers??{});for(let[e,t]of c)s.set(e,t);s.delete(`authorization`),s.delete(`x-api-key`),r&&s.set(`x-api-key`,r),i&&s.set(`authorization`,`Bearer ${i}`);let l=await a(nr(e,n),{...o,headers:s,...r?{redirect:`error`}:{}});if(l.ok)return l;let u=await l.json().catch(e=>{if(!(e instanceof SyntaxError))throw e}),d=rr(u,l.status)?u:void 0;throw Object.assign(Error(d?.detail??`AstralBeam API returned HTTP ${l.status}`),{name:`AstralBeamApiError`,status:l.status,headers:l.headers,body:d})}async function ar(e,t){let n=await ir(e,t);if(n.status!==204)return await n.json()}function or(e){return e instanceof Error&&e.name===`AstralBeamApiError`&&`status`in e&&typeof e.status==`number`}function sr(e,t=`https://astralbeam.ai/api`){return`${t.replace(/\/+$/,``)}${e.replace(/^\/api(?=\/)/,``)}`}function cr(e,t){if(!e||typeof e!=`object`)return!1;let n=e;return n.status===t&&typeof n.type==`string`&&typeof n.title==`string`&&typeof n.detail==`string`&&(n.reference===void 0||typeof n.reference==`string`)&&(n.issues===void 0||Array.isArray(n.issues)&&n.issues.every(e=>e&&typeof e.path==`string`&&typeof e.message==`string`))}async function lr(e,t){let{apiUrl:n,apiKey:r,astralBeamToken:i,fetchClient:a=globalThis.fetch,...o}=t,s=new Headers,c=o.headers instanceof Headers?o.headers.entries():Array.isArray(o.headers)?o.headers:Object.entries(o.headers??{});for(let[e,t]of c)s.set(e,t);s.delete(`authorization`),s.delete(`x-api-key`),r&&s.set(`x-api-key`,r),i&&s.set(`authorization`,`Bearer ${i}`);let l=await a(sr(e,n),{...o,headers:s,...r?{redirect:`error`}:{}});if(l.ok)return l;let u=await l.json().catch(e=>{if(!(e instanceof SyntaxError))throw e}),d=cr(u,l.status)?u:void 0;throw Object.assign(Error(d?.detail??`AstralBeam API returned HTTP ${l.status}`),{name:`AstralBeamApiError`,status:l.status,headers:l.headers,body:d})}async function ur(e,t){let n=await lr(e,t);if(n.status!==204)return await n.json()}function G(e,t){return ur(e,t)}async function dr(e,t){let n=await lr(e,t),r=n.status===204?n.headers.get(`location`):null;if(!r)return n;let i=await globalThis.fetch(r,{credentials:`omit`,redirect:`error`,referrerPolicy:`no-referrer`,signal:t.signal??null});if(!i.ok)throw Error(`The file could not be downloaded. Please try again.`);return i}function fr(e,t){return lr(e,t)}const pr=()=>`/api/v1/organization`,mr=e=>ur(pr(),{...e,method:`GET`}),hr=()=>`/api/v1/chat/files`,gr=(e,t)=>{let n=e=>{if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Symbol.iterator in e)return Object.fromEntries(Array.from(e,e=>Array.from(e)));let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t};return G(hr(),{...t,method:`POST`,headers:{"Content-Type":`application/json`,...n(t?.headers)},body:JSON.stringify(e)})},_r=e=>{let t=new URLSearchParams;Object.entries(e||{}).forEach(([e,n])=>{n!==void 0&&t.append(e,n===null?`null`:String(n))});let n=t.toString();return n.length>0?`/api/v1/chat/files?${n}`:`/api/v1/chat/files`},vr=(e,t)=>dr(_r(e),{...t,method:`GET`}),yr=()=>`/api/v1/chat`,br=e=>{let t=new URLSearchParams;Object.entries(e||{}).forEach(([e,n])=>{n!==void 0&&t.append(e,n===null?`null`:String(n))});let n=t.toString();return n.length>0?`/api/v1/chat/config?${n}`:`/api/v1/chat/config`},xr=(e,t)=>G(br(e),{...t,method:`GET`}),Sr=()=>`/api/v1/chat/threads`,Cr=(e,t)=>{let n=e=>{if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Symbol.iterator in e)return Object.fromEntries(Array.from(e,e=>Array.from(e)));let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t};return G(Sr(),{...t,method:`POST`,headers:{"Content-Type":`application/json`,...n(t?.headers)},body:JSON.stringify(e)})},wr=e=>{let t=new URLSearchParams;Object.entries(e||{}).forEach(([e,n])=>{n!==void 0&&t.append(e,n===null?`null`:String(n))});let n=t.toString();return n.length>0?`/api/v1/chat/threads?${n}`:`/api/v1/chat/threads`},Tr=(e,t)=>G(wr(e),{...t,method:`GET`}),Er=e=>`/api/v1/chat/threads/${encodeURIComponent(String(e))}`,Dr=(e,t,n)=>{let r=e=>{if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Symbol.iterator in e)return Object.fromEntries(Array.from(e,e=>Array.from(e)));let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t};return G(Er(e),{...n,method:`PATCH`,headers:{"Content-Type":`application/json`,...r(n?.headers)},body:JSON.stringify(t)})},Or=(e,t)=>{let n=new URLSearchParams;Object.entries(t||{}).forEach(([e,t])=>{t!==void 0&&n.append(e,t===null?`null`:String(t))});let r=n.toString();return r.length>0?`/api/v1/chat/threads/${encodeURIComponent(String(e))}?${r}`:`/api/v1/chat/threads/${encodeURIComponent(String(e))}`},kr=(e,t,n)=>G(Or(e,t),{...n,method:`DELETE`}),Ar=(e,t)=>{let n=new URLSearchParams;Object.entries(t||{}).forEach(([e,t])=>{t!==void 0&&n.append(e,t===null?`null`:String(t))});let r=n.toString();return r.length>0?`/api/v1/chat/threads/${encodeURIComponent(String(e))}/messages?${r}`:`/api/v1/chat/threads/${encodeURIComponent(String(e))}/messages`},jr=(e,t,n)=>G(Ar(e,t),{...n,method:`GET`}),Mr=e=>`/api/v1/chat/threads/${encodeURIComponent(String(e))}/tool-results`,Nr=()=>`/api/v1/me`,Pr=e=>G(Nr(),{...e,method:`POST`}),Fr=()=>`/api/v1/me/mcp/catalog`,Ir=e=>G(Fr(),{...e,method:`GET`}),Lr=()=>`/api/v1/me/mcp/connections`,Rr=(e,t)=>{let n=e=>{if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Symbol.iterator in e)return Object.fromEntries(Array.from(e,e=>Array.from(e)));let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t};return G(Lr(),{...t,method:`POST`,headers:{"Content-Type":`application/json`,...n(t?.headers)},body:JSON.stringify(e)})},zr=e=>`/api/v1/me/mcp/connections/${encodeURIComponent(String(e))}/headers`,Br=(e,t,n)=>{let r=e=>{if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Symbol.iterator in e)return Object.fromEntries(Array.from(e,e=>Array.from(e)));let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t};return G(zr(e),{...n,method:`POST`,headers:{"Content-Type":`application/json`,...r(n?.headers)},body:JSON.stringify(t)})},Vr=e=>`/api/v1/me/mcp/connections/${encodeURIComponent(String(e))}`,Hr=(e,t)=>G(Vr(e),{...t,method:`DELETE`}),Ur=e=>`/api/v1/me/mcp/connections/${encodeURIComponent(String(e))}/test`,Wr=(e,t)=>G(Ur(e),{...t,method:`POST`}),Gr=e=>`/api/v1/me/mcp/connections/${encodeURIComponent(String(e))}/authorize`,Kr=(e,t)=>G(Gr(e),{...t,method:`POST`}),qr=e=>`/api/v1/me/mcp/connections/${encodeURIComponent(String(e))}/oauth/bind`,Jr=(e,t,n)=>{let r=e=>{if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Symbol.iterator in e)return Object.fromEntries(Array.from(e,e=>Array.from(e)));let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t};return G(qr(e),{...n,method:`POST`,headers:{"Content-Type":`application/json`,...r(n?.headers)},body:JSON.stringify(t)})},Yr=e=>`/api/v1/me/mcp/connections/${encodeURIComponent(String(e))}/oauth/complete`,Xr=(e,t,n)=>{let r=e=>{if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Symbol.iterator in e)return Object.fromEntries(Array.from(e,e=>Array.from(e)));let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t};return G(Yr(e),{...n,method:`POST`,headers:{"Content-Type":`application/json`,...r(n?.headers)},body:JSON.stringify(t)})};var Zr=`0.30.3`;function Qr(e){s.write(`${JSON.stringify(e,null,2)}\n`)}function $r(e,t=``){let n=``;for(let r of e){let e=r.codePointAt(0)??0;n+=(e<32||e>=127&&e<160)&&!t.includes(r)?`\\u${e.toString(16).padStart(4,`0`)}`:r}return n}function ei(e){return e==null?``:$r(typeof e==`string`?e:JSON.stringify(e))}function ti(e){let t=Object.entries(e),n=Math.max(...t.map(([e])=>e.length));for(let[e,r]of t)s.write(`${e.padEnd(n)} ${ei(r)}\n`)}function ni(e,t){t?Qr(e):ti(e)}function ri(e,t){let n=e.map(e=>t.map(t=>ei(e[t]))),r=t.map((e,t)=>n.reduce((e,n)=>Math.max(e,n[t]?.length??0),e.length)),i=e=>`${e.map((e,t)=>e.padEnd(r[t]??0)).join(` `)}`.trimEnd();s.write(`${i(t.map(e=>e.toUpperCase()))}\n`);for(let e of n)s.write(`${i(e)}\n`)}function ii(e){if(e.status===401)return"The API key was rejected. It may be revoked or deleted, so create a new one and run `astralbeam auth login` again.";if(e.status===404&&e.body?.detail===`Resource not found.`)return`This server does not serve that endpoint. Check the API URL, or the server may run an older AstralBeam release than this CLI (${Zr}).`;if(e.status===429)return`The API rate limit was reached. Wait a few minutes and retry.`}function ai(e,t,n,r){let i=e instanceof Error?e.message:String(e);if(t){let t=or(e)?e.body??{status:e.status,detail:i}:{detail:i};a.write(`${JSON.stringify({error:t,context:n??null})}\n`);return}if(!or(e))return void a.write(`Error: ${$r(i)}\n`);let o=r?` from ${r}`:``;a.write(`Error: ${$r(i)} (HTTP ${e.status}${o})\n`);for(let t of e.body?.issues??[])a.write(` ${$r(t.path)}: ${$r(t.message)}\n`);let s=ii(e);s&&a.write(`${s}\n`)}const oi=`https://astralbeam.ai/api`,si=/^key_([0-9a-f-]{36})_[0-9a-f-]{36}_abo_[A-Za-z]{64}$/;function ci(){if(n.ASTRALBEAM_CONFIG_DIR)return se(n.ASTRALBEAM_CONFIG_DIR,`config.json`);let e=i===`win32`?n.APPDATA??ae():n.XDG_CONFIG_HOME??se(ae(),`.config`);return se(e,`astralbeam`,`config.json`)}function li(e){let t=si.exec(e)?.[1];if(!t)throw Error(`The API key must match key_<organizationId>_<id>_abo_<secret>.`);return t}function ui(e){let t;try{t=new URL(e)}catch{throw Error(`The API URL "${e}" is not a valid URL.`)}let n=t.hostname,r=n===`localhost`||n===`[::1]`||w(n)&&n.startsWith(`127.`);if(t.protocol!==`https:`&&!(t.protocol===`http:`&&r))throw Error(`The API URL "${e}" must use https://, or http:// only for loopback hosts.`);return e}function di(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function fi(e){return di(e)&&Object.values(e).every(e=>di(e)&&typeof e.api_url==`string`&&typeof e.api_key==`string`&&di(e.organization)&&typeof e.organization.id==`string`&&typeof e.organization.name==`string`&&typeof e.organization.slug==`string`)}function pi(e){try{let t=JSON.parse(e);if(di(t)){let e=t.bindings===void 0?{}:t.bindings;if(fi(e))return{bindings:e}}}catch{}throw Error(`Invalid AstralBeam login bindings in ${ci()}`)}async function mi(){try{return pi(await b(ci(),`utf8`))}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return{bindings:{}};throw e}}async function hi(e){let t=ci();await re(oe(t),{recursive:!0,mode:448});let n=`${t}.${r}.tmp`;try{await C(n,`${JSON.stringify(e,null,2)}\n`,{mode:384,flag:`wx`}),await ie(n,t)}catch(e){throw await S(n,{force:!0}),e}}async function gi(){return await x(t())}function _i(e,t){for(let n=t;;n=oe(n)){let t=e.bindings[n];if(t)return{directory:n,binding:t};if(oe(n)===n)return}}function vi(e){let t=ae();return e===t||e.startsWith(t+T)?`~${e.slice(t.length)}`:e}const K={json:!1,context:void 0,failedRequest:void 0};function yi(e){K.context={organization:e.organization,bound_directory:e.directory??null},K.json||a.write(bi(e))}function bi(e){let{organization:t,directory:n}=e,r=t.name?`${$r(t.name)} (${$r(t.slug??``)}) · `:``,i=n?`bound at ${vi(n)}`:`from ASTRALBEAM_API_KEY`;return`▸ ${r}org ${t.id} · ${i}\n`}async function xi(){let e=n.ASTRALBEAM_API_KEY,t;if(e)t={apiKey:e,apiUrl:ui(n.ASTRALBEAM_API_URL??`https://astralbeam.ai/api`),organization:{id:li(e)}};else{let e=await gi(),r=_i(await mi(),e);if(!r)throw Error(`No AstralBeam login covers ${vi(e)}. Run \`astralbeam auth login\` in this directory or a parent, or set ASTRALBEAM_API_KEY.`);let{binding:i}=r;t={apiKey:i.api_key,apiUrl:ui(n.ASTRALBEAM_API_URL??i.api_url),organization:i.organization,directory:r.directory}}return yi(t),t}function Si(e,t=[]){let n=(e,r)=>{if(Array.isArray(e)||typeof e!=`object`||!e)return e;let i=Object.entries(e).flatMap(([e,i])=>{let a=[...r,e],o=t.some(e=>e.length===a.length&&e.every((e,t)=>e===a[t])),s=o?i:n(i,a);return s===void 0||!o&&typeof s==`object`&&s&&!Array.isArray(s)&&Object.keys(s).length===0?[]:[[e,s]]});return Object.fromEntries(i)};return n(e,[])}function Ci(e,t){let n=t.startsWith(`--`)?t:`--${t}`,r=e;if(e.startsWith(`@`)){let t=e.slice(1);if(t.length===0)throw Error(`${n} '@' must be followed by a file path (got empty path)`);let i=ce(t);try{r=le(i,`utf-8`)}catch(e){let r=e instanceof Error?e.message:`unknown read error`;throw Error(`${n}: cannot read file at '${t}': ${r}`)}}try{return JSON.parse(r)}catch{throw Error(`Invalid JSON in ${n}. Expected valid JSON.`)}}function wi(e,t=[]){let n=Ci(e,`body`);for(let{path:e,flag:r}of t){let t=n;for(let n of e)t=Ti(t)&&Object.hasOwn(t,n)?t[n]:void 0;if(!Ti(t))throw Error(`--body must include a JSON object at ${e.join(`.`)} (for --${r}).`)}return n}function Ti(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ei(e,t,n=!1){let r=t.startsWith(`--`)?t:`--${t}`;if(e===void 0){if(n)throw Error(`${r} is required (or pass --body with this field set).`);return}if(typeof e!=`string`)throw Error(`${r} must be provided once as a JSON object.`);let i=Ci(e,t);if(!Ti(i))throw Error(`${r} must be a JSON object.`);return i}function Di(e,t,n=`text`){if(e===void 0||!e.startsWith(`@`))return e;let r=e.slice(1);if(r.length===0)throw Error(`--${t} '@' must be followed by a file path (got empty path)`);let i=ce(r),a;try{a=le(i)}catch(e){let n=e instanceof Error?e.message:`unknown read error`;throw Error(`--${t}: cannot read file at '${r}': ${n}`)}switch(n){case`text`:return a.toString(`utf-8`);case`binary`:return a;case`base64`:return a.toString(`base64`);case`json`:{let e=a.toString(`utf-8`);try{return JSON.parse(e)}catch(e){let n=e instanceof Error?e.message:`unknown JSON parse error`;throw Error(`--${t}: file at '${r}' is not valid JSON: ${n}`)}}}}function Oi(e){return e.replace(/^filter_(.+)$/,`filter[$1]`)}async function ki(e){let{apiKey:t,apiUrl:n}=await xi();return{send(e,r={}){let i=new URLSearchParams;for(let t of e.query??[]){let e=r[t];e!==void 0&&i.set(Oi(t),typeof e==`string`?e:JSON.stringify(e))}return ar(e.path(r)+(i.size?`?${i.toString()}`:``),{apiKey:t,apiUrl:n,method:e.method,...e.body?{headers:{"content-type":`application/json`},body:JSON.stringify(r.body)}:{}})}}}function q(e,t){if(e!==void 0){if(K.json||typeof e!=`object`||!e)return Qr(e);if(`items`in e&&Array.isArray(e.items)){let t=e.items;t.length?ri(t,Object.keys(t[0])):a.write(`No results.
|
|
91
|
+
`,`f`),L(this,B,R(this,B,`f`)+e.join(` `),`f`)}}}[_n](e){Qe(R(this,V,`f`)).forEach(t=>{if((e=>e===`configObjects`)(t))return;let n=R(this,V,`f`)[t];Array.isArray(n)?n.includes(e)&&n.splice(n.indexOf(e),1):typeof n==`object`&&delete n[e]}),delete R(this,U,`f`).getDescriptions()[e]}[vn](e,t,n){R(this,Gt,`f`)[n]||(R(this,H,`f`).process.emitWarning(e,t),R(this,Gt,`f`)[n]=!0)}[yn](){R(this,qt,`f`).push({options:R(this,V,`f`),configObjects:R(this,V,`f`).configObjects.slice(0),exitProcess:R(this,Kt,`f`),groups:R(this,Yt,`f`),strict:R(this,ln,`f`),strictCommands:R(this,un,`f`),strictOptions:R(this,dn,`f`),completionCommand:R(this,Vt,`f`),output:R(this,B,`f`),exitError:R(this,Ut,`f`),hasOutput:R(this,Xt,`f`),parsed:this.parsed,parseFn:R(this,nn,`f`),parseContext:R(this,rn,`f`)}),R(this,U,`f`).freeze(),R(this,W,`f`).freeze(),R(this,z,`f`).freeze(),R(this,Jt,`f`).freeze()}[bn](){let e=``,t;return t=/\b(node|iojs|electron)(\.exe)?$/.test(R(this,H,`f`).process.argv()[0])?R(this,H,`f`).process.argv().slice(1,2):R(this,H,`f`).process.argv().slice(0,1),e=t.map(e=>{let t=this[Gn](R(this,Rt,`f`),e);return e.match(/^(\/|([a-zA-Z]:)?\\)/)&&t.length<e.length?t:e}).join(` `).trim(),R(this,H,`f`).getEnv(`_`)&&R(this,H,`f`).getProcessArgvBin()===R(this,H,`f`).getEnv(`_`)&&(e=R(this,H,`f`).getEnv(`_`).replace(`${R(this,H,`f`).path.dirname(R(this,H,`f`).process.execPath())}/`,``)),e}[xn](){return R(this,tn,`f`)}[Sn](){return R(this,fn,`f`)}[Cn](){if(!R(this,Wt,`f`))return;let e=R(this,H,`f`).getEnv(`LC_ALL`)||R(this,H,`f`).getEnv(`LC_MESSAGES`)||R(this,H,`f`).getEnv(`LANG`)||R(this,H,`f`).getEnv(`LANGUAGE`)||`en_US`;this.locale(e.replace(/[.:].*/,``))}[wn](){return this[En]().version||`unknown`}[Tn](e){let t=e[`--`]?e[`--`]:e._;for(let e=0,n;(n=t[e])!==void 0;e++)R(this,H,`f`).Parser.looksLikeNumber(n)&&Number.isSafeInteger(Math.floor(parseFloat(`${n}`)))&&(t[e]=Number(n));return e}[En](e){let t=e||`*`;if(R(this,an,`f`)[t])return R(this,an,`f`)[t];let n={};try{let t=e||R(this,H,`f`).mainFilename;!e&&R(this,H,`f`).path.extname(t)&&(t=R(this,H,`f`).path.dirname(t));let r=R(this,H,`f`).findUp(t,(e,t)=>{if(t.includes(`package.json`))return`package.json`});Xe(r,void 0,R(this,H,`f`)),n=JSON.parse(R(this,H,`f`).readFileSync(r,`utf8`))}catch{}return R(this,an,`f`)[t]=n||{},R(this,an,`f`)[t]}[Dn](e,t){t=[].concat(t),t.forEach(t=>{t=this[jn](t),R(this,V,`f`)[e].push(t)})}[On](e,t,n,r){this[An](e,t,n,r,(e,t,n)=>{R(this,V,`f`)[e][t]=n})}[kn](e,t,n,r){this[An](e,t,n,r,(e,t,n)=>{R(this,V,`f`)[e][t]=(R(this,V,`f`)[e][t]||[]).concat(n)})}[An](e,t,n,r,i){if(Array.isArray(n))n.forEach(t=>{e(t,r)});else if((e=>typeof e==`object`)(n))for(let t of Qe(n))e(t,n[t]);else i(t,this[jn](n),r)}[jn](e){return e===`__proto__`?`___proto___`:e}[Mn](e,t){return this[On](this[Mn].bind(this),`key`,e,t),this}[Nn](){var e,t,n,r,i,a,o,s,c,l,u,d;let f=R(this,qt,`f`).pop();Xe(f,void 0,R(this,H,`f`));let p;e=this,t=this,n=this,r=this,i=this,a=this,o=this,s=this,c=this,l=this,u=this,d=this,{options:{set value(t){L(e,V,t,`f`)}}.value,configObjects:p,exitProcess:{set value(e){L(t,Kt,e,`f`)}}.value,groups:{set value(e){L(n,Yt,e,`f`)}}.value,output:{set value(e){L(r,B,e,`f`)}}.value,exitError:{set value(e){L(i,Ut,e,`f`)}}.value,hasOutput:{set value(e){L(a,Xt,e,`f`)}}.value,parsed:this.parsed,strict:{set value(e){L(o,ln,e,`f`)}}.value,strictCommands:{set value(e){L(s,un,e,`f`)}}.value,strictOptions:{set value(e){L(c,dn,e,`f`)}}.value,completionCommand:{set value(e){L(l,Vt,e,`f`)}}.value,parseFn:{set value(e){L(u,nn,e,`f`)}}.value,parseContext:{set value(e){L(d,rn,e,`f`)}}.value}=f,R(this,V,`f`).configObjects=p,R(this,U,`f`).unfreeze(),R(this,W,`f`).unfreeze(),R(this,z,`f`).unfreeze(),R(this,Jt,`f`).unfreeze()}[Pn](e,t){return ot(t,t=>(e(t),t))}getInternalMethods(){return{getCommandInstance:this[Fn].bind(this),getContext:this[In].bind(this),getHasOutput:this[Ln].bind(this),getLoggerInstance:this[Rn].bind(this),getParseContext:this[zn].bind(this),getParserConfiguration:this[xn].bind(this),getUsageConfiguration:this[Sn].bind(this),getUsageInstance:this[Bn].bind(this),getValidationInstance:this[Vn].bind(this),hasParseCallback:this[Hn].bind(this),isGlobalContext:this[Un].bind(this),postProcess:this[Wn].bind(this),reset:this[Kn].bind(this),runValidation:this[Jn].bind(this),runYargsParserAndExecuteCommands:this[qn].bind(this),setHasOutput:this[Yn].bind(this)}}[Fn](){return R(this,z,`f`)}[In](){return R(this,zt,`f`)}[Ln](){return R(this,Xt,`f`)}[Rn](){return R(this,$t,`f`)}[zn](){return R(this,rn,`f`)||{}}[Bn](){return R(this,U,`f`)}[Vn](){return R(this,W,`f`)}[Hn](){return!!R(this,nn,`f`)}[Un](){return R(this,Qt,`f`)}[Wn](e,t,n,r){return n||F(e)||(t||(e=this[hn](e)),(this[xn]()[`parse-positional-numbers`]||this[xn]()[`parse-positional-numbers`]===void 0)&&(e=this[Tn](e)),r&&(e=at(e,this,R(this,Jt,`f`).getMiddleware(),!1))),e}[Kn](e={}){L(this,V,R(this,V,`f`)||{},`f`);let t={};t.local=R(this,V,`f`).local||[],t.configObjects=R(this,V,`f`).configObjects||[];let n={};return t.local.forEach(t=>{n[t]=!0,(e[t]||[]).forEach(e=>{n[e]=!0})}),Object.assign(R(this,on,`f`),Object.keys(R(this,Yt,`f`)).reduce((e,t)=>{let r=R(this,Yt,`f`)[t].filter(e=>!(e in n));return r.length>0&&(e[t]=r),e},{})),L(this,Yt,{},`f`),[`array`,`boolean`,`string`,`skipValidation`,`count`,`normalize`,`number`,`hiddenOptions`].forEach(e=>{t[e]=(R(this,V,`f`)[e]||[]).filter(e=>!n[e])}),[`narg`,`key`,`alias`,`default`,`defaultDescription`,`config`,`choices`,`demandedOptions`,`demandedCommands`,`deprecatedOptions`].forEach(e=>{t[e]=_t(R(this,V,`f`)[e],e=>!n[e])}),t.envPrefix=R(this,V,`f`).envPrefix,L(this,V,t,`f`),L(this,U,R(this,U,`f`)?R(this,U,`f`).reset(n):bt(this,R(this,H,`f`)),`f`),L(this,W,R(this,W,`f`)?R(this,W,`f`).reset(n):jt(this,R(this,U,`f`),R(this,H,`f`)),`f`),L(this,z,R(this,z,`f`)?R(this,z,`f`).reset():dt(R(this,U,`f`),R(this,W,`f`),R(this,Jt,`f`),R(this,H,`f`)),`f`),R(this,Bt,`f`)||L(this,Bt,Et(this,R(this,U,`f`),R(this,z,`f`),R(this,H,`f`)),`f`),R(this,Jt,`f`).reset(),L(this,Vt,null,`f`),L(this,B,``,`f`),L(this,Ut,null,`f`),L(this,Xt,!1,`f`),this.parsed=!1,this}[Gn](e,t){return R(this,H,`f`).path.relative(e,t)}[qn](e,t,n,r=0,i=!1){let a=!!n||i;e||=R(this,sn,`f`),R(this,V,`f`).__=R(this,H,`f`).y18n.__,R(this,V,`f`).configuration=this[xn]();let o=!!R(this,V,`f`).configuration[`populate--`],s=Object.assign({},R(this,V,`f`).configuration,{"populate--":!0}),c=R(this,H,`f`).Parser.detailed(e,Object.assign({},R(this,V,`f`),{configuration:{"parse-positional-numbers":!1,...s}})),l=Object.assign(c.argv,R(this,rn,`f`)),u,d=c.aliases,f=!1,p=!1;Object.keys(l).forEach(e=>{e===R(this,Zt,`f`)&&l[e]?f=!0:e===R(this,pn,`f`)&&l[e]&&(p=!0)}),l.$0=this.$0,this.parsed=c,r===0&&R(this,U,`f`).clearCachedHelpMessage();try{if(this[Cn](),t)return this[Wn](l,o,!!n,!1);R(this,Zt,`f`)&&[R(this,Zt,`f`)].concat(d[R(this,Zt,`f`)]||[]).filter(e=>e.length>1).includes(``+l._[l._.length-1])&&(l._.pop(),f=!0),L(this,Qt,!1,`f`);let s=R(this,z,`f`).getCommands(),m=R(this,Bt,`f`).completionKey in l,h=f||m||i;if(l._.length){if(s.length){let e;for(let t=r||0,a;l._[t]!==void 0;t++){if(a=String(l._[t]),s.includes(a)&&a!==R(this,Vt,`f`)){let e=R(this,z,`f`).runCommand(a,this,c,t+1,i,f||p||i);return this[Wn](e,o,!!n,!1)}if(!e&&a!==R(this,Vt,`f`)){e=a;break}}!R(this,z,`f`).hasDefaultCommand()&&R(this,cn,`f`)&&e&&!h&&R(this,W,`f`).recommendCommands(e,s)}R(this,Vt,`f`)&&l._.includes(R(this,Vt,`f`))&&!m&&(R(this,Kt,`f`)&&vt(!0),this.showCompletionScript(),this.exit(0))}if(R(this,z,`f`).hasDefaultCommand()&&!h){let e=R(this,z,`f`).runCommand(null,this,c,0,i,f||p||i);return this[Wn](e,o,!!n,!1)}if(m){R(this,Kt,`f`)&&vt(!0),e=[].concat(e);let t=e.slice(e.indexOf(`--${R(this,Bt,`f`).completionKey}`)+1);return R(this,Bt,`f`).getCompletion(t,(e,t)=>{if(e)throw new P(e.message);(t||[]).forEach(e=>{R(this,$t,`f`).log(e)}),this.exit(0)}),this[Wn](l,!o,!!n,!1)}if(R(this,Xt,`f`)||(f?(R(this,Kt,`f`)&&vt(!0),a=!0,this.showHelp(`log`),this.exit(0)):p&&(R(this,Kt,`f`)&&vt(!0),a=!0,R(this,U,`f`).showVersion(`log`),this.exit(0))),!a&&R(this,V,`f`).skipValidation.length>0&&(a=Object.keys(l).some(e=>R(this,V,`f`).skipValidation.indexOf(e)>=0&&l[e]===!0)),!a){if(c.error)throw new P(c.error.message);if(!m){let e=this[Jn](d,{},c.error);n||(u=at(l,this,R(this,Jt,`f`).getMiddleware(),!0)),u=this[Pn](e,u??l),F(u)&&!n&&(u=u.then(()=>at(l,this,R(this,Jt,`f`).getMiddleware(),!1)))}}}catch(e){if(e instanceof P)R(this,U,`f`).fail(e.message,e);else throw e}return this[Wn](u??l,o,!!n,!0)}[Jn](e,t,n,r){let i={...this.getDemandedOptions()};return a=>{if(n)throw new P(n.message);R(this,W,`f`).nonOptionCount(a),R(this,W,`f`).requiredArguments(a,i);let o=!1;R(this,un,`f`)&&(o=R(this,W,`f`).unknownCommands(a)),R(this,ln,`f`)&&!o?R(this,W,`f`).unknownArguments(a,e,t,!!r):R(this,dn,`f`)&&R(this,W,`f`).unknownArguments(a,e,{},!1,!1),R(this,W,`f`).limitedChoices(a),R(this,W,`f`).implications(a),R(this,W,`f`).conflicting(a)}}[Yn](){L(this,Xt,!0,`f`)}[Xn](e){if(typeof e==`string`)R(this,V,`f`).key[e]=!0;else for(let t of e)R(this,V,`f`).key[t]=!0}};function Qn(e){return!!e&&typeof e.getInternalMethods==`function`}const $n=mn(Ye);var er=class extends Error{};function tr(e){if(!Number.isInteger(e)||e<60||e>600)throw new er(`Expected a whole number of seconds from 60 to 600.`);return e}function nr(e,t=`https://astralbeam.ai/api`){return`${t.replace(/\/+$/,``)}${e.replace(/^\/api(?=\/)/,``)}`}function rr(e,t){if(!e||typeof e!=`object`)return!1;let n=e;return n.status===t&&typeof n.type==`string`&&typeof n.title==`string`&&typeof n.detail==`string`&&(n.reference===void 0||typeof n.reference==`string`)&&(n.issues===void 0||Array.isArray(n.issues)&&n.issues.every(e=>e&&typeof e.path==`string`&&typeof e.message==`string`))}async function ir(e,t){let{apiUrl:n,apiKey:r,astralBeamToken:i,fetchClient:a=globalThis.fetch,...o}=t,s=new Headers,c=o.headers instanceof Headers?o.headers.entries():Array.isArray(o.headers)?o.headers:Object.entries(o.headers??{});for(let[e,t]of c)s.set(e,t);s.delete(`authorization`),s.delete(`x-api-key`),r&&s.set(`x-api-key`,r),i&&s.set(`authorization`,`Bearer ${i}`);let l=await a(nr(e,n),{...o,headers:s,...r?{redirect:`error`}:{}});if(l.ok)return l;let u=await l.json().catch(e=>{if(!(e instanceof SyntaxError))throw e}),d=rr(u,l.status)?u:void 0;throw Object.assign(Error(d?.detail??`AstralBeam API returned HTTP ${l.status}`),{name:`AstralBeamApiError`,status:l.status,headers:l.headers,body:d})}async function ar(e,t){let n=await ir(e,t);if(n.status!==204)return await n.json()}function or(e){return e instanceof Error&&e.name===`AstralBeamApiError`&&`status`in e&&typeof e.status==`number`}function sr(e,t=`https://astralbeam.ai/api`){return`${t.replace(/\/+$/,``)}${e.replace(/^\/api(?=\/)/,``)}`}function cr(e,t){if(!e||typeof e!=`object`)return!1;let n=e;return n.status===t&&typeof n.type==`string`&&typeof n.title==`string`&&typeof n.detail==`string`&&(n.reference===void 0||typeof n.reference==`string`)&&(n.issues===void 0||Array.isArray(n.issues)&&n.issues.every(e=>e&&typeof e.path==`string`&&typeof e.message==`string`))}async function lr(e,t){let{apiUrl:n,apiKey:r,astralBeamToken:i,fetchClient:a=globalThis.fetch,...o}=t,s=new Headers,c=o.headers instanceof Headers?o.headers.entries():Array.isArray(o.headers)?o.headers:Object.entries(o.headers??{});for(let[e,t]of c)s.set(e,t);s.delete(`authorization`),s.delete(`x-api-key`),r&&s.set(`x-api-key`,r),i&&s.set(`authorization`,`Bearer ${i}`);let l=await a(sr(e,n),{...o,headers:s,...r?{redirect:`error`}:{}});if(l.ok)return l;let u=await l.json().catch(e=>{if(!(e instanceof SyntaxError))throw e}),d=cr(u,l.status)?u:void 0;throw Object.assign(Error(d?.detail??`AstralBeam API returned HTTP ${l.status}`),{name:`AstralBeamApiError`,status:l.status,headers:l.headers,body:d})}async function ur(e,t){let n=await lr(e,t);if(n.status!==204)return await n.json()}function G(e,t){return ur(e,t)}async function dr(e,t){let n=await lr(e,t),r=n.status===204?n.headers.get(`location`):null;if(!r)return n;let i=await globalThis.fetch(r,{credentials:`omit`,redirect:`error`,referrerPolicy:`no-referrer`,signal:t.signal??null});if(!i.ok)throw Error(`The file could not be downloaded. Please try again.`);return i}function fr(e,t){return lr(e,t)}const pr=()=>`/api/v1/organization`,mr=e=>ur(pr(),{...e,method:`GET`}),hr=()=>`/api/v1/chat/files`,gr=(e,t)=>{let n=e=>{if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Symbol.iterator in e)return Object.fromEntries(Array.from(e,e=>Array.from(e)));let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t};return G(hr(),{...t,method:`POST`,headers:{"Content-Type":`application/json`,...n(t?.headers)},body:JSON.stringify(e)})},_r=e=>{let t=new URLSearchParams;Object.entries(e||{}).forEach(([e,n])=>{n!==void 0&&t.append(e,n===null?`null`:String(n))});let n=t.toString();return n.length>0?`/api/v1/chat/files?${n}`:`/api/v1/chat/files`},vr=(e,t)=>dr(_r(e),{...t,method:`GET`}),yr=()=>`/api/v1/chat`,br=e=>{let t=new URLSearchParams;Object.entries(e||{}).forEach(([e,n])=>{n!==void 0&&t.append(e,n===null?`null`:String(n))});let n=t.toString();return n.length>0?`/api/v1/chat/config?${n}`:`/api/v1/chat/config`},xr=(e,t)=>G(br(e),{...t,method:`GET`}),Sr=()=>`/api/v1/chat/threads`,Cr=(e,t)=>{let n=e=>{if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Symbol.iterator in e)return Object.fromEntries(Array.from(e,e=>Array.from(e)));let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t};return G(Sr(),{...t,method:`POST`,headers:{"Content-Type":`application/json`,...n(t?.headers)},body:JSON.stringify(e)})},wr=e=>{let t=new URLSearchParams;Object.entries(e||{}).forEach(([e,n])=>{n!==void 0&&t.append(e,n===null?`null`:String(n))});let n=t.toString();return n.length>0?`/api/v1/chat/threads?${n}`:`/api/v1/chat/threads`},Tr=(e,t)=>G(wr(e),{...t,method:`GET`}),Er=e=>`/api/v1/chat/threads/${encodeURIComponent(String(e))}`,Dr=(e,t,n)=>{let r=e=>{if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Symbol.iterator in e)return Object.fromEntries(Array.from(e,e=>Array.from(e)));let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t};return G(Er(e),{...n,method:`PATCH`,headers:{"Content-Type":`application/json`,...r(n?.headers)},body:JSON.stringify(t)})},Or=(e,t)=>{let n=new URLSearchParams;Object.entries(t||{}).forEach(([e,t])=>{t!==void 0&&n.append(e,t===null?`null`:String(t))});let r=n.toString();return r.length>0?`/api/v1/chat/threads/${encodeURIComponent(String(e))}?${r}`:`/api/v1/chat/threads/${encodeURIComponent(String(e))}`},kr=(e,t,n)=>G(Or(e,t),{...n,method:`DELETE`}),Ar=(e,t)=>{let n=new URLSearchParams;Object.entries(t||{}).forEach(([e,t])=>{t!==void 0&&n.append(e,t===null?`null`:String(t))});let r=n.toString();return r.length>0?`/api/v1/chat/threads/${encodeURIComponent(String(e))}/messages?${r}`:`/api/v1/chat/threads/${encodeURIComponent(String(e))}/messages`},jr=(e,t,n)=>G(Ar(e,t),{...n,method:`GET`}),Mr=e=>`/api/v1/chat/threads/${encodeURIComponent(String(e))}/tool-results`,Nr=()=>`/api/v1/me`,Pr=e=>G(Nr(),{...e,method:`POST`}),Fr=()=>`/api/v1/me/mcp/catalog`,Ir=e=>G(Fr(),{...e,method:`GET`}),Lr=()=>`/api/v1/me/mcp/connections`,Rr=(e,t)=>{let n=e=>{if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Symbol.iterator in e)return Object.fromEntries(Array.from(e,e=>Array.from(e)));let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t};return G(Lr(),{...t,method:`POST`,headers:{"Content-Type":`application/json`,...n(t?.headers)},body:JSON.stringify(e)})},zr=e=>`/api/v1/me/mcp/connections/${encodeURIComponent(String(e))}/headers`,Br=(e,t,n)=>{let r=e=>{if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Symbol.iterator in e)return Object.fromEntries(Array.from(e,e=>Array.from(e)));let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t};return G(zr(e),{...n,method:`POST`,headers:{"Content-Type":`application/json`,...r(n?.headers)},body:JSON.stringify(t)})},Vr=e=>`/api/v1/me/mcp/connections/${encodeURIComponent(String(e))}`,Hr=(e,t)=>G(Vr(e),{...t,method:`DELETE`}),Ur=e=>`/api/v1/me/mcp/connections/${encodeURIComponent(String(e))}/test`,Wr=(e,t)=>G(Ur(e),{...t,method:`POST`}),Gr=e=>`/api/v1/me/mcp/connections/${encodeURIComponent(String(e))}/authorize`,Kr=(e,t)=>G(Gr(e),{...t,method:`POST`}),qr=e=>`/api/v1/me/mcp/connections/${encodeURIComponent(String(e))}/oauth/bind`,Jr=(e,t,n)=>{let r=e=>{if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Symbol.iterator in e)return Object.fromEntries(Array.from(e,e=>Array.from(e)));let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t};return G(qr(e),{...n,method:`POST`,headers:{"Content-Type":`application/json`,...r(n?.headers)},body:JSON.stringify(t)})},Yr=e=>`/api/v1/me/mcp/connections/${encodeURIComponent(String(e))}/oauth/complete`,Xr=(e,t,n)=>{let r=e=>{if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Symbol.iterator in e)return Object.fromEntries(Array.from(e,e=>Array.from(e)));let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t};return G(Yr(e),{...n,method:`POST`,headers:{"Content-Type":`application/json`,...r(n?.headers)},body:JSON.stringify(t)})};var Zr=`0.30.4`;function Qr(e){s.write(`${JSON.stringify(e,null,2)}\n`)}function $r(e,t=``){let n=``;for(let r of e){let e=r.codePointAt(0)??0;n+=(e<32||e>=127&&e<160)&&!t.includes(r)?`\\u${e.toString(16).padStart(4,`0`)}`:r}return n}function ei(e){return e==null?``:$r(typeof e==`string`?e:JSON.stringify(e))}function ti(e){let t=Object.entries(e),n=Math.max(...t.map(([e])=>e.length));for(let[e,r]of t)s.write(`${e.padEnd(n)} ${ei(r)}\n`)}function ni(e,t){t?Qr(e):ti(e)}function ri(e,t){let n=e.map(e=>t.map(t=>ei(e[t]))),r=t.map((e,t)=>n.reduce((e,n)=>Math.max(e,n[t]?.length??0),e.length)),i=e=>`${e.map((e,t)=>e.padEnd(r[t]??0)).join(` `)}`.trimEnd();s.write(`${i(t.map(e=>e.toUpperCase()))}\n`);for(let e of n)s.write(`${i(e)}\n`)}function ii(e){if(e.status===401)return"The API key was rejected. It may be revoked or deleted, so create a new one and run `astralbeam auth login` again.";if(e.status===404&&e.body?.detail===`Resource not found.`)return`This server does not serve that endpoint. Check the API URL, or the server may run an older AstralBeam release than this CLI (${Zr}).`;if(e.status===429)return`The API rate limit was reached. Wait a few minutes and retry.`}function ai(e,t,n,r){let i=e instanceof Error?e.message:String(e);if(t){let t=or(e)?e.body??{status:e.status,detail:i}:{detail:i};a.write(`${JSON.stringify({error:t,context:n??null})}\n`);return}if(!or(e))return void a.write(`Error: ${$r(i)}\n`);let o=r?` from ${r}`:``;a.write(`Error: ${$r(i)} (HTTP ${e.status}${o})\n`);for(let t of e.body?.issues??[])a.write(` ${$r(t.path)}: ${$r(t.message)}\n`);let s=ii(e);s&&a.write(`${s}\n`)}const oi=`https://astralbeam.ai/api`,si=/^key_([0-9a-f-]{36})_[0-9a-f-]{36}_abo_[A-Za-z]{64}$/;function ci(){if(n.ASTRALBEAM_CONFIG_DIR)return se(n.ASTRALBEAM_CONFIG_DIR,`config.json`);let e=i===`win32`?n.APPDATA??ae():n.XDG_CONFIG_HOME??se(ae(),`.config`);return se(e,`astralbeam`,`config.json`)}function li(e){let t=si.exec(e)?.[1];if(!t)throw Error(`The API key must match key_<organizationId>_<id>_abo_<secret>.`);return t}function ui(e){let t;try{t=new URL(e)}catch{throw Error(`The API URL "${e}" is not a valid URL.`)}let n=t.hostname,r=n===`localhost`||n===`[::1]`||w(n)&&n.startsWith(`127.`);if(t.protocol!==`https:`&&!(t.protocol===`http:`&&r))throw Error(`The API URL "${e}" must use https://, or http:// only for loopback hosts.`);return e}function di(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function fi(e){return di(e)&&Object.values(e).every(e=>di(e)&&typeof e.api_url==`string`&&typeof e.api_key==`string`&&di(e.organization)&&typeof e.organization.id==`string`&&typeof e.organization.name==`string`&&typeof e.organization.slug==`string`)}function pi(e){try{let t=JSON.parse(e);if(di(t)){let e=t.bindings===void 0?{}:t.bindings;if(fi(e))return{bindings:e}}}catch{}throw Error(`Invalid AstralBeam login bindings in ${ci()}`)}async function mi(){try{return pi(await b(ci(),`utf8`))}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return{bindings:{}};throw e}}async function hi(e){let t=ci();await re(oe(t),{recursive:!0,mode:448});let n=`${t}.${r}.tmp`;try{await C(n,`${JSON.stringify(e,null,2)}\n`,{mode:384,flag:`wx`}),await ie(n,t)}catch(e){throw await S(n,{force:!0}),e}}async function gi(){return await x(t())}function _i(e,t){for(let n=t;;n=oe(n)){let t=e.bindings[n];if(t)return{directory:n,binding:t};if(oe(n)===n)return}}function vi(e){let t=ae();return e===t||e.startsWith(t+T)?`~${e.slice(t.length)}`:e}const K={json:!1,context:void 0,failedRequest:void 0};function yi(e){K.context={organization:e.organization,bound_directory:e.directory??null},K.json||a.write(bi(e))}function bi(e){let{organization:t,directory:n}=e,r=t.name?`${$r(t.name)} (${$r(t.slug??``)}) · `:``,i=n?`bound at ${vi(n)}`:`from ASTRALBEAM_API_KEY`;return`▸ ${r}org ${t.id} · ${i}\n`}async function xi(){let e=n.ASTRALBEAM_API_KEY,t;if(e)t={apiKey:e,apiUrl:ui(n.ASTRALBEAM_API_URL??`https://astralbeam.ai/api`),organization:{id:li(e)}};else{let e=await gi(),r=_i(await mi(),e);if(!r)throw Error(`No AstralBeam login covers ${vi(e)}. Run \`astralbeam auth login\` in this directory or a parent, or set ASTRALBEAM_API_KEY.`);let{binding:i}=r;t={apiKey:i.api_key,apiUrl:ui(n.ASTRALBEAM_API_URL??i.api_url),organization:i.organization,directory:r.directory}}return yi(t),t}function Si(e,t=[]){let n=(e,r)=>{if(Array.isArray(e)||typeof e!=`object`||!e)return e;let i=Object.entries(e).flatMap(([e,i])=>{let a=[...r,e],o=t.some(e=>e.length===a.length&&e.every((e,t)=>e===a[t])),s=o?i:n(i,a);return s===void 0||!o&&typeof s==`object`&&s&&!Array.isArray(s)&&Object.keys(s).length===0?[]:[[e,s]]});return Object.fromEntries(i)};return n(e,[])}function Ci(e,t){let n=t.startsWith(`--`)?t:`--${t}`,r=e;if(e.startsWith(`@`)){let t=e.slice(1);if(t.length===0)throw Error(`${n} '@' must be followed by a file path (got empty path)`);let i=ce(t);try{r=le(i,`utf-8`)}catch(e){let r=e instanceof Error?e.message:`unknown read error`;throw Error(`${n}: cannot read file at '${t}': ${r}`)}}try{return JSON.parse(r)}catch{throw Error(`Invalid JSON in ${n}. Expected valid JSON.`)}}function wi(e,t=[]){let n=Ci(e,`body`);for(let{path:e,flag:r}of t){let t=n;for(let n of e)t=Ti(t)&&Object.hasOwn(t,n)?t[n]:void 0;if(!Ti(t))throw Error(`--body must include a JSON object at ${e.join(`.`)} (for --${r}).`)}return n}function Ti(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ei(e,t,n=!1){let r=t.startsWith(`--`)?t:`--${t}`;if(e===void 0){if(n)throw Error(`${r} is required (or pass --body with this field set).`);return}if(typeof e!=`string`)throw Error(`${r} must be provided once as a JSON object.`);let i=Ci(e,t);if(!Ti(i))throw Error(`${r} must be a JSON object.`);return i}function Di(e,t,n=`text`){if(e===void 0||!e.startsWith(`@`))return e;let r=e.slice(1);if(r.length===0)throw Error(`--${t} '@' must be followed by a file path (got empty path)`);let i=ce(r),a;try{a=le(i)}catch(e){let n=e instanceof Error?e.message:`unknown read error`;throw Error(`--${t}: cannot read file at '${r}': ${n}`)}switch(n){case`text`:return a.toString(`utf-8`);case`binary`:return a;case`base64`:return a.toString(`base64`);case`json`:{let e=a.toString(`utf-8`);try{return JSON.parse(e)}catch(e){let n=e instanceof Error?e.message:`unknown JSON parse error`;throw Error(`--${t}: file at '${r}' is not valid JSON: ${n}`)}}}}function Oi(e){return e.replace(/^filter_(.+)$/,`filter[$1]`)}async function ki(e){let{apiKey:t,apiUrl:n}=await xi();return{send(e,r={}){let i=new URLSearchParams;for(let t of e.query??[]){let e=r[t];e!==void 0&&i.set(Oi(t),typeof e==`string`?e:JSON.stringify(e))}return ar(e.path(r)+(i.size?`?${i.toString()}`:``),{apiKey:t,apiUrl:n,method:e.method,...e.body?{headers:{"content-type":`application/json`},body:JSON.stringify(r.body)}:{}})}}}function q(e,t){if(e!==void 0){if(K.json||typeof e!=`object`||!e)return Qr(e);if(`items`in e&&Array.isArray(e.items)){let t=e.items;t.length?ri(t,Object.keys(t[0])):a.write(`No results.
|
|
92
92
|
`),`page_after`in e&&typeof e.page_after==`string`&&a.write(`More results: --page-after ${$r(e.page_after)}\n`)}else ni(e,!1)}}function J(e,t){return t()}let Ai=``;async function ji(e,t,n){return t.dryRun&&(Ai=(await xi()).apiUrl),n()}function Mi(e){e.query&&=Object.fromEntries(Object.entries(e.query).map(([e,t])=>[Oi(e),t])),Qr({...e,note:`Local request preview only. No HTTP request or server-side validation is performed.`,command:e.command.replace(/^cf /,`astralbeam `),url:nr(new URL(e.url).pathname.replace(/^\/client\/v4/,``),Ai)})}function Ni(e,t){throw Error(`Missing required option --${e} (or pass --body).`)}var Pi={method:`GET`,path:()=>`/api/v1/docs/search`,query:[`q`],errors:{400:`BadRequestError`,401:`UnauthorizedError`,403:`ForbiddenError`,404:`NotFoundError`,409:`ConflictError`,413:`ContentTooLargeError`,415:`UnsupportedMediaTypeError`,422:`UnprocessableEntityError`,429:`TooManyRequestsError`,500:`InternalServerError`,503:`ServiceUnavailableError`}};function Fi(e){return e.usage(`$0 docs search
|
|
93
93
|
|
|
94
94
|
Search the published guides and API reference. Returns up to five matching pages with relative URLs and the best matching section. Accepts the same credentials as the resource APIs.`).option(`q`,{type:`string`,description:`Q`,demandOption:!0}).option(`dry-run`,{type:`boolean`,description:`Validate and show what would happen without executing`,default:!1})}const Ii={command:`search`,describe:`Search documentation`,builder:Fi,handler:async e=>ji({command:`docs search`,classification:{safeFlags:[`dry-run`]}},e,async()=>{let t={q:e.q};if(e.dryRun){Mi({command:`cf docs search`,method:`GET`,url:`https://api.cloudflare.com/client/v4/api/v1/docs/search`,pathParams:{},query:t,bodyKind:`none`});return}let n=await ki(e);q(await J(`Loading`,async()=>n.send(Pi,t)),{successLabel:`Loaded`})})},Li={command:`docs`,describe:`docs`,builder:e=>e.command(Ii).demandCommand(1,`Please specify a subcommand`),handler:()=>{}};var Ri={method:`GET`,path:()=>`/api/v1/organization`,errors:{400:`BadRequestError`,401:`UnauthorizedError`,403:`ForbiddenError`,404:`NotFoundError`,409:`ConflictError`,413:`ContentTooLargeError`,415:`UnsupportedMediaTypeError`,422:`UnprocessableEntityError`,429:`TooManyRequestsError`,500:`InternalServerError`,503:`ServiceUnavailableError`}};function zi(e){return e.usage(`$0 organization get
|
|
@@ -144,7 +144,7 @@ var Hl=/* @__PURE__ */ io({compare:()=>$l,generate:()=>Zl,observe:()=>Xl,unobser
|
|
|
144
144
|
`);r=s.pop()||``;for(let e of s){let t=e.endsWith(`\r`)?e.slice(0,-1):e;t.trim()&&(yield t)}}if(r+=n.decode(),r.trim()&&!t?.aborted)throw new ku}finally{try{e.cancel().catch(()=>{})}catch{}e.releaseLock()}}async function*Gu(e){let t;for await(let n of e){if(n===`id`||n.startsWith(`id:`)){let e=n===`id`?``:n.slice(3);t=e.startsWith(` `)?e.slice(1):e;continue}if(n.startsWith(`:`)||n.startsWith(`event:`)||n.startsWith(`retry:`))continue;let e=Io(n),r=ul(JSON.parse(e)),i=t;t=void 0,yield{chunk:r,...i===void 0?{}:{id:i}}}}async function Ku(e){if(!e.ok){if(e.status===401){let t=await e.clone().json().catch(()=>null);if(Eu(t))throw new xu(t.error.provider)}throw new Pu(`HTTP error! status: ${e.status} ${e.statusText}`,e.status,e.headers.get(`retry-after`))}}function qu(e,t){let n={threadId:e};return t?.limit!==void 0&&(n.limit=String(t.limit)),t?.before!==void 0&&(n.before=t.before),n}function Ju(e){return typeof e!=`object`||!e||!(`truncated`in e)||e.truncated!==!0||!(`cursor`in e)||typeof e.cursor!=`string`||e.cursor===``?{truncated:!1}:{truncated:!0,cursor:e.cursor}}async function Yu(e,t,n,r,i,a){let o=await e(Uu(t,qu(i,a)),{method:`GET`,headers:{Accept:`application/json`,...n},credentials:r});await Ku(o);let s=await o.json(),c=s.activeRun&&typeof s.activeRun.runId==`string`?{runId:s.activeRun.runId}:null,l=s.interrupts&&typeof s.interrupts.runId==`string`&&Array.isArray(s.interrupts.pending)&&s.interrupts.pending.length>0?{runId:s.interrupts.runId,pending:s.interrupts.pending}:null;return{messages:Array.isArray(s.messages)?zo(s.messages):[],activeRun:c,interrupts:l,page:Ju(s.page)}}async function Xu(e,t,n,r,i){let a=await e(Uu(t,{threadId:i}),{method:`GET`,headers:{Accept:`application/json`,...n},credentials:r});await Ku(a);let o=await a.json();if(o===null)return{resumeSnapshot:null,activeRun:null};if(typeof o!=`object`||Array.isArray(o))throw Error(`Generation hydration expected a JSON object from ${t}, received ${Array.isArray(o)?`an array`:typeof o}.`);let s=o,c=s.activeRun&&typeof s.activeRun.runId==`string`?{runId:s.activeRun.runId}:null;return{resumeSnapshot:s.resumeSnapshot??null,activeRun:c}}async function*Zu(e,t){await Ku(e),yield*Gu(Wu(Po(e),t))}async function*Qu(e,t){for await(let{chunk:n}of Zu(e,t))yield n}function $u(e,t,n,r){return async function*(i,a){let o;try{o=await e(t,{...n,headers:{...n.headers,...i},...a?{signal:a}:{}})}catch(e){throw new Au(e)}yield*r(o,a)}}async function*ed(e,t,n){let r=Ru(n);for(;;){if(t?.aborted)return;let n=r.lastEventId===void 0?{}:{"Last-Event-ID":r.lastEventId},i=!1,a=!1;try{for await(let{chunk:o,id:s}of e(n,t))r.note(s)!==`duplicate`&&(a=!0,(o.type===`RUN_FINISHED`||o.type===`RUN_ERROR`)&&(i=!0),yield o)}catch(e){if(t?.aborted)return;if((e instanceof ku||e instanceof Au||Iu(e))&&r.lastEventId!==void 0){await r.waitBeforeReconnect(a,t,Iu(e)?e.retryAfterMs:void 0);continue}throw e}if(t?.aborted||i)return;if(r.lastEventId!==void 0){if(a){await r.waitBeforeReconnect(!0,t);continue}throw new ju}return}}function td(e){if(!e)throw Error(`Connection adapter is required`);let t=`connect`in e,n=`subscribe`in e,r=`send`in e;if(t&&(n||r))throw Error(`Connection adapter must provide either connect or both subscribe and send, not both modes`);if(n&&r){let t=e.joinRun?.bind(e),n=e.hydrate?.bind(e);return{subscribe:e.subscribe.bind(e),send:e.send.bind(e),...t?{joinRun:t}:{},...n?{hydrate:n}:{}}}if(!t)throw Error(`Connection adapter must provide either connect or both subscribe and send`);let i=[],a=[],o;function s(e,t){t&&Du.set(e,t);let n=a.shift();n?n(e):i.push(e)}async function c(e){let t=()=>o!==a||i.length===0&&(a.length>0||e?.aborted);for(let n=0;n<16&&!e?.aborted;n++){if(t())return;await Promise.resolve()}for(;!e?.aborted;){if(t())return;await new Promise(e=>setTimeout(e,0))}}return{subscribe(e){let t=i.splice(0),n=[];return i=t,a=n,(async function*(){o=n;try{for(;!e?.aborted;){let r,i=t.shift();r=i===void 0?await new Promise(t=>{let r=()=>t(null);n.push(n=>{e?.removeEventListener(`abort`,r),t(n)}),e?.addEventListener(`abort`,r,{once:!0})}):i,r!==null&&(yield r)}}finally{o===n&&(o=void 0)}})()},async send(t,n,r,i){let a=!1,o,l;try{let c=e.connect(t,n,r,i);for await(let e of c)`threadId`in e&&typeof e.threadId==`string`&&(o=e.threadId),`runId`in e&&typeof e.runId==`string`&&(l=e.runId),(e.type===`RUN_FINISHED`||e.type===`RUN_ERROR`)&&(a=!0),s(e,i.runId);!r?.aborted&&!a&&s(Ko({type:X.RUN_FINISHED,threadId:o??i.threadId,runId:l??i.runId,timestamp:Date.now()},{finishReason:`stop`,model:`connect-wrapper`}),i.runId)}catch(e){if(!r?.aborted&&!a){let t=e instanceof Error?e.message:`Unknown error in connect()`;s({type:X.RUN_ERROR,threadId:o??i.threadId,runId:l??i.runId,timestamp:Date.now(),message:t},i.runId)}throw e}await c(r)},...typeof e.joinRun==`function`?{joinRun:(t,n)=>e.joinRun(t,n)}:{},...(()=>{let t=e.hydrate;return typeof t==`function`?{hydrate:(e,n)=>t(e,n)}:{}})()}}function nd(e,t,n,r){if(!n)throw Error(`Connection adapter: connect() and send() need a run context with a threadId. ChatClient and the generation clients pass one. Pass it when you call the adapter yourself.`);let i=Kc(e),a={...r.body,...n.forwardedProps,...t};return{threadId:n.threadId,runId:n.runId,...n.parentRunId!==void 0&&{parentRunId:n.parentRunId},...n.resume!==void 0&&{resume:n.resume},state:{},messages:i,tools:n.clientTools??[],context:[],forwardedProps:a}}function rd(e,t={}){return{async*connect(n,r,i,a){let o=typeof e==`function`?e():e,s=typeof t==`function`?await t():t,c={"Content-Type":`application/json`,...Bu(s.headers),...Bu(a.headers),...Hu(a.runId)},l=nd(n,r,a,s),u=s.fetchClient??fetch,d=i||s.signal;yield*ed($u(u,o,{method:`POST`,headers:c,body:JSON.stringify(l),credentials:s.credentials||`same-origin`},Zu),d,s.reconnect)},async*joinRun(n,r){let i=typeof e==`function`?e():e,a=typeof t==`function`?await t():t,o=Uu(i,{offset:`-1`,runId:n}),s={...Bu(a.headers)},c=a.fetchClient??fetch,l=r||a.signal;yield*ed($u(c,o,{method:`GET`,headers:s,credentials:a.credentials||`same-origin`},Zu),l,a.reconnect)},async hydrate(n,r){let i=typeof e==`function`?e():e,a=typeof t==`function`?await t():t;return Yu(a.fetchClient??fetch,i,Bu(a.headers),a.credentials||`same-origin`,n,r)},async hydrateGeneration(n){let r=typeof e==`function`?e():e,i=typeof t==`function`?await t():t;return Xu(i.fetchClient??fetch,r,Bu(i.headers),i.credentials||`same-origin`,n)}}}function id(e){return{async*connect(t,n,r,i){if(!r)throw Error(`fetcherToConnectionAdapter requires an AbortSignal — the chat client always supplies one.`);if(!i)throw Error(`fetcherToConnectionAdapter requires a RunAgentInputContext — the chat client always supplies one.`);let a=await e({messages:t,data:n,threadId:i.threadId,runId:i.runId,...i.parentRunId===void 0?{}:{parentRunId:i.parentRunId},...i.resume===void 0?{}:{resume:i.resume}},{signal:r,headers:i.headers});a instanceof Response?yield*Qu(a,r):yield*ad(a,r)}}}async function*ad(e,t){if(t.aborted)return;let n=e[Symbol.asyncIterator](),r=new Promise(e=>{t.addEventListener(`abort`,()=>e({done:!0,value:void 0}),{once:!0})});try{for(;;){let e=await Promise.race([n.next(),r]);if(e.done)return;yield e.value}}finally{await n.return?.()}}function od(e){return e.resumable}function sd(e,t){let n=Hs(e.descriptor);return n?{...t,metadata:Vs(n)}:t}function cd(e){return`cancel`in e&&`clearResolution`in e}var ld=/* @__PURE__ */ new Set([`invalid-payload`,`invalid-edited-args`,`invalid-tool-output`,`invalid-response-schema`,`unknown-interrupt`,`expired`,`stale`,`conflict`]),ud=/* @__PURE__ */ new Set([`incomplete-batch`,`item-validation-failed`,`unsupported-bulk-operation`,`async-resolver`,`inactive-transaction`,`mixed-provenance`,`transport`,`server`,`protocol`,`invalid-response-schema`,`expired`,`stale`,`conflict`]);function dd(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function fd(e){return Fs(e)}function pd(e){if(!dd(e.metadata))return!1;let t=e.metadata[As];return!dd(t)||t.v!==void 0&&t.v!==1?!1:t.kind===`generic`||t.kind===`tool-approval`||t.kind===`client-tool-execution`||`definitionId`in t||`key`in t||`batchIndex`in t||`payloadSchemaHash`in t}function md(e){if(!dd(e.metadata))return!1;let t=e.metadata[As];return!dd(t)||t.kind!==`generic`?!1:`definitionId`in t||`key`in t||`batchIndex`in t||`payloadSchemaHash`in t}function hd(e){return e.metadata?.[`tanstack:interruptPayload`]}function gd(e){if(e.responseSchema!==void 0)try{return ss(os(e.responseSchema))}catch{return}}function _d(e){if(e!==void 0)try{return Rs(e)}catch{return}}function vd(e){return e!==null&&(typeof e==`object`||typeof e==`function`)&&`then`in e&&typeof e.then==`function`}function yd(e,t,n){if(e===void 0)return{valid:!0,payload:t};if(ps(e)){let r=e[`~standard`].validate(t),i=e=>e.issues?{code:n,message:e.issues[0]?.message??`Schema validation failed.`}:{valid:!0,payload:e.value};return vd(r)?Promise.resolve(r).then(i):i(r)}return{valid:!0,payload:t}}function bd(e){for(let t of ld)if(t===e)return!0;return!1}function xd(e){for(let t of ud)if(t===e)return!0;return!1}function Sd(e){if(!dd(e))return!1;let t=e.scope,n=e.code;return typeof n!=`string`||typeof e.message!=`string`||typeof e.retryable!=`boolean`||typeof e.threadId!=`string`||typeof e.interruptedRunId!=`string`||typeof e.generation!=`number`?!1:t===`item`?bd(n)&&typeof e.interruptId==`string`&&(e.source===`client`||e.source===`server`):t===`batch`&&xd(n)&&Array.isArray(e.interruptIds)&&e.interruptIds.every(e=>typeof e==`string`)&&(e.source===`client`||e.source===`server`||e.source===`transport`)}function Cd(e){return Sd(e)?[e]:!dd(e)||!Array.isArray(e.errors)?[]:e.errors.every(Sd)?e.errors:[]}function wd(e,t){if(e.length!==t.length)return!1;let n=[...e].sort(),r=[...t].sort();return n.every((e,t)=>e===r[t])}function Td(e,t){return e.threadId===t.threadId&&e.interruptedRunId===t.interruptedRunId&&e.generation===t.generation&&wd(e.interruptIds,t.interruptIds)}function Ed(e,t,n){let r=n.filter(e=>e.source!==`transport`),i=e=>t.includes(e)&&r.some(t=>Td(e,t)),a=e.filter(e=>!i(e)),o=t.filter(e=>!r.some(t=>Td(e,t)));return Object.freeze({rootErrors:Object.freeze([...a,...n]),submissionRootErrors:Object.freeze([...o,...r])})}function Dd(e,t){if(e.threadId!==t.threadId||e.interruptedRunId!==t.interruptedRunId||e.generation!==t.generation)return!1;let n=t.resolutions.map(e=>e.interruptId);return e.scope===`item`?n.includes(e.interruptId):wd(e.interruptIds,n)}function Od(e,t,n){let r=gd(e)??n?.responseSchemaHash;return Z({v:1,kind:`generic`,interruptId:e.id,interruptedRunId:t.interruptedRunId,generation:t.generation,...r===void 0?{}:{responseSchemaHash:r},...e.expiresAt===void 0?{}:{expiresAt:e.expiresAt}})}function kd(e,t){let n=Z(e.descriptor),r=e.error===void 0?Object.freeze([]):Object.freeze([Z(e.error)]);return{id:n.id,interruptId:n.id,reason:n.reason,...n.message===void 0?{}:{message:n.message},...n.responseSchema===void 0?{}:{responseSchema:n.responseSchema},...n.expiresAt===void 0?{}:{expiresAt:n.expiresAt},...n.metadata===void 0?{}:{metadata:n.metadata},threadId:t.threadId,interruptedRunId:t.interruptedRunId,generation:t.generation,status:e.status,errors:r,canResolve:e.canResolve}}var Ad=class{options;hydration;items=[];snapshot=Object.freeze([]);rootErrors=Object.freeze([]);submissionRootErrors=Object.freeze([]);state=Object.freeze({interrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:!1});activeTransaction;activeSubmissionOperation;retrySubmission;resuming=!1;warnedSchemaMismatches=/* @__PURE__ */ new Set;tools;interruptDefinitions;constructor(e){this.options=e,this.tools=e.tools;let t=/* @__PURE__ */ new Map;for(let n of e.interrupts??[]){if(t.has(n.id))throw Error(`Duplicate interrupt definition id: ${n.id}`);t.set(n.id,n)}this.interruptDefinitions=t}updateTools(e){this.tools=e}hydrate(e,t=`live`){this.activeSubmissionOperation=void 0,this.hydration={threadId:e.threadId,interruptedRunId:e.interruptedRunId,generation:e.generation,interrupts:Z(e.interrupts)};let n=/* @__PURE__ */ new Map;for(let t of e.interrupts){let e=fd(t);e?.kind===`generic`&&e.definitionId!==void 0&&e.key!==void 0&&e.batchIndex!==void 0&&n.set(e.batchIndex,(n.get(e.batchIndex)??0)+1)}this.items=e.interrupts.map(t=>this.hydrateInterrupt(t,e,n)),this.rootErrors=Object.freeze([]),this.submissionRootErrors=Object.freeze([]),this.retrySubmission=void 0,this.resuming=!1,this.publish(t)}getInterrupts(){return this.snapshot}getState(){return this.state}getDescriptors(){return this.hydration?.interrupts??Object.freeze([])}hasValidatedFirstPartyGenericBatch(){return this.items.some(e=>e.kind===`generic`&&e.definition!==void 0)}reset(e){this.activeSubmissionOperation=void 0,this.hydration=void 0,this.items=[],this.snapshot=Object.freeze([]),e?.preserveRootErrors!==!0&&(this.rootErrors=Object.freeze([]),this.submissionRootErrors=Object.freeze([])),this.retrySubmission=void 0,this.resuming=!1,this.state=Object.freeze({interrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:!1}),this.options.onChange?.(e?.source??`live`)}getInterruptErrors(){return this.rootErrors}getResuming(){return this.resuming}resolve(e){this.assertRootMutable(),typeof e==`boolean`?this.resolveBooleanBulk(e):this.resolveTransaction(e)}cancel(){this.assertRootMutable(),this.invalidateRetry();for(let e of this.items)od(e)&&(e.validationGeneration++,e.resolution=Object.freeze(sd(e,{interruptId:e.descriptor.id,status:`cancelled`})),e.status=`staged`,e.error=void 0);this.publish(),this.maybeSubmit()}retry(){if(this.resuming)throw Error(`Interrupt submission is already active.`);let e=this.retrySubmission;e?this.submitBatch(e):this.addRootError(`transport`,`There is no retryable interrupt submission.`,!1)}resolveClientToolOutput(e,t){return this.resolveClientToolResult(e,{state:`output-available`,output:t})}resolveClientToolError(e,t){return this.resolveClientToolResult(e,{state:`output-error`,errorText:t})}resolveClientToolResult(e,t){let n=this.items.find(t=>t.kind===`client-tool-execution`&&t.binding?.kind===`client-tool-execution`&&t.binding.toolCallId===e)??this.items.find(t=>t.kind===`generic`&&t.canResolve&&t.descriptor.toolCallId===e);return n?t.state===`output-available`?(this.resolveItem(n.descriptor.id,t.output),!0):(this.stageClientToolError(n,t.errorText),!0):!1}stageClientToolError(e,t){this.assertItemMutable(),this.invalidateRetry(),e.canResolve?(e.validationGeneration++,e.resolution=Z(Ko(sd(e,{interruptId:e.descriptor.id,status:`resolved`,payload:{error:t}}),{state:`output-error`})),e.status=`staged`,e.error=void 0,this.publish(),this.maybeSubmit()):(e.status=`error`,e.error=this.itemError(e.descriptor.id,`invalid-response-schema`,`The interrupt response schema is invalid and cannot be resolved.`),this.publish())}warnSchemaMismatch(e,t,n){this.warnedSchemaMismatches.has(e)||(this.warnedSchemaMismatches.add(e),console.warn(`[TanStack AI] Interrupt "${e}" for tool "${t}": the server and client tool schemas differ, so it is handled as a generic interrupt. Use the same tool definition on the server and the client.`,...n===void 0?[]:[n]))}hydrateInterrupt(e,t,n){let r=Z(e),i=fd(r);if(i===void 0)return pd(r)?{descriptor:r,binding:Od(r,t,void 0),kind:`generic`,status:`error`,canResolve:!1,resumable:!1,error:this.itemError(r.id,`stale`,`The interrupt binding is invalid or incomplete.`),validationGeneration:0}:{descriptor:r,binding:void 0,kind:`unbound`,status:`pending`,canResolve:!1,resumable:!1,validationGeneration:0};let a=i.interruptId===r.id&&i.interruptedRunId===t.interruptedRunId&&i.generation===t.generation&&gd(r)===i.responseSchemaHash,o=i.interruptId===r.id&&i.interruptedRunId===t.interruptedRunId&&i.generation===t.generation&&i.responseSchemaHash===(gd(r)??i.responseSchemaHash);if(md(r)&&(!o||i.kind!==`generic`||i.definitionId===void 0||i.key===void 0||i.batchIndex===void 0))return{descriptor:r,binding:Od(r,t,i),kind:`generic`,status:`error`,canResolve:!1,resumable:!1,error:this.itemError(r.id,`stale`,`The interrupt binding does not match this interrupted run.`),validationGeneration:0};if(o&&i.kind===`tool-approval`){let e=this.tools?.find(e=>e.name===i.toolName);if(e?.needsApproval===!0&&r.toolCallId===i.toolCallId)try{let t=Os(e.approvalSchema,e.inputSchema);if(ks(e.inputSchema)===i.inputSchemaHash&&t.approvalSchemaHash===i.approvalSchemaHash&&t.responseSchemaHash===i.responseSchemaHash)return{descriptor:r,binding:Z(i),kind:`tool-approval`,status:`pending`,canResolve:!0,resumable:!0,tool:e,validationGeneration:0};this.warnSchemaMismatch(r.id,i.toolName)}catch(e){this.warnSchemaMismatch(r.id,i.toolName,e)}}if(o&&i.kind===`client-tool-execution`){let e=this.tools?.find(e=>e.name===i.toolName);if(e!==void 0&&r.toolCallId===i.toolCallId){if(ks(e.outputSchema)===i.outputSchemaHash)return{descriptor:r,binding:Z(i),kind:`client-tool-execution`,status:`pending`,canResolve:!0,resumable:!0,tool:e,validationGeneration:0};this.warnSchemaMismatch(r.id,i.toolName)}}if(i.kind===`generic`&&i.definitionId!==void 0&&i.key!==void 0&&i.batchIndex!==void 0&&i.key.length>0&&n.get(i.batchIndex)!==1)return{descriptor:r,binding:Z(i),kind:`generic`,status:`error`,canResolve:!1,resumable:!1,error:this.itemError(r.id,`stale`,`Generic interrupt batch contains a duplicate batchIndex.`),validationGeneration:0};if(a&&i.kind===`generic`&&i.definitionId!==void 0&&i.key!==void 0&&i.batchIndex!==void 0&&i.key.length>0&&n.get(i.batchIndex)===1){let e=this.interruptDefinitions.get(i.definitionId);if(e!==void 0&&_d(e.responseSchema)===i.responseSchemaHash&&(e.payloadSchema===void 0?i.payloadSchemaHash===void 0:i.payloadSchemaHash===_d(e.payloadSchema))){let t=hd(r);return{descriptor:r,binding:Z(i),definition:e,kind:`generic`,status:`pending`,canResolve:!0,resumable:!0,...t===void 0?{}:{payload:Z(t)},validationGeneration:0}}}let s=i.interruptId===r.id&&i.interruptedRunId===t.interruptedRunId&&i.generation===t.generation&&(i.kind!==`generic`||gd(r)===void 0||i.responseSchemaHash===gd(r));return{descriptor:r,binding:Od(r,t,i),kind:`generic`,status:`pending`,canResolve:s,resumable:s,validationGeneration:0}}buildSnapshot(e){let t=this.requireHydration(),n=this.items.filter(e=>e.kind!==`client-tool-execution`&&e.status!==`submitting`).map(n=>{let r=kd(n,t);if(n.kind===`unbound`||n.binding===void 0){let e={...r,kind:`unbound`,canResolve:!1};return Object.freeze(e)}if(n.kind===`tool-approval`&&n.binding.kind===`tool-approval`){let t=Z(n.binding),i={...r,kind:`tool-approval`,binding:t,toolName:n.binding.toolName,toolCallId:n.binding.toolCallId,originalArgs:Z(n.binding.originalArgs),cancel:()=>this.cancelItem(n.descriptor.id,e),clearResolution:()=>this.clearItem(n.descriptor.id,e),resolveInterrupt:(t,r)=>{let i=dd(r)?r:void 0;this.resolveItem(n.descriptor.id,{approved:t,...t&&i?.editedArgs!==void 0?{editedArgs:i.editedArgs}:{},...i?.payload===void 0?{}:{payload:i.payload}},e)}};return Object.freeze(i)}let i=n.binding.kind===`generic`?Z(n.binding):Z({v:1,kind:`generic`,interruptId:n.descriptor.id,interruptedRunId:t.interruptedRunId,generation:t.generation,...typeof n.binding.responseSchemaHash==`string`?{responseSchemaHash:n.binding.responseSchemaHash}:{}});if(n.definition!==void 0&&n.binding.kind===`generic`){let t={...r,kind:`generic`,definitionId:n.definition.id,key:n.binding.key??``,payload:n.payload,binding:i,cancel:()=>this.cancelItem(n.descriptor.id,e),clearResolution:()=>this.clearItem(n.descriptor.id,e),resolveInterrupt:t=>this.resolveItem(n.descriptor.id,t,e)};return Object.freeze(t)}let a={...r,kind:`generic`,binding:i,cancel:()=>this.cancelItem(n.descriptor.id,e),clearResolution:()=>this.clearItem(n.descriptor.id,e),resolveInterrupt:t=>this.resolveItem(n.descriptor.id,t,e)};return Object.freeze(a)});return Object.freeze(n)}publish(e=`live`){this.hydration?(this.snapshot=this.buildSnapshot(),this.state=Object.freeze({interrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:this.resuming}),this.options.onChange?.(e)):(this.snapshot=Object.freeze([]),this.state=Object.freeze({interrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:this.resuming}),this.options.onChange?.(e))}resolveItem(e,t,n){this.assertItemMutable(n);let r=this.findItem(e);if(this.invalidateRetry(),!r.canResolve){r.status=`error`,r.error=this.itemError(e,`invalid-response-schema`,`The interrupt response schema is invalid and cannot be resolved.`),n||this.publish();return}let i=++r.validationGeneration,a=this.validateCandidate(r,t);vd(a)?(r.status=`validating`,r.error=void 0,n||this.publish(),Promise.resolve(a).then(e=>{i===r.validationGeneration&&this.applyValidation(r,e,n)}).catch(e=>{i===r.validationGeneration&&this.applyValidation(r,{code:this.validationCode(r),message:e instanceof Error?e.message:String(e)},n)})):this.applyValidation(r,a,n)}cancelItem(e,t){this.assertItemMutable(t);let n=this.findItem(e);this.invalidateRetry(),n.validationGeneration++,n.resolution=Object.freeze(sd(n,{interruptId:e,status:`cancelled`})),n.status=`staged`,n.error=void 0,t||(this.publish(),this.maybeSubmit())}clearItem(e,t){this.assertItemMutable(t);let n=this.findItem(e);this.invalidateRetry(),n.validationGeneration++,n.resolution=void 0,n.error=void 0,n.status=`pending`,t||this.publish()}maybeSubmit(){let e=this.items.some(e=>e.kind===`generic`),t=this.items.filter(t=>od(t)&&!(e&&t.kind===`client-tool-execution`));if(t.length===0||t.some(e=>e.resolution===void 0||e.status!==`staged`))return;let n=this.requireHydration(),r=ls(t.map(e=>e.resolution).filter(e=>e!==void 0)),i=Object.freeze({threadId:n.threadId,interruptedRunId:n.interruptedRunId,generation:n.generation,resolutions:r.resolutions,canonicalResolutions:r.canonicalResolutions,fingerprint:r.fingerprint});this.submitBatch(i)}applyValidation(e,t,n){if(`valid`in t)e.resolution=Z(sd(e,{interruptId:e.descriptor.id,status:`resolved`,payload:t.payload})),e.status=`staged`,e.error=void 0,n||(this.publish(),this.maybeSubmit());else{e.status=`error`;let r=this.itemError(e.descriptor.id,t.code,t.message,t.path);e.error=r,e.kind===`client-tool-execution`&&(this.rootErrors=Object.freeze([...this.rootErrors.filter(t=>!(t.code===`item-validation-failed`&&t.interruptIds.includes(e.descriptor.id))),Object.freeze({scope:`batch`,code:`item-validation-failed`,message:r.message,source:`client`,retryable:!1,interruptIds:Object.freeze([e.descriptor.id]),threadId:r.threadId,interruptedRunId:r.interruptedRunId,generation:r.generation})])),n||this.publish()}}validateCandidate(e,t){if(e.kind===`generic`){let n=yd(e.definition?.responseSchema??e.descriptor.responseSchema,t,`invalid-payload`);if(e.definition===void 0)return n;let r=e=>`valid`in e?{valid:!0,payload:t}:e;return vd(n)?Promise.resolve(n).then(r):r(n)}if(e.kind===`client-tool-execution`){let n=yd(e.tool?.outputSchema,t,`invalid-tool-output`),r=e=>{if(!(`valid`in e))return e;try{return{valid:!0,payload:Z(e.payload)}}catch(e){return{code:`invalid-tool-output`,message:e instanceof Error?e.message:String(e)}}};return vd(n)?Promise.resolve(n).then(r):r(n)}return this.validateApprovalCandidate(e,t)}validateApprovalCandidate(e,t){if(!dd(t)||typeof t.approved!=`boolean`)return{code:`invalid-payload`,message:`Tool approval resolutions require an approved boolean.`};let n=t.approved,r=t.editedArgs;if(!n&&r!==void 0)return{code:`invalid-edited-args`,message:`Rejected tool approvals cannot edit tool arguments.`};if(n&&r!==void 0){let n=yd(e.tool?.inputSchema,r,`invalid-edited-args`);return vd(n)?Promise.resolve(n).then(n=>`valid`in n?this.validateApprovalPayload(e,t,n.payload):n):`valid`in n?this.validateApprovalPayload(e,t,n.payload):n}return this.validateApprovalPayload(e,t,void 0)}validateApprovalPayload(e,t,n){let r=t.approved===!0,i=this.approvalBranchSchema(e.tool,r),a=t.payload;if(i===void 0&&a!==void 0)return{code:`invalid-payload`,message:`This approval branch does not accept a payload.`};if(i!==void 0&&a===void 0)return{code:`invalid-payload`,message:`This approval branch requires a payload.`};let o=yd(i,a,`invalid-payload`),s=e=>`valid`in e?{valid:!0,payload:{approved:r,...n===void 0?{}:{editedArgs:n},...i===void 0?{}:{payload:e.payload}}}:e;return vd(o)?Promise.resolve(o).then(s):s(o)}approvalBranchSchema(e,t){let n=e?.approvalSchema;return!dd(n)||!(`approve`in n||`reject`in n)?n:t?n.approve:n.reject}validationCode(e){return e.kind===`client-tool-execution`?`invalid-tool-output`:`invalid-payload`}resolveBooleanBulk(e){let t=this.items.filter(e=>od(e)&&e.kind!==`client-tool-execution`);if(!t.every(t=>t.kind===`tool-approval`&&this.approvalBranchSchema(t.tool,e)===void 0)||t.length===0)this.addRootError(`unsupported-bulk-operation`,`Boolean bulk resolution requires payloadless tool approvals.`,!1);else{this.invalidateRetry();for(let n of t)n.validationGeneration++,n.resolution=Z({interruptId:n.descriptor.id,status:`resolved`,payload:{approved:e}}),n.status=`staged`,n.error=void 0;this.publish(),this.maybeSubmit()}}resolveTransaction(e){let t=this.items.map(e=>({status:e.status,...e.resolution===void 0?{}:{resolution:e.resolution},...e.error===void 0?{}:{error:e.error},validationGeneration:e.validationGeneration})),n={active:!0};this.activeTransaction=n;let r=this.buildSnapshot(n).filter(cd),i;try{for(let t of r){let n=e(t);if(n!==void 0){i={code:vd(n)?`async-resolver`:`inactive-transaction`,message:vd(n)?`Interrupt transaction resolvers must be synchronous.`:`Interrupt transaction resolvers must return literal undefined.`};break}}i===void 0&&this.items.some(e=>od(e)&&e.kind!==`client-tool-execution`&&(e.resolution===void 0||e.status!==`staged`))&&(i={code:`incomplete-batch`,message:`Interrupt transaction did not resolve every item.`})}catch(e){i={code:`item-validation-failed`,message:e instanceof Error?e.message:String(e)}}finally{n.active=!1,this.activeTransaction=void 0}i?(this.restoreCheckpoints(t),this.addRootError(i.code,i.message,!1)):(this.publish(),this.maybeSubmit())}restoreCheckpoints(e){this.items.forEach((t,n)=>{let r=e[n];r&&(t.status=r.status,t.resolution=r.resolution,t.error=r.error,t.validationGeneration=r.validationGeneration+1)}),this.publish()}assertItemMutable(e){if(e&&!e.active||this.activeTransaction&&e!==this.activeTransaction)throw Error(`Interrupt transaction is inactive.`);if(this.resuming)throw Error(`Interrupts cannot be mutated while submitting.`)}assertRootMutable(){if(this.activeTransaction)throw Error(`Interrupt transaction is already active.`);if(this.resuming)throw Error(`Interrupts cannot be mutated while submitting.`)}invalidateRetry(){this.retrySubmission=void 0}submitBatch(e){let t={submission:e};this.activeSubmissionOperation=t,this.resuming=!0,this.retrySubmission=void 0;for(let e of this.items)od(e)&&(e.status=`submitting`);this.publish(),this.performSubmission(t)}async performSubmission(e){try{await this.options.submit(e.submission)}catch(t){if(this.activeSubmissionOperation!==e)return;this.handleSubmissionFailure(t,e.submission)}finally{this.activeSubmissionOperation===e&&(this.activeSubmissionOperation=void 0,this.resuming=!1,this.publish())}}handleSubmissionFailure(e,t){let n=Cd(e);if(n.length===0){let n=e instanceof Error?e.message:String(e);this.addRootError(`transport`,n,!0,`transport`),this.retrySubmission=t;for(let e of this.items)od(e)&&(e.status=`error`);return}let r=n.filter(e=>Dd(e,t));r.length!==n.length&&this.addRootError(`protocol`,`Interrupt submission errors did not match the active batch.`,!1);let i=!1,a=!1,o=[];for(let e of r)if((e.code===`stale`||e.code===`expired`||e.code===`conflict`)&&(i=!0),a||=e.retryable,e.scope===`item`){let t=this.items.find(t=>od(t)&&t.descriptor.id===e.interruptId);t&&(t.status=`error`,t.error=Z(e))}else o.push(Z(e));let s=Ed(this.rootErrors,this.submissionRootErrors,o);this.rootErrors=s.rootErrors,this.submissionRootErrors=s.submissionRootErrors;for(let e of this.items)od(e)&&e.status===`submitting`&&(e.status=`error`);this.retrySubmission=a&&!i?t:void 0}addRootError(e,t,n,r=`client`){let i=this.requireHydration();this.rootErrors=Object.freeze([...this.rootErrors,Object.freeze({scope:`batch`,code:e,message:t,source:r,retryable:n,interruptIds:Object.freeze(this.items.filter(od).map(e=>e.descriptor.id)),threadId:i.threadId,interruptedRunId:i.interruptedRunId,generation:i.generation})]),this.publish()}findItem(e){let t=this.items.find(t=>t.descriptor.id===e);if(!t)throw Error(`Unknown interrupt: ${e}`);return t}requireHydration(){if(!this.hydration)throw Error(`InterruptManager is not hydrated.`);return this.hydration}itemError(e,t,n,r){let i=this.requireHydration();return Object.freeze({scope:`item`,interruptId:e,code:t,message:n,...r===void 0?{}:{path:Object.freeze([...r])},source:`client`,retryable:!1,threadId:i.threadId,interruptedRunId:i.interruptedRunId,generation:i.generation})}},jd=/* @__PURE__ */ new WeakMap;function Md(e){let t=Object.entries(e.keys()).filter(e=>!!e[1]).map(e=>e[0]).filter(Tu);if(t.length===1)return t[0];let n=jd.get(e)??[];if(n.length===1)return n[0]}function Nd(e,...t){let n=e?.();if(Tu(n))return n;for(let e of t)if(Tu(e))return e}async function Pd(e,t){if(!t)throw new Cu;return await e.prepare(t),e.headers(t)}var Fd=class{clientId;constructor(e){this.clientId=e}clientCreated(e){this.emitEvent(`client:created`,{initialMessageCount:e})}loadingChanged(e){this.emitEvent(`client:loading:changed`,{isLoading:e})}errorChanged(e){this.emitEvent(`client:error:changed`,{error:e})}textUpdated(e,t,n,r){this.emitEvent(`text:chunk:content`,{streamId:e,messageId:t,content:n,...r})}toolCallStateChanged(e,t,n,r,i,a,o){this.emitEvent(`tools:call:updated`,{streamId:e,messageId:t,toolCallId:n,toolName:r,state:i,arguments:a,...o})}thinkingUpdated(e,t,n,r,i){this.emitEvent(`text:chunk:thinking`,{streamId:e,messageId:t,content:n,delta:r,...i})}structuredOutputChanged(e,t,n,r,i){this.emitEvent(e,{streamId:t,messageId:n,...r,...i})}approvalRequested(e,t,n,r,i,a,o){this.emitEvent(`tools:approval:requested`,{streamId:e,messageId:t,toolCallId:n,toolName:r,input:i,approvalId:a,...o})}messageAppended(e,t,n){let r=e.parts.filter(e=>e.type===`text`).map(e=>e.content).join(` `);this.emitEvent(`text:message:created`,{streamId:t,messageId:e.id,role:e.role,content:r,parts:e.parts,...n})}messageSent(e,t){let n=typeof t==`string`?t:t.filter(e=>e.type===`text`).map(e=>e.content).join(``);this.emitEvent(`text:message:created`,{messageId:e,role:`user`,content:n,...Array.isArray(t)&&{parts:t}}),this.emitEvent(`text:message:user`,{messageId:e,role:`user`,content:n,...Array.isArray(t)&&{parts:t}})}reloaded(e){this.emitEvent(`client:reloaded`,{fromMessageIndex:e})}stopped(){this.emitEvent(`client:stopped`)}messagesCleared(){this.emitEvent(`client:messages:cleared`)}toolResultAdded(e,t,n,r,i){this.emitEvent(`tools:result:added`,{toolCallId:e,toolName:t,output:n,state:r,...i})}toolFixtureApplied(e){this.emitEvent(`devtools:tool-fixture:applied`,{...e})}},Id=class extends Fd{emitEvent(){}},Ld=class{events;constructor(e){this.events=new Id(e.clientId)}emitRegistered(){}emitUpdated(){}emitSnapshot(){}emitToolsRegistered(){}emitRunLifecycle(e,t,n,r){}deactivate(){}supersede(){}dispose(){}mountWithTools(e){}notifyToolsChanged(){}setCurrentStreamId(e){}recordStreamId(e){}getCurrentStreamId(){return null}getLastStreamId(){return null}resolveStreamId(){return``}observeChunk(e){}recordMemoryState(e){}recordCompactionEvent(e,t){}recordCompactionState(e){}recordSkillsState(e){}beginRun(e,t){}getCurrentRunEventContext(){}getCurrentOrLastRunEventContext(){}findToolCallContext(e){return{toolCallId:e}}async applyFixture(e){}},Rd=e=>new Ld(e);function zd(e){return`toolCallId`in e&&typeof e.toolCallId==`string`?e.toolCallId:void 0}function Bd(e){return`messageId`in e&&typeof e.messageId==`string`?e.messageId:void 0}function Vd(e){return`parentMessageId`in e&&typeof e.parentMessageId==`string`?e.parentMessageId:void 0}var Hd=class{adapter;id;applyMessages;applyResume;skipNextPersist=!1;generation=0;queue=Promise.resolve();queuePending=!1;messagesGeneration=0;lastMessages=[];lastResume=null;legacyStored=!1;clearedMessageIds=/* @__PURE__ */ new Set;clearedRunIds=/* @__PURE__ */ new Set;ignoredActiveRunIds=/* @__PURE__ */ new Set;clearedToolCallIds=/* @__PURE__ */ new Set;currentRunlessRunId=null;constructor(e,t,n,r){this.adapter=e,this.id=t,this.applyMessages=n,this.applyResume=r}writeState(){if(this.legacyStored)return;let e=[...this.lastMessages];if(e.length===0&&!this.lastResume){let e=this.generation;this.runOperation(()=>{if(e===this.generation)return this.adapter.removeItem(this.id)});return}let t=this.generation,n={messages:e,...this.lastResume?{resume:this.lastResume}:{}};this.runOperation(()=>{if(t===this.generation)return this.adapter.setItem(this.id,n)})}normalize(e){if(Array.isArray(e))this.legacyStored=!0,console.error(`[TanStack AI] The stored chat for threadId "${this.id}" is in the 0.x format (a bare message array). TanStack AI 1.0 does not read this format, so the chat starts empty and the stored value is not overwritten. Clear the chat or the stored value to start saving again.`);else if(e&&Array.isArray(e.messages))return e}readInitial(){try{let e=this.adapter.getItem(this.id);if(e instanceof Promise)return e.then(e=>this.normalize(e)).catch(()=>void 0);let t=this.normalize(e);return t&&(this.lastMessages=t.messages,this.lastResume=t.resume??null),t}catch{return}}hydrateAsync(e){if(!(e instanceof Promise))return;let t=this.messagesGeneration;return e.then(e=>{e&&this.messagesGeneration===t&&(this.lastResume=e.resume??null,this.lastMessages=e.messages,this.applyMessages(e.messages),e.resume&&this.applyResume&&this.applyResume(e.resume))}).catch(()=>{})}notifyMessagesChanged(e){this.messagesGeneration++,this.lastMessages=[...e],this.skipNextPersist?this.skipNextPersist=!1:this.writeState()}persistResumeSnapshot(e){this.lastResume=e,!this.skipNextPersist&&this.writeState()}remove(){this.legacyStored=!1,this.lastMessages=[],this.lastResume=null;let e=++this.generation;this.runOperation(()=>{if(e===this.generation)return this.adapter.removeItem(this.id)})}runOperation(e){if(this.queuePending){let t=this.queue.then(e).catch(()=>{});this.queue=t,t.finally(()=>{this.queue===t&&(this.queuePending=!1)})}else try{let t=e();if(t instanceof Promise){this.queuePending=!0;let e=t.catch(()=>{});this.queue=e,e.finally(()=>{this.queue===e&&(this.queuePending=!1)})}}catch{}}snapshotClear(e){for(let t of e.messages)this.clearedMessageIds.add(t.id);for(let t of e.activeRunIds)this.clearedRunIds.add(t),this.ignoredActiveRunIds.add(t);e.currentRunId&&(this.clearedRunIds.add(e.currentRunId),this.ignoredActiveRunIds.add(e.currentRunId))}beginClear(){this.skipNextPersist=!0}shouldIgnoreChunk(e){let t=Ou(e);if(t&&this.clearedRunIds.has(t))return e.type===`RUN_STARTED`&&(this.ignoredActiveRunIds.add(t),this.currentRunlessRunId=t),this.markIgnoredChunkIds(e),!0;if(t&&this.ignoredActiveRunIds.has(t)||this.isRunlessChunkFromIgnoredRun(e))return this.markIgnoredChunkIds(e),!0;let n=zd(e);if(n&&this.clearedToolCallIds.has(n))return!0;let r=Vd(e);if(r&&this.clearedMessageIds.has(r))return n&&this.clearedToolCallIds.add(n),!0;let i=Bd(e);return i?!!this.clearedMessageIds.has(i):!1}onRunStarted(e){this.currentRunlessRunId=e}onRunSettled(e){this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId===e&&(this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null)}onSessionRunError(){this.ignoredActiveRunIds.clear(),this.currentRunlessRunId=null}resetIgnored(){this.ignoredActiveRunIds.clear()}takeRunlessRunId(){let e=this.currentRunlessRunId;return e?(this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null,e):null}markIgnoredChunkIds(e){let t=Bd(e);t&&this.clearedMessageIds.add(t);let n=zd(e);n&&this.clearedToolCallIds.add(n)}isRunlessChunkFromIgnoredRun(e){return Ou(e)||!this.currentRunlessRunId||!this.ignoredActiveRunIds.has(this.currentRunlessRunId)&&!this.clearedRunIds.has(this.currentRunlessRunId)?!1:e.type===`TEXT_MESSAGE_START`||e.type===`TEXT_MESSAGE_CONTENT`||e.type===`TEXT_MESSAGE_CHUNK`||e.type===`TOOL_CALL_START`||e.type===`TOOL_CALL_ARGS`||e.type===`TOOL_CALL_END`||e.type===`TOOL_CALL_RESULT`||e.type===`TOOL_CALL_CHUNK`||e.type===`MESSAGES_SNAPSHOT`||e.type===`RUN_ERROR`}};function Ud(e){return`toolCallId`in e&&typeof e.toolCallId==`string`?e.toolCallId:void 0}function Wd(e){return`messageId`in e&&typeof e.messageId==`string`?e.messageId:void 0}function Gd(e){return`parentMessageId`in e&&typeof e.parentMessageId==`string`?e.parentMessageId:void 0}var Kd=class{clearedMessageIds=/* @__PURE__ */ new Set;clearedRunIds=/* @__PURE__ */ new Set;ignoredActiveRunIds=/* @__PURE__ */ new Set;clearedToolCallIds=/* @__PURE__ */ new Set;currentRunlessRunId=null;snapshotClear(e){for(let t of e.messages)this.clearedMessageIds.add(t.id);for(let t of e.activeRunIds)this.clearedRunIds.add(t),this.ignoredActiveRunIds.add(t);e.currentRunId&&(this.clearedRunIds.add(e.currentRunId),this.ignoredActiveRunIds.add(e.currentRunId))}shouldIgnoreChunk(e){let t=Ou(e);if(t&&this.clearedRunIds.has(t))return e.type===`RUN_STARTED`&&(this.ignoredActiveRunIds.add(t),this.currentRunlessRunId=t),this.markIgnoredChunkIds(e),!0;if(t&&this.ignoredActiveRunIds.has(t)||this.isRunlessChunkFromIgnoredRun(e))return this.markIgnoredChunkIds(e),!0;let n=Ud(e);if(n&&this.clearedToolCallIds.has(n))return!0;let r=Gd(e);if(r&&this.clearedMessageIds.has(r))return n&&this.clearedToolCallIds.add(n),!0;let i=Wd(e);return!!(i&&this.clearedMessageIds.has(i))}onRunStarted(e){this.currentRunlessRunId=e}onRunSettled(e){this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId===e&&(this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null)}onSessionRunError(){this.ignoredActiveRunIds.clear(),this.currentRunlessRunId=null}resetActiveRuns(){this.ignoredActiveRunIds.clear(),this.currentRunlessRunId=null}takeRunlessRunId(){let e=this.currentRunlessRunId;return e?(this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null,e):null}markIgnoredChunkIds(e){let t=Wd(e);t&&this.clearedMessageIds.add(t);let n=Ud(e);n&&this.clearedToolCallIds.add(n)}isRunlessChunkFromIgnoredRun(e){return Ou(e)||!this.currentRunlessRunId||!this.ignoredActiveRunIds.has(this.currentRunlessRunId)&&!this.clearedRunIds.has(this.currentRunlessRunId)?!1:e.type===`TEXT_MESSAGE_START`||e.type===`TEXT_MESSAGE_CONTENT`||e.type===`TEXT_MESSAGE_CHUNK`||e.type===`TOOL_CALL_START`||e.type===`TOOL_CALL_ARGS`||e.type===`TOOL_CALL_END`||e.type===`TOOL_CALL_RESULT`||e.type===`TOOL_CALL_CHUNK`||e.type===`MESSAGES_SNAPSHOT`||e.type===`RUN_ERROR`}},qd=8;function Jd(){let{scheduler:e}=globalThis;return e?.yield?e.yield():new Promise(e=>setTimeout(e,0))}function Yd(e){let t=/* @__PURE__ */ new Set;for(let n of e??[]){if(t.has(n.id))throw Error(`Duplicate interrupt definition id: ${n.id}`);t.add(n.id)}}function Xd(e){let{connection:t,fetcher:n}=e;if(t&&n)throw Error("ChatClient: pass either `connection` or `fetcher`, not both.");if(t)return t;if(n)return id(n);throw Error("ChatClient: either `connection` or `fetcher` is required.")}function Zd(e){return`connect`in e}function Qd(e){if(e.type!==`RUN_FINISHED`||e.outcome?.type===`interrupt`)return!1;let t=e;return t.finishReason===void 0?Y(e)?.finishReason===`tool_calls`:t.finishReason===`tool_calls`}function $d(e){let t={whenBusy:`queue`,drain:`fifo`,onOverflow:`reject`};if(!e)return t;if(typeof e==`string`)return{...t,whenBusy:e};if(typeof e==`function`)return{...t,strategy:e};let n=e.maxSize;if(n!==void 0&&(!Number.isInteger(n)||n<0))throw Error(`ChatClient: queue.maxSize must be a non-negative integer`);return{whenBusy:e.whenBusy??`queue`,drain:e.drain??`fifo`,onOverflow:e.onOverflow??`reject`,...n===void 0?{}:{maxSize:n}}}function ef(e){let t=e.at(-1)?.body,n=[];for(let t of e){if(typeof t.content!=`string`)break;n.push(t.content)}if(n.length===e.length)return{content:n.join(`
|
|
145
145
|
`),...t===void 0?{}:{body:t}};let r=[],i;for(let t of e)typeof t.content==`string`?r.push({type:`text`,content:t.content}):(typeof t.content.content==`string`?r.push({type:`text`,content:t.content.content}):r.push(...t.content.content),i=Go(i,t.content.metadata));return{content:{content:r,...i===void 0?{}:{metadata:i}},...t===void 0?{}:{body:t}}}function tf(e){if(typeof e==`object`&&e&&!Array.isArray(e)&&`approved`in e&&typeof e.approved==`boolean`)return e.approved}function nf(e){let t=e;if(typeof t!=`object`||!t||!(`resumeState`in t))return;let n=t.resumeState;if(typeof n==`object`&&n&&`threadId`in n&&typeof n.threadId==`string`&&n.threadId.length!==0&&`runId`in n&&typeof n.runId==`string`&&n.runId.length!==0)return{threadId:n.threadId,runId:n.runId}}var rf=2e3,af=/* @__PURE__ */ new Set([`TEXT_MESSAGE_START`,`TEXT_MESSAGE_CONTENT`,`TEXT_MESSAGE_CHUNK`,`REASONING_MESSAGE_CONTENT`,`REASONING_MESSAGE_CHUNK`,`TOOL_CALL_START`,`TOOL_CALL_CHUNK`,`MESSAGES_SNAPSHOT`,`SUBAGENT_STARTED`]);function of(e){return e.type===`REASONING_ENCRYPTED_VALUE`?e.subtype===`message`&&typeof e.encryptedValue==`string`&&e.encryptedValue.length>0:af.has(e.type)}function sf(e){return e.map(e=>({...e,parts:e.parts.map(e=>Object.isFrozen(e)?e.type===`subagent`?{...e,subagent:{...e.subagent,messages:sf(e.subagent.messages)}}:{...e}:e)}))}function cf(e){let t=[];for(let n of e)for(let e of n.parts)e.type===`subagent`&&(t.push(e),t.push(...cf(e.subagent.messages)));return t}function lf(e){if(`subagentRunId`in e&&typeof e.subagentRunId==`string`)return e.subagentRunId}var uf=64;function df(e){if(Array.isArray(e))return e.map(df);if(e instanceof Date)return new Date(e.getTime());if(typeof e!=`object`||!e)return e;let t={};for(let[n,r]of Object.entries(e))typeof r!=`function`&&(t[n]=df(r));return t}var ff=class{processor;subagentHandles=/* @__PURE__ */ new Map;stoppedSubagentIds=/* @__PURE__ */ new Set;connection;threadId;persistor;clearedStreamTracker=new Kd;snapshotAtom=xo({messages:[],status:`ready`,isLoading:!1,error:void 0,isSubscribed:!1,connectionStatus:`disconnected`,sessionGenerating:!1,queue:[],runId:null,hasOlderMessages:!1,isHydrating:!1,interruptState:{interrupts:Object.freeze([]),interruptErrors:Object.freeze([]),resuming:!1}});get status(){return this.snapshotAtom.get().status}get isLoading(){return this.snapshotAtom.get().isLoading}get error(){return this.snapshotAtom.get().error}get isSubscribed(){return this.snapshotAtom.get().isSubscribed}get connectionStatus(){return this.snapshotAtom.get().connectionStatus}get sessionGenerating(){return this.snapshotAtom.get().sessionGenerating}get hasOlderMessages(){return this.snapshotAtom.get().hasOlderMessages}get isHydrating(){return this.snapshotAtom.get().isHydrating}get currentRunId(){return this.snapshotAtom.get().runId}lastResume=null;runParents=/* @__PURE__ */ new Map;supersededInterruptRunIds=/* @__PURE__ */ new Set;rejoinedRunId=null;interruptManager;activeInterruptSubmission;interruptSubmissionFailure;joinedRunWaiters=/* @__PURE__ */ new Map;pendingResumeParentRunId=null;pendingResumeThreadId=null;pendingResumeItems=null;activeResumeThreadId=null;activeResumeRunId=null;forwardedPropsOption={};byok;byokProvider;context=void 0;pendingMessageBody=void 0;queueConfig;messageQueue=[];sendInFlight=!1;messageQueueDraining=!1;stopMessageQueueDrain=!1;deliverClaim=!1;abortController=null;clientToolsRef;devtoolsBridge;events;currentStreamId=null;currentMessageId=null;postStreamActions=[];pendingToolExecutions=/* @__PURE__ */ new Map;handingOverPendingToolCalls=!1;activeClientTools=null;activeContext=void 0;continuationPending=!1;subscriptionAbortController=null;processingResolve=null;connectionDrainsOnSend=!1;errorReportedGeneration=null;streamGeneration=0;continuationGeneration=0;streamContinuationGeneration=0;continuationSkipped=!1;draining=!1;activeRunIds=/* @__PURE__ */ new Set;disposed=!1;hydrationError;tailing=!1;hydrationInFlight;storeHydrating=!1;rejoinRunId;cachesMessages;historyPageSize;olderMessagesCursor;knownServerMessageIds=/* @__PURE__ */ new Set;loadOlderMessagesInFlight=!1;historyGeneration=0;devtoolsMounted=!1;callbacksRef;constructor(e){if(Yd(e.interrupts),typeof e.threadId!=`string`||e.threadId===``)throw Error(`ChatClient: threadId is required (a non-empty string).`);this.threadId=e.threadId;let t=!0;e.persistence===!0?(t=!1,this.historyPageSize=e.history?.pageSize):(e.persistence&&(this.persistor=new Hd(e.persistence,e.threadId,e=>this.processor.setMessages(e),e=>this.applyPersistedResume(e))),this.historyPageSize=void 0),this.forwardedPropsOption=e.forwardedProps||{},this.byok=e.byok,this.byokProvider=e.byokProvider,this.context=e.context,this.queueConfig=$d(e.queue);let n=Xd(e);if(this.connectionDrainsOnSend=Zd(n),this.connection=td(n),this.clientToolsRef={current:/* @__PURE__ */ new Map},e.tools)for(let t of e.tools)this.clientToolsRef.current.set(t.name,t);this.devtoolsBridge=(e.devtoolsBridgeFactory??Rd)(this.buildDevtoolsBridgeOptions(e.devtools)),this.events=this.devtoolsBridge.events,this.callbacksRef={current:{onResponse:e.onResponse||(()=>{}),onChunk:e.onChunk||(()=>{}),onFinish:e.onFinish||(()=>{}),onError:e.onError||(()=>{}),onMessagesChange:e.onMessagesChange||(()=>{}),onLoadingChange:e.onLoadingChange||(()=>{}),onErrorChange:e.onErrorChange||(()=>{}),onStatusChange:e.onStatusChange||(()=>{}),onSubscriptionChange:e.onSubscriptionChange||(()=>{}),onConnectionStatusChange:e.onConnectionStatusChange||(()=>{}),onSessionGeneratingChange:e.onSessionGeneratingChange||(()=>{}),onHydratingChange:e.onHydratingChange||(()=>{}),onQueueChange:e.onQueueChange||(()=>{}),onResumeStateChange:e.onResumeStateChange||(()=>{}),onRunIdChange:e.onRunIdChange||(()=>{}),onInterruptStateChange:e.onInterruptStateChange||(()=>{}),onCustomEvent:e.onCustomEvent||(()=>{})}},this.interruptManager=new Ad({...e.tools===void 0?{}:{tools:e.tools},...e.interrupts===void 0?{}:{interrupts:e.interrupts},submit:e=>this.submitInterruptBatch(e),onChange:e=>this.notifyResumeStateChange(e)}),e.initialResumeSnapshot&&this.applyResumeSnapshot(e.initialResumeSnapshot);let r=this.persistor?.readInitial(),i=r instanceof Promise?void 0:r,a=i?i.messages:e.initialMessages&&sf(e.initialMessages),o=null;if(i?.resume){let e=i.resume;Array.isArray(e.pendingInterrupts)&&e.pendingInterrupts.length>0?this.applyResumeSnapshot(e):e.resumeState.runId&&(o=e.resumeState.runId)}if(!o&&e.initialResumeSnapshot){let t=e.initialResumeSnapshot;!(Array.isArray(t.pendingInterrupts)&&t.pendingInterrupts.length>0)&&t.resumeState.runId&&(o=t.resumeState.runId)}this.processor=new yu({...e.streamProcessor?.chunkStrategy?{chunkStrategy:e.streamProcessor.chunkStrategy}:{},...a?{initialMessages:a}:{},events:{onMessagesChange:e=>{this.syncSubagentHandles(),this.persistor?.notifyMessagesChanged(e),ko(this.snapshotAtom,{messages:Oo(this.frozenMessages,e)}),this.callbacksRef.current.onMessagesChange(e),this.queueDevtoolsSnapshot()},onStreamStart:()=>{this.setStatus(`streaming`);let e=this.processor.getCurrentAssistantMessageId();if(!e)return;let t=this.processor.getMessages().find(t=>t.id===e);t&&(this.currentMessageId=t.id,this.events.messageAppended(t,this.currentStreamId||void 0))},onStreamEnd:e=>{this.callbacksRef.current.onFinish(e),this.setStatus(`ready`),this.resolveProcessing()},onError:e=>{this.reportStreamError(e)},onTextUpdate:(e,t)=>{this.currentStreamId&&this.events.textUpdated(this.currentStreamId,e,t)},onThinkingUpdate:(e,t)=>{this.currentStreamId&&this.events.thinkingUpdated(this.currentStreamId,e,t,void 0)},onStructuredOutputChange:e=>{let t=this.devtoolsBridge.resolveStreamId(),n=e.phase===`start`?`structured-output:started`:e.phase===`complete`?`structured-output:completed`:e.phase===`error`?`structured-output:errored`:`structured-output:updated`;this.currentMessageId=e.messageId,this.events.structuredOutputChanged(n,t,e.messageId,{status:e.status,raw:e.raw,...e.partial===void 0?{}:{partial:e.partial},...e.data===void 0?{}:{data:e.data},...e.reasoning===void 0?{}:{reasoning:e.reasoning},...e.errorMessage===void 0?{}:{errorMessage:e.errorMessage},...e.delta===void 0?{}:{delta:e.delta}})},onToolCallStateChange:(e,t,n,r)=>{let i=this.processor.getMessages().find(t=>t.id===e)?.parts.find(e=>e.type===`tool-call`&&e.id===t)?.name||`unknown`;this.currentStreamId&&this.events.toolCallStateChanged(this.currentStreamId,e,t,i,n,r)},onToolCall:e=>{let t=(this.activeClientTools??this.clientToolsRef.current).get(e.toolName),n=t?.execute;if(this.handingOverPendingToolCalls&&t?.needsApproval===!0)console.warn(`[ChatClient] Did not run tool call ${e.toolCallId}: ${e.toolName} needs approval, and the server did not ask for it`);else if(n){let r=this.continuationGeneration,i=this.devtoolsBridge.getCurrentRunEventContext(),a=(async()=>{try{let a=this.activeClientTools===null?this.context:this.activeContext,o=await n(e.input,{toolCallId:e.toolCallId,threadId:this.threadId,context:a,emitCustomEvent:()=>{}});await this.addToolResultForClientTool({toolCallId:e.toolCallId,tool:e.toolName,output:o,state:`output-available`},t,r,i)}catch(n){await this.addToolResultForClientTool({toolCallId:e.toolCallId,tool:e.toolName,output:null,state:`output-error`,errorText:n.message},t,r,i)}finally{this.pendingToolExecutions.delete(e.toolCallId)}})();this.pendingToolExecutions.set(e.toolCallId,a)}},onApprovalRequest:e=>{let t=this.devtoolsBridge.resolveStreamId(),n=this.findMessageIdForToolCall(e.toolCallId)??this.currentMessageId??``;this.events.approvalRequested(t,n,e.toolCallId,e.toolName,e.input,e.approvalId)},onCustomEvent:(e,t,n)=>{e===`memory:state`&&this.devtoolsBridge.recordMemoryState(t),(e===`compaction:started`||e===`compaction:state`||e===`compaction:ended`)&&this.devtoolsBridge.recordCompactionEvent(e,t),e===`skills:state`&&this.devtoolsBridge.recordSkillsState(t),this.callbacksRef.current.onCustomEvent(e,t,n)}}}),this.syncSubagentHandles();let s=this.persistor?.hydrateAsync(r);s&&(this.storeHydrating=!0,s.finally(()=>{this.storeHydrating=!1,this.syncIsHydrating()})),this.rejoinRunId=o,this.cachesMessages=t,this.snapshotAtom.set(this.readSnapshot(this.storeHydrating||!t&&!!this.connection.hydrate))}attach(){this.disposed||this.tailing||(this.tailing=!0,this.rejoinRunId&&this.maybeRejoinInFlight(this.rejoinRunId),!this.cachesMessages&&this.connection.hydrate&&this.hydrateFromServer())}detach(){this.tailing&&(this.tailing=!1,this.cancelInFlightStream({setReadyStatus:!0}),this.rejoinedRunId=null)}applyResumeSnapshot(e){let t=nf(e);if(t===void 0){this.interruptManager.reset({source:`hydrate`});return}this.lastResume=t;let n=Array.isArray(e.pendingInterrupts)?e.pendingInterrupts:[];if(n.length===0){this.interruptManager.reset({source:`hydrate`});return}let r=this.interruptGeneration(n);this.interruptManager.hydrate({threadId:t.threadId,interruptedRunId:t.runId,generation:r,interrupts:n},`hydrate`)}applyPersistedResume(e){this.applyResumeSnapshot(e);let t=Array.isArray(e.pendingInterrupts)&&e.pendingInterrupts.length>0,n=e.resumeState?.runId;!t&&n&&this.maybeRejoinInFlight(n)}maybeRejoinInFlight(e){this.connection.joinRun&&!this.disposed&&this.tailing&&this.rejoinedRunId!==e&&(this.isLoading||this.abortController||(this.rejoinedRunId=e,this.resumeInFlightRun(e)))}hydrateFromServer(){let e=this.connection.hydrate;if(!e||this.isLoading||this.abortController||this.disposed){this.syncIsHydrating();return}if(this.hydrationInFlight===this.historyGeneration)return;let t=this.historyPageSize,n=t===void 0?void 0:{limit:t};(async()=>{let t,r=this.historyGeneration;this.hydrationInFlight=r,this.syncIsHydrating();let i=()=>this.hydrationInFlight===r&&r===this.historyGeneration,a;try{t=await e(this.threadId,n)}catch(e){i()&&this.failHydration(e);return}finally{a=i(),this.hydrationInFlight===r&&(this.hydrationInFlight=void 0)}if(a&&!this.disposed&&this.tailing&&!(this.isLoading||this.abortController)){if(this.hydrationError&&this.error===this.hydrationError&&(this.setError(void 0),this.setStatus(`ready`)),this.hydrationError=void 0,this.applyHydrationPage(t.page),t.messages.length>0){let e=zo(t.messages);this.processor.setMessages(e),this.rememberServerMessageIds(e)}t.interrupts&&t.interrupts.pending.length>0&&(!t.activeRun?.runId||t.activeRun.runId===t.interrupts.runId)?this.applyResumeSnapshot({resumeState:{threadId:this.threadId,runId:t.interrupts.runId},pendingInterrupts:t.interrupts.pending}):t.activeRun?.runId&&this.maybeRejoinInFlight(t.activeRun.runId)}})().finally(()=>this.syncIsHydrating())}failHydration(e){if(this.disposed||!this.tailing||this.isLoading||this.abortController)return;let t=e instanceof Error?e:Error(String(e));t instanceof xu&&this.byok?.request(t.provider,`missing`),t instanceof Su&&t.reason===`locked`&&this.byok?.request(t.provider,`locked`),this.hydrationError=t,this.setStatus(`error`),this.setError(t),this.callbacksRef.current.onError(t)}mountDevtools(){this.devtoolsMounted||(this.devtoolsMounted=!0,this.devtoolsBridge.mountWithTools(this.processor.getMessages().length))}drainIgnoredRunlessChunk(e){if(e.type!==`RUN_ERROR`)return;let t=this.clearedStreamTracker.takeRunlessRunId();t&&(this.activeRunIds.delete(t),this.setSessionGenerating(this.activeRunIds.size>0),this.resolveProcessing())}retireIgnoredClearedTerminalChunk(e){if(e.type!==`RUN_FINISHED`&&e.type!==`RUN_ERROR`)return;let t=Ou(e)??this.clearedStreamTracker.takeRunlessRunId();t&&(this.activeRunIds.delete(t),this.setSessionGenerating(this.activeRunIds.size>0),Ou(e)||this.resolveProcessing())}updateRunLifecycle(e,t){if(e.type===`RUN_STARTED`){let t=Ou(e)??e.runId,n=`parentRunId`in e&&typeof e.parentRunId==`string`?e.parentRunId:void 0;n&&(this.runParents.set(t,n),this.supersededInterruptRunIds.has(t)&&this.markLineageAnswered(n)),this.activeResumeThreadId=`threadId`in e&&typeof e.threadId==`string`?e.threadId:this.activeResumeThreadId,this.activeResumeRunId=t;let r=this.supersededInterruptRunIds.has(t)&&!this.isLoading;r||(this.activeRunIds.add(t),this.clearedStreamTracker.onRunStarted(t),this.setSessionGenerating(!0)),this.persistor&&this.connection.joinRun&&!this.lastResume&&!r&&this.persistResumeSnapshot({threadId:this.activeResumeThreadId??this.threadId,runId:t}),this.lastResume&&this.supersededInterruptRunIds.has(this.lastResume.runId)&&(this.lastResume=null,this.persistor?.persistResumeSnapshot(null),this.interruptManager.reset());return}if(e.type!==`RUN_FINISHED`&&e.type!==`RUN_ERROR`)return;let n=Ou(e);n?(this.activeRunIds.delete(n),this.clearedStreamTracker.onRunSettled(n)):e.type===`RUN_ERROR`&&(this.activeRunIds.clear(),this.clearedStreamTracker.onSessionRunError()),this.setSessionGenerating(this.activeRunIds.size>0);let r=e.type===`RUN_FINISHED`&&Qd(e);t?.resolveProcessing!==!1&&!r&&this.resolveProcessing()}observeInterruptState(e){if(e.type!==`RUN_FINISHED`&&e.type!==`RUN_ERROR`||this.activeInterruptSubmission&&e.type===`RUN_ERROR`)return;let t=Ou(e),n=`threadId`in e&&typeof e.threadId==`string`?e.threadId:this.activeResumeThreadId;if(t&&!Qd(e)&&(e.type===`RUN_ERROR`||e.type===`RUN_FINISHED`&&e.outcome?.type!==`interrupt`)&&this.markLineageAnswered(t),e.type===`RUN_FINISHED`&&e.outcome?.type===`interrupt`){let r=this.currentRunId??t??this.activeResumeRunId??``;if(r&&this.supersededInterruptRunIds.has(r))return;this.lastResume={threadId:n??this.threadId,runId:r},this.interruptManager.hydrate({threadId:this.lastResume.threadId,interruptedRunId:r,generation:this.interruptGeneration(e.outcome.interrupts),interrupts:e.outcome.interrupts},`live`);return}let r=e.type===`RUN_ERROR`&&!t,i=!!(t&&this.lastResume?.runId===t),a=!!(t&&this.currentRunId===t||this.currentRunId&&this.lastResume?.runId===this.currentRunId),o=!(!this.isLoading||!t||t!==this.activeResumeRunId&&t!==this.currentRunId),s=this.isLoading&&e.type===`RUN_FINISHED`&&!t,c=!!(this.activeInterruptSubmission&&this.isLoading&&e.type===`RUN_FINISHED`&&e.outcome?.type!==`interrupt`),l=!!(this.lastResume&&this.supersededInterruptRunIds.has(this.lastResume.runId));r||i||a||o||s||c||l?(this.lastResume=null,this.persistor?.persistResumeSnapshot(null),this.interruptManager.reset()):this.notifyResumeStateChange(`live`)}markLineageAnswered(e){let t=e,n=0;for(;t!==void 0&&n<uf;){if(this.supersededInterruptRunIds.has(t))return;this.supersededInterruptRunIds.add(t),t=this.runParents.get(t),n++}}getResumeState(){return this.lastResume?{...this.lastResume}:null}getCurrentRunId(){return this.currentRunId}setCurrentRunId(e){this.currentRunId!==e&&(ko(this.snapshotAtom,{runId:e}),this.callbacksRef.current.onRunIdChange(e))}getInterruptState(){return this.interruptManager.getState()}getInterrupts(){return this.interruptManager.getInterrupts()}resolveInterrupts(e){this.interruptManager.resolve(e)}cancelInterrupts(){this.interruptManager.cancel()}retryInterrupts(){this.interruptManager.retry()}resumeInterruptsUnsafe(e,t){let n=t??this.lastResume;return n?this.resumeInterruptsUnsafeForGeneration(e,n,this.continuationGeneration):Promise.resolve(!1)}resumeInterruptsUnsafeForGeneration(e,t,n){return n===this.continuationGeneration?this.isLoading?new Promise((r,i)=>{this.queuePostStreamAction(async()=>{try{r(await this.resumeInterruptsUnsafeForGeneration(e,t,n))}catch(e){i(e)}})}):(this.pendingResumeThreadId=t.threadId,this.pendingResumeParentRunId=t.runId,this.pendingResumeItems=[...e],this.streamResponse()):Promise.resolve(!1)}async submitInterruptBatch(e){let t=this.continuationGeneration;this.activeInterruptSubmission=e,this.interruptSubmissionFailure=void 0;for(let t of e.resolutions){let e=tf(t.payload);if(e===void 0)continue;let n=t.interruptId;this.processor.addToolApprovalResponse(n,e)}let n=await this.resumeInterruptsUnsafeForGeneration([...e.resolutions],{threadId:e.threadId,runId:e.interruptedRunId},t).finally(()=>{this.activeInterruptSubmission===e&&(this.activeInterruptSubmission=void 0)});if(t!==this.continuationGeneration)return;let r=this.takeInterruptSubmissionFailure();if(r!==void 0)throw{errors:r.errors};if(!n)throw Error(`Interrupt continuation could not be started.`);this.lastResume?.runId===e.interruptedRunId&&(this.lastResume=null,this.interruptManager.reset())}takeInterruptSubmissionFailure(){let e=this.interruptSubmissionFailure;return this.interruptSubmissionFailure=void 0,e}interruptGeneration(e){let t;for(let n of e){let e=n.metadata?.[`tanstack:interruptBinding`];if(typeof e!=`object`||!e||!(`generation`in e)||typeof e.generation!=`number`||!Number.isInteger(e.generation)||e.generation<0||t!==void 0&&t!==e.generation)return 0;t=e.generation}return t??0}generateUniqueId(e){return`${e}-${Date.now()}-${Math.random().toString(36).substring(7)}`}frozenMessages=/* @__PURE__ */ new WeakMap;freezeSnapshotQueue(e){return Object.freeze(e.map(e=>{if(typeof e.content!=`object`)return Object.freeze({...e});let t=Array.isArray(e.content.content)?Object.freeze(e.content.content.map(e=>Eo(e))):e.content.content;return Object.freeze({...e,content:Object.freeze({...e.content,content:t})})}))}readSnapshot(e){return Object.freeze({...this.snapshotAtom.get(),messages:Oo(this.frozenMessages,this.processor.getMessages()),queue:this.freezeSnapshotQueue(this.getQueue()),isHydrating:e,interruptState:this.interruptManager.getState()})}subscribeSnapshot=e=>jo(this.snapshotAtom,e);getSnapshot=()=>this.snapshotAtom.get();setIsLoading(e){ko(this.snapshotAtom,{isLoading:e}),this.callbacksRef.current.onLoadingChange(e),this.events.loadingChanged(e),e&&this.supersedeHydration()}supersedeHydration(){this.hydrationInFlight=void 0,this.storeHydrating=!1,this.syncIsHydrating()}setStatus(e){ko(this.snapshotAtom,{status:e}),this.callbacksRef.current.onStatusChange(e),this.devtoolsBridge.emitSnapshot()}setIsSubscribed(e){ko(this.snapshotAtom,{isSubscribed:e}),this.callbacksRef.current.onSubscriptionChange(e),this.devtoolsBridge.emitSnapshot()}setConnectionStatus(e){ko(this.snapshotAtom,{connectionStatus:e}),this.callbacksRef.current.onConnectionStatusChange(e),this.devtoolsBridge.emitSnapshot()}syncIsHydrating(){let e=this.hydrationInFlight!==void 0||this.storeHydrating;this.isHydrating!==e&&(ko(this.snapshotAtom,{isHydrating:e}),this.callbacksRef.current.onHydratingChange(e))}setSessionGenerating(e){this.sessionGenerating!==e&&(ko(this.snapshotAtom,{sessionGenerating:e}),this.callbacksRef.current.onSessionGeneratingChange(e),this.devtoolsBridge.emitSnapshot())}notifyResumeStateChange(e){let t=this.getResumeState(),n=this.interruptManager.getState();ko(this.snapshotAtom,{interruptState:n}),this.persistResumeSnapshot(t),this.callbacksRef.current.onResumeStateChange(t,n.interrupts),this.callbacksRef.current.onInterruptStateChange(n,{source:e})}persistResumeSnapshot(e){if(!this.persistor)return;if(!e){this.persistor.persistResumeSnapshot(null);return}let t=this.interruptManager.getDescriptors();this.persistor.persistResumeSnapshot({resumeState:e,...t.length>0?{pendingInterrupts:[...t]}:{}})}resetSessionGenerating(e){this.activeRunIds.clear(),e?.preserveClearedStreamTracking||this.clearedStreamTracker.resetActiveRuns(),this.setSessionGenerating(!1)}setError(e){ko(this.snapshotAtom,{error:e}),this.callbacksRef.current.onErrorChange(e),this.events.errorChanged(e?.message||null)}buildDevtoolsBridgeOptions(e){return{hookId:this.threadId,clientId:this.threadId,threadId:this.threadId,metadata:{hookName:e?.hookName??`useChat`,outputKind:e?.outputKind??`chat`,...e?.framework?{framework:e.framework}:{},...e?.name?{name:e.name}:{}},getSnapshot:()=>this.getDevtoolsSnapshot(),getTools:()=>this.clientToolsRef.current.values(),getMessages:()=>this.processor.getMessages(),setMessages:e=>{this.processor.setMessages(e)},addToolResult:(e,t,n)=>{this.processor.addToolResult(e,t,n)},generateId:e=>this.generateUniqueId(e)}}getDevtoolsSnapshot(){return{messages:df(this.processor.getMessages()),status:this.status,isLoading:this.isLoading,isSubscribed:this.isSubscribed,connectionStatus:this.connectionStatus,sessionGenerating:this.sessionGenerating,activeRunIds:Array.from(this.activeRunIds),queue:this.getQueue(),...this.error?{error:this.error.message}:{}}}findMessageIdForToolCall(e){let t=this.processor.getMessages();for(let n of t)if(n.parts.find(t=>t.type===`tool-call`&&t.id===e))return n.id}abortSubscriptionLoop(){this.subscriptionAbortController?.abort(),this.subscriptionAbortController=null}resolveProcessing(){this.processingResolve?.(),this.processingResolve=null}cancelInFlightStream(e){this.abortController?.abort(),this.abortController=null,e?.abortSubscription&&this.abortSubscriptionLoop(),this.resolveProcessing(),this.setIsLoading(!1),this.deliverClaim=!1,e?.setReadyStatus&&this.setStatus(`ready`)}reportStreamError(e){let t=this.errorReportedGeneration===this.streamGeneration;this.setError(e),(this.isLoading||this.status===`submitted`||this.status===`streaming`)&&this.setStatus(`error`),t||(this.errorReportedGeneration=this.streamGeneration,this.callbacksRef.current.onError(e))}startSubscription(){this.subscriptionAbortController=new AbortController;let e=this.subscriptionAbortController.signal;this.consumeSubscription(e).catch(e=>{e instanceof Error&&e.name!==`AbortError`&&(this.setConnectionStatus(`error`),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.reportStreamError(e)),this.resolveProcessing()}).finally(()=>{this.subscriptionAbortController?.signal===e&&(this.subscriptionAbortController=null,!e.aborted&&this.isSubscribed&&(this.setIsSubscribed(!1),this.connectionStatus!==`error`&&this.setConnectionStatus(`disconnected`)))})}async consumeSubscription(e){let t=this.connection.subscribe(e),n=0;for await(let r of t){if(e.aborted)break;let t=performance.now();this.processIncomingChunk(r),n+=performance.now()-t,!(n<qd)&&(n=0,!(typeof document<`u`&&document.hidden)&&await Jd())}}resumeInFlightRun(e){let t=this.connection.joinRun;if(!t)return;let n=new AbortController;this.abortController=n,this.setCurrentRunId(e),this.lastResume={threadId:this.threadId,runId:e},this.streamContinuationGeneration=this.continuationGeneration,this.setIsLoading(!0),this.setStatus(`streaming`),(async()=>{let r=!1,i=!1,a=!1,o=setTimeout(()=>{i||n.abort()},rf);try{for await(let a of t(e,n.signal)){if(n.signal.aborted)break;i||(i=!0,clearTimeout(o)),!r&&of(a)&&(r=!0,this.dropTrailingInFlightAssistant()),this.processIncomingChunk(a)}this.pendingToolExecutions.size>0&&await Promise.all(this.pendingToolExecutions.values())}catch(e){let t=e instanceof Error&&(e.name===`AbortError`||e.name===`TimeoutError`);!i&&!t&&(a=!0),i&&!t&&this.reportStreamError(e instanceof Error?e:Error(String(e)))}finally{clearTimeout(o),!i&&a&&this.tailing&&!this.disposed&&(this.lastResume=null,this.persistor?.persistResumeSnapshot(null)),this.abortController===n&&(this.abortController=null,this.setIsLoading(!1),this.status===`streaming`&&this.setStatus(`ready`),await this.drainPostStreamActions())}})()}dropTrailingInFlightAssistant(){let e=this.processor.getMessages(),t=e[e.length-1];t&&t.role===`assistant`&&this.processor.setMessages(e.slice(0,-1))}processIncomingChunk(e){if(e=ul(e),e.type===`RUN_ERROR`&&this.isActiveInterruptSubmissionFailure(e)){let t=Y(e)?.interruptErrors;this.interruptSubmissionFailure={errors:Array.isArray(t)?t:[]}}if(this.connectionStatus===`connecting`&&this.setConnectionStatus(`connected`),this.clearedStreamTracker.shouldIgnoreChunk(e)){(e.type===`RUN_FINISHED`||e.type===`RUN_ERROR`)&&(Ou(e)?this.updateRunLifecycle(e,{resolveProcessing:!1}):this.drainIgnoredRunlessChunk(e),this.retireIgnoredClearedTerminalChunk(e),this.resolveJoinedRun(e));return}this.callbacksRef.current.onChunk(e),this.devtoolsBridge.observeChunk(e);let t=lf(e);if(t&&e.type===X.SUBAGENT_STARTED&&this.stoppedSubagentIds.delete(t),t&&this.stoppedSubagentIds.has(t))this.updateRunLifecycle(e),this.resolveJoinedRun(e);else{this.handingOverPendingToolCalls=e.type===`RUN_FINISHED`&&e.outcome?.type!==`interrupt`;try{this.processor.processChunk(e)}finally{this.handingOverPendingToolCalls=!1}this.syncSubagentHandles(),this.updateRunLifecycle(e),this.observeInterruptState(e),this.resolveJoinedRun(e)}}isActiveInterruptSubmissionFailure(e){let t=this.activeInterruptSubmission,n=Y(e)?.interruptErrors;if(!t||!Array.isArray(n)||n.length===0)return!1;let r=Ou(e);return r!==void 0&&r!==this.currentRunId||typeof e.threadId==`string`&&e.threadId!==t.threadId?!1:n.every(e=>typeof e!=`object`||!e||typeof e.threadId!=`string`||typeof e.interruptedRunId!=`string`||typeof e.generation!=`number`?!1:e.threadId===t.threadId&&e.interruptedRunId===t.interruptedRunId&&e.generation===t.generation)}resolveJoinedRun(e){if(e.type!==`RUN_FINISHED`&&e.type!==`RUN_ERROR`)return;let t=Ou(e);if(t===void 0)return;let n=this.joinedRunWaiters.get(t);n!==void 0&&(this.joinedRunWaiters.delete(t),n())}ensureSubscription(){this.isSubscribed?(!this.subscriptionAbortController||this.subscriptionAbortController.signal.aborted)&&this.subscribe({restart:!0}):this.subscribe()}waitForProcessing(){return this.resolveProcessing(),new Promise(e=>{this.processingResolve=e})}async sendMessage(e,t,n){if(this.mountDevtools(),typeof e==`string`&&!e.trim())return;if(this.hasPendingInterrupts())throw Error(`ChatClient: cannot send normal input while pending interrupts exist. Resolve the interrupts first.`);let r={...t,...n?.body};if(this.isSendBusy()){let{action:t,id:i}=this.decideWhenBusy(e,n);if(t===`drop`)return;if(t===`queue`){this.enqueueMessage(e,r,i);return}this.stopMessageQueueDrain=!0,this.sendInFlight=!0,this.cancelInFlightStream({setReadyStatus:!0}),this.resetSessionGenerating()}else this.sendInFlight=!0;try{await this.deliverMessage(e,r)}finally{this.sendInFlight=!1}}hasPendingInterrupts(){return this.interruptManager.getDescriptors().length>0}isSendBusy(){return this.isLoading||this.sendInFlight||this.messageQueueDraining}resolveBusyReason(){return this.isLoading?`streaming`:this.messageQueueDraining?`draining`:`sendInFlight`}async deliverMessage(e,t){if(this.isLoading||this.deliverClaim)return!1;this.deliverClaim=!0;try{let n=this.normalizeMessageInput(e);this.pendingMessageBody=t;let r=this.processor.addUserMessage(n.content,n.id,n.metadata);return this.events.messageSent(r.id,n.content),await this.streamResponse()}finally{this.deliverClaim=!1}}decideWhenBusy(e,t){let n=this.generateUniqueId(`queued`);if(t?.whenBusy)return{action:t.whenBusy,id:n};let{strategy:r,whenBusy:i}=this.queueConfig;if(r){let{action:t}=r({pending:{id:n,content:e,createdAt:Date.now()},busyReason:this.resolveBusyReason(),queued:this.getQueue()});return{action:t,id:n}}return{action:i,id:n}}enqueueMessage(e,t,n){let{maxSize:r,onOverflow:i}=this.queueConfig;if(r!==void 0&&this.messageQueue.length>=r){if(i===`reject`||r===0)return;this.messageQueue.shift()}this.messageQueue.push({id:n??this.generateUniqueId(`queued`),content:e,createdAt:Date.now(),...t===void 0?{}:{body:t}}),this.emitQueueChange()}normalizeMessageInput(e){return typeof e==`string`?{content:e.trim()}:{content:e.content,id:e.id,...e.metadata===void 0?{}:{metadata:e.metadata}}}async append(e){if(this.mountDevtools(),this.hasPendingInterrupts())throw Error(`ChatClient: cannot append normal input while pending interrupts exist. Resolve the interrupts first.`);let t=Hc(e,Uc);if(t.role===`system`)return;if(t.role===`activity`){let e=t;this.events.messageAppended(e);let n=this.processor.getMessages();this.processor.setMessages([...n,e]),this.devtoolsBridge.emitSnapshot();return}let n=t;this.events.messageAppended(n);let r=this.processor.getMessages();this.processor.setMessages([...r,n]),this.devtoolsBridge.emitSnapshot(),this.isLoading?this.queuePostStreamAction(async()=>{await this.streamResponse()}):await this.streamResponse()}async streamResponse(){if(this.isLoading)return!1;let e=++this.streamGeneration;this.streamContinuationGeneration=this.continuationGeneration;let t=this.pendingResumeThreadId,n=this.pendingResumeParentRunId,r=this.pendingResumeItems;this.pendingResumeThreadId=null,this.pendingResumeParentRunId=null,this.pendingResumeItems=null;let i=`run-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.setCurrentRunId(i),this.activeResumeThreadId=t??this.threadId,this.activeResumeRunId=i,this.setIsLoading(!0),this.deliverClaim=!1,this.setStatus(`submitted`),this.setError(void 0),this.errorReportedGeneration=null,this.abortController=new AbortController;let a=this.abortController.signal;this.pendingToolExecutions.clear();let o=!1,s=null,c=!1;try{let l=this.messagesForSend(this.processor.getMessages()),u=new Map(this.clientToolsRef.current),d=this.context;if(await this.callbacksRef.current.onResponse(),a.aborted)return!1;let f={...this.forwardedPropsOption,...this.pendingMessageBody};this.pendingMessageBody=void 0,this.currentStreamId=this.generateUniqueId(`stream`),this.devtoolsBridge.setCurrentStreamId(this.currentStreamId),this.currentMessageId=null,this.activeClientTools=u,this.activeContext=d,this.processor.prepareAssistantMessage(),this.ensureSubscription();let p=this.waitForProcessing(),m;if(this.byok){let e=Nd(this.byokProvider,f.provider,Md(this.byok));m=await Pd(this.byok,e)}let h={threadId:t??this.threadId,runId:i,...n===null?{}:{parentRunId:n},clientTools:Array.from(u.values()).map(e=>({name:e.name,description:e.description,parameters:e.inputSchema?vs(e.inputSchema):{type:`object`}})),forwardedProps:{...f},...r?{resume:r}:{},...m?{headers:m}:{}};if(this.devtoolsBridge.beginRun(h.runId,h.threadId),s=h.runId,this.devtoolsBridge.emitRunLifecycle(`run:created`,h.runId,`created`),this.devtoolsBridge.emitRunLifecycle(`run:started`,h.runId,`started`),this.devtoolsBridge.emitSnapshot(),await this.connection.send(l,f,a,h),e!==this.streamGeneration||a.aborted||(this.connectionDrainsOnSend&&this.resolveProcessing(),await p,e!==this.streamGeneration))return!1;if(this.status===`error`)return s&&(this.devtoolsBridge.emitRunLifecycle(`run:errored`,s,`errored`,this.error?{error:this.error.message}:{}),c=!0),!1;this.pendingToolExecutions.size>0&&await Promise.all(this.pendingToolExecutions.values()),this.processor.finalizeStream(),o=!0}catch(t){let n=t instanceof Error?t:Error(String(t));if(n.name===`AbortError`)return s&&(this.devtoolsBridge.emitRunLifecycle(`run:cancelled`,s,`cancelled`),c=!0),!1;if(n instanceof xu&&this.byok?.request(n.provider,`missing`),n instanceof Su&&n.reason===`locked`&&this.byok?.request(n.provider,`locked`),e===this.streamGeneration&&(this.reportStreamError(n),s&&(this.devtoolsBridge.emitRunLifecycle(`run:errored`,s,`errored`,{error:n.message}),c=!0)),e===this.streamGeneration&&(n instanceof xu||n instanceof Su||n instanceof Cu))throw n}finally{e===this.streamGeneration&&(this.currentStreamId=null,this.devtoolsBridge.setCurrentStreamId(null),this.currentMessageId=null,this.setCurrentRunId(null),this.activeClientTools=null,this.activeContext=void 0,this.abortController=null,this.setIsLoading(!1),this.pendingMessageBody=void 0,s&&!c&&(o?this.devtoolsBridge.emitRunLifecycle(`run:completed`,s,`completed`):a.aborted&&this.devtoolsBridge.emitRunLifecycle(`run:cancelled`,s,`cancelled`)),await this.drainPostStreamActions(),o?(this.rememberProcessorMessageIds(),this.status!==`ready`&&this.setStatus(`ready`),this.messageQueueDraining||await this.drainQueue()):this.flushQueue())}return o}subscribe(e){let t=e?.restart===!0;(!this.isSubscribed||t)&&(this.isSubscribed&&t&&this.abortSubscriptionLoop(),this.setIsSubscribed(!0),this.setConnectionStatus(`connecting`),this.startSubscription())}unsubscribe(){this.cancelInFlightStream({setReadyStatus:!0,abortSubscription:!0}),this.discardPendingSends(),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.setConnectionStatus(`disconnected`)}async reload(){let e=this.processor.getMessages();if(e.length===0)return;let t=e.findLastIndex(e=>e.role===`user`);t!==-1&&(this.isLoading&&this.cancelInFlightStream(),this.discardPendingSends(),this.events.reloaded(t),this.processor.removeMessagesAfter(t),this.devtoolsBridge.emitSnapshot(),await this.streamResponse())}stop(){this.continuationGeneration++;let e=this.abortController!==null;this.cancelInFlightStream({setReadyStatus:!0}),this.discardPendingSends(),this.lastResume=null,this.activeInterruptSubmission=void 0,this.interruptManager.reset(),e&&this.resetSessionGenerating(),this.events.stopped()}clear(){let e=this.abortController!==null;this.clearedStreamTracker.snapshotClear({messages:this.processor.getMessages(),activeRunIds:this.activeRunIds,currentRunId:this.currentRunId}),this.isLoading||e?(this.cancelInFlightStream({setReadyStatus:!0}),this.resetSessionGenerating({preserveClearedStreamTracking:!0})):this.activeRunIds.size>0&&this.resetSessionGenerating({preserveClearedStreamTracking:!0}),this.persistor?.beginClear(),this.processor.clearMessages(),this.resetHistoryPaging(),this.supersedeHydration(),this.discardPendingSends(),this.persistor?.remove(),this.stoppedSubagentIds.clear(),this.lastResume=null,this.interruptManager.reset(),this.pendingResumeThreadId=null,this.pendingResumeParentRunId=null,this.pendingResumeItems=null,this.setError(void 0),this.events.messagesCleared()}async addToolResult(e){let t=this.clientToolsRef.current.get(e.tool);await this.addToolResultForClientTool(e,t,this.streamContinuationGeneration)}async addToolResultForClientTool(e,t,n,r){if(e.state!==`output-error`)try{let n=t?.outputSchema&&ps(t.outputSchema)?await this.validateClientToolOutput(t,e.output):e.output;this.interruptManager.getDescriptors().some(t=>t.toolCallId===e.toolCallId)&&(n=Z(n)),e={...e,output:n}}catch(t){e={...e,output:null,state:`output-error`,errorText:t.message}}this.events.toolResultAdded(e.toolCallId,e.tool,e.output,e.state||`output-available`,r),n===this.continuationGeneration&&(this.processor.addToolResult(e.toolCallId,e.output,e.state===`output-error`?e.errorText||`Tool execution failed`:void 0),this.devtoolsBridge.emitSnapshot(),!(e.state===`output-error`?this.interruptManager.resolveClientToolError(e.toolCallId,e.errorText||`Tool execution failed`):this.interruptManager.resolveClientToolOutput(e.toolCallId,e.output))&&(this.isLoading?this.queuePostStreamAction(()=>n===this.continuationGeneration?this.checkForContinuation():Promise.resolve()):await this.checkForContinuation()))}async validateClientToolOutput(e,t){let n=await ys(e.outputSchema,t);if(!n.success)throw Error(n.issues.map(e=>e.message).join(`, `));return n.data}queuePostStreamAction(e){let t=this.continuationGeneration;this.postStreamActions.push(async()=>{t===this.continuationGeneration&&await e()})}async drainPostStreamActions(){if(!this.draining){this.draining=!0;try{let e;for(;(e=this.postStreamActions.shift())!==void 0;)await e()}finally{this.draining=!1}}}async checkForContinuation(){if(this.streamContinuationGeneration===this.continuationGeneration&&!this.hasPendingInterrupts()){if(this.continuationPending||this.isLoading)this.continuationSkipped=!0;else if(this.shouldAutoSend()){this.continuationPending=!0,this.continuationSkipped=!1;let e=!1;try{e=await this.streamResponse()}finally{this.continuationPending=!1}this.continuationSkipped&&e&&(this.continuationSkipped=!1,await this.checkForContinuation())}}}shouldAutoSend(){if(this.lastResume||this.activeInterruptSubmission&&this.hasPendingInterrupts()||this.interruptManager.getInterrupts().length>0)return!1;let e=this.processor.getMessages().findLast(e=>e.role===`assistant`);return!e||!e.parts.some(e=>e.type===`tool-call`)?!1:this.processor.areAllToolsComplete()}getMessages(){return this.processor.getMessages()}getSubagents(){return[...this.subagentHandles.values()]}devtoolsSnapshotQueued=!1;queueDevtoolsSnapshot(){this.devtoolsSnapshotQueued||(this.devtoolsSnapshotQueued=!0,queueMicrotask(()=>{this.devtoolsSnapshotQueued=!1,this.devtoolsBridge.emitSnapshot()}))}syncSubagentHandles(){let e=e=>{let{input:t,...n}=e,r=Gs(n.metadata);return r===void 0?n:{...n,input:r}},t=cf(this.processor.getMessages()),n=new Set(t.map(e=>e.subagent.id));for(let e of this.subagentHandles.keys())n.has(e)||this.subagentHandles.delete(e);for(let n of t){let t=n.subagent.id,r=this.subagentHandles.get(t);if(r){if(n.subagent===r)continue;let{stop:t}=r;for(let e of Object.keys(r))Reflect.deleteProperty(r,e);Object.assign(r,e(n.subagent),{stop:t}),n.subagent=r;continue}let i={...e(n.subagent),stop:()=>{this.stopSubagent(t)}};this.subagentHandles.set(t,i),n.subagent=i}}stopSubagent(e){let t=this.subagentHandles.get(e);t&&t.status===`running`&&(this.stoppedSubagentIds.add(e),this.processor.processChunk({type:X.SUBAGENT_ERROR,subagentRunId:e,message:`Stopped`,timestamp:Date.now()}),this.syncSubagentHandles(),t.status=`error`,t.error={message:`Stopped`},this.abortController?.abort())}getHasOlderMessages(){return this.hasOlderMessages}async loadOlderMessages(){let e=this.connection.hydrate;if(e===void 0||this.disposed||!this.hasOlderMessages)return;let t=this.olderMessagesCursor;if(t===void 0||this.loadOlderMessagesInFlight)return;let n={before:t};this.historyPageSize!==void 0&&(n.limit=this.historyPageSize),this.loadOlderMessagesInFlight=!0;let r=this.historyGeneration;try{let t=await e(this.threadId,n);if(this.disposed||r!==this.historyGeneration)return;let i=zo(t.messages);if(i.length===0)throw Error(`Older page was empty`);this.applyHydrationPage(t.page),this.processor.prependMessages(i),this.rememberServerMessageIds(i)}finally{this.loadOlderMessagesInFlight=!1}}setHasOlderMessages(e){ko(this.snapshotAtom,{hasOlderMessages:e})}resetHistoryPaging(){this.setHasOlderMessages(!1),this.olderMessagesCursor=void 0,this.knownServerMessageIds.clear(),this.historyGeneration++}applyHydrationPage(e){e?.truncated===!0?(this.setHasOlderMessages(!0),this.olderMessagesCursor=e.cursor):(this.setHasOlderMessages(!1),this.olderMessagesCursor=void 0)}rememberServerMessageIds(e){let t=e.map(e=>e.id);for(let e of t)this.knownServerMessageIds.add(e)}rememberProcessorMessageIds(){this.historyPageSize!==void 0&&this.rememberServerMessageIds(this.processor.getMessages())}messagesForSend(e){let t=e.filter(e=>e.role!==`activity`);if(this.historyPageSize===void 0)return t;let n=[];for(let e of t)this.knownServerMessageIds.has(e.id)||n.push(e);if(n.length>0)return n;let r=t.findLastIndex(e=>e.role===`user`);return r===-1?[]:t.slice(r)}shouldAbortMessageQueueDrain(){return this.isLoading||this.stopMessageQueueDrain}async drainQueue(){if(!(this.messageQueueDraining||this.isLoading||this.messageQueue.length===0)){this.messageQueueDraining=!0,this.stopMessageQueueDrain=!1;try{if(this.queueConfig.drain===`batch`){for(;this.messageQueue.length>0;){if(this.shouldAbortMessageQueueDrain())return;let e=this.messageQueue.splice(0);this.emitQueueChange();let t=ef(e);if(!await this.deliverMessage(t.content,t.body)||this.shouldAbortMessageQueueDrain())return}return}for(;this.messageQueue.length>0;){if(this.shouldAbortMessageQueueDrain())return;let e=this.messageQueue.shift();if(e===void 0||(this.emitQueueChange(),!await this.deliverMessage(e.content,e.body)||this.shouldAbortMessageQueueDrain()))return}}finally{this.messageQueueDraining=!1,this.stopMessageQueueDrain=!1}}}discardPendingSends(){this.sendInFlight=!1,this.flushQueue()}getQueue(){return this.messageQueue.map(({id:e,content:t,createdAt:n})=>({id:e,content:t,createdAt:n}))}emitQueueChange(){let e=this.getQueue();ko(this.snapshotAtom,{queue:this.freezeSnapshotQueue(e)}),this.callbacksRef.current.onQueueChange(e),this.devtoolsBridge.emitSnapshot()}cancelQueued(e){let t=this.messageQueue.findIndex(t=>t.id===e);t!==-1&&(this.messageQueue.splice(t,1),this.emitQueueChange())}flushQueue(){this.messageQueue.length!==0&&(this.messageQueue=[],this.emitQueueChange())}getIsLoading(){return this.isLoading}getStatus(){return this.status}getIsSubscribed(){return this.isSubscribed}getConnectionStatus(){return this.connectionStatus}getSessionGenerating(){return this.sessionGenerating}getIsHydrating(){return this.isHydrating}getError(){return this.error}setMessagesManually(e){this.processor.setMessages(sf(e)),this.devtoolsBridge.emitSnapshot()}updateOptions(e){if(e.connection!==void 0||e.fetcher!==void 0){let t=this.isSubscribed;this.isLoading?this.cancelInFlightStream({setReadyStatus:!0,abortSubscription:!0}):t&&this.abortSubscriptionLoop(),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.setConnectionStatus(`disconnected`);let n=Xd({connection:e.connection,fetcher:e.fetcher});this.connectionDrainsOnSend=Zd(n),this.connection=td(n),t&&this.subscribe()}if(e.forwardedProps!==void 0&&(this.forwardedPropsOption=e.forwardedProps),e.byok!==void 0&&(this.byok=e.byok),e.byokProvider!==void 0&&(this.byokProvider=e.byokProvider),`context`in e&&(this.context=e.context),e.tools!==void 0){this.interruptManager.updateTools(e.tools),this.clientToolsRef.current=/* @__PURE__ */ new Map;for(let t of e.tools)this.clientToolsRef.current.set(t.name,t);this.devtoolsBridge.notifyToolsChanged()}e.queue!==void 0&&(this.queueConfig=$d(e.queue)),e.onResponse!==void 0&&(this.callbacksRef.current.onResponse=e.onResponse),e.onChunk!==void 0&&(this.callbacksRef.current.onChunk=e.onChunk),e.onFinish!==void 0&&(this.callbacksRef.current.onFinish=e.onFinish),e.onError!==void 0&&(this.callbacksRef.current.onError=e.onError),e.onSubscriptionChange!==void 0&&(this.callbacksRef.current.onSubscriptionChange=e.onSubscriptionChange),e.onConnectionStatusChange!==void 0&&(this.callbacksRef.current.onConnectionStatusChange=e.onConnectionStatusChange),e.onSessionGeneratingChange!==void 0&&(this.callbacksRef.current.onSessionGeneratingChange=e.onSessionGeneratingChange),e.onHydratingChange!==void 0&&(this.callbacksRef.current.onHydratingChange=e.onHydratingChange),e.onQueueChange!==void 0&&(this.callbacksRef.current.onQueueChange=e.onQueueChange),e.onResumeStateChange!==void 0&&(this.callbacksRef.current.onResumeStateChange=e.onResumeStateChange),e.onRunIdChange!==void 0&&(this.callbacksRef.current.onRunIdChange=e.onRunIdChange),e.onInterruptStateChange!==void 0&&(this.callbacksRef.current.onInterruptStateChange=e.onInterruptStateChange),e.onCustomEvent!==void 0&&(this.callbacksRef.current.onCustomEvent=e.onCustomEvent)}dispose(){this.disposed=!0,this.unsubscribe(),this.devtoolsBridge.dispose(),this.devtoolsMounted=!1}};const pf=e=>`background:${e};color:#fff;border-radius:3px;padding:1px 5px`,mf=`${pf(`#7c3aed`)};font-weight:600`,hf={mount:`#7c3aed`,auth:`#be185d`,theme:`#8b5cf6`,send:`#2563eb`,run:`#0891b2`,stream:`#0e7490`,text:`#16a34a`,reasoning:`#64748b`,tool:`#d97706`,widget:`#db2777`,attachment:`#0d9488`,sandbox:`#0369a1`,questionnaire:`#9333ea`,status:`#475569`,error:`#dc2626`};function gf(e){if(e)return(e,t,n)=>{console.log(`%cAstralBeam%c ${(/* @__PURE__ */ new Date()).toISOString().slice(11,19)} %c${e}%c ${t}`,mf,`color:#94a3b8;font-weight:400`,pf(hf[e]),``,...n===void 0?[]:[n])}}function _f(){let e=crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function vf(e,t=!0){return{id:e.id,title:e.title,agentId:e.agent_id,version:e.version,role:e.role,writerActive:e.writer_active,hasMessages:t,updatedAt:e.updated_at}}function yf(e,t,n){return`saved:${e}:${t}${n?`:${n}`:``}`}async function bf(e,t,n,r=/* @__PURE__ */ new Map){let i=await jr(e,{page_size:100,...n?{page_after:n}:{}},t),a=i.pending_interactions.map(e=>({sourceMessageId:e.source_message_id,sourcePartId:e.source_part_id,responseTargetId:e.response_target_id,toolCallId:r.get(e.tool_call_id)===e.source_message_id?e.tool_call_id:yf(e.source_message_id,e.source_part_id,e.response_target_id),targetTenantUserId:e.target_tenant_user_id,targetClientId:e.target_client_id,executionLocation:e.execution_location}));return{...i,pendingInteractions:a}}function xf(e,t=[],n=/* @__PURE__ */ new Map){let r=[],i=/* @__PURE__ */ new Map;for(let a of e){if(a.role===`tool`){for(let e of a.parts){let t=i.get(yf(a.source_assistant_message_id,a.source_tool_part_id,a.response_target_id));t&&(t.output=e.output??null,Object.assign(t,{resultOutcome:e.outcome}),t.state=e.outcome===`succeeded`?`complete`:`error`)}continue}let e=a.parts.flatMap(e=>{let r=e.source;if(typeof e.type==`string`&&[`image`,`document`,`audio`,`video`].includes(e.type)&&r&&typeof r==`object`&&!Array.isArray(r)&&`type`in r&&r.type===`attachment`)return[{...e,source:{...r,type:`url`,value:``},fileId:`id`in r&&typeof r.id==`string`?r.id:void 0}];if(e.type!==`tool-call`||e.executionLocation===`provider`)return[e];let o=String(e.toolCallId),s=Array.isArray(e.targets)?e.targets.flatMap(e=>e&&typeof e==`object`&&!Array.isArray(e)&&`id`in e&&typeof e.id==`string`?[e.id]:[]):t.filter(t=>t.sourceMessageId===a.id&&t.sourcePartId===e.id).map(e=>e.responseTargetId);return(s.length?s:[void 0]).map(t=>{let r=yf(a.id,String(e.id),t),s={...e,savedToolTitle:e.declaration&&typeof e.declaration==`object`&&!Array.isArray(e.declaration)&&`title`in e.declaration&&typeof e.declaration.title==`string`?e.declaration.title:void 0,id:n.get(o)===a.id?o:r,upstreamToolCallId:o,applicationPartId:e.id,sourceMessageId:a.id,responseTargetId:t};return i.set(r,s),s})});r.push({id:a.id,role:a.role,parts:e,createdAt:new Date(a.created_at),metadata:{astralbeam:{state:a.state,authorTenantUserId:a.author_tenant_user_id}}})}return r}function Sf(e){return e.placementKey??e.agentId??`default`}function Cf(e,t){try{if(t===void 0)return globalThis.sessionStorage?.getItem(e)??void 0;t===null?globalThis.sessionStorage?.removeItem(e):globalThis.sessionStorage?.setItem(e,t)}catch{}}let wf;function Tf(e,t,n){if(!n){if(!wf)try{let e=`astralbeam:draft-session`;wf=globalThis.sessionStorage?.getItem(e)??_f(),globalThis.sessionStorage?.setItem(e,wf)}catch{wf??=_f()}n=`new:${wf}`}return JSON.stringify([e.replace(/\/+$/,``),t,n])}function Ef(e){return typeof e==`object`&&!!e&&`id`in e&&typeof e.id==`string`&&`name`in e&&typeof e.name==`string`&&`size`in e&&typeof e.size==`number`&&Number.isFinite(e.size)&&e.size>=0&&`mimeType`in e&&typeof e.mimeType==`string`&&`status`in e&&e.status===`ready`&&`fileId`in e&&typeof e.fileId==`string`&&(!(`kind`in e)||typeof e.kind==`string`&&[`image`,`pdf`,`text`,`data`,`office`].includes(e.kind))&&(!(`error`in e)||typeof e.error==`string`)}function Df(e,t,n,r,i=`draft`){if(!t)return``;let a=`astralbeam:${i}:${Tf(e,t,n)}`;try{if(r===void 0)return globalThis.localStorage?.getItem(a)??``;r?globalThis.localStorage?.setItem(a,r):globalThis.localStorage?.removeItem(a)}catch{}return``}function Of({apiUrl:e,identity:t,threadId:n,update:r,moveTo:i}){let a=()=>{if(!t)return[];let a=`astralbeam:attachments:${Tf(e,t,n)}`,o=e=>{let t=JSON.parse(globalThis.localStorage?.getItem(e)??`[]`);if(!Array.isArray(t)||!t.every(Ef))throw TypeError(`Stored attachment draft is invalid`);return t},s=o(a);if(r&&(s=r(s).filter(e=>e.status===`ready`&&e.fileId!==void 0)),i!==void 0){let n=`astralbeam:attachments:${Tf(e,t,i)}`;s=[...new Map([...o(n),...s].map(e=>[e.id,e])).values()],globalThis.localStorage?.setItem(n,JSON.stringify(s)),globalThis.localStorage?.removeItem(a)}else r&&(s.length?globalThis.localStorage?.setItem(a,JSON.stringify(s)):globalThis.localStorage?.removeItem(a));return s};return globalThis.navigator?.locks?navigator.locks.request(`astralbeam:attachment-drafts`,a):Promise.resolve().then(a)}function kf(e){return e?`~standard`in e?`jsonSchema`in e[`~standard`]?vs(e):{type:`object`}:e:{type:`object`,properties:{}}}async function Af(e,t){let n=await ys(e,t);return n.success?n.data??{}:null}const jf=Symbol(`Host tool was not executed`);function Mf(e,t,n,r,i){return[...Object.keys(e).length>0?[Nf(e,n)]:[],Pf(),...Ff(t,r,i)]}function Nf(e,t){return dl({name:`render_widget`,description:`Render one of the host application's own UI widgets inline in the conversation. The widget appears in the transcript at the point of the call, so prefer it over describing the same information in text. Available widgets:
|
|
146
146
|
`+Object.entries(e).map(([e,{description:t,parameters:n}])=>`- ${e}: ${t} Props schema: ${JSON.stringify(kf(n))}`).join(`
|
|
147
|
-
`),inputSchema:{type:`object`,properties:{widget:{type:`string`,enum:Object.keys(e),description:`Name of the widget to render.`},props:{type:`object`,description:`Props for the widget, matching its props schema.`}},required:[`widget`]}}).client((e,n)=>t(e,n?.toolCallId??``))}function Pf(){return dl({name:`ask_questionnaire`,description:`Ask the user a short structured questionnaire rendered inline in the chat. Use it when the next step genuinely depends on their choices instead of asking in prose. The call stays pending until the user submits; their answers arrive as the tool output. Skipped optional questions come back with an empty answers array. An output with skipped: true means the user dismissed the questionnaire by continuing the conversation instead — do not re-ask; address their next message.`,inputSchema:{type:`object`,properties:{items:{type:`array`,minItems:1,description:`Questions shown one at a time, in order.`,items:{type:`object`,properties:{name:{type:`string`,description:`Unique key identifying the question.`},title:{type:`string`,description:`The question itself.`},description:{type:`string`,description:`Optional helper text.`},required:{type:`boolean`,description:`Whether an answer is mandatory.`},multiple:{type:`boolean`,description:`Whether several choices may be selected.`},choices:{type:`array`,minItems:1,items:{type:`object`,properties:{value:{type:`string`},label:{type:`string`},description:{type:`string`}},required:[`value`,`label`]}},input:{type:`object`,description:`Optional free-form alternative to the fixed choices.`,properties:{label:{type:`string`},placeholder:{type:`string`}},required:[`label`,`placeholder`]}},required:[`name`,`title`,`choices`]}}},required:[`items`]}}).client()}function Ff(e,t,n){return Object.entries(e).map(([e,r])=>dl({name:e,description:r.description,inputSchema:kf(r.parameters),...r.metadata?{metadata:r.metadata}:{}}).client(async(i,a)=>{let o=!1;try{let s=n?.(e,r,a?.toolCallId);t?.(`tool`,`executing host tool "${e}"`,{input:i});let c=await Af(r.parameters,i??{});if(c==null)throw t?.(`error`,`input for host tool "${e}" failed schema validation`,{input:i}),Error(`Input for tool "${e}" failed schema validation`);a?.abortSignal?.throwIfAborted();let l=s?.()??r;o=!0;let u=await l.execute(c);try{u=Z(u)}catch{throw Error(`Tool "${e}" ran, but its result is not JSON-compatible. Its changes may already be applied. Read current state before retrying. Return plain JSON values and omit undefined fields.`)}return t?.(`tool`,`host tool "${e}" returned`,{output:u}),u}catch(n){t?.(`error`,`host tool "${e}" threw`,{error:n});let r=n instanceof Error?n:Error(String(n));throw o||Object.assign(r,{[jf]:!0}),r}}))}function If(e){if(e.length>16384)throw Error(`The chat auth token is too large`);let{exp:t,iat:n,user:r}=ao(e);if(!Number.isInteger(t)||Number(t)<=0)throw Error(`The chat auth token has no valid expiry`);let i=Number(t)*1e3,a=n===void 0?3e5:i-n*1e3,o=Math.min(6e4,a*.2),s=r?.admin===!0;return{expiresAt:i,refreshAt:i-o,tenantAdmin:s}}async function Lf(e,t){let{fetchAstralBeamToken:n,fetchClient:r}=e;if(typeof n==`function`)return(await n())?.token;if(!n)throw Error(`Provide fetchAstralBeamToken.`);let{url:i,...a}=n,o=new Headers(a.headers);o.has(`accept`)||o.set(`accept`,`application/json`);let s=await r(i,{method:`POST`,credentials:`include`,cache:`no-store`,...a,headers:o,signal:a.signal?AbortSignal.any([t,a.signal]):t});if(!s.ok)throw Object.assign(/* @__PURE__ */ Error(`Authentication endpoint returned HTTP ${s.status}`),{status:s.status,headers:s.headers});return(await s.json())?.token}const Rf={status:`loading`};function zf(e){return{...e,fetchAstralBeamToken:e.fetchAstralBeamToken,session:{cached:void 0,refreshPromise:void 0,abortController:new AbortController,state:Rf,listeners:/* @__PURE__ */ new Set},fetchClient:globalThis.fetch.bind(globalThis),debug:void 0}}function Bf(e){return e.session.state}function Vf(e,t){let{listeners:n}=e.session;return n.add(t),()=>{n.delete(t)}}function Hf(e,t){e.session.state=t;for(let t of e.session.listeners)t()}function Uf(e,t){e.apiUrl!==t.apiUrl&&(Yf(e),e.session.abortController=new AbortController,Hf(e,{status:`loading`})),e.apiUrl=t.apiUrl,e.fetchAstralBeamToken=t.fetchAstralBeamToken}function Wf(e,t){return JSON.stringify([e.scope,e.organization.id,e.scope===`tenant`?e.tenant.id:null,e.user.id,t===void 0?null:e.scope===`tenant`?t:e.user.role])}async function Gf(e){let{session:t,debug:n,apiUrl:r}=e,{signal:i}=t.abortController,a=typeof e.fetchAstralBeamToken==`function`?`fetchAstralBeamToken`:`Authentication endpoint`;try{for(let o=0;o<2;o++){let s=await Lf(e,i);if(i.throwIfAborted(),typeof s!=`string`||!s)throw Error(`${a} did not return a token`);let{expiresAt:c,refreshAt:l,tenantAdmin:u}=If(s);if(c<=Date.now())throw Error(`${a} returned an expired token`);if(!Number.isFinite(l)||l<=Date.now()||c-Date.now()<5e3)throw Error(`${a} returned a token too close to expiry`);let d;try{d=await Pr({apiUrl:r,astralBeamToken:s,fetchClient:e.fetchClient,signal:i,cache:`no-store`,credentials:`omit`})}catch(t){if(!o&&e.retryUnauthorized!==!1&&or(t)&&t.status===401)continue;throw t}if(i.throwIfAborted(),e.scope&&e.scope!==d.scope)throw Error(`Expected ${e.scope} authentication`);return t.cached={value:s,expiresAt:c,refreshAt:l,synchronizedAt:Date.now(),tenantAdmin:u},Hf(e,{status:`ready`,currentUser:d}),n?.(`auth`,`authentication ready`,{expiresAt:new Date(c)}),s}throw Error(`Authentication failed`)}catch(n){i.throwIfAborted();let r=n instanceof Error?n:/* @__PURE__ */ Error(`Authentication failed`);throw or(r)&&r.status===401&&(r.message=`AstralBeam rejected the chat token after renewal. Check that apiUrl matches the deployment that issued your API key. If the key was revoked or expired, create a replacement in API Keys and update your server's secret.`),t.cached=void 0,Hf(e,{status:`error`,error:r}),r}}async function Kf(e){let{session:t,force:n=!1}=e;if(t.abortController.signal.throwIfAborted(),t.refreshPromise)return await t.refreshPromise;if(!n&&t.cached&&t.cached.refreshAt>Date.now())return t.cached.value;(!t.cached||t.cached.expiresAt<=Date.now())&&Hf(e,{status:`loading`});let r=Gf(e);t.refreshPromise=r;try{return await r}finally{t.refreshPromise===r&&(t.refreshPromise=void 0)}}function qf(e,t){let n=!t||e.session.cached?.value===t;return n&&(e.session.cached=void 0),Kf({...e,force:n,retryUnauthorized:!1})}async function Jf(e){e.session.abortController.signal.aborted&&(e.session.abortController=new AbortController),await Kf(e)}function Yf({session:e}){e.abortController.abort(),e.refreshPromise=void 0,e.cached=void 0,e.state=Rf}async function Xf(e){let{input:t,init:n,session:r,fetchClient:i,debug:a}=e,o=Bf(e),s=await i(t,n);if(s.status!==401||r.abortController.signal.aborted)return s;let c=new Headers(n?.headers),l=c.get(`authorization`),u=l?.startsWith(`Bearer `)?l.slice(7):void 0;a?.(`auth`,`chat auth token was rejected; refreshing once`),await s.body?.cancel();let d=await qf(e,u),f=Bf(e);if(o.status!==`ready`||f.status!==`ready`||Wf(o.currentUser)!==Wf(f.currentUser))throw new DOMException(`Identity changed`,`AbortError`);return n?.signal?.throwIfAborted(),c.set(`authorization`,`Bearer ${d}`),await i(t,{...n,headers:c})}function Zf(e){let t,n=new AbortController,r=0,i=()=>typeof document>`u`||document.visibilityState!==`hidden`&&globalThis.navigator?.onLine!==!1,a=()=>{!n.signal.aborted&&i()&&Kf({...e,force:!0}).catch(()=>{})},o=()=>{if(clearTimeout(t),n.signal.aborted||typeof document>`u`||!i())return;let o=Bf(e);if(o.status===`ready`)r=0,t=setTimeout(a,Math.max(1e3,e.session.cached.refreshAt-Date.now()));else if(o.status===`error`&&r<3){let e=o.error;if(e.status!==void 0&&e.status!==429&&e.status<500||e.status===void 0&&!(e instanceof TypeError))return;let n=e.headers?.get(`retry-after`),i=n?/^\d+$/.test(n)?Number(n)*1e3:Date.parse(n)-Date.now():0;t=setTimeout(a,Math.max(1e3*2**r++,Number.isFinite(i)?i:0))}},s=()=>{if(!i()){clearTimeout(t);return}let n=e.session.cached;!n||Date.now()-n.synchronizedAt>=6e4||n.refreshAt<=Date.now()?a():o()},c=Vf(e,o);if(typeof document<`u`){for(let e of[`focus`,`online`,`offline`])globalThis.addEventListener(e,s,{signal:n.signal});document.addEventListener(`visibilitychange`,s,{signal:n.signal})}return Jf(e).catch(()=>{}),o(),()=>{n.abort(),clearTimeout(t),c()}}async function Qf(e,t){switch(e.action){case`connect`:return Rr({mcp_server_id:e.mcpServerId},t);case`headers`:{let n=await Rr({mcp_server_id:e.mcpServerId},t);return await Br(n.id,{lock_version:n.lock_version,headers:e.headers},t),{id:n.id}}case`disconnect`:return Hr(e.id,t);case`test`:return Wr(e.id,t)}}async function $f(e,t){let n=window.open(`about:blank`,`_blank`,`popup,width=600,height=720`);if(!n)throw Error(`Allow popups to authorize this connection.`);try{let r=e.id??(await Rr({mcp_server_id:e.mcpServerId},await t())).id,i=await Kr(r,await t()),a={organizationId:i.attempt.organization_id,tenantId:i.attempt.tenant_id,connectionId:i.attempt.connection_id,id:i.attempt.id},o=new URL(i.popup_url);return o.searchParams.set(`origin`,window.location.origin),await new Promise((e,i)=>{let s,c=!1,l=!1,u=!1,d=()=>{l=!0,window.removeEventListener(`message`,m),clearInterval(h),clearTimeout(g)},f=e=>{d(),i(e instanceof Error?e:/* @__PURE__ */ Error(`Authorization failed.`))},p=async()=>{if(!(u||l)){u=!0;try{if(s){if(c||=(await Jr(r,{attempt_id:a.id,challenge:s},await t()),!0),l)return;let n=await Xr(r,{attempt_id:a.id},await t());if(l)return;if(n){d(),e();return}}n.closed&&f(/* @__PURE__ */ Error(`Authorization window closed.`))}catch(e){let t=e instanceof Error?e.status:void 0;!(e instanceof TypeError)&&t!==429&&(t??0)<500&&f(e)}finally{u=!1}}},m=e=>{if(e.source!==n||e.origin!==o.origin)return;let t=e.data;t?.attempt&&t.attempt.id===a.id&&t.attempt.organizationId===a.organizationId&&t.attempt.tenantId===a.tenantId&&t.attempt.connectionId===a.connectionId&&t.type===`mcp-browser-challenge`&&!s&&typeof t.challenge==`string`&&(s=t.challenge,p())},h=setInterval(()=>void p(),5e3),g=setTimeout(()=>f(/* @__PURE__ */ Error(`Authorization expired. Try connecting again.`)),6e5);window.addEventListener(`message`,m),n.location.replace(o.href)}),r}finally{n.close()}}function ep(e){return e.state===`complete`||e.state===`error`||e.output!==void 0}function tp(e){return e.metadata??{}}function np(e,t){return typeof e==`object`&&e&&t in e?e[t]:void 0}function rp(e,t){let n=np(e,t);return typeof n==`string`?n:void 0}function ip(e,t){let n=np(e,t);return typeof n==`number`?n:void 0}function ap(e){return rp(e.output,`refusal`)}function op(e){if(e.name!==`sandbox_write_file`)return;let t=rp(e.output,`path`)??rp(e.input,`path`);if(t===void 0)return;let n=rp(e.input,`content`)??``;return{toolCallId:e.id,path:t,label:sp(e)??t,content:n,lines:n.length===0?0:n.split(`
|
|
147
|
+
`),inputSchema:{type:`object`,properties:{widget:{type:`string`,enum:Object.keys(e),description:`Name of the widget to render.`},props:{type:`object`,description:`Props for the widget, matching its props schema.`}},required:[`widget`]}}).client((e,n)=>t(e,n?.toolCallId??``))}function Pf(){return dl({name:`ask_questionnaire`,description:`Ask the user a short structured questionnaire rendered inline in the chat. Use it when the next step genuinely depends on their choices instead of asking in prose. The call stays pending until the user submits; their answers arrive as the tool output. Skipped optional questions come back with an empty answers array. An output with skipped: true means the user dismissed the questionnaire by continuing the conversation instead — do not re-ask; address their next message.`,inputSchema:{type:`object`,properties:{items:{type:`array`,minItems:1,description:`Questions shown one at a time, in order.`,items:{type:`object`,properties:{name:{type:`string`,description:`Unique key identifying the question.`},title:{type:`string`,description:`The question itself.`},description:{type:`string`,description:`Optional helper text.`},required:{type:`boolean`,description:`Whether an answer is mandatory.`},multiple:{type:`boolean`,description:`Whether several choices may be selected.`},choices:{type:`array`,minItems:1,items:{type:`object`,properties:{value:{type:`string`},label:{type:`string`},description:{type:`string`}},required:[`value`,`label`]}},input:{type:`object`,description:`Optional free-form alternative to the fixed choices.`,properties:{label:{type:`string`},placeholder:{type:`string`}},required:[`label`,`placeholder`]}},required:[`name`,`title`,`choices`]}}},required:[`items`]}}).client()}function Ff(e,t,n){return Object.entries(e).map(([e,r])=>dl({name:e,description:r.description,inputSchema:kf(r.parameters),...r.metadata?{metadata:r.metadata}:{}}).client(async(i,a)=>{let o=!1;try{let s=n?.(e,r,a?.toolCallId);t?.(`tool`,`executing host tool "${e}"`,{input:i});let c=await Af(r.parameters,i??{});if(c==null)throw t?.(`error`,`input for host tool "${e}" failed schema validation`,{input:i}),Error(`Input for tool "${e}" failed schema validation`);a?.abortSignal?.throwIfAborted();let l=s?.()??r;o=!0;let u=await l.execute(c);try{u=Z(u)}catch{throw Error(`Tool "${e}" ran, but its result is not JSON-compatible. Its changes may already be applied. Read current state before retrying. Return plain JSON values and omit undefined fields.`)}return t?.(`tool`,`host tool "${e}" returned`,{output:u}),u}catch(n){t?.(`error`,`host tool "${e}" threw`,{error:n});let r=n instanceof Error?n:Error(String(n));throw o||Object.assign(r,{[jf]:!0}),r}}))}function If(e){if(e.length>16384)throw Error(`The chat auth token is too large`);let{exp:t,iat:n,user:r}=ao(e);if(!Number.isInteger(t)||Number(t)<=0)throw Error(`The chat auth token has no valid expiry`);let i=Number(t)*1e3,a=n===void 0?3e5:i-n*1e3,o=Math.min(6e4,a*.2),s=r?.admin===!0;return{expiresAt:i,refreshAt:i-o,tenantAdmin:s}}async function Lf(e,t){let{fetchAstralBeamToken:n,fetchClient:r}=e;if(typeof n==`function`)return(await n())?.token;if(!n)throw Error(`Provide fetchAstralBeamToken.`);let{url:i,...a}=n,o=new Headers(a.headers);o.has(`accept`)||o.set(`accept`,`application/json`);let s=await r(i,{method:`POST`,credentials:`include`,cache:`no-store`,...a,headers:o,signal:a.signal?AbortSignal.any([t,a.signal]):t});if(!s.ok)throw Object.assign(/* @__PURE__ */ Error(`Authentication endpoint returned HTTP ${s.status}`),{status:s.status,headers:s.headers});return(await s.json())?.token}const Rf={status:`loading`};function zf(e){return{...e,fetchAstralBeamToken:e.fetchAstralBeamToken,session:{cached:void 0,refreshPromise:void 0,abortController:new AbortController,state:Rf,listeners:/* @__PURE__ */ new Set},fetchClient:globalThis.fetch.bind(globalThis),debug:void 0}}function Bf(e){return e.session.state}function Vf(e,t){let{listeners:n}=e.session;return n.add(t),()=>{n.delete(t)}}function Hf(e,t){e.session.state=t;for(let t of e.session.listeners)t()}function Uf(e,t){e.apiUrl!==t.apiUrl&&(Yf(e),e.session.abortController=new AbortController,Hf(e,{status:`loading`})),e.apiUrl=t.apiUrl,e.fetchAstralBeamToken=t.fetchAstralBeamToken}function Wf(e,t){return JSON.stringify([e.scope,e.organization.id,e.scope===`tenant`?e.tenant.id:null,e.user.id,t===void 0?null:e.scope===`tenant`?t:e.user.role])}async function Gf(e){let{session:t,debug:n,apiUrl:r}=e,{signal:i}=t.abortController,a=typeof e.fetchAstralBeamToken==`function`?`fetchAstralBeamToken`:`Authentication endpoint`;try{for(let o=0;o<2;o++){let s=await Lf(e,i);if(i.throwIfAborted(),typeof s!=`string`||!s)throw Error(`${a} did not return a token`);let{expiresAt:c,refreshAt:l,tenantAdmin:u}=If(s);if(c<=Date.now())throw Error(`${a} returned an expired token`);if(!Number.isFinite(l)||l<=Date.now()||c-Date.now()<5e3)throw Error(`${a} returned a token too close to expiry`);let d;try{d=await Pr({apiUrl:r,astralBeamToken:s,fetchClient:e.fetchClient,signal:i,cache:`no-store`,credentials:`omit`})}catch(t){if(!o&&e.retryUnauthorized!==!1&&or(t)&&t.status===401)continue;throw t}if(i.throwIfAborted(),e.scope&&e.scope!==d.scope)throw Error(`Expected ${e.scope} authentication`);return t.cached={value:s,expiresAt:c,refreshAt:l,synchronizedAt:Date.now(),tenantAdmin:u},Hf(e,{status:`ready`,currentUser:d}),n?.(`auth`,`authentication ready`,{expiresAt:new Date(c)}),s}throw Error(`Authentication failed`)}catch(n){i.throwIfAborted();let r=n instanceof Error?n:/* @__PURE__ */ Error(`Authentication failed`);throw or(r)&&r.status===401&&(r.message=`AstralBeam rejected the chat token after renewal. Check that apiUrl matches the deployment that issued your API key. If the key was revoked or expired, create a replacement in API Keys and update your server's secret.`),t.cached=void 0,Hf(e,{status:`error`,error:r}),r}}async function Kf(e){let{session:t,force:n=!1}=e;if(t.abortController.signal.throwIfAborted(),t.refreshPromise)return await t.refreshPromise;if(!n&&t.cached&&t.cached.refreshAt>Date.now())return t.cached.value;(!t.cached||t.cached.expiresAt<=Date.now())&&Hf(e,{status:`loading`});let r=Gf(e);t.refreshPromise=r;try{return await r}finally{t.refreshPromise===r&&(t.refreshPromise=void 0)}}function qf(e,t){let n=!t||e.session.cached?.value===t;return n&&(e.session.cached=void 0),Kf({...e,force:n,retryUnauthorized:!1})}async function Jf(e){e.session.abortController.signal.aborted&&(e.session.abortController=new AbortController),await Kf(e)}function Yf({session:e}){e.abortController.abort(),e.refreshPromise=void 0,e.cached=void 0,e.state=Rf}async function Xf(e){let{input:t,init:n,session:r,fetchClient:i,debug:a}=e,o=Bf(e),s=await i(t,n);if(s.status!==401||r.abortController.signal.aborted)return s;let c=new Headers(n?.headers),l=c.get(`authorization`),u=l?.startsWith(`Bearer `)?l.slice(7):void 0;a?.(`auth`,`chat auth token was rejected; refreshing once`),await s.body?.cancel();let d=await qf(e,u),f=Bf(e);if(o.status!==`ready`||f.status!==`ready`||Wf(o.currentUser)!==Wf(f.currentUser))throw new DOMException(`Identity changed`,`AbortError`);return n?.signal?.throwIfAborted(),c.set(`authorization`,`Bearer ${d}`),await i(t,{...n,headers:c})}function Zf(e){let t,n=new AbortController,r=0,i=()=>typeof document>`u`||document.visibilityState!==`hidden`&&globalThis.navigator?.onLine!==!1,a=()=>{!n.signal.aborted&&i()&&Kf({...e,force:!0}).catch(()=>{})},o=()=>{if(clearTimeout(t),n.signal.aborted||typeof document>`u`||!i())return;let o=Bf(e);if(o.status===`ready`)r=0,t=setTimeout(a,Math.max(1e3,e.session.cached.refreshAt-Date.now()));else if(o.status===`error`&&r<3){let e=o.error;if(e.status!==void 0&&e.status!==429&&e.status<500||e.status===void 0&&!(e instanceof TypeError))return;let n=e.headers?.get(`retry-after`),i=n?/^\d+$/.test(n)?Number(n)*1e3:Date.parse(n)-Date.now():0;t=setTimeout(a,Math.max(1e3*2**r++,Number.isFinite(i)?i:0))}},s=()=>{if(!i()){clearTimeout(t);return}let n=e.session.cached;!n||Date.now()-n.synchronizedAt>=6e4||n.refreshAt<=Date.now()?a():o()},c=Vf(e,o);if(typeof document<`u`){for(let e of[`focus`,`online`,`offline`])globalThis.addEventListener(e,s,{signal:n.signal});document.addEventListener(`visibilitychange`,s,{signal:n.signal})}return Jf(e).catch(()=>{}),o(),()=>{n.abort(),clearTimeout(t),c()}}async function Qf(e,t){switch(e.action){case`connect`:case`headers`:{let n=await Rr({mcp_server_id:e.mcpServerId},t);return e.action===`connect`?n:(await Br(n.id,{lock_version:n.lock_version,headers:e.headers},t),{id:n.id})}case`disconnect`:return Hr(e.id,t);case`test`:return Wr(e.id,t)}}async function $f(e,t){let n=window.open(`about:blank`,`_blank`,`popup,width=600,height=720`);if(!n)throw Error(`Allow popups to authorize this connection.`);try{let r=e.id??(await Rr({mcp_server_id:e.mcpServerId},await t())).id,i=await Kr(r,await t()),a={organizationId:i.attempt.organization_id,tenantId:i.attempt.tenant_id,connectionId:i.attempt.connection_id,id:i.attempt.id},o=new URL(i.popup_url);o.searchParams.set(`origin`,window.location.origin);let{promise:s,resolve:c,reject:l}=Promise.withResolvers(),u={state:`waiting`},d=new AbortController,f=!1,p=e=>l(e instanceof Error?e:/* @__PURE__ */ Error(`Authorization failed.`)),m=async()=>{let e=await t();return d.signal.throwIfAborted(),{...e,signal:AbortSignal.any([d.signal,...e.signal?[e.signal]:[]])}},h=async()=>{if(!(f||d.signal.aborted)){f=!0;try{if(u.state===`binding`&&(await Jr(r,{attempt_id:a.id,challenge:u.challenge},await m()),d.signal.throwIfAborted(),u={state:`completing`}),u.state===`completing`){let e=await Xr(r,{attempt_id:a.id},await m());if(d.signal.throwIfAborted(),e){c();return}}n.closed&&p(/* @__PURE__ */ Error(`Authorization window closed.`))}catch(e){let t=e instanceof Error?e.status:void 0;!(e instanceof TypeError)&&t!==429&&(t??0)<500&&p(e)}finally{f=!1}}},g=e=>{if(e.source!==n||e.origin!==o.origin)return;let t=e.data;t?.attempt&&t.attempt.id===a.id&&t.attempt.organizationId===a.organizationId&&t.attempt.tenantId===a.tenantId&&t.attempt.connectionId===a.connectionId&&t.type===`mcp-browser-challenge`&&u.state===`waiting`&&typeof t.challenge==`string`&&(u={state:`binding`,challenge:t.challenge},h())},_=setInterval(()=>void h(),5e3),v=setTimeout(()=>p(/* @__PURE__ */ Error(`Authorization expired. Try connecting again.`)),6e5);try{window.addEventListener(`message`,g),n.location.replace(o.href),await s}finally{d.abort(),window.removeEventListener(`message`,g),clearInterval(_),clearTimeout(v)}return r}finally{n.close()}}function ep(e){return e.state===`complete`||e.state===`error`||e.output!==void 0}function tp(e){return e.metadata??{}}function np(e,t){return typeof e==`object`&&e&&t in e?e[t]:void 0}function rp(e,t){let n=np(e,t);return typeof n==`string`?n:void 0}function ip(e,t){let n=np(e,t);return typeof n==`number`?n:void 0}function ap(e){return rp(e.output,`refusal`)}function op(e){if(e.name!==`sandbox_write_file`)return;let t=rp(e.output,`path`)??rp(e.input,`path`);if(t===void 0)return;let n=rp(e.input,`content`)??``;return{toolCallId:e.id,path:t,label:sp(e)??t,content:n,lines:n.length===0?0:n.split(`
|
|
148
148
|
`).length,written:e.output!=null&&ap(e)===void 0}}function sp(e){let t=rp(e.output,`relativePath`);return t!==void 0&&t!==`.`?t:rp(e.output,`path`)??rp(e.input,`path`)}function cp(e){if(e.name!==`sandbox_run_command`)return;let t=rp(e.input,`command`);if(t===void 0)return;let n=e.output;return{toolCallId:e.id,command:t,cwd:rp(e.input,`cwd`),exitCode:ip(n,`exitCode`),stdout:rp(n,`stdout`)??``,stderr:rp(n,`stderr`)??``,durationMs:ip(n,`durationMs`),timedOut:np(n,`timedOut`)===!0,truncated:np(n,`truncated`)===!0,finished:n!=null}}function lp(e){let t=/* @__PURE__ */ new Map,n=[];for(let r of e)for(let e of r.parts){if(e.type!==`tool-call`)continue;let r=op(e);r?.written&&t.set(r.path,r);let i=cp(e);i&&ap(e)===void 0&&n.push(i)}return{files:[...t.values()],commands:n}}const up=`Reopen this conversation or start a new one before sending.`;function dp(e,t){return e.length===t.length&&e.every((e,n)=>e.name===t[n]?.name&&e.title===t[n]?.title)}function fp(e,t=!1){let n={...e},r=gf(n.debug),i=/* @__PURE__ */ new Set,a,o=()=>a?.options??n,s={messages:[],status:`ready`,error:void 0,auth:{status:`loading`},capabilities:{attachments:!0},agentTools:[],sandboxStatus:void 0,usageLimitReached:void 0,sandbox:{files:[],commands:[]},thread:void 0,history:`idle`,messagesCursor:void 0,olderMessagesLoading:!1,submission:void 0,activeToolCallIds:[],pendingInteractions:[]},c,l=/* @__PURE__ */ new Map,u,d=`ready`,f,p=e=>{let t=f||c?.phase===`submitting`?d===`streaming`||s.status===`streaming`?`streaming`:`submitted`:d;s={...s,...e,status:t,history:u?.phase??`idle`};for(let e of i)e()},m=e=>e.client===N&&e.selection===w,h=e=>f===e&&m(e),g=e=>{h(e)&&(f=void 0,p({}))},_=({id:e,content:t,phase:n,error:r})=>({id:e,content:t,phase:n,...r?{error:r}:{}}),v={submitting:[`accepted`,`failed`,`refused`],failed:[`submitting`],accepted:[],refused:[]},ee=(e,t,n)=>v[e.phase].includes(t)?(e.phase=t,e.error=n,e===c&&p({submission:_(e)}),!0):!1,y=e=>e.submission===c&&h(e),te=e=>y(e)&&e.submission.phase===`submitting`,ne=(e,t)=>e.delivery.state===`undispatched`?ee(e,`refused`,t):ee(e,`failed`,t??/* @__PURE__ */ Error(`This message may not have been sent. Retry to send it.`)),re=e=>{let t=c;return t?.phase===`submitting`&&ne(t,t.delivery.state===`uncertain`?void 0:Error(e)),t?.phase===`refused`&&t.onRefused?.(),c=void 0,t},b=zf({apiUrl:n.apiUrl,scope:`tenant`,fetchAstralBeamToken:n.fetchAstralBeamToken??{url:`/api/astralbeam/token`}}),x,ie,S,C=!1,w=0,ae=0,oe=async e=>{for(;m(e);){let e=u;try{await e?.completion}catch(t){if(e===u)throw t}if(e===u)return}},se=async e=>{if(await oe(e).catch(()=>void 0),!te(e))return!1;if(s.history===`failed`)throw Error(up);return!0},ce=new AbortController,T,le=!1,ue=[],E=/* @__PURE__ */ new Map,de=0,D=/* @__PURE__ */ new WeakMap,fe=e=>{for(let t of e){if(t.role!==`user`||E.get(t.id)?.attachmentParts||!t.parts.some(e=>`fileId`in e))continue;let e=t.parts.map(e=>Object.freeze({...e}));Object.freeze(e),E.set(t.id,{...E.get(t.id),attachmentParts:e}),de++}},pe=_f(),me=()=>{c&&ee(c,`accepted`)&&(s.thread&&p({thread:{...s.thread,hasMessages:!0}}),c.callbacks?.onAccepted?.())},he=e=>{let t=[...N.getSnapshot().messages],n=t.findLastIndex(e=>e.role===`user`);n!==-1&&(t[n]=xf([e])[0],fe([t[n]]),N.setMessagesManually(t),P&&Ue())},ge=/* @__PURE__ */ new Set,O=/* @__PURE__ */ new Map,_e=/* @__PURE__ */ new Map,k=/* @__PURE__ */ new Map,A=/* @__PURE__ */ new Map,ve=e=>{let t=O.get(e);return t?`live:${t}:${e}`:e},ye=e=>{let t=/* @__PURE__ */ new Map;for(let n of e.pending_interactions){let e=`live:${n.source_message_id}:${n.tool_call_id}`,r=yf(n.source_message_id,n.source_part_id,n.response_target_id),i=k.get(e)??k.get(r);i&&(t.set(r,i),O.get(n.tool_call_id)===n.source_message_id&&t.set(e,i))}k.clear();for(let[e,n]of t)k.set(e,n)},be=e=>{(s.auth.status!==`error`||s.auth.error!==e)&&n.streamCallbacks?.onError?.(e)},xe=e=>{if(e instanceof Error&&e.name===`AbortError`)return;let t=e instanceof Error?e:Error(String(e));p({error:t}),be(t)},Se=e=>{p({unavailableMcpConnections:s.unavailableMcpConnections?.filter(t=>t!==e)??[]})},j=async(e=!0)=>{let t=w,n=b.session.abortController.signal,r=await Kf(b);if(n.throwIfAborted(),e&&t!==w)throw new DOMException(`Conversation changed`,`AbortError`);return{apiUrl:b.apiUrl,astralBeamToken:r,cache:`no-store`,signal:e?AbortSignal.any([ce.signal,n]):n,fetchClient:(e,t)=>Xf({...b,input:e,init:t})}},Ce=0,we,Te=async()=>{let e=++Ce,t=w;if(s.thread?.agentId===null){p({capabilities:{attachments:!1}});return}let i=s.thread?s.thread.agentId:n.agentId;try{let n=await j();if(e!==Ce||t!==w)return;let a=await xr(i?{agentId:i}:{},n);if(e!==Ce||t!==w)return;let o=a.capabilities?.attachments!==!1;p({capabilities:{attachments:o}}),r?.(`mount`,`agent capabilities resolved`,{attachments:o})}catch(e){r?.(`error`,`agent capabilities could not be resolved; keeping the defaults`,e)}},Ee=/* @__PURE__ */ new Map,M=/* @__PURE__ */ new Set,De=/* @__PURE__ */ new Set,Oe=0,ke=()=>{Oe++;for(let e of Ee.values())e();Ee.clear(),M.clear(),De.clear()},Ae=async(e,t)=>{if(!o().onRenderWidget)return{widget:e.widget,rendered:!1};let n=w,r=Oe,i=o().widgets??{};if(!Object.hasOwn(i,e.widget))throw Error(`Unknown widget "${e.widget}"`);let a=i[e.widget],c=await Af(a?.parameters,e.props??{});if(n!==w||r!==Oe||s.thread?.role===`viewer`)return{widget:e.widget,rendered:!1};if(a!==o().widgets?.[e.widget])return Ae(e,t);if(c==null)throw Error(`Props for widget "${e.widget}" failed validation`);let l=o().onRenderWidget;if(!l)return{widget:e.widget,rendered:!1};Ee.get(t)?.(),Ee.delete(t);let u,d=l({widget:e.widget,props:c,toolCallId:t,release:()=>{Ee.get(t)===u&&Ee.delete(t)}});return d&&(u=d,Ee.set(t,d)),M.add(t),{widget:e.widget,rendered:!0}},je=e=>Object.freeze(e.map(e=>{let t=E.get(e.id),n=D.get(e);if(n&&n.presentation===t)return n.message;let r=t?.attachmentParts??e.parts,i=t?.renderIds,a=r.map(t=>{if(t.type!==`tool-call`||t.name!==`render_widget`||t.state!==`complete`||!t.input)return t;let n=t,r=yf(e.id,t.id),a=n.applicationPartId?yf(e.id,n.applicationPartId,n.responseTargetId):r,o=n.upstreamToolCallId,s=n.widgetRenderId??i?.get(r)??i?.get(a)??(o&&O.get(o)===e.id&&M.has(o)?o:t.id);return(i?.get(r)!==s||i.get(a)!==s)&&(i=new Map(i).set(r,s).set(a,s)),n.widgetRenderId===s?t:Object.freeze({...t,widgetRenderId:s})});a.some((e,t)=>e!==r[t])&&(Object.freeze(a),r=a),i&&i!==t?.renderIds&&(t={...t,renderIds:i},E.set(e.id,t),de++);let o=r===e.parts?e:Object.freeze({...e,parts:r});return D.set(e,{presentation:t,message:o}),o})),Me=e=>{if(s.thread?.role!==`viewer`)for(let t of e)for(let e of t.parts){if(e.type!==`tool-call`||e.name!==`render_widget`||e.state!==`complete`||!e.input)continue;let t=e.widgetRenderId??e.id;if(M.has(t)||De.has(t))continue;De.add(t);let n=w,i=Oe,{widgets:a,onRenderWidget:c}=o();Ae(e.input,t).catch(e=>r?.(`error`,`Saved widget could not be rendered`,e)).finally(()=>{n===w&&i===Oe&&(De.delete(t),(a!==o().widgets||c!==o().onRenderWidget)&&Me(s.messages))})}},Ne=()=>{let e=w;return Mf(o().widgets??{},n.tools??{},Ae,r,(t,r,i)=>{let a=ae,o=N,c=S,l=b.apiUrl;return()=>{let u=n.tools&&Object.hasOwn(n.tools,t)?n.tools[t]:void 0;if(e!==w||a!==ae||o!==N||c!==S||l!==b.apiUrl||s.thread?.role===`viewer`||!i||!ge.has(i)||!u||u.parameters!==r.parameters)throw new DOMException(`Host tool authority changed`,`AbortError`);return u}}).map(e=>{if(!e.execute)return e;let t=e.execute;return{...e,execute:async(e,n)=>{let r=n?.toolCallId;if(!r||!ge.has(r))throw Error(`A saved tool call cannot execute again. Send a new message to request it.`);let i=k,a=ve(r),o=S,s=b.apiUrl;try{let r=await t(e,n);return S===o&&b.apiUrl===s&&i.set(a,{outcome:`succeeded`,output:r??null}),r}catch(e){throw!(e instanceof Error&&jf in e)&&S===o&&b.apiUrl===s&&i.set(a,{outcome:`unknown`,output:{error:e instanceof Error?e.message:String(e)}}),e}}}})},Pe=()=>{let e=Ne(),t=e.map(e=>{let t=e.metadata?.title;return{name:e.name,title:typeof t==`string`&&t.length>0?t:void 0}});return dp(s.agentTools,t)||p({agentTools:t}),e},Fe=()=>n.debug?{debug:!0}:{},Ie=async(e,t,n)=>{if(!h(n))throw new DOMException(`Request cancelled`,`AbortError`);let r=s.thread;if(!r||typeof e.body!=`string`)throw Error(`Open a conversation before sending.`);let i=JSON.parse(e.body),a=yr(),o,c=i.messages.at(-1)?.role===`user`&&n.kind===`submission`&&te(n)?n.submission:void 0,l=c?.delivery;if(c)o={...i,threadId:r.id,resume:void 0,parentRunId:void 0,messages:[i.messages.at(-1)],tools:l?.state===`uncertain`?l.tools:i.tools,forwardedProps:{...i.forwardedProps,clientId:pe}};else{Ke();let e=await bf(r.id,t,void 0,O);if(!h(n))throw new DOMException(`Request cancelled`,`AbortError`);p({thread:vf(e.thread,e.messages.length>0)}),ye(e);let s=e.pendingInteractions.filter(e=>k.has(ve(e.toolCallId))),c=s.find(e=>e.toolCallId===i.messages.at(-1)?.toolCallId)??s[0],l=e.pendingInteractions.flatMap(e=>{let t=k.get(ve(e.toolCallId));return t&&e.sourceMessageId===c?.sourceMessageId?[{source_message_id:e.sourceMessageId,source_part_id:e.sourcePartId,response_target_id:e.responseTargetId,...t}]:[]});if(l.length===0)return new Response(``,{headers:{"Content-Type":`text/event-stream`}});a=Mr(r.id),o={client_id:pe,run_id:i.runId,...i.parentRunId?{parent_run_id:i.parentRunId}:{},results:l}}ge.clear(),p({activeToolCallIds:[]});let u=new Headers(e.headers);if(c&&u.set(`Idempotency-Key`,c.key),!h(n))throw new DOMException(`Request cancelled`,`AbortError`);c&&c.delivery.state===`undispatched`&&(c.delivery={state:`uncertain`,tools:i.tools});let d=await fr(a,{...t,...e,headers:u,body:JSON.stringify(o)}).catch(e=>{if(!h(n))throw e;c&&l?.state===`undispatched`&&or(e)&&(e.status===400||e.status===413||e.status===429)&&(c.delivery={state:`undispatched`});let t=or(e)?e.body?.usage_limit:void 0;throw t&&p({usageLimitReached:{name:t.name,resetsAt:t.resets_at}}),e});if(!h(n))throw new DOMException(`Request cancelled`,`AbortError`);if(d.headers.get(`Content-Type`)?.includes(`application/json`)){let e=await d.json();if(!h(n))throw new DOMException(`Request cancelled`,`AbortError`);if(p({thread:{...s.thread,version:e.thread_version},...e.usage_limit?{usageLimitReached:{name:e.usage_limit.name,resetsAt:e.usage_limit.resets_at}}:{}}),c){let i=await bf(r.id,t,void 0,O);if(!h(n))throw new DOMException(`Request cancelled`,`AbortError`);let a=i.messages.find(t=>t.id===e.accepted_message_id);a&&he(a),me()}return new Response(``,{headers:{"Content-Type":`text/event-stream`}})}return d},Le=rd(()=>sr(yr(),b.apiUrl),async()=>{let e=f;if(!e||!h(e))throw new DOMException(`Request cancelled`,`AbortError`);let t=await j();if(!h(e))throw new DOMException(`Request cancelled`,`AbortError`);return{fetchClient:(n,r)=>Ie(r??{},{...t,signal:r?.signal??t.signal},e)}}),Re=Le.connect;Le.connect=async function*(...e){try{for await(let t of Re(...e)){if(t.type===X.TOOL_CALL_START&&t.parentMessageId&&O.set(t.toolCallId,t.parentMessageId),t.type!==X.MESSAGES_SNAPSHOT){yield t;continue}let e;yield{...t,messages:t.messages.map(t=>t.role===`assistant`?(e=_e.get(t.id),e&&t.toolCalls?{...t,toolCalls:t.toolCalls.map(t=>({...t,id:e?.get(t.id)??t.id}))}:t):t.role===`tool`?{...t,toolCallId:e?.get(t.toolCallId)??t.toolCallId}:(e=void 0,t))}}}catch(e){throw e instanceof Error&&or(e.cause)?e.cause:e}};let ze=()=>{let e=new ff({connection:{...Le,hydrate:(t,n)=>{let r=Be;if(!r)return Promise.resolve({messages:[],activeRun:null,interrupts:null,page:{truncated:!1}});let i=n?.before!==void 0,a=i?u?.owner:{client:e,selection:w},o=()=>a!==void 0&&u?.owner===a&&m(a),c=(async()=>{let t=await bf(r,await j(),n?.before,O);for(;n?.before&&t.messages.every(e=>e.role===`tool`)&&t.page_after;){let e=await bf(r,await j(),t.page_after,O);t={...e,messages:[...e.messages,...t.messages]}}if(!o())throw new DOMException(`Conversation changed`,`AbortError`);i||ye(t),ue=i?[...t.messages,...ue]:t.messages;let a=new Set(t.messages.map(e=>e.id)),c=xf(ue,i?s.pendingInteractions:t.pendingInteractions,O).filter(e=>a.has(e.id));if(fe(c),i)p({messagesCursor:t.page_after??void 0});else{t.thread.role===`viewer`&&ke();let n=s.thread?.agentId!==t.thread.agent_id;p({thread:vf(t.thread,t.messages.length>0),messagesCursor:t.page_after??void 0,pendingInteractions:t.pendingInteractions}),n&&Te(),c.length===0&&e.setMessagesManually([])}return{messages:c,activeRun:null,interrupts:null,page:t.page_after?{truncated:!0,cursor:t.page_after}:{truncated:!1}}})();if(!i&&a){let e=c.then(()=>`idle`,()=>`failed`).then(e=>(u&&o()&&(u.phase=e,P&&Ue(),p({})),c));u={owner:a,phase:s.messages.length>0||s.thread?.hasMessages===!1?`refreshing`:`loading`,completion:e},e.catch(()=>void 0),p({olderMessagesLoading:!1})}return c}},threadId:Be??pe,persistence:!0,history:{pageSize:100},queue:`drop`,tools:Pe(),forwardedProps:Fe(),onInterruptStateChange:t=>{N===e&&r?.(`tool`,`interrupt state changed`,t)},onCustomEvent:(t,n)=>{if(N!==e)return;if(t===`astralbeam_thread`){let e=n;if(s.thread?.id===e.threadId){if(e.acceptedMessage&&c?.phase===`submitting`&&he(e.acceptedMessage),e.acceptedMessageId&&me(),e.saved)for(let t of e.executableToolCallIds??[])ge.has(t)||k.delete(ve(t)),ge.add(t);p({thread:{...s.thread,version:e.version},activeToolCallIds:[...ge]})}return}if(t===`astralbeam_mcp_tools`){let e=n,t={};for(let n of e.tools??[])typeof n.name==`string`&&typeof n.title==`string`&&(t[n.name]=n.title);p({serverToolTitles:t,unavailableMcpConnections:e.unavailable??[]});return}let i=n;if(t===`astralbeam.usage_limit.reached`&&typeof i?.name==`string`&&typeof i.resetsAt==`string`){p({usageLimitReached:{name:i.name,resetsAt:i.resetsAt}});return}let a=n?.state;t===`astralbeam.sandbox.status`&&(a===`starting`||a===`ready`||a===`error`)?(r?.(`sandbox`,`sandbox ${a}`),p({sandboxStatus:a})):r?.(`stream`,`custom event "${t}"`,n)},onChunk:t=>{N===e&&(t.type===X.RUN_STARTED&&p({serverToolTitles:{},unavailableMcpConnections:[]}),n.streamCallbacks?.onChunk?.(t))},onResponse:t=>{N===e&&n.streamCallbacks?.onResponse?.(t)},onFinish:t=>{N===e&&n.streamCallbacks?.onFinish?.(t)},onError:t=>{N===e&&(c?.phase!==`submitting`&&t.name!==`AbortError`&&p({error:t}),be(t))}});return e},Be,N=ze(),P,Ve,He=-1,Ue=()=>{let e=N.getSnapshot(),t=Ve!==e.messages||He!==de;if(!t&&d===e.status)return;let n={};d!==e.status&&e.status===`submitted`&&(n.usageLimitReached=void 0),d=e.status,t&&(n.messages=je(e.messages),n.sandbox=lp(n.messages),Ve=e.messages,He=de),p(n),t&&Me(s.messages)},We=()=>{if(!P){let e=N,t=w;P=e.subscribeSnapshot(()=>{N===e&&t===w&&Ue()}),Ue(),Me(s.messages)}N.attach()},Ge=e=>{let t=N;f=void 0,u=void 0,P?.(),P=void 0,Ve=void 0,N=ze(),e&&N.setMessagesManually(e),d=`ready`,t.stop(),t.detach(),ge.clear(),p({activeToolCallIds:[]}),C&&We(),t.dispose()},Ke=()=>{_e.clear(),N.setMessagesManually(N.getSnapshot().messages.map(e=>{let t=/* @__PURE__ */ new Map,n=e.parts.map(n=>{if(n.type!==`tool-call`||tp(n).providerExecuted)return n;let r=n,i=r.upstreamToolCallId??n.id;if(O.get(i)===e.id&&!ep(n))return n;let a=yf(e.id,r.applicationPartId??i,r.responseTargetId);return t.set(i,a),{...n,upstreamToolCallId:i,id:a,...n.name===`render_widget`?{widgetRenderId:r.widgetRenderId??E.get(e.id)?.renderIds?.get(yf(e.id,n.id))??n.id}:{}}});return t.size&&_e.set(e.id,t),{...e,parts:n}}))},qe=e=>{let t=s.thread?.id,n=re(`The conversation changed before this was sent.`);t&&(n?.phase===`failed`?l.set(t,n):l.delete(t),A.set(t,k)),w++,u=void 0,Be=e,ce.abort(),ce=new AbortController,k=A.get(e??``)??/* @__PURE__ */ new Map,_e.clear(),O.clear(),ue=[],E.clear(),D=/* @__PURE__ */ new WeakMap,de++,ke(),p({thread:void 0,messages:[],submission:void 0,error:void 0,sandbox:{files:[],commands:[]},sandboxStatus:void 0,usageLimitReached:void 0,pendingInteractions:[],serverToolTitles:{},unavailableMcpConnections:[],messagesCursor:void 0,olderMessagesLoading:!1}),Ge()},Je=async(e,t=!1)=>{qe(e);let r=w;c=l.get(e),c&&p({submission:_(c)});try{if(C||We(),await oe({client:N,selection:r}),r!==w)return;T&&Cf(T,e)}catch(e){if(r!==w)return;t&&(n.threadId===void 0||n.threadId===`auto`)&&or(e)&&e.status===404?Ye():xe(e)}},Ye=()=>{qe(),C&&Te(),T?Cf(T,null):le=!0},Xe=(e=!1)=>{let t=n.threadId;if(t===void 0||t===`auto`){if(!T)return;t=Cf(T)}t&&t!==`new`?t===s.thread?.id&&T?Cf(T,t):Je(t,e):e||Ye()},Ze=async e=>{if(s.thread)return;let t=await j();if(!te(e))throw new DOMException(`Send cancelled`,`AbortError`);let r=await Cr(n.agentId?{agent_id:n.agentId}:{},t);if(!te(e))throw new DOMException(`Send cancelled`,`AbortError`);Be=r.id,p({thread:vf(r,!1)}),Te(),T&&Cf(T,r.id)},Qe=async(e=!0)=>{if(!s.thread)return;let t=w;try{N.detach(),We(),await oe({client:N,selection:t}),e&&t===w&&p({error:void 0})}catch(e){if(t!==w)return;or(e)&&e.status===404?Ye():xe(e)}},F=async()=>{if(!N.getHasOlderMessages()||s.olderMessagesLoading||s.history!==`idle`||c?.phase===`submitting`)return;let e=w;p({olderMessagesLoading:!0});try{await N.loadOlderMessages(),e===w&&P&&Ue()}catch(t){e===w&&xe(t)}finally{e===w&&p({olderMessagesLoading:!1})}},$e=async e=>{let t=s.thread;if(!t||t.role!==`manager`)return!1;let n=w;try{let r=await Dr(t.id,{title:e,expected_version:t.version},await j());if(n!==w)return!1;let i=vf(r,t.hasMessages);return p({thread:i}),!0}catch(e){return n===w&&xe(e),!1}},et=async(e=s.thread)=>{if(!e||e.role!==`manager`)return!1;let t=w;try{return await kr(e.id,{expected_version:String(e.version)},await j()),t===w&&s.thread?.id===e.id&&Ye(),!0}catch(e){return t===w&&xe(e),!1}},I=async e=>{let t=w;if(f||c?.phase===`submitting`||N.getIsLoading()){xe(/* @__PURE__ */ Error(`Wait for this client's current request to finish before responding.`));return}let n=Bf(b),r=ve(e.toolCallId),i=s.pendingInteractions.find(t=>t.toolCallId===e.toolCallId),a=!(`tool`in e)&&i&&(s.thread?.role===`manager`||n.status===`ready`&&i.targetTenantUserId===n.currentUser.user.id),o=`tool`in e&&e.tool===`ask_questionnaire`&&n.status===`ready`&&i?.targetTenantUserId===n.currentUser.user.id;if(s.thread?.role===`viewer`||!ge.has(e.toolCallId)&&!o&&!a&&!k.has(r)){xe(/* @__PURE__ */ Error(`This tool call belongs to another session and cannot be executed here.`));return}if(!k.has(r)){if(a)k.set(r,{outcome:`unknown`,output:null});else if(`tool`in e){let t=e.output;k.set(r,{outcome:e.state===`output-error`?`failed`:`succeeded`,output:t??null})}}let l={kind:`tool-result`,client:N,selection:t};f=l;try{if(p({}),!h(l)||(Ke(),!h(l)))return;if(i){if(l.client.stop(),await Qe(!1),!h(l))return;await l.client.append({role:`tool`,toolCallId:e.toolCallId,content:JSON.stringify(k.get(ve(e.toolCallId)))})}else`tool`in e&&await l.client.addToolResult(e);h(l)&&await Qe(!1)}finally{g(l)}},tt=e=>I({toolCallId:e}),nt=async e=>{if(e!==c||e.phase!==`submitting`)return _(e);let t={kind:`submission`,submission:e,client:N,selection:w};f=t;try{if(await Kf(b),!await se(t)||(await Ze(t),!te(t))||(e.callbacks?.onThreadReady?.(s.thread.id),!te(t))||(Ke(),!await se(t))||(await t.client.sendMessage(e.content),!y(t)))return _(e);ne(e,t.client.getError()),y(t)&&await Qe(!1)}catch(n){if(!y(t))return _(e);let r=n instanceof Error?n:Error(String(n));r.name===`AbortError`?ne(e):ne(e,r)&&be(r)}finally{g(t)}return _(e)},rt=async(e,t)=>{let n=f||c?.phase===`submitting`||N.getIsLoading()?`Wait for this client's current request to finish before sending.`:s.history===`loading`?`Wait for this conversation to load before sending.`:s.history===`failed`?up:s.thread?.agentId===null?`This conversation’s agent is unavailable. Start a new conversation to continue.`:s.thread?.role===`viewer`?`You have read-only access to this conversation.`:c?.phase===`failed`?`The previous message’s acceptance is unconfirmed. Retry that message before sending different text, or start a new conversation.`:void 0;if(n)return{id:_f(),content:e,phase:`refused`,error:Error(n)};let r={id:_f(),content:e,phase:`submitting`,key:_f(),delivery:{state:`undispatched`},callbacks:t};c=r,p({submission:_(r),error:void 0,olderMessagesLoading:!1}),N.stop(),ge.clear(),Ke(),O.clear(),p({activeToolCallIds:[]});let i=new Promise(e=>r.onRefused=e);return Promise.race([nt(r),i.then(()=>_(r))])},it=async()=>{let e=c;if(!f&&!N.getIsLoading()&&e&&ee(e,`submitting`))return p({error:void 0}),nt(e)},at=()=>{let e=Bf(b),t=s.auth;if(e.status===`ready`){let t=Wf(e.currentUser);S!==void 0&&S!==t&&(re(`The account changed before this was sent.`),l.clear(),A.clear(),k.clear(),qe(),T=void 0),S=t;let r=JSON.stringify(Sf(n)),i=`astralbeam:thread:${n.apiUrl??`https://astralbeam.ai/api`}:${t}:session:${r}`;T!==i&&(T!==void 0&&qe(),T=i,le?(Cf(i,null),le=!1):Xe(!0)),we!==t&&(we=t,Te())}p({auth:e}),e.status===`error`&&(t.status!==`error`||t.error!==e.error)&&n.streamCallbacks?.onError?.(e.error)},ot=()=>{if(C)return;C=!0;let e=ce.signal.aborted&&N.getIsHydrating();N.updateOptions({tools:Pe()}),ce.signal.aborted&&(ce=new AbortController),ie=Vf(b,at),at(),x=Zf(b),e?Ge(N.getSnapshot().messages):We()};return t||ot(),{start:ot,getState:()=>s,getOptions:()=>n,attachView:e=>{if(a)throw Error(`This chat session already has a view attached`);let t={options:e},n=()=>{N.updateOptions({tools:Pe()}),Me(s.messages)};return ke(),a=t,n(),{update:e=>{if(a!==t)return;let r=t.options;t.options=e,(r.widgets!==e.widgets||r.onRenderWidget!==e.onRenderWidget)&&n()},dispose:()=>{a===t&&(ke(),a=void 0,n())}}},subscribe:e=>(i.add(e),()=>i.delete(e)),updateOptions:e=>{let t=n.agentId,i=n.apiUrl,a=n.threadId,o=Sf(n),{widgets:c,onRenderWidget:u}=n;n={...n,...e};let d=Sf(n)!==o;r=gf(n.debug),Uf(b,{apiUrl:n.apiUrl,fetchAstralBeamToken:n.fetchAstralBeamToken??{url:`/api/astralbeam/token`}}),b.debug=r,N.updateOptions({tools:Pe(),forwardedProps:Fe()}),n.apiUrl===i?d?(le=!1,(!s.thread||n.threadId!==s.thread.id)&&qe(),T=void 0,at()):n.threadId!==a&&Xe():(re(`The chat service changed before this was sent.`),l.clear(),A.clear(),k.clear(),qe(),T=void 0,at()),(c!==n.widgets||u!==n.onRenderWidget)&&Me(s.messages),C&&(n.agentId!==t||n.apiUrl!==i||d)&&Te()},sendMessage:rt,retry:it,addToolResult:I,stop:()=>{ae++;let e=c,t=f;e?.phase===`submitting`&&ne(e),N.stop(),t&&g(t),e?.phase===`refused`&&e.onRefused?.()},retryAuthentication:()=>{Kf({...b,force:!0}).catch(()=>void 0)},reload:async()=>{let e=w;if(await Qe(),e!==w||s.error)return;let t=/* @__PURE__ */ new Set;for(;e===w;){let e=s.pendingInteractions.find(e=>!t.has(e.sourceMessageId)&&k.has(ve(e.toolCallId)));if(!e||(t.add(e.sourceMessageId),await I({toolCallId:e.toolCallId}),s.error))return}},searchThreads:async(e=``,t,n)=>{let r=await j(),i=await Tr({q:e,page_size:50,...t?{page_after:t}:{}},{...r,signal:AbortSignal.any([r.signal,...n?[n]:[]])});return{items:i.items.map(e=>vf(e)),page_after:i.page_after}},openThread:Je,renameThread:$e,deleteThread:et,refreshThread:()=>Qe(),loadOlderMessages:F,uploadAttachment:async({data:e,filename:t,mimeType:r})=>{let i=s.thread?s.thread.agentId:n.agentId,[a,o]=await Promise.all([e,j(!1)]);return gr({...i?{agentId:i}:{},type:r.startsWith(`image/`)?`image`:`document`,source:{type:`data`,value:a,mimeType:r},metadata:{filename:t}},o)},getThreadAttachment:async(e,t)=>{if(!e.threadId&&!t?.preview)throw Error(`A conversation ID is required to download files.`);return(await vr({...e,delivery:`direct`},{...await j(!!e.threadId||!t?.preview),headers:t?.preview?{"X-File-Preview":`true`}:{}})).blob()},getMcpCatalog:async()=>Ir(await j(!1)),manageMcpConnection:async e=>{let t=await Qf(e,await j(!1));return`id`in e?Se(e.id):t&&`id`in t&&Se(t.id),t},authorizeMcpConnection:async e=>{let t=await $f(e,()=>j(!1));Se(t)},abandonToolCall:tt,reset:()=>{if(r?.(`status`,`conversation reset`),Ye(),s.auth.status===`ready`){let e=JSON.stringify([S,Sf(n)]),t=n.apiUrl??`https://astralbeam.ai/api`;Df(t,e,``,``),Df(t,e,``,``,`sent`),Of({apiUrl:t,identity:e,threadId:``,update:()=>[]}).catch(e=>r?.(`error`,`Draft could not be cleared`,e))}a?.options.onReset()},dispose:()=>{re(`The chat closed before this was sent.`),f=void 0,u=void 0,P?.(),P=void 0,N.detach(),ke(),N.stop(),ce.abort(),w++,Ce++,we=void 0,x?.(),ie?.(),Yf(b),C=!1,queueMicrotask(()=>{C||(N.dispose(),T=void 0,E.clear(),D=/* @__PURE__ */ new WeakMap)}),i.clear()}}}const pp=e=>e[Symbol.toStringTag],mp=(e,t,n)=>{let{alg:r}=e;if(t.use!==void 0){let e=n===`sign`||n===`verify`?`sig`:`enc`;if(t.use!==e)throw TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(t.alg!==void 0&&t.alg!==r)throw TypeError(`Invalid key for this operation, its "alg" must be "${r}" when present`);if(Array.isArray(t.key_ops)){let r=n===`encrypt`||n===`decrypt`?e.ops?.[n===`encrypt`?0:1]:n;if(r&&!t.key_ops.includes(r))throw TypeError(`Invalid key for this operation, its "key_ops" must include "${r}" when present`)}};async function hp(e,t,n){let{alg:r,secret:i}=e,a=n===`decrypt`||n===`sign`;if(i&&t instanceof Uint8Array)return t;let o,s;if(Ja(t)){if(o=Op(t),typeof o.kty!=`string`)throw Sp(r,t,i);if(!(i?o.kty===`oct`&&typeof o.k==`string`:o.kty!==`oct`&&(a?o.kty===`AKP`&&typeof o.priv==`string`||typeof o.d==`string`:o.d===void 0&&o.priv===void 0)))throw TypeError(i?`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`:`JSON Web Key for this operation must be a ${a?`private`:`public`} JWK`);if(mp(e,o,n),o.kty===`oct`)return Ka(o.k);if(!Object.isFrozen(t)){let{key_ops:e}=t;Array.isArray(e)&&Object.freeze(e),Object.freeze(t)}}else{if(!bp(t))throw Sp(r,t,i);let e=i?`secret`:a?`private`:`public`;if(t.type!==e&&(i||[`secret`,`public`,`private`].includes(t.type)))throw TypeError(`${pp(t)} instances must be of type "${e}" for the ${r} algorithm`);if(vp(t))return t;if(s=t,s.type===`secret`)return s.export()}gp||=/* @__PURE__ */ new WeakMap;let c=t,l=gp.get(c);if(l?.[r])return l[r];if(l||gp.set(c,l={}),s&&typeof s.toCryptoKey==`function`){let t=s.type===`public`,n=_p[s.asymmetricKeyDetails?.namedCurve],i=e.resolve?.({crv:n,asymmetricKeyType:s.asymmetricKeyType})??e.subtle;return l[r]=s.toCryptoKey(i,t,e.usages[+!t])}return o??=s.export({format:`jwk`}),o.alg=r,l[r]=await kp(e,o)}let gp;const _p={__proto__:null,prime256v1:`P-256`,secp384r1:`P-384`,secp521r1:`P-521`},vp=e=>{if(e?.[Symbol.toStringTag]===`CryptoKey`)return!0;try{return e instanceof CryptoKey}catch{return!1}},yp=e=>e?.[Symbol.toStringTag]===`KeyObject`,bp=e=>vp(e)||yp(e);function xp(e,t,...n){if(n.length>2){let t=n.pop();e+=`one of type ${n.join(`, `)}, or ${t}.`}else n.length===2?e+=`one of type ${n[0]} or ${n[1]}.`:e+=`of type ${n[0]}.`;return t==null?e+=` Received ${t}`:typeof t==`function`&&t.name?e+=` Received function ${t.name}`:typeof t==`object`&&t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}function Sp(e,t,n){let r=[`CryptoKey`,`KeyObject`,`JSON Web Key`];return n&&r.push(`Uint8Array`),TypeError(xp(`Key for the ${e} algorithm must be `,t,...r))}const Cp=(e,t=`algorithm.name`)=>/* @__PURE__ */ TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function wp(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function Tp(e,t){let{modulusLength:n}=t.algorithm;if(typeof n!=`number`||n<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}function Ep(e,t,n){let r=e.algorithm;if(r.name!==t.name)throw Cp(t.name);if(t.hash&&r.hash?.name!==t.hash)throw Cp(t.hash,`algorithm.hash`);if(t.namedCurve&&r.namedCurve!==t.namedCurve)throw Cp(t.namedCurve,`algorithm.namedCurve`);if(t.length!==void 0&&r.length!==t.length)throw Cp(t.length,`algorithm.length`);wp(e,n)}function Dp(e){return{__proto__:null,...e}}function Op(e){let t=Dp(e);if(t.ext!==void 0&&typeof t.ext!=`boolean`)throw TypeError(`"ext" (Extractable) Parameter must be a boolean`);if(t.key_ops!==void 0){let e=t.key_ops,n=Array.isArray(e)?[...e]:void 0;if(!n||n.some(e=>typeof e!=`string`)||new Set(n).size!==n.length)throw TypeError(`"key_ops" (Key Operations) Parameter must be an array of unique strings`);t.key_ops=n}return t}async function kp(e,t,n){if(!e.kty.includes(t.kty))throw new Ua(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`);let r=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,i=!!(t.d||t.priv),a={...t,ext:n??t.ext};return a.kty!==`AKP`&&delete a.alg,delete a.use,crypto.subtle.importKey(`jwk`,a,r,a.ext??!i,t.key_ops??e.usages[+!!i])}async function Ap(e,t,n,r=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey(`raw`,e,t,r,[n])),Ep(e,t,n),e}function jp(e){let t={__proto__:null};for(let n in e)t[n]={...e[n],alg:n};return t}const Mp=[[`verify`],[`sign`]];function Np(e){let t={name:`HMAC`,hash:`SHA-${e}`};return{kty:[`oct`],secret:!0,subtle:t,signing:t,usages:Mp}}function Pp(e,t){let n={name:t?`RSA-PSS`:`RSASSA-PKCS1-v1_5`,hash:`SHA-${e}`};return{kty:[`RSA`],subtle:n,signing:t?{...n,saltLength:t}:n,usages:Mp,minRsaBits:2048}}function Fp(e,t){return{kty:[`EC`],crv:e,subtle:{name:`ECDSA`,namedCurve:e},signing:{name:`ECDSA`,hash:`SHA-${t}`},usages:Mp}}function Ip(){let e={name:`Ed25519`};return{kty:[`OKP`],crv:`Ed25519`,subtle:e,signing:e,usages:Mp}}function Lp(e){let t={name:`ML-DSA-${e}`};return{kty:[`AKP`],subtle:t,signing:t,usages:Mp}}const Rp=jp({HS256:Np(256),HS384:Np(384),HS512:Np(512),RS256:Pp(256),RS384:Pp(384),RS512:Pp(512),PS256:Pp(256,32),PS384:Pp(384,48),PS512:Pp(512,64),ES256:Fp(`P-256`,256),ES384:Fp(`P-384`,384),ES512:Fp(`P-521`,512),EdDSA:Ip(),Ed25519:Ip(),"ML-DSA-44":Lp(44),"ML-DSA-65":Lp(65),"ML-DSA-87":Lp(87)});function zp(e){let t=typeof e==`string`?Rp[e]:void 0;if(!t)throw new Ua(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}const Bp=e=>Math.floor(e.getTime()/1e3),Vp={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},Hp=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function Up(){throw TypeError(`Invalid time period format`)}function Wp(e){typeof e!=`string`&&Up();let t=Hp.exec(e);(!t||t[4]&&t[1])&&Up();let n=parseFloat(t[2]),r=Math.round(n*Vp[t[3][0].toLowerCase()]);return Number.isFinite(r)||Up(),t[1]===`-`||t[4]===`ago`?-r:r}function Gp(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}function Kp(e,t){if(typeof t!=`string`)throw TypeError(`"${e}" claim must be a string`)}function qp(e){if(typeof e!=`string`&&(!Array.isArray(e)||Array.from(e).some(e=>typeof e!=`string`)))throw TypeError(`"aud" claim must be a string or an array of strings`)}function Jp(e,t){return typeof e==`number`?Gp(t,e):e instanceof Date?Gp(t,Bp(e)):Bp(/* @__PURE__ */ new Date)+Wp(e)}let Yp;function Xp(e){return Yp.get(e)}function Zp(e){let t=Xp(e);for(let e of[`iat`,`nbf`,`exp`]){let n=t[e];if(typeof n==`number`&&!Number.isFinite(n))throw TypeError(`"${e}" claim must be a finite number`)}return Pa.encode(JSON.stringify(t))}var Qp=class{constructor(e={}){if(!Ja(e))throw TypeError(`JWT Claims Set MUST be an object`);(Yp||=/* @__PURE__ */ new WeakMap).set(this,structuredClone(e))}setIssuer(e){return Kp(`iss`,e),Xp(this).iss=e,this}setSubject(e){return Kp(`sub`,e),Xp(this).sub=e,this}setAudience(e){return qp(e),Xp(this).aud=e,this}setJti(e){return Kp(`jti`,e),Xp(this).jti=e,this}setNotBefore(e){return Xp(this).nbf=Jp(e,`setNotBefore`),this}setExpirationTime(e){return Xp(this).exp=Jp(e,`setExpirationTime`),this}setIssuedAt(e){let t=Xp(this);return t.iat=e===void 0?Bp(/* @__PURE__ */ new Date):typeof e==`string`?Gp(`setIssuedAt`,Bp(/* @__PURE__ */ new Date)+Wp(e)):Jp(e,`setIssuedAt`),this}};async function $p(e,t,n){let[r,i,a,o]=e,s=``;if(i!==void 0){let e=to(Wa,i);i=e[0],s=qa(e[1])}if(a!==void 0&&(a=to(Wa,a)[0]),!i&&!a)throw new Wa(`either setProtectedHeader or setUnprotectedHeader must be called before #sign()`);if(!Ya(i,a))throw new Wa(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let c={...i,...a};Qa(Wa,i);let l=eo(i,$a(Wa,Za,o,i,c));l||n?.();let{alg:u}=c;if(typeof u!=`string`||!u)throw new Wa(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);let d=zp(u),f=``,p=r,m;if(l){let t=e[4];t?(f=t[0]??=qa(r),p=t[1]??=za(f)):(f=qa(r),m=Pa.encode(`${s}.${f}`))}m??=La(za(s),za(`.`),p);let h=await Ap(await hp(d,t,`sign`),d.subtle,`sign`);d.minRsaBits&&Tp(d.alg,h);let g={signature:qa(new Uint8Array(await crypto.subtle.sign(d.signing,h,m))),payload:f};return i&&(g.protected=s),a&&(g.header=a),[g,l]}async function em(e,t,n,r,i){let[a]=await $p([e,t,void 0,n],r,i);return`${a.protected}.${a.payload}.${a.signature}`}const tm=Qp;var nm=class extends tm{#e;setProtectedHeader(e){return Xa(this.#e,`setProtectedHeader`),this.#e=e,this}async sign(e,t){return em(Zp(this),this.#e,t?.crit,e,()=>{throw new Ga(`JWTs MUST NOT use unencoded payload`)})}};const rm=`astralbeam`,im=16384,am=8192,om=/^key_[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}_[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}_abo_[A-Za-z]{64}$/,sm=/^limit_[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}_[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,cm=[`id`,`name`,`metadata`],lm=[`id`,`name`,`admin`,`metadata`],um=new TextEncoder;function dm(e){if(!om.test(e))throw Error(`apiKey must match key_<organizationId>_<id>_abo_<secret>`);let t=e.lastIndexOf(`_abo_`),n=e.slice(0,t),r=e.slice(t+1);return{keyId:n,organizationId:n.slice(4,n.indexOf(`_`,4)),keySecret:r}}function fm(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function pm(e){return e===null||typeof e==`string`||typeof e==`boolean`?!0:typeof e==`number`?Number.isFinite(e):Array.isArray(e)?e.every(pm):fm(e)&&Object.values(e).every(pm)}function mm(e,t,n){if(!fm(t))throw Error(`${e} must be an object`);let r=n?lm:cm;for(let n of Object.keys(t))if(!r.includes(n))throw Error(`${e} has an unknown field "${n}"`);let{id:i,name:a,admin:o,metadata:s}=t;if(typeof i!=`string`||i.length<1||i.length>255)throw Error(`${e}.id must be a 1-255 character string`);if(a!==void 0&&typeof a!=`string`)throw Error(`${e}.name must be a string`);if(n&&o!==void 0&&typeof o!=`boolean`)throw Error(`${e}.admin must be a boolean`);if(s!==void 0&&!(fm(s)&&pm(s)))throw Error(`${e}.metadata must be a JSON object`)}function hm(e,t){mm(`user`,e,!0),mm(`tenant`,t,!1);let n=JSON.stringify({user:e,tenant:t});if(um.encode(n).byteLength>am)throw Error(`user and tenant must not exceed ${am} bytes`);return JSON.parse(n)}async function gm(e){let t=await crypto.subtle.digest(`SHA-256`,um.encode(e));return um.encode(qa(new Uint8Array(t)))}async function _m({apiKey:e,email:t,organizationId:n,expiresInSeconds:r=300}){if(typeof t!=`string`||t.length>320||t.includes(`\0`)||!/^[^\s@]+@[^\s@]+$/.test(t))throw Error(`email must be an email address of at most 320 characters`);if(!Number.isInteger(r)||r<60||r>600)throw Error(`organization auth tokens must live for 60-600 seconds`);let{keyId:i,organizationId:a,keySecret:o}=dm(e);if(n!==a)throw Error(`organizationId must match the API key organization`);let s=Math.floor(Date.now()/1e3);return await new nm({ver:1,email:t,organization_id:n}).setProtectedHeader({alg:`HS256`,typ:`astralbeam-organization+jwt`,kid:i}).setIssuer(n).setAudience(rm).setIssuedAt(s).setExpirationTime(s+r).sign(await gm(o))}async function vm({apiKey:e,user:t,tenant:n,usageLimits:r,expiresInSeconds:i=300}){if(!Number.isInteger(i)||i<60||i>600)throw Error(`chat auth tokens must live for 60-600 seconds`);let{keyId:a,organizationId:o,keySecret:s}=dm(e),c=hm(t,n);if(r!==void 0&&(!Array.isArray(r)||r.length>20||!r.every(e=>typeof e==`string`&&sm.test(e))))throw Error(`usageLimits must list at most 20 IDs of the form limit_<organizationId>_<id>`);let l=Math.floor(Date.now()/1e3),u=await new nm({ver:4,user:c.user,tenant:c.tenant,...r?.length?{usage_limits:[...new Set(r)]}:{}}).setProtectedHeader({alg:`HS256`,typ:`astralbeam+jwt`,kid:a}).setIssuer(o).setAudience(rm).setIssuedAt(l).setExpirationTime(l+i).sign(await gm(s));if(um.encode(u).byteLength>im)throw Error(`chat auth tokens must not exceed ${im} bytes`);return u}function ym(e){return e.string([`tenant`,`user`,`tenant-name`,`user-name`]).demandOption([`tenant`,`user`]).boolean(`admin`).number(`expires-in`).coerce(`expires-in`,tr).describe({tenant:`Tenant external ID, signed as tenant.id`,user:`TenantUser external ID, signed as user.id`,"tenant-name":`Tenant display name`,"user-name":`TenantUser display name`,admin:`sign user.admin: true, granting Tenant admin API access`,"expires-in":`token lifetime, 60-600 (default 300)`})}function bm(e){return{tenant:{id:e.tenant,...e.tenantName===void 0?{}:{name:e.tenantName}},user:{id:e.user,...e.userName===void 0?{}:{name:e.userName},...e.admin?{admin:!0}:{}}}}function xm(e,t,n){let r=new Date(Date.now()+t*1e3).toISOString();n?Qr({token:e,expires_at:r}):s.write(`${e}\n`)}function Sm(e){return e.command(`chat`,`Mint a chat JWT for a Tenant's user, as a token endpoint would`,ym,async e=>{let{apiKey:t}=await xi(),n=e.expiresIn??300;xm(await vm({apiKey:t,expiresInSeconds:n,...bm(e)}),n,K.json)}),e.command(`organization`,`Mint an organization-management JWT delegating a member's current role`,e=>e.string(`email`).demandOption(`email`).number(`expires-in`).coerce(`expires-in`,tr).describe({email:`email of an existing member of the organization`,"expires-in":`token lifetime, 60-600 (default 300)`}),async e=>{let{apiKey:t}=await xi(),n=e.expiresIn??300;xm(await _m({apiKey:t,email:e.email,organizationId:li(t),expiresInSeconds:n}),n,K.json)}),e.demandCommand(1)}function Cm(e){return e.filter(e=>e.role===`assistant`).map(e=>e.parts.map(e=>e.type===`text`?e.content:``).join(``)).filter(Boolean).join(`
|
|
149
149
|
|
|
150
150
|
`)}async function wm(e,t,n){let r=e.getState().messages.length,i=``,o=/* @__PURE__ */ new Set,c=e.subscribe(()=>{if(n)return;let t=e.getState().messages.slice(r),c=Cm(t);c.startsWith(i)&&(s.write($r(c.slice(i.length),`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@astralbeam/cli",
|
|
3
|
-
"version": "0.30.
|
|
3
|
+
"version": "0.30.4",
|
|
4
4
|
"description": "Command-line interface for AstralBeam organization admins and their coding agents",
|
|
5
5
|
"homepage": "https://astralbeam.ai/docs/cli/getting-started",
|
|
6
6
|
"bugs": "https://github.com/AstralBeamAI/astralbeam/issues",
|
|
@@ -44,7 +44,7 @@
|
|
|
44
44
|
"generate:api": "bun run scripts/forge/generate.ts"
|
|
45
45
|
},
|
|
46
46
|
"devDependencies": {
|
|
47
|
-
"@astralbeam/sdk": "0.30.
|
|
47
|
+
"@astralbeam/sdk": "0.30.4",
|
|
48
48
|
"@types/bun": "1.4.4",
|
|
49
49
|
"@types/node": "^26.2.0",
|
|
50
50
|
"@types/yargs": "17.0.35",
|