@astralbeam/cli 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -20,12 +20,12 @@ Or install it globally as `astralbeam`:
20
20
  npm install --global @astralbeam/cli
21
21
  ```
22
22
 
23
- Each [GitHub release](https://github.com/AstralBeamAI/astralbeam/releases) also attaches standalone binaries that need no Node, named `astralbeam-v<version>-<platform>` for `linux-x86_64`, `linux-arm64`, `macos-x86_64`, `macos-arm64`, and `windows-x86_64.exe`.
23
+ Each [GitHub release](https://github.com/AstralBeamAI/astralbeam/releases) also attaches standalone binaries that need no Node, named `astralbeam-<platform>` for `linux-x86_64`, `linux-arm64`, `macos-x86_64`, `macos-arm64`, and `windows-x86_64.exe`. The `releases/latest/download` URL always serves the newest release, so rerunning the download upgrades the CLI.
24
24
 
25
25
  ```sh
26
- gh release download v0.12.0 --repo AstralBeamAI/astralbeam --pattern 'astralbeam-v0.12.0-macos-arm64'
27
- chmod +x astralbeam-v0.12.0-macos-arm64
28
- mv astralbeam-v0.12.0-macos-arm64 /usr/local/bin/astralbeam
26
+ curl -fsSLo astralbeam https://github.com/AstralBeamAI/astralbeam/releases/latest/download/astralbeam-macos-arm64
27
+ chmod +x astralbeam
28
+ mv astralbeam /usr/local/bin/astralbeam
29
29
  ```
30
30
 
31
31
  **NOTE**: The binaries are not signed. On macOS, a binary downloaded through a browser needs `xattr -d com.apple.quarantine <file>` before its first run.
@@ -86,6 +86,8 @@ astralbeam chat --tenant customer-42 --user user-7 "What can you do?"
86
86
 
87
87
  Human-readable tables and records go to stdout. With `--json`, stdout carries the API's JSON and stderr holds one JSON object: `{"context": {...}}` naming the organization on success, or `{"error": {...}, "context": {...}}` with the API's problem details on failure. Commands exit with `0` on success, `1` when the API or runtime fails, and `2` for invalid usage.
88
88
 
89
+ When a command fails unexpectedly, rerun it with `--debug` to log each HTTP request's method, URL, status, and duration, plus the failure's stack trace, to stderr. It never logs headers, so keys and tokens stay out of the output, but it adds lines that break the single JSON object `--json` writes to stderr.
90
+
89
91
  ## Coding agents
90
92
 
91
93
  The CLI ships an [Agent Skill](skills/astralbeam/SKILL.md) that teaches an agent its commands, JSON output, and safety rules. Let's install it for Claude Code in the current project:
@@ -17,28 +17,28 @@ Expecting one of '${n.join(`', '`)}'`);return this._lifeCycleHooks[e]?this._life
17
17
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
18
18
  - ${t?`searched for local subcommand relative to directory '${t}'`:`no directory for search for local subcommand, use .executableDir() to supply a custom directory`}`;throw Error(r)}_executeSubCommand(t,n){n=n.slice();let r=[`.js`,`.ts`,`.tsx`,`.mjs`,`.cjs`];function i(e,t){let n=u.resolve(e,t);if(h.existsSync(n))return n;if(r.includes(u.extname(t)))return;let i=r.find(e=>h.existsSync(`${n}${e}`));if(i)return`${n}${i}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let a=t._executableFile||`${this._name}-${t._name}`,o=this._executableDir||``;if(this._scriptPath){let e;try{e=h.realpathSync(this._scriptPath)}catch{e=this._scriptPath}o=u.resolve(u.dirname(e),o)}if(o){let e=i(o,a);if(!e&&!t._executableFile&&this._scriptPath){let n=u.basename(this._scriptPath,u.extname(this._scriptPath));n!==this._name&&(e=i(o,`${n}-${t._name}`))}a=e||a}let s=r.includes(u.extname(a)),c;e.platform===`win32`?(this._checkForMissingExecutable(a,o,t._name),n.unshift(a),n=ge(e.execArgv).concat(n),c=l.spawn(e.execPath,n,{stdio:`inherit`})):s?(n.unshift(a),n=ge(e.execArgv).concat(n),c=l.spawn(e.argv[0],n,{stdio:`inherit`})):c=l.spawn(a,n,{stdio:`inherit`}),c.killed||[`SIGUSR1`,`SIGUSR2`,`SIGTERM`,`SIGINT`,`SIGHUP`].forEach(t=>{e.on(t,()=>{c.killed===!1&&c.exitCode===null&&c.kill(t)})});let d=this._exitCallback;c.on(`close`,t=>{t??=1,d?d(new b(t,`commander.executeSubCommandAsync`,`(close)`)):e.exit(t)}),c.on(`error`,n=>{if(n.code===`ENOENT`)this._checkForMissingExecutable(a,o,t._name);else if(n.code===`EACCES`)throw Error(`'${a}' not executable`);if(!d)e.exit(1);else{let e=new b(1,`commander.executeSubCommandAsync`,`(error)`);e.nestedError=n,d(e)}}),this.runningCommand=c}_dispatchSubcommand(e,t,n){let r=this._findCommand(e);r||this.help({error:!0}),r._prepareForParse();let i;return i=this._chainOrCallSubCommandHook(i,r,`preSubcommand`),i=this._chainOrCall(i,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(n));else return r._parseCommand(t,n)}),i}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??`--help`])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(e,t,n)=>{let r=t;if(t!==null&&e.parseArg){let i=`error: command-argument value '${t}' is invalid for argument '${e.name()}'.`;r=this._callParseArg(e,t,n,i)}return r};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,r)=>{let i=n.defaultValue;n.variadic?r<this.args.length?(i=this.args.slice(r),n.parseArg&&(i=i.reduce((t,r)=>e(n,r,t),n.defaultValue))):i===void 0&&(i=[]):r<this.args.length&&(i=this.args[r],n.parseArg&&(i=e(n,i,n.defaultValue))),t[r]=i}),this.processedArgs=t}_chainOrCall(e,t){return e?.then&&typeof e.then==`function`?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,r=[];return this._getCommandAndAncestors().reverse().filter(e=>e._lifeCycleHooks[t]!==void 0).forEach(e=>{e._lifeCycleHooks[t].forEach(t=>{r.push({hookedCommand:e,callback:t})})}),t===`postAction`&&r.reverse(),r.forEach(e=>{n=this._chainOrCall(n,()=>e.callback(e.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let r=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(e=>{r=this._chainOrCall(r,()=>e(this,t))}),r}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){r(),this._processArguments();let n;return n=this._chainOrCallHooks(n,`preAction`),n=this._chainOrCall(n,()=>this._actionHandler(this.processedArgs)),this.parent&&(n=this._chainOrCall(n,()=>{this.parent.emit(i,e,t)})),n=this._chainOrCallHooks(n,`postAction`),n}if(this.parent?.listenerCount(i))r(),this._processArguments(),this.parent.emit(i,e,t);else if(e.length){if(this._findCommand(`*`))return this._dispatchSubcommand(`*`,e,t);this.listenerCount(`command:*`)?this.emit(`command:*`,e,t):this.commands.length?this.unknownCommand():(r(),this._processArguments())}else this.commands.length?(r(),this.help({error:!0})):(r(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(e=>{let t=e.attributeName();return this.getOptionValue(t)!==void 0&&this.getOptionValueSource(t)!=="default"});e.filter(e=>e.conflictsWith.length>0).forEach(t=>{let n=e.find(e=>t.conflictsWith.includes(e.attributeName()));n&&this._conflictingOption(t,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],r=t;function i(e){return e.length>1&&e[0]===`-`}let a=e=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(e)?!this._getCommandAndAncestors().some(e=>e.options.map(e=>e.short).some(e=>/^-\d$/.test(e))):!1,o=null,s=null,c=0;for(;c<e.length||s;){let l=s??e[c++];if(s=null,l===`--`){r===n&&r.push(l),r.push(...e.slice(c));break}if(o&&(!i(l)||a(l))){this.emit(`option:${o.name()}`,l);continue}if(o=null,i(l)){let t=this._findOption(l);if(t){if(t.required){let n=e[c++];n===void 0&&this.optionMissingArgument(t),this.emit(`option:${t.name()}`,n)}else if(t.optional){let n=null;c<e.length&&(!i(e[c])||a(e[c]))&&(n=e[c++]),this.emit(`option:${t.name()}`,n)}else this.emit(`option:${t.name()}`);o=t.variadic?t:null;continue}}if(l.length>2&&l[0]===`-`&&l[1]!==`-`){let e=this._findOption(`-${l[1]}`);if(e){e.required||e.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${e.name()}`,l.slice(2)):(this.emit(`option:${e.name()}`),s=`-${l.slice(2)}`);continue}}if(/^--[^=]+=/.test(l)){let e=l.indexOf(`=`),t=this._findOption(l.slice(0,e));if(t&&(t.required||t.optional)){this.emit(`option:${t.name()}`,l.slice(e+1));continue}}if(r===t&&i(l)&&!(this.commands.length===0&&a(l))&&(r=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(l)){t.push(l),n.push(...e.slice(c));break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l,...e.slice(c));break}else if(this._defaultCommandName){n.push(l,...e.slice(c));break}}if(this._passThroughOptions){r.push(l,...e.slice(c));break}r.push(l)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let t=this.options[n].attributeName();e[t]=t===this._versionOptionName?this._version:this[t]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}\n`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==`string`?this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
19
19
  `),this.outputHelp({error:!0}));let n=t||{},r=n.exitCode||1,i=n.code||`commander.error`;this._exit(r,i,e)}_parseOptionsEnv(){this.options.forEach(t=>{if(t.envVar&&t.envVar in e.env){let n=t.attributeName();(this.getOptionValue(n)===void 0||[`default`,`config`,`env`].includes(this.getOptionValueSource(n)))&&(t.required||t.optional?this.emit(`optionEnv:${t.name()}`,e.env[t.envVar]):this.emit(`optionEnv:${t.name()}`))}})}_parseOptionsImplied(){let e=new ue(this.options),t=e=>this.getOptionValue(e)!==void 0&&![`default`,`implied`].includes(this.getOptionValueSource(e));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(e=>{Object.keys(e.implied).filter(e=>!t(e)).forEach(t=>{this.setOptionValueWithSource(t,e.implied[t],`implied`)})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:`commander.missingArgument`})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:`commander.optionMissingArgument`})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:`commander.missingMandatoryOptionValue`})}_conflictingOption(e,t){let n=e=>{let t=e.attributeName(),n=this.getOptionValue(t),r=this.options.find(e=>e.negate&&t===e.attributeName()),i=this.options.find(e=>!e.negate&&t===e.attributeName());return r&&(r.presetArg===void 0&&n===!1||r.presetArg!==void 0&&n===r.presetArg)?r:i||e},r=e=>{let t=n(e),r=t.attributeName();return this.getOptionValueSource(r)===`env`?`environment variable '${t.envVar}'`:`option '${t.flags}'`},i=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(i,{code:`commander.conflictingOption`})}unknownOption(e){if(this._allowUnknownOption)return;let t=``;if(e.startsWith(`--`)&&this._showSuggestionAfterError){let n=[],r=this;do{let e=r.createHelp().visibleOptions(r).filter(e=>e.long).map(e=>e.long);n=n.concat(e),r=r.parent}while(r&&!r._enablePositionalOptions);t=me(e,n)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:`commander.unknownOption`})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?``:`s`,r=e.length,i=`error: too many arguments${this.parent?` for '${this.name()}'`:``}. Expected ${t} argument${n} but got ${r}: ${e.join(`, `)}.`;this.error(i,{code:`commander.excessArguments`})}unknownCommand(){let e=this.args[0],t=``;if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(e=>{n.push(e.name()),e.alias()&&n.push(e.alias())}),t=me(e,n)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:`commander.unknownCommand`})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t||=`-V, --version`,n||=`output the version number`;let r=this.createOption(t,n);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on(`option:`+r.name(),()=>{this._outputConfiguration.writeOut(`${e}\n`),this._exit(0,`commander.version`,e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw Error(`Command alias can't be the same as its name`);let n=this.parent?._findCommand(e);if(n){let t=[n.name()].concat(n.aliases()).join(`|`);throw Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${t}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(e=>this.alias(e)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let e=this.registeredArguments.map(e=>ce(e));return[].concat(this.options.length||this._helpOption!==null?`[options]`:[],this.commands.length?`[command]`:[],this.registeredArguments.length?e:[]).join(` `)}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}helpGroup(e){return e===void 0?this._helpGroupHeading??``:(this._helpGroupHeading=e,this)}commandsGroup(e){return e===void 0?this._defaultCommandGroup??``:(this._defaultCommandGroup=e,this)}optionsGroup(e){return e===void 0?this._defaultOptionGroup??``:(this._defaultOptionGroup=e,this)}_initOptionGroup(e){this._defaultOptionGroup&&!e.helpGroupHeading&&e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){this._defaultCommandGroup&&!e.helpGroup()&&e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=u.basename(e,u.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),n=this._getOutputContext(e);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let r=t.formatHelp(this,t);return n.hasColors?r:this._outputConfiguration.stripColor(r)}_getOutputContext(e){e||={};let t=!!e.error,n,r,i;return t?(n=e=>this._outputConfiguration.writeErr(e),r=this._outputConfiguration.getErrHasColors(),i=this._outputConfiguration.getErrHelpWidth()):(n=e=>this._outputConfiguration.writeOut(e),r=this._outputConfiguration.getOutHasColors(),i=this._outputConfiguration.getOutHelpWidth()),{error:t,write:e=>(r||(e=this._outputConfiguration.stripColor(e)),n(e)),hasColors:r,helpWidth:i}}outputHelp(e){let t;typeof e==`function`&&(t=e,e=void 0);let n=this._getOutputContext(e),r={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(e=>e.emit(`beforeAllHelp`,r)),this.emit(`beforeHelp`,r);let i=this.helpInformation({error:n.error});if(t&&(i=t(i),typeof i!=`string`&&!Buffer.isBuffer(i)))throw Error(`outputHelp callback must return a string or a Buffer`);n.write(i),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit(`afterHelp`,r),this._getCommandAndAncestors().forEach(e=>e.emit(`afterAllHelp`,r))}helpOption(e,t){return typeof e==`boolean`?(e?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(e??`-h, --help`,t??`display help for command`),(e||t)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(t){this.outputHelp(t);let n=Number(e.exitCode??0);n===0&&t&&typeof t!=`function`&&t.error&&(n=1),this._exit(n,`commander.help`,`(outputHelp)`)}addHelpText(e,t){let n=[`beforeAll`,`before`,`after`,`afterAll`];if(!n.includes(e))throw Error(`Unexpected value for position to addHelpText.
20
- Expecting one of '${n.join(`', '`)}'`);let r=`${e}Help`;return this.on(r,e=>{let n;n=typeof t==`function`?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(e=>t.is(e))&&(this.outputHelp(),this._exit(0,`commander.helpDisplayed`,`(outputHelp)`))}};function ge(e){return e.map(e=>{if(!e.startsWith(`--inspect`))return e;let t,n=`127.0.0.1`,r=`9229`,i;return(i=e.match(/^(--inspect(-brk)?)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],r=i[4]):(t=i[1],/^\d+$/.test(i[3])?r=i[3]:n=i[3]):t=i[1],t&&r!==`0`?`${t}=${n}:${parseInt(r)+1}`:e})}function _e(){if(e.env.NO_COLOR||e.env.FORCE_COLOR===`0`||e.env.FORCE_COLOR===`false`)return!1;if(e.env.FORCE_COLOR||e.env.CLICOLOR_FORCE!==void 0)return!0}new he;var ve=`0.12.0`;function C(e){return e instanceof Error&&e.name===`AstralBeamApiError`&&`status`in e&&typeof e.status==`number`}function ye(e,t=`https://app.astralbeam.ai/api`){return`${t.replace(/\/+$/,``)}${e.replace(/^\/api(?=\/)/,``)}`}function be(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.issues===void 0||Array.isArray(n.issues)&&n.issues.every(e=>e&&typeof e.path==`string`&&typeof e.message==`string`))}async function xe(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(ye(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=be(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 w(e,t){return await(await xe(e,t)).json()}function Se(e,t){return w(e,t)}function Ce(e,t){return xe(e,t)}const we=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/tenants?${n}`:`/api/v1/tenants`},Te=(e,t)=>w(we(e),{...t,method:`GET`}),Ee=()=>`/api/v1/tenants`,De=(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 w(Ee(),{...t,method:`POST`,headers:{"Content-Type":`application/json`,...n(t?.headers)},body:JSON.stringify(e)})},Oe=e=>`/api/v1/tenants/${encodeURIComponent(String(e))}`,ke=(e,t)=>w(Oe(e),{...t,method:`GET`}),Ae=e=>`/api/v1/tenants/${encodeURIComponent(String(e))}`,je=(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 w(Ae(e),{...n,method:`PATCH`,headers:{"Content-Type":`application/json`,...r(n?.headers)},body:JSON.stringify(t)})},Me=(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/tenants/${encodeURIComponent(String(e))}/tenant_users?${r}`:`/api/v1/tenants/${encodeURIComponent(String(e))}/tenant_users`},Ne=(e,t,n)=>w(Me(e,t),{...n,method:`GET`}),Pe=e=>`/api/v1/tenants/${encodeURIComponent(String(e))}/tenant_users`,Fe=(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 w(Pe(e),{...n,method:`POST`,headers:{"Content-Type":`application/json`,...r(n?.headers)},body:JSON.stringify(t)})},Ie=(e,t)=>`/api/v1/tenants/${encodeURIComponent(String(e))}/tenant_users/${encodeURIComponent(String(t))}`,Le=(e,t,n)=>w(Ie(e,t),{...n,method:`GET`}),Re=(e,t)=>`/api/v1/tenants/${encodeURIComponent(String(e))}/tenant_users/${encodeURIComponent(String(t))}`,ze=(e,t,n,r)=>{let i=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 w(Re(e,t),{...r,method:`PATCH`,headers:{"Content-Type":`application/json`,...i(r?.headers)},body:JSON.stringify(n)})},Be=()=>`/api/v1/organization`,Ve=e=>w(Be(),{...e,method:`GET`}),He=()=>`/api/v1/chat`,Ue=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`},We=(e,t)=>Se(Ue(e),{...t,method:`GET`}),Ge=()=>`/api/v1/me`,Ke=e=>Se(Ge(),{...e,method:`POST`});function qe(e){s.write(`${JSON.stringify(e,null,2)}\n`)}function T(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 Je(e){return e==null?``:T(typeof e==`string`?e:JSON.stringify(e))}function Ye(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)} ${Je(r)}\n`)}function E(e,t){t?qe(e):Ye(e)}function Xe(e,t){let n=e.map(e=>t.map(t=>Je(e[t]))),r=t.map((e,t)=>Math.max(e.length,...n.map(e=>e[t]?.length??0))),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 Ze(e,t,n){let r=e instanceof Error?e.message:String(e);if(t){let t=C(e)?e.body??{status:e.status,detail:r}:{detail:r};a.write(`${JSON.stringify({error:t,context:n??null})}\n`);return}let i=C(e)?` (HTTP ${e.status})`:``;if(a.write(`Error: ${T(r)}${i}\n`),C(e))for(let t of e.body?.issues??[])a.write(` ${T(t.path)}: ${T(t.message)}\n`)}const Qe=`https://app.astralbeam.ai/api`,$e=/^key_([0-9a-f-]{36})_[0-9a-f-]{36}_abo_[A-Za-z]{64}$/;function et(){return n.ASTRALBEAM_CONFIG_DIR?f(n.ASTRALBEAM_CONFIG_DIR,`config.json`):f(i===`win32`?n.APPDATA??ie():n.XDG_CONFIG_HOME??f(ie(),`.config`),`astralbeam`,`config.json`)}function tt(e){let t=$e.exec(e)?.[1];if(!t)throw Error(`The API key must match key_<organizationId>_<id>_abo_<secret>.`);return t}function nt(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]`||y(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 localhost.`);return e}async function D(){try{return{bindings:JSON.parse(await v(et(),`utf8`)).bindings??{}}}catch(e){if(e.code===`ENOENT`)return{bindings:{}};throw e}}async function rt(e){let t=et();await _(d(t),{recursive:!0,mode:448});let n=`${t}.${r}.tmp`;try{await re(n,`${JSON.stringify(e,null,2)}\n`,{mode:384,flag:`wx`}),await te(n,t)}catch(e){throw await ne(n,{force:!0}),e}}async function it(){return await ee(t())}function at(e,t){for(let n=t;;n=d(n)){let t=e.bindings[n];if(t)return{directory:n,binding:t};if(d(n)===n)return}}function ot(e){let t=ie();return e===t||e.startsWith(t+m)?`~${e.slice(t.length)}`:e}const O={json:!1,context:void 0};function st(e){O.context={organization:e.organization,bound_directory:e.directory??null},O.json||a.write(ct(e))}function ct(e){let{organization:t,directory:n}=e,r=t.name?`${T(t.name)} (${T(t.slug??``)}) · `:``,i=n?`bound at ${ot(n)}`:`from ASTRALBEAM_API_KEY`;return`▸ ${r}org ${t.id} · ${i}\n`}function k(e){return{json:e.optsWithGlobals().json===!0}}async function A(){let{apiKey:e,apiUrl:t}=await j();return{apiKey:e,apiUrl:t}}async function j(){let e=n.ASTRALBEAM_API_KEY,t;if(e)t={apiKey:e,apiUrl:nt(n.ASTRALBEAM_API_URL??`https://app.astralbeam.ai/api`),organization:{id:tt(e)}};else{let e=await it(),n=at(await D(),e);if(!n)throw Error(`No AstralBeam login covers ${ot(e)}. Run \`astralbeam auth login\` in this directory or a parent, or set ASTRALBEAM_API_KEY.`);let{binding:r}=n;t={apiKey:r.api_key,apiUrl:nt(r.api_url),organization:r.organization,directory:n.directory}}return st(t),t}function lt(e){o.setRawMode(!0),a.write(e),o.setEncoding(`utf8`),o.resume();let t=``;return new Promise((e,n)=>{let r=()=>{o.off(`data`,i),o.setRawMode(!1),o.pause(),a.write(`
20
+ Expecting one of '${n.join(`', '`)}'`);let r=`${e}Help`;return this.on(r,e=>{let n;n=typeof t==`function`?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(e=>t.is(e))&&(this.outputHelp(),this._exit(0,`commander.helpDisplayed`,`(outputHelp)`))}};function ge(e){return e.map(e=>{if(!e.startsWith(`--inspect`))return e;let t,n=`127.0.0.1`,r=`9229`,i;return(i=e.match(/^(--inspect(-brk)?)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],r=i[4]):(t=i[1],/^\d+$/.test(i[3])?r=i[3]:n=i[3]):t=i[1],t&&r!==`0`?`${t}=${n}:${parseInt(r)+1}`:e})}function _e(){if(e.env.NO_COLOR||e.env.FORCE_COLOR===`0`||e.env.FORCE_COLOR===`false`)return!1;if(e.env.FORCE_COLOR||e.env.CLICOLOR_FORCE!==void 0)return!0}new he;var ve=`0.13.0`;function ye(e){return e instanceof Error&&e.name===`AstralBeamApiError`&&`status`in e&&typeof e.status==`number`}function be(e,t=`https://app.astralbeam.ai/api`){return`${t.replace(/\/+$/,``)}${e.replace(/^\/api(?=\/)/,``)}`}function xe(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.issues===void 0||Array.isArray(n.issues)&&n.issues.every(e=>e&&typeof e.path==`string`&&typeof e.message==`string`))}async function Se(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(be(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=xe(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 C(e,t){return await(await Se(e,t)).json()}function Ce(e,t){return C(e,t)}function we(e,t){return Se(e,t)}const Te=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/tenants?${n}`:`/api/v1/tenants`},Ee=(e,t)=>C(Te(e),{...t,method:`GET`}),De=()=>`/api/v1/tenants`,Oe=(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 C(De(),{...t,method:`POST`,headers:{"Content-Type":`application/json`,...n(t?.headers)},body:JSON.stringify(e)})},ke=e=>`/api/v1/tenants/${encodeURIComponent(String(e))}`,Ae=(e,t)=>C(ke(e),{...t,method:`GET`}),je=e=>`/api/v1/tenants/${encodeURIComponent(String(e))}`,Me=(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 C(je(e),{...n,method:`PATCH`,headers:{"Content-Type":`application/json`,...r(n?.headers)},body:JSON.stringify(t)})},Ne=(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/tenants/${encodeURIComponent(String(e))}/tenant_users?${r}`:`/api/v1/tenants/${encodeURIComponent(String(e))}/tenant_users`},Pe=(e,t,n)=>C(Ne(e,t),{...n,method:`GET`}),Fe=e=>`/api/v1/tenants/${encodeURIComponent(String(e))}/tenant_users`,Ie=(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 C(Fe(e),{...n,method:`POST`,headers:{"Content-Type":`application/json`,...r(n?.headers)},body:JSON.stringify(t)})},Le=(e,t)=>`/api/v1/tenants/${encodeURIComponent(String(e))}/tenant_users/${encodeURIComponent(String(t))}`,Re=(e,t,n)=>C(Le(e,t),{...n,method:`GET`}),ze=(e,t)=>`/api/v1/tenants/${encodeURIComponent(String(e))}/tenant_users/${encodeURIComponent(String(t))}`,Be=(e,t,n,r)=>{let i=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 C(ze(e,t),{...r,method:`PATCH`,headers:{"Content-Type":`application/json`,...i(r?.headers)},body:JSON.stringify(n)})},Ve=()=>`/api/v1/organization`,He=e=>C(Ve(),{...e,method:`GET`}),Ue=()=>`/api/v1/chat`,We=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`},Ge=(e,t)=>Ce(We(e),{...t,method:`GET`}),Ke=()=>`/api/v1/me`,qe=e=>Ce(Ke(),{...e,method:`POST`});function w(e){s.write(`${JSON.stringify(e,null,2)}\n`)}function T(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 Je(e){return e==null?``:T(typeof e==`string`?e:JSON.stringify(e))}function Ye(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)} ${Je(r)}\n`)}function E(e,t){t?w(e):Ye(e)}function Xe(e,t){let n=e.map(e=>t.map(t=>Je(e[t]))),r=t.map((e,t)=>Math.max(e.length,...n.map(e=>e[t]?.length??0))),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 Ze(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 (${ve}).`;if(e.status===429)return`The API rate limit was reached. Wait a few minutes and retry.`}function Qe(e,t,n,r){let i=e instanceof Error?e.message:String(e);if(t){let t=ye(e)?e.body??{status:e.status,detail:i}:{detail:i};a.write(`${JSON.stringify({error:t,context:n??null})}\n`);return}if(!ye(e))return void a.write(`Error: ${T(i)}\n`);let o=r?` from ${r}`:``;a.write(`Error: ${T(i)} (HTTP ${e.status}${o})\n`);for(let t of e.body?.issues??[])a.write(` ${T(t.path)}: ${T(t.message)}\n`);let s=Ze(e);s&&a.write(`${s}\n`)}const $e=`https://app.astralbeam.ai/api`,et=/^key_([0-9a-f-]{36})_[0-9a-f-]{36}_abo_[A-Za-z]{64}$/;function tt(){return n.ASTRALBEAM_CONFIG_DIR?f(n.ASTRALBEAM_CONFIG_DIR,`config.json`):f(i===`win32`?n.APPDATA??ie():n.XDG_CONFIG_HOME??f(ie(),`.config`),`astralbeam`,`config.json`)}function nt(e){let t=et.exec(e)?.[1];if(!t)throw Error(`The API key must match key_<organizationId>_<id>_abo_<secret>.`);return t}function rt(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]`||y(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 localhost.`);return e}async function D(){try{return{bindings:JSON.parse(await v(tt(),`utf8`)).bindings??{}}}catch(e){if(e.code===`ENOENT`)return{bindings:{}};throw e}}async function it(e){let t=tt();await _(d(t),{recursive:!0,mode:448});let n=`${t}.${r}.tmp`;try{await re(n,`${JSON.stringify(e,null,2)}\n`,{mode:384,flag:`wx`}),await te(n,t)}catch(e){throw await ne(n,{force:!0}),e}}async function at(){return await ee(t())}function ot(e,t){for(let n=t;;n=d(n)){let t=e.bindings[n];if(t)return{directory:n,binding:t};if(d(n)===n)return}}function st(e){let t=ie();return e===t||e.startsWith(t+m)?`~${e.slice(t.length)}`:e}const O={json:!1,context:void 0,failedRequest:void 0};function ct(e){O.context={organization:e.organization,bound_directory:e.directory??null},O.json||a.write(lt(e))}function lt(e){let{organization:t,directory:n}=e,r=t.name?`${T(t.name)} (${T(t.slug??``)}) · `:``,i=n?`bound at ${st(n)}`:`from ASTRALBEAM_API_KEY`;return`▸ ${r}org ${t.id} · ${i}\n`}function k(e){return{json:e.optsWithGlobals().json===!0}}async function A(){let{apiKey:e,apiUrl:t}=await j();return{apiKey:e,apiUrl:t}}async function j(){let e=n.ASTRALBEAM_API_KEY,t;if(e)t={apiKey:e,apiUrl:rt(n.ASTRALBEAM_API_URL??`https://app.astralbeam.ai/api`),organization:{id:nt(e)}};else{let e=await at(),n=ot(await D(),e);if(!n)throw Error(`No AstralBeam login covers ${st(e)}. Run \`astralbeam auth login\` in this directory or a parent, or set ASTRALBEAM_API_KEY.`);let{binding:r}=n;t={apiKey:r.api_key,apiUrl:rt(r.api_url),organization:r.organization,directory:n.directory}}return ct(t),t}function ut(e){o.setRawMode(!0),a.write(e),o.setEncoding(`utf8`),o.resume();let t=``;return new Promise((e,n)=>{let r=()=>{o.off(`data`,i),o.setRawMode(!1),o.pause(),a.write(`
21
21
  `)},i=i=>{for(let a of i){if(a===`\r`||a===`
22
- `)return r(),e(t.trim());if(a===``)return r(),n(Error(`Cancelled.`));t=a===``||a===`\b`?t.slice(0,-1):t+a}};o.on(`data`,i)})}async function ut(){if(o.isTTY)return await lt(`Paste an organization API key: `);let e=[];for await(let t of o)e.push(t);return Buffer.concat(e).toString(`utf8`).trim()}async function dt(e,t){let n=tt(e),{id:r,name:i,slug:a}=await Ve({apiKey:e,apiUrl:t});if(r!==n)throw Error(`The API returned a different organization.`);return{id:r,name:i,slug:a}}function ft(e){return`${e.slice(0,e.indexOf(`_abo_`)+5)}…${e.slice(-4)}`}function pt(e){let t=e.command(`auth`).description(`Bind organization API keys to directories, and check them`);t.command(`login`).description(`Verify an API key, read from a hidden prompt or stdin, and bind it to this directory and everything below it`).option(`--api-url <url>`,`API base URL, ending in /api (default ${Qe})`).action(async(e,t)=>{let{json:r}=k(t),i=nt(e.apiUrl??n.ASTRALBEAM_API_URL??`https://app.astralbeam.ai/api`),a=await ut(),o=await dt(a,i),s=await it(),c=await D();c.bindings[s]={api_url:i,api_key:a,organization:o},await rt(c),st({apiKey:a,apiUrl:i,organization:o,directory:s}),E({directory:s,organization:o,api_url:i},r)}),t.command(`logout`).description(`Remove the binding that covers this directory`).action(async(e,t)=>{let n=await D(),r=at(n,await it());if(!r)throw Error(`No AstralBeam login covers this directory.`);delete n.bindings[r.directory],await rt(n);let{organization:i}=r.binding;E({directory:r.directory,organization:i},k(t).json)}),t.command(`status`).description(`Show which organization commands here use, and verify the key against the API`).action(async(e,t)=>{let{apiKey:n,apiUrl:r,directory:i}=await j(),a=await dt(n,r);if(O.context&&(O.context.organization=a),i){let e=await D(),t=e.bindings[i];t&&JSON.stringify(t.organization)!==JSON.stringify(a)&&(t.organization=a,await rt(e))}E({organization:a,api_url:r,api_key:ft(n),source:i??`ASTRALBEAM_API_KEY`},k(t).json)}),t.command(`list`).description(`List every directory binding`).action(async(e,t)=>{let{bindings:n}=await D(),r=Object.entries(n).map(([e,t])=>({directory:e,organization:t.organization,api_url:t.api_url}));if(k(t).json)return qe({items:r});if(r.length===0)return void a.write(`No bindings.
23
- `);Xe(r.map(({directory:e,organization:t,api_url:n})=>({directory:ot(e),name:t.name,slug:t.slug,organization_id:t.id,api_url:n})),[`directory`,`name`,`slug`,`organization_id`,`api_url`])})}const mt=new TextEncoder,ht=new TextDecoder,gt=new TextDecoder(`utf-8`,{fatal:!0});function _t(...e){let t=e.reduce((e,{length:t})=>e+t,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function vt(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r>127)throw TypeError(`non-ASCII string encountered in encode()`);t[n]=r}return t}var yt=class extends Error{static code=`ERR_JOSE_GENERIC`;code=`ERR_JOSE_GENERIC`;constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},bt=class extends yt{static code=`ERR_JOSE_NOT_SUPPORTED`;code=`ERR_JOSE_NOT_SUPPORTED`},M=class extends yt{static code=`ERR_JWS_INVALID`;code=`ERR_JWS_INVALID`},N=class extends yt{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`};function xt(e){if(Uint8Array.prototype.toBase64)return e.toBase64();let t=32768,n=[];for(let r=0;r<e.length;r+=t)n.push(String.fromCharCode.apply(null,e.subarray(r,r+t)));return btoa(n.join(``))}function St(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}const Ct=`The input to be decoded is not correctly encoded.`;function wt(e){if(Uint8Array.fromBase64)try{return Uint8Array.fromBase64(typeof e==`string`?e:ht.decode(e),{alphabet:`base64url`})}catch(e){throw TypeError(Ct,{cause:e})}let t=e;if(t instanceof Uint8Array&&(t=ht.decode(t)),t.includes(`+`)||t.includes(`/`))throw TypeError(Ct);t=t.replace(/-/g,`+`).replace(/_/g,`/`);try{return St(t)}catch{throw TypeError(Ct)}}function Tt(e){let t=e;return typeof t==`string`&&(t=mt.encode(t)),Uint8Array.prototype.toBase64?t.toBase64({alphabet:`base64url`,omitPadding:!0}):xt(t).replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}function Et(e){if(typeof e!=`object`||!e||Object.prototype.toString.call(e)!==`[object Object]`)return!1;let t=Object.getPrototypeOf(e);if(t===null)return!0;let n=t;for(;Object.getPrototypeOf(n)!==null;)n=Object.getPrototypeOf(n);return t===n}function Dt(...e){let t=new Set;for(let n of e)if(n)for(let e of Object.keys(n)){if(t.has(e))return!1;t.add(e)}return!0}const Ot=e=>Et(e)&&typeof e.kty==`string`,kt=e=>e.kty!==`oct`&&(e.kty===`AKP`&&typeof e.priv==`string`||typeof e.d==`string`),At=e=>e.kty!==`oct`&&e.d===void 0&&e.priv===void 0,jt=e=>e.kty===`oct`&&typeof e.k==`string`;var Mt=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports);function Nt(e){if(typeof e!=`string`)throw new N(`JWTs must use Compact JWS serialization, JWT must be a string`);let{1:t,length:n}=e.split(`.`);if(n===5)throw new N(`Only JWTs using Compact JWS serialization can be decoded`);if(n!==3)throw new N(`Invalid JWT`);if(!t)throw new N(`JWTs must contain a payload`);let r;try{r=wt(t)}catch{throw new N(`Failed to base64url decode the payload`)}let i;try{i=JSON.parse(gt.decode(r))}catch{throw new N(`Failed to parse the decoded payload as JSON`)}if(!Et(i))throw new N(`Invalid JWT Claims Set`);return i}var Pt=class extends Error{missingFeature;constructor(e){super(Ft(e)),this.name=`UnsupportedResponseStreamError`,this.missingFeature=e}};function Ft(e){return`Streaming fetch responses are not supported in this runtime because ${e} is unavailable. React Native users need a compatible fetch/stream/TextDecoder polyfill, or should use a fetch, XHR, or custom transport that can deliver streaming chunks.`}function It(e){if(!e.body)throw new Pt(`Response.body`);if(typeof e.body.getReader!=`function`)throw new Pt(`Response.body.getReader`);return e.body.getReader()}function Lt(){if(typeof globalThis.TextDecoder!=`function`)throw new Pt(`TextDecoder`);return new globalThis.TextDecoder}function Rt(e){if(!e.startsWith(`data:`))return e;let t=e.slice(5);return t.startsWith(` `)?t.slice(1):t}function zt(e){return Object.keys(e).length>0?e:void 0}function Bt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&`promptTokens`in e}function Vt(e,t){return Bt(e)?e:Ht(Array.isArray(e)?e:void 0,t)}function Ht(e,t){let n=e?.[0];if(n==null&&t==null)return;let{promptTokensDetails:r,completionTokensDetails:i,...a}=t??{},o=zt({...n?.cachedInputTokens===void 0?{}:{cachedTokens:n.cachedInputTokens},...r}),s=zt({...n?.reasoningTokens===void 0?{}:{reasoningTokens:n.reasoningTokens},...i});return{promptTokens:n?.inputTokens??0,completionTokens:n?.outputTokens??0,totalTokens:n?.totalTokens??0,...a,...o===void 0?{}:{promptTokensDetails:o},...s===void 0?{}:{completionTokensDetails:s}}}function Ut(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Wt(e,t){if(t==null)return e;if(e==null)return{...t};let n={...e,...t};return Ut(e.tanstack)&&Ut(t.tanstack)&&(n.tanstack={...e.tanstack,...t.tanstack}),n}function P(e){if(e==null)return;let t=`metadata`in e?e.metadata:void 0,n=(typeof t==`object`&&t&&!Array.isArray(t)?t:e).tanstack;if(!(typeof n!=`object`||!n||Array.isArray(n)))return n}function Gt(e,t){let n=e.metadata,r=P(e)??{};return{...e,metadata:{...n??{},tanstack:{...r,...t}}}}let Kt=function(e){return e.TEXT_MESSAGE_START=`TEXT_MESSAGE_START`,e.TEXT_MESSAGE_CONTENT=`TEXT_MESSAGE_CONTENT`,e.TEXT_MESSAGE_END=`TEXT_MESSAGE_END`,e.TEXT_MESSAGE_CHUNK=`TEXT_MESSAGE_CHUNK`,e.TOOL_CALL_START=`TOOL_CALL_START`,e.TOOL_CALL_ARGS=`TOOL_CALL_ARGS`,e.TOOL_CALL_END=`TOOL_CALL_END`,e.TOOL_CALL_CHUNK=`TOOL_CALL_CHUNK`,e.TOOL_CALL_RESULT=`TOOL_CALL_RESULT`,e.THINKING_START=`THINKING_START`,e.THINKING_END=`THINKING_END`,e.THINKING_TEXT_MESSAGE_START=`THINKING_TEXT_MESSAGE_START`,e.THINKING_TEXT_MESSAGE_CONTENT=`THINKING_TEXT_MESSAGE_CONTENT`,e.THINKING_TEXT_MESSAGE_END=`THINKING_TEXT_MESSAGE_END`,e.STATE_SNAPSHOT=`STATE_SNAPSHOT`,e.STATE_DELTA=`STATE_DELTA`,e.MESSAGES_SNAPSHOT=`MESSAGES_SNAPSHOT`,e.ACTIVITY_SNAPSHOT=`ACTIVITY_SNAPSHOT`,e.ACTIVITY_DELTA=`ACTIVITY_DELTA`,e.RAW=`RAW`,e.CUSTOM=`CUSTOM`,e.RUN_STARTED=`RUN_STARTED`,e.RUN_FINISHED=`RUN_FINISHED`,e.RUN_ERROR=`RUN_ERROR`,e.STEP_STARTED=`STEP_STARTED`,e.STEP_FINISHED=`STEP_FINISHED`,e.REASONING_START=`REASONING_START`,e.REASONING_MESSAGE_START=`REASONING_MESSAGE_START`,e.REASONING_MESSAGE_CONTENT=`REASONING_MESSAGE_CONTENT`,e.REASONING_MESSAGE_END=`REASONING_MESSAGE_END`,e.REASONING_MESSAGE_CHUNK=`REASONING_MESSAGE_CHUNK`,e.REASONING_END=`REASONING_END`,e.REASONING_ENCRYPTED_VALUE=`REASONING_ENCRYPTED_VALUE`,e}({});var qt=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function F(e,t){return e>>>t|e<<32-t}function Jt(e){let t=new TextEncoder().encode(e),n=t.length*8,r=t.length+1,i=r+(56-r%64+64)%64+8,a=new Uint8Array(i);a.set(t),a[t.length]=128;let o=new DataView(a.buffer);o.setUint32(i-8,Math.floor(n/4294967296)),o.setUint32(i-4,n>>>0);let s=1779033703,c=3144134277,l=1013904242,u=2773480762,d=1359893119,f=2600822924,p=528734635,m=1541459225,h=new Uint32Array(64);for(let e=0;e<i;e+=64){for(let t=0;t<16;t++)h[t]=o.getUint32(e+t*4);for(let e=16;e<64;e++){let t=h[e-15]??0,n=h[e-2]??0,r=F(t,7)^F(t,18)^t>>>3,i=F(n,17)^F(n,19)^n>>>10;h[e]=(h[e-16]??0)+r+(h[e-7]??0)+i>>>0}let t=s,n=c,r=l,i=u,a=d,g=f,_=p,v=m;for(let e=0;e<64;e++){let o=F(a,6)^F(a,11)^F(a,25),s=a&g^~a&_,c=v+o+s+(qt[e]??0)+(h[e]??0)>>>0,l=(F(t,2)^F(t,13)^F(t,22))+(t&n^t&r^n&r)>>>0;v=_,_=g,g=a,a=i+c>>>0,i=r,r=n,n=t,t=c+l>>>0}s=s+t>>>0,c=c+n>>>0,l=l+r>>>0,u=u+i>>>0,d=d+a>>>0,f=f+g>>>0,p=p+_>>>0,m=m+v>>>0}let g=e=>(e>>>0).toString(16).padStart(8,`0`);return g(s)+g(c)+g(l)+g(u)+g(d)+g(f)+g(p)+g(m)}function Yt(e){return`sha256:${Jt(e)}`}function Xt(e,t){if(e===null)return`null`;if(typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return JSON.stringify(e);if(typeof e!=`object`)throw TypeError(`Interrupt values must be JSON-compatible.`);if(t.has(e))throw TypeError(`Interrupt values must not cycle.`);if(!Array.isArray(e)&&Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw TypeError(`Interrupt values must use plain JSON objects.`);t.add(e);let n;if(Array.isArray(e)){let r=[];for(let n=0;n<e.length;n++)r.push(Xt(e[n],t));n=`[${r.join(`,`)}]`}else{let r=e;n=`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${Xt(r[e],t)}`).join(`,`)}}`}return t.delete(e),n}function I(e){return Xt(e,new WeakSet)}function L(e,t=Yt){if(typeof e!=`string`)throw TypeError(`Interrupt digests require canonical JSON text.`);return t(e)}function Zt(e){typeof e!=`object`||!e||Object.isFrozen(e)||(Object.values(e).forEach(Zt),Object.freeze(e))}function R(e){let t=JSON.parse(I(e));return Zt(t),t}function Qt(e){let t=R([...e].sort((e,t)=>e.interruptId.localeCompare(t.interruptId))),n=I(t);return Object.freeze({resolutions:t,canonicalResolutions:n,fingerprint:L(n)})}function $t(e){let t={};for(let[n,r]of Object.entries(e))n!==`$schema`&&(t[n]=r);return t}function en(e){return(typeof e==`object`||typeof e==`function`)&&e!==null}function z(e){if(!en(e)||!(`~standard`in e))return!1;let t=e[`~standard`];return typeof t!=`object`||!t||!(`version`in t)||t.version!==1||!(`jsonSchema`in t)||typeof t.jsonSchema!=`object`||t.jsonSchema===null||!(`input`in t.jsonSchema)?!1:typeof t.jsonSchema.input==`function`}function B(e){return en(e)&&`~standard`in e&&typeof e[`~standard`]==`object`&&e[`~standard`]!==null&&`version`in e[`~standard`]&&e[`~standard`].version===1&&`validate`in e[`~standard`]&&typeof e[`~standard`].validate==`function`}function tn(e){return Object.keys(e).length>0?e:void 0}function nn(e,t=[]){let n={...e},r={};if(n.type===`object`&&n.properties){let e={...n.properties},i=Object.keys(e),a={};for(let n of i){let r=e[n];if(!r)continue;let i=!t.includes(n),o=!1,s;if(r.type===`object`&&r.properties){let t=nn(r,r.required||[]);e[n]=i?{...t.schema,type:[`object`,`null`]}:t.schema,o=i,s=t.nullWidening}else if(r.type===`array`&&r.items){let t=Array.isArray(r.items)?r.items[0]:r.items,a=t?nn(t,t.required||[]):void 0;e[n]={...r,items:a?a.schema:r.items,...i?{type:[`array`,`null`]}:{}},o=i,s=a?.nullWidening?{items:a.nullWidening}:void 0}else i&&(r.type&&!Array.isArray(r.type)?(e[n]={...r,type:[r.type,`null`]},o=!0):Array.isArray(r.type)&&!r.type.includes(`null`)&&(e[n]={...r,type:[...r.type,`null`]},o=!0));(o||s)&&(a[n]={...s??{},...o?{widened:!0}:{}})}n.properties=e,n.required=i,n.additionalProperties=!1,Object.keys(a).length>0&&(r.properties=a)}if(n.type===`array`&&n.items){let e=Array.isArray(n.items)?n.items[0]:n.items;if(e){let t=nn(e,e.required||[]);n.items=t.schema,t.nullWidening&&(r.items=t.nullWidening)}}return{schema:n,nullWidening:tn(r)}}function rn(e){if(z(e)){let t=$t(e[`~standard`].jsonSchema.input({target:`draft-07`}));return`properties`in t&&!t.type&&(t.type=`object`),t.type===`object`&&!(`properties`in t)&&(t.properties={}),t.type===`object`&&!(`required`in t)&&(t.required=[]),t}if(B(e))throw Error("Schema is a Standard Schema validator but does not expose a JSON Schema converter on `~standard.jsonSchema`. Use Zod v4.2+, ArkType v2.1.28+, or wrap a Valibot schema with `toStandardJsonSchema()` from `@valibot/to-json-schema` before passing it as `outputSchema`.");return typeof e==`object`?$t(e):e}function an(e,t={}){if(!e)return;let{forStructuredOutput:n=!1}=t;if(!n&&!z(e)&&!B(e))return e;let r=rn(e);return!r||typeof r!=`object`||!n?r:nn(r,r.required||[]).schema}var on=class extends Error{name=`StandardSchemaValidationError`;issues;constructor(e){super(`Validation failed: ${e.map(e=>e.message||`Validation failed`).join(`, `)}`),this.issues=e}};function sn(e,t){if(!B(e))return t;let n=e[`~standard`].validate(t);if(n instanceof Promise)throw Error(`Schema validation returned a Promise. Use validateWithStandardSchema for async validation.`);if(!n.issues)return n.value;throw new on(n.issues)}var cn=new Set([`$schema`,`$id`,`$ref`,`$defs`,`type`,`properties`,`required`,`additionalProperties`,`items`,`oneOf`,`anyOf`,`allOf`,`enum`,`const`,`format`,`minimum`,`maximum`,`minLength`,`maxLength`,`pattern`]);function ln(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null)}function un(e){return ln(e)&&Object.keys(e).some(e=>cn.has(e))}function dn(e){return B(e)||z(e)||un(e)}function fn(e){if(!ln(e))return!1;let t=Object.keys(e);return t.length>0&&t.every(e=>e===`approve`||e===`reject`)&&t.every(t=>dn(e[t]))}function pn(e){let t={};for(let[n,r]of Object.entries(e))t[n]=r;return t}function V(e){if(B(e)){let t=z(e)?pn(e[`~standard`].jsonSchema.input({target:`draft-2020-12`})):void 0;return{source:e,validator:e,...t!==void 0&&{jsonSchema:t}}}if(un(e))return{source:e,jsonSchema:e};throw TypeError(`Expected a supported SchemaInput.`)}function mn(e){let t={approved:{const:e.approved}},n=[`approved`];return e.approved&&e.inputSchema&&(t.editedArgs=e.inputSchema.jsonSchema??{}),e.payload&&(t.payload=e.payload.jsonSchema??{},n.push(`payload`)),{type:`object`,properties:t,required:n,additionalProperties:!1}}function hn(e,t){let n=t===void 0?null:V(t),r=null,i=null;if(e!==void 0)if(B(e)||un(e))r=V(e),i=r;else if(fn(e))r=e.approve===void 0?null:V(e.approve),i=e.reject===void 0?null:V(e.reject);else throw TypeError(`approvalSchema must be a SchemaInput or a nonempty map containing approve or reject.`);let a={oneOf:[mn({approved:!0,payload:r,inputSchema:n}),mn({approved:!1,payload:i,inputSchema:null})]},o=I(a),s=I({approve:r?.jsonSchema??null,reject:i?.jsonSchema??null});return{branches:{approve:r,reject:i},responseSchema:a,responseSchemaHash:L(o),approvalSchemaHash:L(s)}}function gn(e){return L(e===void 0?`undefined`:I(V(e).jsonSchema??{standardValidator:`unserialized`}))}var _n=`tanstack:interruptBinding`,vn=_n;function yn(e){return e&&typeof e==`object`?e:null}function H(e,t){return typeof e[t]==`string`?e[t]:void 0}function bn(e){let t=e.v;return t===void 0||t===1}function xn(e){let t=yn(e.metadata),n=t?yn(t[vn]):null;if(!n||H(n,`interruptId`)!==e.id||!bn(n))return;let r=H(n,`kind`),i=H(n,`interruptId`),a=H(n,`responseSchemaHash`),o=H(n,`expiresAt`);if(!i||a===``||o!==void 0&&!Number.isFinite(Date.parse(o)))return;if(r===`generic`){let e=H(n,`definitionId`),t=H(n,`key`),s=n.batchIndex,c=H(n,`payloadSchemaHash`);return(e!==void 0||t!==void 0||s!==void 0||c!==void 0)&&(!e||!t||typeof s!=`number`||!Number.isInteger(s)||s<0)?void 0:{v:1,kind:r,interruptId:i,...a?{responseSchemaHash:a}:{},...o?{expiresAt:o}:{},...e?{definitionId:e}:{},...t?{key:t}:{},...typeof s==`number`?{batchIndex:s}:{},...c?{payloadSchemaHash:c}:{}}}if(!a)return;let s=H(n,`toolName`),c=H(n,`toolCallId`);if(!(!s||!c)){if(r===`client-tool-execution`){let e=H(n,`outputSchemaHash`);return e?{v:1,kind:r,interruptId:i,toolName:s,toolCallId:c,outputSchemaHash:e,responseSchemaHash:a,...o?{expiresAt:o}:{}}:void 0}if(r===`tool-approval`){let e=H(n,`inputSchemaHash`),t=H(n,`approvalSchemaHash`);return!e||!t?void 0:{v:1,kind:r,interruptId:i,toolName:s,toolCallId:c,originalArgs:n.originalArgs,inputSchemaHash:e,approvalSchemaHash:t,responseSchemaHash:a,...o?{expiresAt:o}:{}}}}}function Sn(e){let t=xn(e);if(!t)return;let n=yn(e.metadata),r=n?yn(n[vn]):null;if(!r)return;let i=H(r,`interruptedRunId`),a=r.generation;if(!(!i||typeof a!=`number`||!Number.isInteger(a)||a<0))return{...t,interruptedRunId:i,generation:a}}var Cn=`tanstack:interruptPayload`;function wn(e,t){if(!z(e))throw TypeError(`${t} must be a Standard Schema with a JSON Schema converter.`);try{let t=e[`~standard`].jsonSchema.input({target:`draft-07`});if(t===void 0)throw TypeError(`The exported schema is undefined.`);if(typeof t==`function`)throw TypeError(`The exported schema must not be a function.`);if(Array.isArray(t)||!t||typeof t!=`object`||![Object.prototype,null].includes(Object.getPrototypeOf(t)))throw TypeError(`The exported schema must be a plain JSON object.`);let n={};for(let[e,r]of Object.entries(t))e!==`$schema`&&(n[e]=r);return{json:n,canonicalJson:I(n)}}catch(e){throw TypeError(`${t} could not export compatible JSON Schema: ${e instanceof Error?e.message:String(e)}`)}}function Tn(e){return L(wn(e,`Interrupt schema`).canonicalJson)}var En=`tanstack:interruptContinuation`;function Dn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function On(e){return{[En]:e}}function kn(e){let t=xn(e);if(t?.kind!==`generic`||t.definitionId===void 0||t.key===void 0||t.batchIndex===void 0)return;let n=Dn(e.metadata)?e.metadata:void 0,r=n!==void 0&&Object.prototype.hasOwnProperty.call(n,`tanstack:interruptPayload`);return{v:1,definitionId:t.definitionId,key:t.key,batchIndex:t.batchIndex,reason:e.reason,message:e.message??``,...e.expiresAt===void 0?{}:{expiresAt:e.expiresAt},...t.responseSchemaHash===void 0?{}:{responseSchemaHash:t.responseSchemaHash},...t.payloadSchemaHash===void 0?{}:{payloadSchemaHash:t.payloadSchemaHash},...r?{payload:n[Cn]}:{}}}function An(e){let t=[];for(let n of e){let e=n.parts??[];if(n.role===`system`){t.push(jn(n,{content:e.length>0?Fn(e):n.content??``},e));continue}if(n.role===`user`){t.push(jn(n,{content:e.length>0?In(e):n.content??``},e));continue}for(let r of e)if(r.type===`thinking`){let e={role:`reasoning`,id:zn(n.id,r),content:r.content};r.signature&&(e.encryptedValue=r.signature),t.push(e)}let r=Fn(e),i=Rn(e);t.push(jn(n,{...r!==``&&{content:r},...i&&{toolCalls:i}},e));for(let n of e)n.type===`tool-result`&&t.push({role:`tool`,id:Bn(n.toolCallId),toolCallId:n.toolCallId,content:typeof n.content==`string`?n.content:JSON.stringify(n.content),...n.error!==void 0&&{error:n.error}})}return t}function jn(e,t,n){let r=Mn(e,n),i=e.name;return{id:e.id,role:e.role,...i!==void 0&&{name:i},...t,...r!==void 0&&{metadata:r}}}function Mn(e,t){let n={...e.metadata??{}},r={...P(e)??{}};e.createdAt&&(r.createdAt=e.createdAt.toISOString());let i=Nn(t);i&&(r.structuredOutput=i);let a={};for(let e of t)e.type===`tool-call`&&e.metadata!==void 0&&(a[e.id]=e.metadata);Object.keys(a).length>0&&(r.toolCallMetadata=a);let o=t.filter(e=>e.type===`ui-resource`);return o.length>0&&(r.uiResources=o),Object.keys(r).length>0&&(n.tanstack=r),Object.keys(n).length>0?n:void 0}function Nn(e){for(let t of e)if(t.type===`structured-output`&&t.status!==`complete`)return Pn(t)}function Pn(e){return{status:e.status,raw:e.raw,...e.errorMessage!==void 0&&{errorMessage:e.errorMessage}}}function Fn(e){let t=[];for(let n of e)n.type===`text`?t.push(n.content):n.type===`structured-output`&&n.status===`complete`&&n.raw!==``&&t.push(n.raw);return t.join(``)}function In(e){if(!e.some(e=>e.type===`image`||e.type===`audio`||e.type===`video`||e.type===`document`))return Fn(e);let t=[];for(let n of e)n.type===`text`?t.push({type:`text`,text:n.content}):(n.type===`image`||n.type===`audio`||n.type===`video`||n.type===`document`)&&t.push(n);return t}function Ln(e){if(typeof e!=`object`||!e||Array.isArray(e)||!(`thoughtSignature`in e))return;let t=e.thoughtSignature;return typeof t==`string`&&t!==``?t:void 0}function Rn(e){let t=[];for(let n of e)if(n.type===`tool-call`){let e=Ln(n.metadata);t.push({id:n.id,type:`function`,function:{name:n.name,arguments:n.arguments},...e===void 0?{}:{encryptedValue:e}})}return t.length>0?t:void 0}function zn(e,t){return`${e}-reasoning-${t.id??Vn(t.content)}`}function Bn(e){return`tool-${e}`}function Vn(e){let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)|0;return Math.abs(t).toString(36)}function Hn(e){if((e.type===Kt.RUN_FINISHED||e.type===Kt.RUN_ERROR)&&(Array.isArray(e.usage)||Bt(e.usage))){let t=Vt(e.usage,P(e)?.usage);t!==void 0&&(e.usage=t)}if(e.type===Kt.TOOL_CALL_START&&e.toolName===void 0&&e.toolCallName&&(e.toolName=e.toolCallName),e.type===Kt.TOOL_CALL_END&&e.input===void 0){let t=P(e)?.input;t!==void 0&&(e.input=t)}return e}function Un(e){Hn(e);let t=P(e),n=e;if(t==null)return n;for(let[e,r]of Object.entries(t))e===`usage`||e===`interruptErrors`||n[e]===void 0&&r!==void 0&&(n[e]=r);return t.interruptErrors!==void 0&&(n[`tanstack:interruptErrors`]=t.interruptErrors),n}var Wn=new Set([`text`,`image`,`audio`,`video`,`document`]);function Gn(e){if(typeof e!=`object`||!e)return!1;let t=e;if(typeof t.type!=`string`||!Wn.has(t.type))return!1;if(t.type===`text`)return typeof t.content==`string`;let n=t.source;if(typeof n!=`object`||!n)return!1;let r=n;return typeof r.value==`string`?r.type===`data`?typeof r.mimeType==`string`:r.type===`url`:!1}function Kn(e){return Array.isArray(e)&&e.length>0&&e.every(Gn)}function qn(e){return typeof e==`string`||Kn(e)?e:JSON.stringify(e)}function Jn(e){let t=e?.metadata;return typeof t==`object`&&t&&t.providerExecuted===!0?t:null}function Yn(e){return Jn(e)!==null}function Xn(e){return e.type===`text`||e.type===`image`||e.type===`audio`||e.type===`video`||e.type===`document`}function Zn(e){try{return JSON.stringify(e)??``}catch{return``}}function Qn(e){return typeof e==`string`&&e!==``?e:void 0}function $n(e){if(`encryptedValue`in e){let t=Qn(e.encryptedValue);if(t!==void 0)return t}return Qn(P(e)?.signature)}function er(e){return e.length===0?null:e.every(e=>e.type===`text`)?e.map(e=>e.content).join(``)||null:e}function tr(e){return e==null?``:typeof e==`string`?e:e.filter(e=>e.type===`text`).map(e=>e.content).join(``)}function nr(e){return e.role===`system`?[]:e.role===`assistant`?or(e):[rr(e)]}function rr(e){let t=[];for(let n of e.parts)Xn(n)&&t.push(n);return{id:e.id,role:e.role,content:er(t),...e.createdAt!==void 0&&{createdAt:e.createdAt}}}function ir(){return{contentParts:[],toolCalls:[]}}function ar(e){return e.state===`input-complete`||e.state===`complete`||e.state===`approval-requested`||e.state===`approval-responded`||e.state===`error`||e.output!==void 0}function or(e){let t=[],n=ir(),r=[],i=new Set;function a(){let i=er(n.contentParts),a=i!==null,o=n.toolCalls.length>0,s=r.length>0;(a||o||s)&&(t.push({id:e.id,role:`assistant`,content:i,...o&&{toolCalls:n.toolCalls},...s&&{thinking:r},...n.structuredOutput&&{structuredOutput:n.structuredOutput},...e.createdAt!==void 0&&{createdAt:e.createdAt}}),r=[]),n=ir()}for(let o of e.parts)switch(o.type){case`text`:case`image`:case`audio`:case`video`:case`document`:n.contentParts.push(o);break;case`tool-call`:ar(o)&&n.toolCalls.push({id:o.id,type:`function`,function:{name:o.name,arguments:o.arguments},...o.metadata!==void 0&&{metadata:o.metadata}});break;case`tool-result`:a(),(o.state===`complete`||o.state===`error`)&&!i.has(o.toolCallId)&&(t.push({id:e.id,role:`tool`,content:o.content,toolCallId:o.toolCallId,...e.createdAt!==void 0&&{createdAt:e.createdAt}}),i.add(o.toolCallId));break;case`thinking`:o.content&&(n.toolCalls.some(Yn)&&a(),r.push({content:o.content,...o.signature&&{signature:o.signature}}));break;case`structured-output`:if(o.status===`complete`){let e=o.raw===``?o.data===void 0?``:Zn(o.data):o.raw;e!==``&&(n.contentParts.push({type:`text`,content:e}),n.structuredOutput=o)}}a();for(let n of e.parts)if(n.type===`tool-call`&&(n.output!==void 0&&!i.has(n.id)&&(t.push({id:e.id,role:`tool`,content:qn(n.output),toolCallId:n.id,...e.createdAt!==void 0&&{createdAt:e.createdAt}}),i.add(n.id)),n.output===void 0&&n.state===`approval-responded`&&n.approval?.approved!==void 0&&!i.has(n.id))){let r=n.approval.approved;t.push({id:e.id,role:`tool`,content:JSON.stringify({approved:r,...r&&{pendingExecution:!0},message:r?`User approved this action`:`User denied this action`}),toolCallId:n.id,...e.createdAt!==void 0&&{createdAt:e.createdAt}}),i.add(n.id)}return t.length===0&&t.push({id:e.id,role:`assistant`,content:null,...e.createdAt!==void 0&&{createdAt:e.createdAt}}),t}function sr(e,t){let n=[];if(e.role===`assistant`&&e.thinking?.length)for(let t of e.thinking)t.content&&n.push({type:`thinking`,content:t.content,...t.signature&&{signature:t.signature}});if(e.role===`assistant`&&e.structuredOutput)n.push(e.structuredOutput);else if(e.role===`tool`&&e.toolCallId)n.push({type:`tool-result`,toolCallId:e.toolCallId,content:tr(e.content),state:`complete`});else if(Array.isArray(e.content))for(let t of e.content)n.push(t);else{let t=tr(e.content);t&&n.push({type:`text`,content:t})}if(e.toolCalls&&e.toolCalls.length>0)for(let t of e.toolCalls){let e;try{e=JSON.parse(t.function.arguments)}catch{e=void 0}n.push({type:`tool-call`,id:t.id,name:t.function.name,arguments:t.function.arguments,state:`input-complete`,...e!==void 0&&{input:e},...t.metadata!==void 0&&{metadata:t.metadata}})}return{id:t||W(),role:e.role===`tool`?`assistant`:e.role,parts:n,...e.createdAt!==void 0&&{createdAt:e.createdAt}}}function cr(e){if(`parts`in e)return U(e,{...e,id:e.id||W()});let t=e.id||W();switch(e.role){case`user`:return U(e,{id:t,role:`user`,parts:lr(e.content)});case`assistant`:{let n=P(e)?.toolCallMetadata,r=e.toolCalls?.map(e=>{let t=typeof n==`object`&&n?n[e.id]:void 0;return t===void 0?e:{...e,metadata:t}});return U(e,sr({role:`assistant`,content:e.content??null,...r&&{toolCalls:r}},t))}case`tool`:return U(e,sr({role:`tool`,content:e.content,toolCallId:e.toolCallId},t));case`system`:case`developer`:return U(e,{id:t,role:`system`,parts:e.content?[{type:`text`,content:e.content}]:[]});case`reasoning`:{let n=$n(e);return U(e,{id:t,role:`assistant`,parts:e.content?[{type:`thinking`,content:e.content,...n===void 0?{}:{signature:n}}]:[]})}default:return U(e,{id:t,role:`assistant`,parts:[]})}}function U(e,t){if(!(`metadata`in e))return t;let n=e.metadata;if(typeof n!=`object`||!n||Array.isArray(n))return t;let r=n,i=P(r)?.createdAt,a=typeof i==`string`?new Date(i):void 0,o=a!==void 0&&!Number.isNaN(a.getTime());return{...t,metadata:r,...o?{createdAt:a}:{}}}function lr(e){if(typeof e==`string`)return e?[{type:`text`,content:e}]:[];let t=[];for(let n of e)n.type===`text`?t.push({type:`text`,content:n.text}):n.type!==`binary`&&t.push(n);return t}function ur(e,t){return`parts`in e?{...e,id:e.id||t(),createdAt:e.createdAt||new Date}:{...sr(e,t()),createdAt:e.createdAt??new Date}}function W(){return`msg-${Date.now()}-${Math.random().toString(36).substring(7)}`}function dr(e){if(e.approvalSchema!==void 0&&e.needsApproval!==!0)throw TypeError(`approvalSchema requires needsApproval: true.`);let t=e.inputSchema,n=e.outputSchema,r=e.approvalSchema,i=e.needsApproval;return{__toolSide:`definition`,...e,inputSchema:t,outputSchema:n,approvalSchema:r,needsApproval:i,server(a){return{__toolSide:`server`,...e,inputSchema:t,outputSchema:n,approvalSchema:r,needsApproval:i,execute:a}},client(a){return{__toolSide:`client`,...e,inputSchema:t,outputSchema:n,approvalSchema:r,needsApproval:i,...a!==void 0&&{execute:a}}}}}function fr(e){return typeof e==`string`&&e!==``?e:void 0}function pr(e){if(`runId`in e){let t=fr(e.runId);if(t!==void 0)return t}return fr(P(e)?.runId)}var mr=Mt((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.ALL=e.COLLECTION=e.ATOM=e.SPECIAL=e.INF=e._INFINITY=e.INFINITY=e.NAN=e.BOOL=e.NULL=e.OBJ=e.ARR=e.NUM=e.STR=void 0,e.STR=1,e.NUM=2,e.ARR=4,e.OBJ=8,e.NULL=16,e.BOOL=32,e.NAN=64,e.INFINITY=128,e._INFINITY=256,e.INF=e.INFINITY|e._INFINITY,e.SPECIAL=e.NULL|e.BOOL|e.INF|e.NAN,e.ATOM=e.STR|e.NUM|e.SPECIAL,e.COLLECTION=e.ARR|e.OBJ,e.ALL=e.ATOM|e.COLLECTION,e.Allow={STR:e.STR,NUM:e.NUM,ARR:e.ARR,OBJ:e.OBJ,NULL:e.NULL,BOOL:e.BOOL,NAN:e.NAN,INFINITY:e.INFINITY,_INFINITY:e._INFINITY,INF:e.INF,SPECIAL:e.SPECIAL,ATOM:e.ATOM,COLLECTION:e.COLLECTION,ALL:e.ALL},e.default=e.Allow})),hr=Mt((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__exportStar||function(e,n){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(n,r)&&t(n,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.MalformedJSON=e.PartialJSON=e.parseJSON=e.parse=void 0;let r=mr();Object.defineProperty(e,"Allow",{enumerable:!0,get:function(){return r.Allow}}),n(mr(),e);var i=class extends Error{};e.PartialJSON=i;var a=class extends Error{};e.MalformedJSON=a;function o(e,t=r.Allow.ALL){if(typeof e!=`string`)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return s(e.trim(),t)}e.parseJSON=o;let s=(e,t)=>{let n=e.length,o=0,s=e=>{throw new i(`${e} at position ${o}`)},c=e=>{throw new a(`${e} at position ${o}`)},l=()=>(m(),o>=n&&s(`Unexpected end of input`),e[o]===`"`?u():e[o]===`{`?d():e[o]===`[`?f():e.substring(o,o+4)===`null`||r.Allow.NULL&t&&n-o<4&&`null`.startsWith(e.substring(o))?(o+=4,null):e.substring(o,o+4)===`true`||r.Allow.BOOL&t&&n-o<4&&`true`.startsWith(e.substring(o))?(o+=4,!0):e.substring(o,o+5)===`false`||r.Allow.BOOL&t&&n-o<5&&`false`.startsWith(e.substring(o))?(o+=5,!1):e.substring(o,o+8)===`Infinity`||r.Allow.INFINITY&t&&n-o<8&&`Infinity`.startsWith(e.substring(o))?(o+=8,1/0):e.substring(o,o+9)===`-Infinity`||r.Allow._INFINITY&t&&1<n-o&&n-o<9&&`-Infinity`.startsWith(e.substring(o))?(o+=9,-1/0):e.substring(o,o+3)===`NaN`||r.Allow.NAN&t&&n-o<3&&`NaN`.startsWith(e.substring(o))?(o+=3,NaN):p()),u=()=>{let i=o,a=!1;for(o++;o<n&&(e[o]!==`"`||a&&e[o-1]===`\\`);)a=e[o]===`\\`&&!a,o++;if(e.charAt(o)==`"`)try{return JSON.parse(e.substring(i,++o-Number(a)))}catch(e){c(String(e))}else if(r.Allow.STR&t)try{return JSON.parse(e.substring(i,o-Number(a))+`"`)}catch{return JSON.parse(e.substring(i,e.lastIndexOf(`\\`))+`"`)}s(`Unterminated string literal`)},d=()=>{o++,m();let i={};try{for(;e[o]!==`}`;){if(m(),o>=n&&r.Allow.OBJ&t)return i;let a=u();m(),o++;try{i[a]=l()}catch(e){if(r.Allow.OBJ&t)return i;throw e}m(),e[o]===`,`&&o++}}catch{if(r.Allow.OBJ&t)return i;s(`Expected '}' at end of object`)}return o++,i},f=()=>{o++;let n=[];try{for(;e[o]!==`]`;)n.push(l()),m(),e[o]===`,`&&o++}catch{if(r.Allow.ARR&t)return n;s(`Expected ']' at end of array`)}return o++,n},p=()=>{if(o===0){e===`-`&&c(`Not sure what '-' is`);try{return JSON.parse(e)}catch(n){if(r.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf(`e`)))}catch{}c(String(n))}}let i=o;for(e[o]===`-`&&o++;e[o]&&`,]}`.indexOf(e[o])===-1;)o++;o==n&&!(r.Allow.NUM&t)&&s(`Unterminated number literal`);try{return JSON.parse(e.substring(i,o))}catch{e.substring(i,o)===`-`&&s(`Not sure what '-' is`);try{return JSON.parse(e.substring(i,e.lastIndexOf(`e`)))}catch(e){c(String(e))}}},m=()=>{for(;o<n&&`
24
- \r `.includes(e[o]);)o++};return l()};e.parse=o}))(),gr=new class{parse(e){if(!(!e||e.trim()===``))try{return(0,hr.parse)(e)}catch{return}}};function _r(e){return gr.parse(e)}var vr=class{shouldEmit(e,t){return!0}};function yr(e){let t=Error(e.message||e.error?.message||`An error occurred`),n=e.code??e.error?.code;return n!==void 0&&Object.assign(t,{code:n}),e.rawEvent!==void 0&&Object.assign(t,{rawEvent:e.rawEvent}),t}function br(e,t,n){return e.map(e=>{if(e.id!==t)return e;let r=[...e.parts],i=r.length>0?r[r.length-1]:null;return i&&i.type===`text`?r[r.length-1]={type:`text`,content:n}:r.push({type:`text`,content:n}),{...e,parts:r}})}function xr(e,t,n){return e.map(e=>{if(e.id!==t)return e;let r=[...e.parts],i=r.find(e=>e.type===`tool-call`&&e.id===n.id),a=n.metadata??i?.metadata,o=n.input??i?.input,s={type:`tool-call`,id:n.id,name:n.name,arguments:n.arguments,state:n.state,...i?.approval&&{approval:{...i.approval}},...i?.output!==void 0&&{output:i.output},...o!==void 0&&{input:o},...a!==void 0&&{metadata:a}};return i?r[r.indexOf(i)]=s:r.push(s),{...e,parts:r}})}function Sr(e,t,n,r,i,a){return e.map(e=>{if(e.id!==t)return e;let o=[...e.parts],s=o.findIndex(e=>e.type===`tool-result`&&e.toolCallId===n),c={type:`tool-result`,toolCallId:n,content:r,state:i,...a&&{error:a}};return s>=0?o[s]=c:o.push(c),{...e,parts:o}})}function Cr(e,t,n,r){return e.map(e=>{if(e.id!==t)return e;let i=[...e.parts],a=i.find(e=>e.type===`tool-call`&&e.id===n);if(a){let e=i.indexOf(a);i[e]={...a,state:`approval-requested`,approval:{id:r,needsApproval:!0}}}return{...e,parts:i}})}function wr(e,t,n,r,i){return e.map(e=>{let a=[...e.parts],o=a.find(e=>e.type===`tool-call`&&e.id===t);if(o){let e=a.indexOf(o);a[e]={...o,output:i?{error:i}:n,state:r??(i?`error`:`complete`)}}return{...e,parts:a}})}function Tr(e,t,n){return e.map(e=>{let r=[...e.parts],i=r.find(e=>e.type===`tool-call`&&e.approval?.id===t);if(i&&i.approval){let e=r.indexOf(i);r[e]={...i,approval:{...i.approval,approved:n},state:`approval-responded`}}return{...e,parts:r}})}function Er(e,t,n){return e.map(e=>{if(e.id!==t)return e;let r=[...e.parts],i=r.findIndex(e=>e.type===`structured-output`),a=i>=0?r[i]:null,o=(a?.raw??``)+n,s=_r(o)??a?.partial,c={type:`structured-output`,status:`streaming`,raw:o,...s===void 0?{}:{partial:s},...a?.reasoning===void 0?{}:{reasoning:a.reasoning}};return i>=0?r[i]=c:r.push(c),{...e,parts:r}})}function Dr(e,t,n,r,i){return e.map(e=>{if(e.id!==t)return e;let a=[...e.parts],o=a.findIndex(e=>e.type===`structured-output`),s=o>=0?a[o].raw:``,c=r||s;if(c===``&&n!==void 0)try{c=JSON.stringify(n)}catch{}let l={type:`structured-output`,status:`complete`,data:n,partial:n,raw:c,...i===void 0?{}:{reasoning:i}};return o>=0?a[o]=l:a.push(l),{...e,parts:a}})}function Or(e,t,n){return e.map(e=>{if(e.id!==t)return e;let r=[...e.parts],i=r.findIndex(e=>e.type===`structured-output`);if(i<0)return r.push({type:`structured-output`,status:`error`,raw:``,errorMessage:n}),{...e,parts:r};let a=r[i];return a.status===`complete`?e:(r[i]={...a,status:`error`,errorMessage:n},{...e,parts:r})})}function kr(e,t,n,r,i){return e.map(e=>{if(e.id!==t)return e;let a=[...e.parts],o=a.findIndex(e=>e.type===`thinking`&&e.stepId===n),s={type:`thinking`,content:r,stepId:n,...i&&{signature:i}};return o>=0?a[o]=s:a.push(s),{...e,parts:a}})}var Ar=12;function jr(e){return e.some(e=>{let t=e.metadata;if(!t||typeof t!=`object`||Array.isArray(t))return!1;let n=t[_n];return typeof n==`object`&&!!n&&!Array.isArray(n)&&n.kind===`generic`})}var Mr=class e{chunkStrategy;events;jsonParser;recordingEnabled;messages=[];messageStates=new Map;activeMessageIds=new Set;toolCallToMessage=new Map;pendingManualMessageId=null;pendingThinkingStepId=null;structuredMessageIds=new Set;structuredOutputUpdateBatches=new Map;activeRuns=new Set;finishReason=null;hasError=!1;isDone=!1;recording=null;recordingStartTime=0;constructor(e={}){this.chunkStrategy=e.chunkStrategy||new vr,this.events=e.events||{},this.jsonParser=e.jsonParser||gr,this.recordingEnabled=e.recording??!1,e.initialMessages&&(this.messages=[...e.initialMessages])}setMessages(e){this.messages=[...e],this.emitMessagesChange()}addUserMessage(e,t,n){let r=typeof e==`string`?[{type:`text`,content:e}]:e.map(e=>e),i={id:t??W(),role:`user`,parts:r,createdAt:new Date,...n==null?{}:{metadata:n}};return this.messages=[...this.messages,i],this.emitMessagesChange(),i}prepareAssistantMessage(){this.resetStreamState()}startAssistantMessage(e){this.prepareAssistantMessage();let{messageId:t}=this.ensureAssistantMessage(e);return this.pendingManualMessageId=t,t}getCurrentAssistantMessageId(){let e=null;for(let[t,n]of this.messageStates)n.role===`assistant`&&(e=t);return e}addToolResult(e,t,n){let r=this.messages.find(t=>t.parts.some(t=>t.type===`tool-call`&&t.id===e));if(!r){console.warn(`[StreamProcessor] Could not find message with tool call ${e}`);return}let i=wr(this.messages,e,t,n?`error`:void 0,n),a=qn(t),o=n?`error`:`complete`;i=Sr(i,r.id,e,a,o,n),this.messages=i,this.emitMessagesChange()}addToolApprovalResponse(e,t){this.messages=Tr(this.messages,e,t),this.emitMessagesChange()}toModelMessages(){let e=[];for(let t of this.messages)e.push(...nr(t));return e}getMessages(){return this.messages}areAllToolsComplete(){let e=this.messages.findLast(e=>e.role===`assistant`);if(!e)return!0;let t=e.parts.filter(e=>e.type===`tool-call`);if(t.length===0)return!0;let n=new Set(e.parts.filter(e=>e.type===`tool-result`).map(e=>e.toolCallId));return t.every(e=>e.state===`complete`||e.state===`approval-responded`||e.output!==void 0&&!e.approval||n.has(e.id)||Yn(e))}removeMessagesAfter(e){let t=new Set(this.messages.slice(0,e+1).map(e=>e.id));for(let e of this.structuredMessageIds)t.has(e)||this.structuredMessageIds.delete(e);for(let e of this.structuredOutputUpdateBatches.keys())t.has(e)||this.structuredOutputUpdateBatches.delete(e);for(let e of this.messageStates.keys())t.has(e)||this.messageStates.delete(e);for(let[e,n]of this.toolCallToMessage)t.has(n)||this.toolCallToMessage.delete(e);for(let e of this.activeMessageIds)t.has(e)||this.activeMessageIds.delete(e);this.messages=this.messages.slice(0,e+1),this.emitMessagesChange()}clearMessages(){this.messages=[],this.messageStates.clear(),this.activeMessageIds.clear(),this.toolCallToMessage.clear(),this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.pendingManualMessageId=null,this.emitMessagesChange()}async process(e){this.resetStreamState(),this.recordingEnabled&&this.startRecording();for await(let t of e)this.processChunk(t);return this.finalizeStream(),this.recording&&(this.recording.result=this.getResult()),this.getResult()}processChunk(e){switch(this.recording&&this.recording.chunks.push({chunk:e,timestamp:Date.now(),index:this.recording.chunks.length}),e.type){case`TEXT_MESSAGE_START`:this.handleTextMessageStartEvent(e);break;case`TEXT_MESSAGE_CONTENT`:this.handleTextMessageContentEvent(e);break;case`TEXT_MESSAGE_END`:this.handleTextMessageEndEvent(e);break;case`TOOL_CALL_START`:this.handleToolCallStartEvent(e);break;case`TOOL_CALL_ARGS`:this.handleToolCallArgsEvent(e);break;case`TOOL_CALL_END`:this.handleToolCallEndEvent(e);break;case`RUN_FINISHED`:this.handleRunFinishedEvent(e);break;case`RUN_ERROR`:this.handleRunErrorEvent(e);break;case`STEP_FINISHED`:this.handleStepFinishedEvent(e);break;case`MESSAGES_SNAPSHOT`:this.handleMessagesSnapshotEvent(e);break;case`CUSTOM`:this.handleCustomEvent(e);break;case`RUN_STARTED`:this.handleRunStartedEvent(e);break;case`REASONING_START`:case`REASONING_MESSAGE_START`:case`REASONING_MESSAGE_END`:case`REASONING_END`:break;case`REASONING_MESSAGE_CONTENT`:this.handleReasoningMessageContentEvent(e);break;case`REASONING_ENCRYPTED_VALUE`:this.handleReasoningEncryptedValueEvent(e);break;case`TOOL_CALL_RESULT`:this.handleToolCallResultEvent(e);break;case`STEP_STARTED`:this.handleStepStartedEvent(e)}}createMessageState(e,t){let n={id:e,role:t,totalTextContent:``,currentSegmentText:``,lastEmittedText:``,hasSeenReasoningEvents:!1,thinkingSteps:new Map,thinkingStepSignatures:new Map,thinkingStepOrder:[],currentThinkingStepId:null,toolCalls:new Map,toolCallOrder:[],hasToolCallsSinceTextStart:!1,isComplete:!1};return this.messageStates.set(e,n),n}getMessageState(e){return this.messageStates.get(e)}consumePendingThinkingStep(e){if(!this.pendingThinkingStepId)return;let t=this.pendingThinkingStepId;e.currentThinkingStepId=t,e.thinkingSteps.has(t)||(e.thinkingSteps.set(t,``),e.thinkingStepOrder.push(t)),this.pendingThinkingStepId=null}getActiveAssistantMessageId(){let e=Array.from(this.activeMessageIds).reverse();for(let t of e){let e=this.messageStates.get(t);if(e&&e.role===`assistant`)return t}return null}ensureAssistantMessage(e){if(e){let t=this.getMessageState(e);if(t)return{messageId:e,state:t}}let t=this.getActiveAssistantMessageId();if(t){let e=this.getMessageState(t);if(e)return{messageId:t,state:e}}if(e){let t=this.messages.find(t=>t.id===e);if(t){let n=this.createMessageState(e,t.role);this.activeMessageIds.add(e);let r=t.parts.length>0?t.parts[t.parts.length-1]:null;return r&&r.type===`text`&&(n.currentSegmentText=r.content,n.lastEmittedText=r.content,n.totalTextContent=r.content),{messageId:e,state:n}}}let n=e||W(),r={id:n,role:`assistant`,parts:[],createdAt:new Date};this.messages=[...this.messages,r];let i=this.createMessageState(n,`assistant`);return this.activeMessageIds.add(n),this.pendingManualMessageId=n,this.events.onStreamStart?.(),this.emitMessagesChange(),{messageId:n,state:i}}mergeMessageMetadata(e,t){if(typeof t!=`object`||!t||Array.isArray(t))return;let n=this.messages.find(t=>t.id===e);if(!n)return;let r=t,i=P(r),a=i!=null&&(`content`in i||`args`in i)?{...r,tanstack:Object.fromEntries(Object.entries(i).filter(([e])=>e!==`content`&&e!==`args`))}:r,o=Wt(n.metadata,a),s=P(r)?.createdAt,c=typeof s==`string`?new Date(s):void 0,l=c!==void 0&&!Number.isNaN(c.getTime());this.messages=this.messages.map(t=>t.id===e?{...t,...o===void 0?{}:{metadata:o},...l?{createdAt:c}:{}}:t),this.emitMessagesChange()}handleTextMessageStartEvent(e){let{messageId:t,role:n}=e,r=n===`user`||n===`system`?n:`assistant`;if(this.pendingManualMessageId){let n=this.pendingManualMessageId;if(this.pendingManualMessageId=null,n!==t){this.messages=this.messages.map(e=>e.id===n?{...e,id:t}:e);let e=this.messageStates.get(n);e&&(e.id=t,this.messageStates.delete(n),this.messageStates.set(t,e)),this.activeMessageIds.delete(n),this.activeMessageIds.add(t);for(let[e,r]of this.toolCallToMessage)r===n&&this.toolCallToMessage.set(e,t)}this.messageStates.has(t)||(this.createMessageState(t,r),this.activeMessageIds.add(t)),this.mergeMessageMetadata(t,e.metadata),this.emitMessagesChange();return}if(this.messages.find(e=>e.id===t)){this.activeMessageIds.add(t);let n=this.messageStates.get(t);n?n.hasToolCallsSinceTextStart&&=(n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(t),n.currentSegmentText=``,n.lastEmittedText=``,!1):this.createMessageState(t,r),this.mergeMessageMetadata(t,e.metadata);return}let i={id:t,role:r,parts:[],createdAt:new Date};this.messages=[...this.messages,i],this.createMessageState(t,r),this.activeMessageIds.add(t),this.mergeMessageMetadata(t,e.metadata),this.events.onStreamStart?.(),this.emitMessagesChange()}handleTextMessageEndEvent(e){let{messageId:t}=e;this.mergeMessageMetadata(t,e.metadata);let n=this.getMessageState(t);n&&(n.isComplete||n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(t))}handleMessagesSnapshotEvent(e){this.resetStreamState();let t=this.messages,n=new Map(t.map(e=>[e.id,e])),r=this.mergeReasoningFanOut(e.messages.map(cr));this.messages=this.reconcileSnapshotToolCalls(r,t).map(e=>{if(e.metadata!=null)return e;let t=n.get(e.id);return t?.metadata==null?e:{...e,metadata:t.metadata}}),this.emitMessagesChange()}mergeReasoningFanOut(e){let t=[],n=[],r=e=>e.parts.filter(e=>e.type===`thinking`),i=e=>e.role===`assistant`&&e.parts.length>0&&e.parts.every(e=>e.type===`thinking`),a=e=>e.role===`assistant`&&e.parts.length===1&&e.parts[0]?.type===`tool-result`,o=()=>{t.push(...n),n=[]};for(let s of e){if(i(s)){n.push(s);continue}if(s.role===`assistant`&&n.length>0&&!a(s)){t.push({...s,parts:[...n.flatMap(r),...s.parts]}),n=[];continue}o(),t.push(s)}return o(),t}reconcileSnapshotToolCalls(e,t){let n=new Map;for(let e of t)for(let t of e.parts)t.type===`tool-call`&&n.set(t.id,t);let r=new Set;for(let t of e)for(let e of t.parts)e.type===`tool-call`&&r.add(e.id);let i=[];for(let t of e){let e=t.role===`assistant`&&t.parts.length===1?t.parts.find(e=>e.type===`tool-result`):void 0;if(!e){i.push(t);continue}let a=i.findLast(t=>t.parts.some(t=>t.type===`tool-call`&&t.id===e.toolCallId))??i.findLast(e=>e.role===`assistant`&&!(e.parts.length===1&&e.parts[0]?.type===`tool-result`));if(!a){r.has(e.toolCallId)||console.warn(`[StreamProcessor] MESSAGES_SNAPSHOT contains a tool-result for "${e.toolCallId}" but no matching tool-call exists in the snapshot, and there is no assistant message to anchor into; addToolResult("${e.toolCallId}") will not be able to locate this call`),i.push(t);continue}let o=[...a.parts];if(!r.has(e.toolCallId)&&!o.some(t=>t.type===`tool-call`&&t.id===e.toolCallId)){let t=n.get(e.toolCallId);t?(o.push({...t}),r.add(t.id)):console.warn(`[StreamProcessor] MESSAGES_SNAPSHOT contains a tool-result for "${e.toolCallId}" but no matching tool-call exists in the snapshot or the pre-snapshot state; addToolResult("${e.toolCallId}") will not be able to locate this call`)}o.push(e),a.parts=o}return this.enrichSnapshotToolCallsFromResults(i,n)}enrichSnapshotToolCallsFromResults(e,t){let n=new Map;for(let t of e)for(let e of t.parts)e.type===`tool-result`&&n.set(e.toolCallId,e);return e.map(e=>{let r=e.parts.map(e=>{if(e.type!==`tool-call`)return e;let r=t.get(e.id),i=n.get(e.id),a=e;if(r&&(r.output!==void 0||r.state===`complete`||r.state===`error`)&&(e.output===void 0||e.state===`input-complete`||e.state===`input-streaming`||e.state===`awaiting-input`)&&(a={...e,...r.output===void 0?{}:{output:r.output},state:r.state,...r.approval===void 0?{}:{approval:r.approval},...r.metadata===void 0?{}:{metadata:r.metadata}}),i&&a.output===void 0){let e;if(Array.isArray(i.content))e=i.content;else try{e=JSON.parse(i.content)}catch{e=i.content}let t=i.state===`error`?this.extractToolResultError(e):void 0;a={...a,output:t?{error:t}:e,state:i.state===`error`?`error`:`complete`}}return a});return r.some((t,n)=>t!==e.parts[n])?{...e,parts:r}:e})}handleTextMessageContentEvent(e){let{messageId:t,state:n}=this.ensureAssistantMessage(e.messageId);if(this.mergeMessageMetadata(t,e.metadata),this.structuredMessageIds.has(t)){let r=e.delta||``;r!==``&&(this.messages=Er(this.messages,t,r),n.totalTextContent+=r,this.queueStructuredOutputUpdate(t,r),this.emitMessagesChange());return}let r=n.currentSegmentText;n.hasToolCallsSinceTextStart&&r.length>0&&this.isNewTextSegment(e,r)&&(r!==n.lastEmittedText&&this.emitTextUpdateForMessage(t),n.currentSegmentText=``,n.lastEmittedText=``,n.hasToolCallsSinceTextStart=!1);let i=n.currentSegmentText,a=e.delta||``,o=a===``?i:i+a,s=o.slice(i.length);n.currentSegmentText=o,n.totalTextContent+=s;let c=e.delta||``;this.chunkStrategy.shouldEmit(c,n.currentSegmentText)&&n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(t)}handleToolCallStartEvent(e){let t=e.parentMessageId??this.getActiveAssistantMessageId(),{messageId:n,state:r}=this.ensureAssistantMessage(t??void 0);r.hasToolCallsSinceTextStart=!0;let i=e.toolCallId;if(!r.toolCalls.get(i)){let t=`awaiting-input`,a=e.toolCallName,o=e.metadata,s={id:e.toolCallId,name:a,arguments:``,state:t,parsedArguments:void 0,index:r.toolCalls.size,...o!==void 0&&{metadata:o}};r.toolCalls.set(i,s),r.toolCallOrder.push(i),this.toolCallToMessage.set(i,n),this.messages=xr(this.messages,n,{id:e.toolCallId,name:a,arguments:``,state:t,...o!==void 0&&{metadata:o}}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(n,e.toolCallId,t,``)}}handleToolCallArgsEvent(e){let t=e.toolCallId,n=this.toolCallToMessage.get(t);if(!n)return;let r=this.getMessageState(n);if(!r)return;let i=r.toolCalls.get(t);if(!i)return;let a=i.state===`awaiting-input`;i.arguments+=e.delta||``,a&&e.delta&&(i.state=`input-streaming`),i.parsedArguments=this.jsonParser.parse(i.arguments),this.messages=xr(this.messages,n,{id:i.id,name:i.name,arguments:i.arguments,state:i.state}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(n,i.id,i.state,i.arguments)}handleToolCallEndEvent(e){let t=this.toolCallToMessage.get(e.toolCallId);if(!t)return;let n=this.getMessageState(t);if(!n)return;let r=e.input===void 0?P(e)?.input:e.input,i=n.toolCalls.get(e.toolCallId);if(i&&i.state!==`input-complete`){if(r!==void 0&&!i.arguments)try{i.arguments=JSON.stringify(r)}catch{}let a=n.toolCallOrder.indexOf(e.toolCallId);this.completeToolCall(t,a,i),r!==void 0&&(i.parsedArguments=r,this.messages=xr(this.messages,t,{id:i.id,name:i.name,arguments:i.arguments,state:`input-complete`,input:r,...i.metadata!==void 0&&{metadata:i.metadata}}),this.emitMessagesChange())}}extractToolResultError(e){return e&&typeof e==`object`&&`error`in e&&typeof e.error==`string`?e.error:typeof e==`string`?e:`Tool execution failed`}handleToolCallResultEvent(e){let t=this.toolCallToMessage.get(e.toolCallId)??this.messages.find(t=>t.parts.some(t=>t.type===`tool-call`&&t.id===e.toolCallId))?.id;if(!t)return;let n=e.state===`output-error`||P(e)?.state===`output-error`,r;try{r=JSON.parse(e.content)}catch{r=e.content}this.messages=wr(this.messages,e.toolCallId,r,n?`error`:void 0);let i=n?`error`:`complete`;this.messages=Sr(this.messages,t,e.toolCallId,e.content,i,i===`error`?this.extractToolResultError(r):void 0),this.emitMessagesChange()}handleRunStartedEvent(e){this.activeRuns.add(e.runId)}handleRunFinishedEvent(e){let t=e;this.finishReason=t.finishReason===void 0?P(e)?.finishReason??null:t.finishReason,this.activeRuns.delete(e.runId),e.outcome?.type===`interrupt`&&this.handleInterrupts(e.outcome.interrupts),this.activeRuns.size===0&&(this.isDone=!0,this.completeAllToolCalls(),this.finalizeStream())}handleInterrupts(e){let t=jr(e);for(let n of e){let e=n.metadata&&typeof n.metadata==`object`?n.metadata:{},r=typeof e.kind==`string`?e.kind:void 0,i=n.toolCallId;if(!i)continue;let a=typeof e.toolName==`string`?e.toolName:this.findToolCallName(i),o=Object.hasOwn(e,`input`)?e.input:{};if(r===`approval`||n.reason===`approval_required`){let e=this.getActiveAssistantMessageId()??this.toolCallToMessage.get(i)??this.messages.find(e=>e.role===`assistant`&&e.parts.some(e=>e.type===`tool-call`&&e.id===i))?.id;e&&(this.messages=Cr(this.messages,e,i,n.id),this.emitMessagesChange()),this.events.onApprovalRequest?.({toolCallId:i,toolName:a,input:o,approvalId:n.id});continue}if(r===`client_tool`||n.reason===`client_tool_input`){if(t)continue;this.events.onToolCall?.({toolCallId:i,toolName:a,input:o})}}}findToolCallName(e){for(let t of this.messageStates.values()){let n=t.toolCalls.get(e);if(n)return n.name}return``}handleRunErrorEvent(e){this.hasError=!0;let t=pr(e);t?this.activeRuns.delete(t):this.activeRuns.clear();let{messageId:n}=this.ensureAssistantMessage(),r=e.message||`An error occurred`;e.message||console.error(`[StreamProcessor] RUN_ERROR with no message; original chunk:`,e),this.structuredMessageIds.has(n)&&(this.flushStructuredOutputUpdate(n),this.messages=Or(this.messages,n,r),this.structuredMessageIds.delete(n),this.emitStructuredOutputChange(n,`error`),this.emitMessagesChange()),this.events.onError?.(yr(e))}handleStepStartedEvent(e){let t=e.stepName||W(),n=this.getActiveAssistantMessageId();if(n){let e=this.getMessageState(n);if(e){e.currentThinkingStepId=t,e.thinkingSteps.has(t)||(e.thinkingSteps.set(t,``),e.thinkingStepOrder.push(t)),this.pendingThinkingStepId=null;return}}this.pendingThinkingStepId=t}handleStepFinishedEvent(e){let t=e,n=t.signature;if(!n)return;let{messageId:r,state:i}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0),a=i.currentThinkingStepId??t.stepId;if(!a)return;let o=i.thinkingSteps.get(a);o!==void 0&&(i.thinkingStepSignatures.set(a,n),this.messages=kr(this.messages,r,a,o,n),this.emitMessagesChange())}handleReasoningMessageContentEvent(e){let{messageId:t,state:n}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0);n.hasSeenReasoningEvents=!0;let r=e.delta||``;this.consumePendingThinkingStep(n);let i=n.currentThinkingStepId??e.messageId;n.thinkingSteps.has(i)||(n.thinkingSteps.set(i,``),n.thinkingStepOrder.push(i),n.currentThinkingStepId=i);let a=(n.thinkingSteps.get(i)??``)+r;n.thinkingSteps.set(i,a),this.messages=kr(this.messages,t,i,a,n.thinkingStepSignatures.get(i)),this.emitMessagesChange(),this.events.onThinkingUpdate?.(t,i,a)}handleReasoningEncryptedValueEvent(e){let t=e.encryptedValue;if(typeof t!=`string`||t===``)return;if(e.subtype===`tool-call`){this.attachToolCallSignature(e.entityId,t);return}let{messageId:n,state:r}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0),i=r.currentThinkingStepId??e.entityId;r.thinkingStepSignatures.set(i,t);let a=r.thinkingSteps.get(i)??``;r.thinkingSteps.has(i)||(r.thinkingSteps.set(i,a),r.thinkingStepOrder.push(i)),this.messages=kr(this.messages,n,i,a,t),this.emitMessagesChange()}attachToolCallSignature(e,t){this.messages=this.messages.map(n=>{let r=!1,i=n.parts.map(n=>n.type!==`tool-call`||n.id!==e?n:(r=!0,{...n,metadata:{...n.metadata!=null&&typeof n.metadata==`object`?n.metadata:{},thoughtSignature:t}}));return r?{...n,parts:i}:n});for(let n of this.messageStates.values()){let r=n.toolCalls.get(e);r&&(r.metadata={...r.metadata??{},thoughtSignature:t})}this.emitMessagesChange()}handleCustomEvent(e){let t=this.getActiveAssistantMessageId();if(e.name===`structured-output.start`&&e.value){let n=e.value,{messageId:r}=this.ensureAssistantMessage(n.messageId??t??void 0);r&&(this.structuredMessageIds.add(r),this.structuredOutputUpdateBatches.delete(r),this.events.onStructuredOutputChange?.({phase:`start`,messageId:r,status:`streaming`,raw:``}));return}if(e.name===`structured-output.complete`&&e.value){let n=e.value,{messageId:r}=this.ensureAssistantMessage(n.messageId??t??void 0);r&&(this.flushStructuredOutputUpdate(r),this.messages=Dr(this.messages,r,n.object,n.raw??``,n.reasoning),this.structuredMessageIds.delete(r),this.emitStructuredOutputChange(r,`complete`),this.emitMessagesChange())}if(e.name===`tool-input-available`&&e.value){let{toolCallId:t,toolName:n,input:r}=e.value;this.events.onToolCall?.({toolCallId:t,toolName:n,input:r});return}if(e.name===`approval-requested`&&e.value){let{toolCallId:n,toolName:r,input:i,approval:a}=e.value,o=t??this.toolCallToMessage.get(n);o&&(this.messages=Cr(this.messages,o,n,a.id),this.emitMessagesChange()),this.events.onApprovalRequest?.({toolCallId:n,toolName:r,input:i,approvalId:a.id});return}if(e.name===`ui-resource`&&e.value){let n=e.value,r=this.toolCallToMessage.get(n.toolCallId)??t;if(r){let e={type:`ui-resource`,resource:n.resource,toolCallId:n.toolCallId,toolName:n.toolName,...n.serverId!==void 0&&{serverId:n.serverId},...n.meta!==void 0&&{meta:n.meta}};this.messages=this.messages.map(t=>t.id===r?{...t,parts:[...t.parts,e]}:t),this.emitMessagesChange()}else console.warn(`[mcp-apps] dropped ui-resource: no target message for toolCallId "${n.toolCallId}" (toolName "${n.toolName}")`);return}if(this.events.onCustomEvent){let t=e.value&&typeof e.value==`object`?e.value.toolCallId:void 0;this.events.onCustomEvent(e.name,e.value,{toolCallId:t})}}isNewTextSegment(e,t){return!0}completeAllToolCalls(){for(let e of this.activeMessageIds)this.completeAllToolCallsForMessage(e)}completeAllToolCallsForMessage(e){let t=this.getMessageState(e);t&&t.toolCalls.forEach((n,r)=>{if(n.state!==`input-complete`){let i=t.toolCallOrder.indexOf(r);this.completeToolCall(e,i,n)}})}completeToolCall(e,t,n){n.state=`input-complete`;let r=!1;try{n.parsedArguments=JSON.parse(n.arguments),r=!0}catch{n.parsedArguments=void 0}this.isToolCallPartErrored(n.id)||this.isToolCallPartAwaitingUserAction(n.id)||(this.messages=xr(this.messages,e,{id:n.id,name:n.name,arguments:n.arguments,state:`input-complete`,...r&&{input:n.parsedArguments},...n.metadata!==void 0&&{metadata:n.metadata}}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(e,n.id,`input-complete`,n.arguments))}isToolCallPartAwaitingUserAction(e){return this.messages.some(t=>t.parts?.some(t=>t.type===`tool-call`&&t.id===e&&(t.state===`approval-requested`||t.state===`approval-responded`)))}isToolCallPartErrored(e){return this.messages.some(t=>t.parts?.some(t=>t.type===`tool-call`&&t.id===e&&t.state===`error`))}emitTextUpdateForMessage(e){let t=this.getMessageState(e);t&&(t.lastEmittedText=t.currentSegmentText,this.messages=br(this.messages,e,t.currentSegmentText),this.emitMessagesChange(),this.events.onTextUpdate?.(e,t.currentSegmentText))}queueStructuredOutputUpdate(e,t){let n=this.structuredOutputUpdateBatches.get(e),r={delta:`${n?.delta??``}${t}`,chunkCount:(n?.chunkCount??0)+1};this.structuredOutputUpdateBatches.set(e,r),r.chunkCount>=Ar&&this.flushStructuredOutputUpdate(e)}flushStructuredOutputUpdate(e){let t=this.structuredOutputUpdateBatches.get(e);!t||t.chunkCount===0||(this.structuredOutputUpdateBatches.delete(e),this.emitStructuredOutputChange(e,`update`,t.delta))}emitStructuredOutputChange(e,t,n){let r=this.messages.find(t=>t.id===e)?.parts.find(e=>e.type===`structured-output`);r&&this.events.onStructuredOutputChange?.({phase:t,messageId:e,status:r.status,raw:r.raw,...r.partial===void 0?{}:{partial:r.partial},...r.data===void 0?{}:{data:r.data},...r.reasoning===void 0?{}:{reasoning:r.reasoning},...r.errorMessage===void 0?{}:{errorMessage:r.errorMessage},...n===void 0?{}:{delta:n}})}emitMessagesChange(){this.events.onMessagesChange?.([...this.messages])}finalizeStream(){let e;for(let t of this.activeMessageIds){let n=this.getMessageState(t);if(!n)continue;this.completeAllToolCallsForMessage(t),n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(t),n.isComplete=!0;let r=this.messages.find(e=>e.id===t);r&&r.role===`assistant`&&(e=r)}for(let e of this.structuredMessageIds)this.flushStructuredOutputUpdate(e),this.messages=Or(this.messages,e,`Stream ended without structured-output.complete`),this.emitStructuredOutputChange(e,`error`);if(this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.activeMessageIds.clear(),e&&!this.hasError&&this.isWhitespaceOnlyMessage(e)){this.messages=this.messages.filter(t=>t.id!==e.id),this.emitMessagesChange();return}e&&this.events.onStreamEnd?.(e)}getCompletedToolCalls(){let e=[];for(let t of this.messageStates.values())for(let n of t.toolCalls.values())n.state===`input-complete`&&e.push({id:n.id,type:`function`,function:{name:n.name,arguments:n.arguments},...n.metadata!==void 0&&{metadata:n.metadata}});return e}getResult(){let e=this.getCompletedToolCalls(),t=``,n=``;for(let e of this.messageStates.values()){t+=e.totalTextContent;for(let t of e.thinkingStepOrder)n+=e.thinkingSteps.get(t)??``}return{content:t,thinking:n||void 0,toolCalls:e.length>0?e:void 0,finishReason:this.finishReason}}getState(){let e=``,t=``,n=new Map,r=[];for(let i of this.messageStates.values()){e+=i.totalTextContent;for(let e of i.thinkingStepOrder)t+=i.thinkingSteps.get(e)??``;for(let[e,t]of i.toolCalls)n.set(e,t);r.push(...i.toolCallOrder)}return{content:e,thinking:t,toolCalls:n,toolCallOrder:r,finishReason:this.finishReason,done:this.isDone}}startRecording(){this.recordingEnabled=!0,this.recordingStartTime=Date.now(),this.recording={version:`1.0`,timestamp:this.recordingStartTime,chunks:[]}}getRecording(){return this.recording}resetStreamState(){this.messageStates.clear(),this.activeMessageIds.clear(),this.activeRuns.clear(),this.toolCallToMessage.clear(),this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.pendingManualMessageId=null,this.pendingThinkingStepId=null,this.finishReason=null,this.hasError=!1,this.isDone=!1,this.chunkStrategy.reset?.()}reset(){this.resetStreamState(),this.messages=[]}isWhitespaceOnlyMessage(e){return e.parts.length!==0&&e.parts.every(e=>e.type===`text`&&e.content.trim()===``)}static async replay(t,n){return new e(n).process(Nr(t))}};function Nr(e){return{async*[Symbol.asyncIterator](){for(let{chunk:t}of e.chunks)yield t}}}var Pr=function(e){return e.TEXT_MESSAGE_START=`TEXT_MESSAGE_START`,e.TEXT_MESSAGE_CONTENT=`TEXT_MESSAGE_CONTENT`,e.TEXT_MESSAGE_END=`TEXT_MESSAGE_END`,e.TEXT_MESSAGE_CHUNK=`TEXT_MESSAGE_CHUNK`,e.TOOL_CALL_START=`TOOL_CALL_START`,e.TOOL_CALL_ARGS=`TOOL_CALL_ARGS`,e.TOOL_CALL_END=`TOOL_CALL_END`,e.TOOL_CALL_CHUNK=`TOOL_CALL_CHUNK`,e.TOOL_CALL_RESULT=`TOOL_CALL_RESULT`,e.THINKING_START=`THINKING_START`,e.THINKING_END=`THINKING_END`,e.THINKING_TEXT_MESSAGE_START=`THINKING_TEXT_MESSAGE_START`,e.THINKING_TEXT_MESSAGE_CONTENT=`THINKING_TEXT_MESSAGE_CONTENT`,e.THINKING_TEXT_MESSAGE_END=`THINKING_TEXT_MESSAGE_END`,e.STATE_SNAPSHOT=`STATE_SNAPSHOT`,e.STATE_DELTA=`STATE_DELTA`,e.MESSAGES_SNAPSHOT=`MESSAGES_SNAPSHOT`,e.ACTIVITY_SNAPSHOT=`ACTIVITY_SNAPSHOT`,e.ACTIVITY_DELTA=`ACTIVITY_DELTA`,e.RAW=`RAW`,e.CUSTOM=`CUSTOM`,e.RUN_STARTED=`RUN_STARTED`,e.RUN_FINISHED=`RUN_FINISHED`,e.RUN_ERROR=`RUN_ERROR`,e.STEP_STARTED=`STEP_STARTED`,e.STEP_FINISHED=`STEP_FINISHED`,e.REASONING_START=`REASONING_START`,e.REASONING_MESSAGE_START=`REASONING_MESSAGE_START`,e.REASONING_MESSAGE_CONTENT=`REASONING_MESSAGE_CONTENT`,e.REASONING_MESSAGE_END=`REASONING_MESSAGE_END`,e.REASONING_MESSAGE_CHUNK=`REASONING_MESSAGE_CHUNK`,e.REASONING_END=`REASONING_END`,e.REASONING_ENCRYPTED_VALUE=`REASONING_ENCRYPTED_VALUE`,e}({}),Fr=/^[a-z][a-z0-9-]{0,63}$/;function Ir(e){return typeof e==`string`&&Fr.test(e)}function Lr(e){if(typeof e!=`object`||!e||!(`error`in e))return!1;let t=e.error;return!(typeof t!=`object`||!t||!(`type`in t)||t.type!==`byok_missing`||!(`provider`in t)||typeof t.provider!=`string`||!Ir(t.provider)||!(`message`in t)||typeof t.message!=`string`)}var Rr=class extends Error{provider;constructor(e){super(`Missing ${e} API key`),this.name=`ByokMissingError`,this.provider=e}},zr=class extends Error{provider;reason;constructor(e,t){super(t===`locked`?`${e} key is locked`:`Missing ${e} API key`),this.name=`ByokBlockedError`,this.provider=e,this.reason=t}},Br=class extends Error{constructor(){super(`BYOK is enabled but no provider slug was resolved. Pass byokProvider or forwardedProps.provider.`),this.name=`ByokUnresolvedProviderError`}},Vr=new WeakMap;function G(e){return Vr.get(e)??pr(e)}var Hr=class extends Error{constructor(){super(`Stream ended with unterminated trailing data — connection was likely cut short.`),this.name=`StreamTruncatedError`}},Ur=class extends Error{constructor(e){super(`Stream response body read failed`,{cause:e}),this.name=`StreamReadError`}},Wr=class extends Error{constructor(){super(`Durable run ended without a terminal event and could not resume — the run did not complete.`),this.name=`DurableStreamIncompleteError`}},Gr=class extends Error{constructor(e){super(`Durable run exceeded its reconnect ceiling of ${e} attempts — giving up.`),this.name=`StreamReconnectLimitError`}};function Kr(e){let t=e?.maxAttempts??5,n=e?.delayMs??250;if(!Number.isInteger(t)||t<0)throw Error(`Invalid reconnect.maxAttempts: ${t}. Must be a non-negative integer.`);if(!Number.isFinite(n)||n<0)throw Error(`Invalid reconnect.delayMs: ${n}. Must be a non-negative finite number.`);return{maxAttempts:t,delayMs:n}}function qr(e){let t=Kr(e),n=new Set,r,i=0;return{get lastEventId(){return r},note(e){return e===void 0?`new`:e===``?(r=void 0,n.clear(),`reset`):n.has(e)?`duplicate`:(n.add(e),r=e,`new`)},async waitBeforeReconnect(e,n){if(e)i=0;else if(i+=1,i>t.maxAttempts)throw new Gr(t.maxAttempts);await Jr(t.delayMs,n)}}}function Jr(e,t){return e<=0||t?.aborted?Promise.resolve():new Promise(n=>{let r=()=>{clearTimeout(i),n()},i=setTimeout(()=>{t?.removeEventListener(`abort`,r),n()},e);t?.addEventListener(`abort`,r,{once:!0})})}function Yr(e){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function Xr(e,t){if(!e)throw Error(`Cannot synthesize terminal event: ${t} not supplied via runContext and not observed in the upstream stream.`);return e}function K(e){if(!e)return{};if(e instanceof Headers){let t={};return e.forEach((e,n)=>{t[n]=e}),t}return e}var Zr=`X-Run-Id`;function Qr(e){return e===void 0?{}:{[Zr]:e}}function $r(e,t){let n=e.indexOf(`#`),r=n===-1?``:e.slice(n),i=n===-1?e:e.slice(0,n),a=i.indexOf(`?`),o=a===-1?i:i.slice(0,a),s=new URLSearchParams(a===-1?``:i.slice(a+1));for(let[e,n]of Object.entries(t))s.set(e,n);let c=s.toString();return`${o}${c.length===0?``:`?${c}`}${r}`}async function*ei(e,t){try{let n=Lt(),r=``;for(;!t?.aborted;){let i;try{i=await e.read()}catch(e){if(t?.aborted)return;throw new Ur(e)}let{done:a,value:o}=i;if(a)break;r+=n.decode(o,{stream:!0});let s=r.split(`
25
- `);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 Hr}finally{e.releaseLock()}}function ti(e){return Un(e)}function ni(e){let t=P(e)?.model;if(typeof t==`string`)return t;let n=`usage`in e?e.usage:void 0;if(Array.isArray(n)){let e=n[0]?.model;if(typeof e==`string`)return e}}async function*ri(e,t){let n,r,i,a;for await(let o of e){if(o===`id`||o.startsWith(`id:`)){let e=o===`id`?``:o.slice(3);a=e.startsWith(` `)?e.slice(1):e;continue}if(o.startsWith(`:`)||o.startsWith(`event:`)||o.startsWith(`retry:`))continue;let e=Rt(o);if(e===`[DONE]`){yield{chunk:Gt({type:Pr.RUN_FINISHED,threadId:n??t?.threadId??``,runId:r??t?.runId??``,timestamp:Date.now()},{finishReason:`stop`,...i===void 0?{}:{model:i}})};return}let s=ti(JSON.parse(e));`threadId`in s&&typeof s.threadId==`string`&&(n=s.threadId),`runId`in s&&typeof s.runId==`string`&&(r=s.runId);let c=ni(s);c!==void 0&&(i=c);let l=a;a=void 0,yield{chunk:s,...l===void 0?{}:{id:l}}}}async function ii(e){if(!e.ok){if(e.status===401){let t=await e.clone().json().catch(()=>null);if(Lr(t))throw new Rr(t.error.provider)}throw Error(`HTTP error! status: ${e.status} ${e.statusText}`)}}async function ai(e,t,n,r,i){let a=await e($r(t,{threadId:i}),{method:`GET`,headers:{Accept:`application/json`,...n},credentials:r});await ii(a);let o=await a.json(),s=o.activeRun&&typeof o.activeRun.runId==`string`?{runId:o.activeRun.runId}:null,c=o.interrupts&&typeof o.interrupts.runId==`string`&&Array.isArray(o.interrupts.pending)&&o.interrupts.pending.length>0?{runId:o.interrupts.runId,pending:o.interrupts.pending}:null;return{messages:Array.isArray(o.messages)?o.messages:[],activeRun:s,interrupts:c}}async function oi(e,t,n,r,i){let a=await e($r(t,{threadId:i}),{method:`GET`,headers:{Accept:`application/json`,...n},credentials:r});await ii(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*si(e,t,n){await ii(e),yield*ri(ei(It(e),t),n)}async function*ci(e,t){for await(let{chunk:n}of si(e,t))yield n}function li(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 Ur(e)}yield*r(o,a)}}async function*ui(e,t,n){let r=qr(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 Hr||e instanceof Ur)&&r.lastEventId!==void 0){await r.waitBeforeReconnect(a,t);continue}throw e}if(t?.aborted||i)return;if(r.lastEventId!==void 0){if(a){await r.waitBeforeReconnect(!0,t);continue}throw new Wr}return}}function di(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=[];function o(e,t){t&&Vr.set(e,t);let n=a.shift();n?n(e):i.push(e)}return{subscribe(e){let t=i.splice(0),n=[];return i=t,a=n,(async function*(){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)}})()},async send(t,n,r,i){let a=!1,s,c;try{let l=e.connect(t,n,r,i);for await(let e of l)`threadId`in e&&typeof e.threadId==`string`&&(s=e.threadId),`runId`in e&&typeof e.runId==`string`&&(c=e.runId),(e.type===`RUN_FINISHED`||e.type===`RUN_ERROR`)&&(a=!0),o(e,i?.runId);!r?.aborted&&!a&&o(Gt({type:Pr.RUN_FINISHED,threadId:Xr(s??i?.threadId,`threadId`),runId:Xr(c??i?.runId,`runId`),timestamp:Date.now()},{finishReason:`stop`,model:`connect-wrapper`}),i?.runId)}catch(e){if(!r?.aborted&&!a)try{let t=e instanceof Error?e.message:`Unknown error in connect()`;o({type:Pr.RUN_ERROR,threadId:Xr(s??i?.threadId,`threadId`),runId:Xr(c??i?.runId,`runId`),timestamp:Date.now(),message:t},i?.runId)}catch{}throw e}},...typeof e.joinRun==`function`?{joinRun:(t,n)=>e.joinRun(t,n)}:{},...(()=>{let t=e.hydrate;return typeof t==`function`?{hydrate:e=>t(e)}:{}})()}}function fi(e,t,n,r){let i=An(e),a={...r.body,...n?.forwardedProps??{},...t};return{threadId:n?.threadId??Yr(`thread`),runId:n?.runId??Yr(`run`),...n?.parentRunId!==void 0&&{parentRunId:n.parentRunId},...n?.resume!==void 0&&{resume:n.resume},state:{},messages:i,tools:n?.clientTools??[],context:[],forwardedProps:a,data:{...a}}}function pi(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`,...K(s.headers),...K(a?.headers),...Qr(a?.runId)},l=fi(n,r,a,s),u=s.fetchClient??fetch,d=i||s.signal;yield*ui(li(u,o,{method:`POST`,headers:c,body:JSON.stringify(l),credentials:s.credentials||`same-origin`},(e,t)=>si(e,t,{...a?.threadId===void 0?{}:{threadId:a.threadId},...a?.runId===void 0?{}:{runId:a.runId}})),d,s.reconnect)},async*joinRun(n,r){let i=typeof e==`function`?e():e,a=typeof t==`function`?await t():t,o=$r(i,{offset:`-1`,runId:n}),s={...K(a.headers)},c=a.fetchClient??fetch,l=r||a.signal;yield*ui(li(c,o,{method:`GET`,headers:s,credentials:a.credentials||`same-origin`},(e,t)=>si(e,t,{runId:n})),l,a.reconnect)},async hydrate(n){let r=typeof e==`function`?e():e,i=typeof t==`function`?await t():t;return ai(i.fetchClient??fetch,r,K(i.headers),i.credentials||`same-origin`,n)},async hydrateGeneration(n){let r=typeof e==`function`?e():e,i=typeof t==`function`?await t():t;return oi(i.fetchClient??fetch,r,K(i.headers),i.credentials||`same-origin`,n)}}}function mi(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*ci(a,r):yield*hi(a,r)}}}async function*hi(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 q(e){return e.resumable}function gi(e,t){let n=kn(e.descriptor);return n?{...t,metadata:On(n)}:t}function _i(e){return`cancel`in e&&`clearResolution`in e}var vi=new Set([`invalid-payload`,`invalid-edited-args`,`invalid-tool-output`,`invalid-response-schema`,`unknown-interrupt`,`expired`,`stale`,`conflict`,`legacy-unsupported`]),yi=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`,`legacy-submit-failed`]);function J(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function bi(e){return J(e)&&e.kind===`approval`&&typeof e.toolName==`string`&&`input`in e}function xi(e){return J(e)&&e.kind===`client_tool`&&typeof e.toolName==`string`&&`input`in e}function Si(e){return bi(e.metadata)||xi(e.metadata)}function Ci(e){return Sn(e)}function wi(e){if(!J(e.metadata))return!1;let t=e.metadata[_n];return!J(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 Ti(e){if(!J(e.metadata))return!1;let t=e.metadata[_n];return!J(t)||t.kind!==`generic`?!1:`definitionId`in t||`key`in t||`batchIndex`in t||`payloadSchemaHash`in t}function Ei(e){return e.metadata?.[`tanstack:interruptPayload`]}function Di(e){return e===`tanstack:client_tool_execution`||e===`client_tool_input`}function Y(e){if(e.responseSchema!==void 0)try{return L(I(e.responseSchema))}catch{return}}function Oi(e){if(e!==void 0)try{return Tn(e)}catch{return}}function X(e){return e!==null&&(typeof e==`object`||typeof e==`function`)&&`then`in e&&typeof e.then==`function`}function ki(e,t,n){if(e===void 0)return{valid:!0,payload:t};if(B(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 X(r)?Promise.resolve(r).then(i):i(r)}return{valid:!0,payload:t}}function Ai(e){for(let t of vi)if(t===e)return!0;return!1}function ji(e){for(let t of yi)if(t===e)return!0;return!1}function Mi(e){if(!J(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`?t===`item`?Ai(n)&&typeof e.interruptId==`string`&&(e.source===`client`||e.source===`server`):t===`batch`&&ji(n)&&Array.isArray(e.interruptIds)&&e.interruptIds.every(e=>typeof e==`string`)&&(e.source===`client`||e.source===`server`||e.source===`transport`):!1}function Ni(e){return Mi(e)?[e]:!J(e)||!Array.isArray(e.errors)?[]:e.errors.every(Mi)?e.errors:[]}function Pi(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 Fi(e,t){return e.threadId===t.threadId&&e.interruptedRunId===t.interruptedRunId&&e.generation===t.generation&&Pi(e.interruptIds,t.interruptIds)}function Ii(e,t,n){let r=n.filter(e=>e.source!==`transport`),i=e=>t.includes(e)&&r.some(t=>Fi(e,t)),a=e.filter(e=>!i(e)),o=t.filter(e=>!r.some(t=>Fi(e,t)));return Object.freeze({rootErrors:Object.freeze([...a,...n]),submissionRootErrors:Object.freeze([...o,...r])})}function Li(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):Pi(e.interruptIds,n)}function Ri(e,t,n){let r=Y(e)??n?.responseSchemaHash;return R({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 zi(e,t){let n=R(e.descriptor),r=e.error===void 0?Object.freeze([]):Object.freeze([R(e.error)]),i=r[0];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,...i===void 0?{}:{error:i},canResolve:e.canResolve}}var Bi=class{options;hydration;items=[];snapshot=Object.freeze([]);rootErrors=Object.freeze([]);submissionRootErrors=Object.freeze([]);state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:!1});activeTransaction;activeSubmissionOperation;retrySubmission;resuming=!1;tools;interruptDefinitions;constructor(e){this.options=e,this.tools=e.tools;let t=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:R(e.interrupts)};let n=new Map;for(let t of e.interrupts){let e=Ci(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,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:!1}),this.options.onChange?.(e?.source??`live`)}getInterruptErrors(){return this.rootErrors}getResuming(){return this.resuming}resolve(e){if(this.assertRootMutable(),typeof e==`boolean`){this.resolveBooleanBulk(e);return}this.resolveTransaction(e)}cancel(){this.assertRootMutable(),this.invalidateRetry();for(let e of this.items)q(e)&&(e.validationGeneration++,e.resolution=Object.freeze(gi(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;if(!e){this.addRootError(`transport`,`There is no retryable interrupt submission.`,!1);return}this.submitBatch(e)}resolveClientToolOutput(e,t){let n=this.items.find(t=>t.kind===`client-tool-execution`&&t.binding?.kind===`client-tool-execution`&&t.binding.toolCallId===e||t.kind===`generic`&&Di(t.descriptor.reason)&&t.descriptor.toolCallId===e&&xi(t.descriptor.metadata));return n?(this.resolveItem(n.descriptor.id,t),!0):!1}resolveToolApprovalDecision(e,t){let n=this.items.find(t=>t.descriptor.id===e&&(t.kind===`tool-approval`||t.kind===`generic`&&t.descriptor.reason===`approval_required`&&bi(t.descriptor.metadata)));return n?(this.resolveItem(n.descriptor.id,{approved:t}),!0):!1}hydrateInterrupt(e,t,n){let r=R(e),i=Ci(r),a=i===void 0&&Si(r);if(i===void 0&&!a)return wi(r)?{descriptor:r,binding:Ri(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 o=i!==void 0&&i.interruptId===r.id&&i.interruptedRunId===t.interruptedRunId&&i.generation===t.generation&&Y(r)===i.responseSchemaHash,s=i!==void 0&&i.interruptId===r.id&&i.interruptedRunId===t.interruptedRunId&&i.generation===t.generation&&i.responseSchemaHash===(Y(r)??i.responseSchemaHash);if(i!==void 0&&Ti(r)&&(!s||i.kind!==`generic`||i.definitionId===void 0||i.key===void 0||i.batchIndex===void 0))return{descriptor:r,binding:Ri(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(s&&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=hn(e.approvalSchema,e.inputSchema);if(gn(e.inputSchema)===i.inputSchemaHash&&t.approvalSchemaHash===i.approvalSchemaHash&&t.responseSchemaHash===i.responseSchemaHash)return{descriptor:r,binding:R(i),kind:`tool-approval`,status:`pending`,canResolve:!0,resumable:!0,tool:e,validationGeneration:0}}catch{}}if(s&&i.kind===`client-tool-execution`){let e=this.tools?.find(e=>e.name===i.toolName);if(e!==void 0&&r.toolCallId===i.toolCallId&&gn(e.outputSchema)===i.outputSchemaHash)return{descriptor:r,binding:R(i),kind:`client-tool-execution`,status:`pending`,canResolve:!0,resumable:!0,tool:e,validationGeneration:0}}if(i!==void 0&&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:R(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(o&&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&&Oi(e.responseSchema)===i.responseSchemaHash&&(e.payloadSchema===void 0?i.payloadSchemaHash===void 0:i.payloadSchemaHash===Oi(e.payloadSchema))){let t=Ei(r);return{descriptor:r,binding:R(i),definition:e,kind:`generic`,status:`pending`,canResolve:!0,resumable:!0,...t===void 0?{}:{payload:R(t)},validationGeneration:0}}}let c=a||i!==void 0&&i.interruptId===r.id&&i.interruptedRunId===t.interruptedRunId&&i.generation===t.generation&&(i.kind!==`generic`||Y(r)===void 0||i.responseSchemaHash===Y(r));return{descriptor:r,binding:Ri(r,t,i),kind:`generic`,status:`pending`,canResolve:c,resumable:c,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=zi(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=R(n.binding),i={...r,kind:`tool-approval`,binding:t,toolName:n.binding.toolName,toolCallId:n.binding.toolCallId,originalArgs:R(n.binding.originalArgs),cancel:()=>this.cancelItem(n.descriptor.id,e),clearResolution:()=>this.clearItem(n.descriptor.id,e),resolveInterrupt:(t,r)=>{let i=J(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`?R(n.binding):R({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`){if(!this.hydration){this.snapshot=Object.freeze([]),this.state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:this.resuming}),this.options.onChange?.(e);return}this.snapshot=this.buildSnapshot(),this.state=Object.freeze({interrupts:this.snapshot,pendingInterrupts: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);if(X(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)});return}this.applyValidation(r,a,n)}cancelItem(e,t){this.assertItemMutable(t);let n=this.findItem(e);this.invalidateRetry(),n.validationGeneration++,n.resolution=Object.freeze(gi(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=>q(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=Qt(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.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();return}e.resolution=R(gi(e,{interruptId:e.descriptor.id,status:`resolved`,payload:t.payload})),e.status=`staged`,e.error=void 0,n||(this.publish(),this.maybeSubmit())}validateCandidate(e,t){if(e.kind===`generic`){let n=ki(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 X(n)?Promise.resolve(n).then(r):r(n)}return e.kind===`client-tool-execution`?ki(e.tool?.outputSchema,t,`invalid-tool-output`):this.validateApprovalCandidate(e,t)}validateApprovalCandidate(e,t){if(!J(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=ki(e.tool?.inputSchema,r,`invalid-edited-args`);return X(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=ki(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 X(o)?Promise.resolve(o).then(s):s(o)}approvalBranchSchema(e,t){let n=e?.approvalSchema;return!J(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=>q(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);return}this.invalidateRetry();for(let n of t)n.validationGeneration++,n.resolution=R({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(_i),i;try{for(let t of r){let n=e(t);if(n!==void 0){i={code:X(n)?`async-resolver`:`inactive-transaction`,message:X(n)?`Interrupt transaction resolvers must be synchronous.`:`Interrupt transaction resolvers must return literal undefined.`};break}}i===void 0&&this.items.some(e=>q(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}if(i){this.restoreCheckpoints(t),this.addRootError(i.code,i.message,!1);return}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)q(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=Ni(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)q(e)&&(e.status=`error`);return}let r=n.filter(e=>Li(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=>q(t)&&t.descriptor.id===e.interruptId);t&&(t.status=`error`,t.error=R(e))}else o.push(R(e));let s=Ii(this.rootErrors,this.submissionRootErrors,o);this.rootErrors=s.rootErrors,this.submissionRootErrors=s.submissionRootErrors;for(let e of this.items)q(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(q).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})}};function Vi(e,...t){let n=e?.();if(Ir(n))return n;for(let e of t)if(Ir(e))return e}async function Hi(e,t){if(!t)throw new Br;return await e.prepare(t),e.headers(t)}var Ui=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})}toolApprovalResponded(e,t,n,r){this.emitEvent(`tools:approval:responded`,{approvalId:e,toolCallId:t,approved:n,...r})}toolFixtureApplied(e){this.emitEvent(`devtools:tool-fixture:applied`,{...e})}},Wi=class extends Ui{emitEvent(){}},Gi=class{events;constructor(e){this.events=new Wi(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){}beginRun(e,t){}getCurrentRunEventContext(){}getCurrentOrLastRunEventContext(){}findToolCallContext(e){return{toolCallId:e}}async applyFixture(e){}},Ki=e=>new Gi(e);function qi(e){if(Array.isArray(e))return{messages:e};if(e&&Array.isArray(e.messages))return e}function Ji(e){return`toolCallId`in e&&typeof e.toolCallId==`string`?e.toolCallId:void 0}function Yi(e){return`messageId`in e&&typeof e.messageId==`string`?e.messageId:void 0}function Xi(e){return`parentMessageId`in e&&typeof e.parentMessageId==`string`?e.parentMessageId:void 0}var Zi=class{adapter;id;applyMessages;applyResume;skipNextPersist=!1;generation=0;queue=Promise.resolve();queuePending=!1;messagesGeneration=0;lastMessages=[];lastResume=null;clearedMessageIds=new Set;clearedRunIds=new Set;ignoredActiveRunIds=new Set;clearedToolCallIds=new Set;currentRunlessRunId=null;constructor(e,t,n,r){this.adapter=e,this.id=t,this.applyMessages=n,this.applyResume=r}writeState(){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)})}readInitial(){try{let e=this.adapter.getItem(this.id);if(e instanceof Promise)return e.then(qi).catch(()=>void 0);let t=qi(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;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){if(this.messagesGeneration++,this.lastMessages=[...e],this.skipNextPersist){this.skipNextPersist=!1;return}this.writeState()}persistResumeSnapshot(e){this.lastResume=e,!this.skipNextPersist&&this.writeState()}remove(){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)});return}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=G(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=Ji(e);if(n&&this.clearedToolCallIds.has(n))return!0;let r=Xi(e);if(r&&this.clearedMessageIds.has(r))return n&&this.clearedToolCallIds.add(n),!0;let i=Yi(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=Yi(e);t&&this.clearedMessageIds.add(t);let n=Ji(e);n&&this.clearedToolCallIds.add(n)}isRunlessChunkFromIgnoredRun(e){return G(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===`TOOL_CALL_START`||e.type===`TOOL_CALL_ARGS`||e.type===`TOOL_CALL_END`||e.type===`TOOL_CALL_RESULT`||e.type===`MESSAGES_SNAPSHOT`||e.type===`RUN_ERROR`}};function Qi(e){return`toolCallId`in e&&typeof e.toolCallId==`string`?e.toolCallId:void 0}function $i(e){return`messageId`in e&&typeof e.messageId==`string`?e.messageId:void 0}function ea(e){return`parentMessageId`in e&&typeof e.parentMessageId==`string`?e.parentMessageId:void 0}var ta=class{clearedMessageIds=new Set;clearedRunIds=new Set;ignoredActiveRunIds=new Set;clearedToolCallIds=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=G(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=Qi(e);if(n&&this.clearedToolCallIds.has(n))return!0;let r=ea(e);if(r&&this.clearedMessageIds.has(r))return n&&this.clearedToolCallIds.add(n),!0;let i=$i(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=$i(e);t&&this.clearedMessageIds.add(t);let n=Qi(e);n&&this.clearedToolCallIds.add(n)}isRunlessChunkFromIgnoredRun(e){return G(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===`TOOL_CALL_START`||e.type===`TOOL_CALL_ARGS`||e.type===`TOOL_CALL_END`||e.type===`TOOL_CALL_RESULT`||e.type===`MESSAGES_SNAPSHOT`||e.type===`RUN_ERROR`}};function na(e){let t=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 ra(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 mi(n);throw Error("ChatClient: either `connection` or `fetcher` is required.")}function ia(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 aa(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(`
26
- `),...t===void 0?{}:{body:t}};let r=[],i;for(let t of e){if(typeof t.content==`string`){r.push({type:`text`,content:t.content});continue}typeof t.content.content==`string`?r.push({type:`text`,content:t.content.content}):r.push(...t.content.content),i=Wt(i,t.content.metadata)}return{content:{content:r,...i===void 0?{}:{metadata:i}},...t===void 0?{}:{body:t}}}function oa(e){if(!(typeof e!=`object`||!e||Array.isArray(e))&&!(!(`approved`in e)||typeof e.approved!=`boolean`))return e.approved}function sa(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 ca=2e3,la=new Set([`TEXT_MESSAGE_START`,`TEXT_MESSAGE_CONTENT`,`TOOL_CALL_START`,`MESSAGES_SNAPSHOT`]),ua=class{processor;connection;uniqueId;threadId;persistor;clearedStreamTracker=new ta;currentRunId=null;lastResume=null;rejoinedRunId=null;interruptManager;activeInterruptSubmission;interruptSubmissionFailure;joinedRunWaiters=new Map;pendingResumeParentRunId=null;pendingResumeThreadId=null;pendingResumeItems=null;activeResumeThreadId=null;activeResumeRunId=null;bodyOption={};forwardedPropsOption={};byok;byokProvider;context=void 0;pendingMessageBody=void 0;queueConfig;messageQueue=[];sendInFlight=!1;messageQueueDraining=!1;stopMessageQueueDrain=!1;deliverClaim=!1;isLoading=!1;isSubscribed=!1;error=void 0;status=`ready`;connectionStatus=`disconnected`;abortController=null;clientToolsRef;devtoolsBridge;events;currentStreamId=null;currentMessageId=null;postStreamActions=[];pendingToolExecutions=new Map;activeClientTools=null;activeContext=void 0;continuationPending=!1;subscriptionAbortController=null;processingResolve=null;errorReportedGeneration=null;streamGeneration=0;continuationSkipped=!1;draining=!1;sessionGenerating=!1;activeRunIds=new Set;disposed=!1;tailing=!1;rejoinRunId;cachesMessages;devtoolsMounted=!1;callbacksRef;constructor(e){na(e.interrupts),this.threadId=e.threadId||``,this.uniqueId=this.threadId;let t=!0;if(e.persistence===!0){if(!e.threadId)throw Error("[TanStack AI] persistence needs a stable `threadId` to key on. Pass a threadId from your app (for example support-42).");t=!1}else if(e.persistence){if(!e.threadId)throw Error("[TanStack AI] persistence needs a stable `threadId` to key on. Pass a threadId from your app (for example support-42).");this.persistor=new Zi(e.persistence,e.threadId,e=>this.processor.setMessages(e),e=>this.applyPersistedResume(e))}if(this.bodyOption=e.body||{},this.forwardedPropsOption=e.forwardedProps||{},this.byok=e.byok,this.byokProvider=e.byokProvider,this.context=e.context,this.queueConfig=ia(e.queue),this.connection=di(ra(e)),this.clientToolsRef={current:new Map},e.tools)for(let t of e.tools)this.clientToolsRef.current.set(t.name,t);this.devtoolsBridge=(e.devtoolsBridgeFactory??Ki)(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||(()=>{}),onQueueChange:e.onQueueChange||(()=>{}),onResumeStateChange:e.onResumeStateChange||(()=>{}),onRunIdChange:e.onRunIdChange||(()=>{}),onInterruptStateChange:e.onInterruptStateChange||(()=>{}),onCustomEvent:e.onCustomEvent||(()=>{})}},this.interruptManager=new Bi({...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 n=this.persistor?.readInitial(),r=n instanceof Promise?void 0:n,i=r?r.messages:e.initialMessages,a=null;if(r?.resume){let e=r.resume;Array.isArray(e.pendingInterrupts)&&e.pendingInterrupts.length>0?this.applyResumeSnapshot(e):e.resumeState.runId&&(a=e.resumeState.runId)}if(!a&&e.initialResumeSnapshot){let t=e.initialResumeSnapshot;!(Array.isArray(t.pendingInterrupts)&&t.pendingInterrupts.length>0)&&t.resumeState.runId&&(a=t.resumeState.runId)}this.processor=new Mr({...e.streamProcessor?.chunkStrategy?{chunkStrategy:e.streamProcessor.chunkStrategy}:{},...i?{initialMessages:i}:{},events:{onMessagesChange:e=>{this.persistor?.notifyMessagesChanged(e),this.callbacksRef.current.onMessagesChange(e)},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(n){let r=this.devtoolsBridge.getCurrentRunEventContext(),i=(async()=>{try{let i=this.activeClientTools===null?this.context:this.activeContext,a=await n(e.input,{toolCallId:e.toolCallId,context:i,emitCustomEvent:()=>{}});await this.addToolResultForClientTool({toolCallId:e.toolCallId,tool:e.toolName,output:a,state:`output-available`},t,r)}catch(n){await this.addToolResultForClientTool({toolCallId:e.toolCallId,tool:e.toolName,output:null,state:`output-error`,errorText:n.message},t,r)}finally{this.pendingToolExecutions.delete(e.toolCallId)}})();this.pendingToolExecutions.set(e.toolCallId,i)}},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),this.callbacksRef.current.onCustomEvent(e,t,n)}}}),this.persistor?.hydrateAsync(n),this.rejoinRunId=a,this.cachesMessages=t}attach(){this.disposed||this.tailing||(this.ensureThreadId(),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=sa(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;e&&(this.isLoading||this.abortController||this.disposed||(async()=>{let t;try{t=await e(this.threadId)}catch{return}this.disposed||!this.tailing||this.isLoading||this.abortController||(t.messages.length>0&&this.processor.setMessages(t.messages),t.interrupts&&t.interrupts.pending.length>0?this.applyResumeSnapshot({resumeState:{threadId:this.threadId,runId:t.interrupts.runId},pendingInterrupts:t.interrupts.pending}):t.activeRun?.runId&&this.maybeRejoinInFlight(t.activeRun.runId))})())}mountDevtools(){this.ensureThreadId(),!this.devtoolsMounted&&(this.devtoolsMounted=!0,this.devtoolsBridge.mountWithTools(this.processor.getMessages().length))}ensureThreadId(){return this.threadId||=this.generateUniqueId(`thread`),this.uniqueId=this.threadId,this.threadId}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=G(e)??this.clearedStreamTracker.takeRunlessRunId();t&&(this.activeRunIds.delete(t),this.setSessionGenerating(this.activeRunIds.size>0),G(e)||this.resolveProcessing())}updateRunLifecycle(e,t){if(e.type===`RUN_STARTED`){let t=G(e)??e.runId;this.activeResumeThreadId=`threadId`in e&&typeof e.threadId==`string`?e.threadId:this.activeResumeThreadId,this.activeResumeRunId=t,this.activeRunIds.add(t),this.clearedStreamTracker.onRunStarted(t),this.setSessionGenerating(!0),this.persistor&&this.connection.joinRun&&!this.lastResume&&this.persistResumeSnapshot({threadId:this.activeResumeThreadId??this.threadId,runId:t});return}if(e.type!==`RUN_FINISHED`&&e.type!==`RUN_ERROR`)return;let n=G(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),t?.resolveProcessing!==!1&&this.resolveProcessing()}observeInterruptState(e){if(e.type!==`RUN_FINISHED`&&e.type!==`RUN_ERROR`||this.activeInterruptSubmission&&e.type===`RUN_ERROR`)return;let t=G(e),n=`threadId`in e&&typeof e.threadId==`string`?e.threadId:this.activeResumeThreadId;if(e.type===`RUN_FINISHED`&&e.outcome?.type===`interrupt`){let r=this.currentRunId??t??this.activeResumeRunId??``;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`);if(r||i||a||o||s||c){this.lastResume=null,this.persistor?.persistResumeSnapshot(null),this.interruptManager.reset();return}this.notifyResumeStateChange(`live`)}getResumeState(){return this.lastResume?{...this.lastResume}:null}getCurrentRunId(){return this.currentRunId}setCurrentRunId(e){this.currentRunId!==e&&(this.currentRunId=e,this.callbacksRef.current.onRunIdChange(e))}getInterruptState(){return this.interruptManager.getState()}getInterrupts(){return this.interruptManager.getInterrupts()}getPendingInterrupts(){return this.interruptManager.getInterrupts()}resolveInterrupts(e){if(typeof e==`boolean`){this.interruptManager.resolve(e);return}this.interruptManager.resolve(e)}cancelInterrupts(){this.interruptManager.cancel()}retryInterrupts(){this.interruptManager.retry()}resumeInterruptsUnsafe(e,t){let n=t??this.lastResume;return n?this.isLoading?new Promise((t,r)=>{this.queuePostStreamAction(async()=>{try{t(await this.resumeInterruptsUnsafe(e,n))}catch(e){r(e)}})}):(this.pendingResumeThreadId=n.threadId,this.pendingResumeParentRunId=n.runId,this.pendingResumeItems=[...e],this.streamResponse()):Promise.resolve(!1)}resumeInterrupts(e,t){return this.resumeInterruptsUnsafe(e,t)}async submitInterruptBatch(e){this.activeInterruptSubmission=e,this.interruptSubmissionFailure=void 0;for(let t of e.resolutions){let e=oa(t.payload);if(e===void 0)continue;let n=t.interruptId;this.processor.addToolApprovalResponse(n,e)}let t=await this.resumeInterruptsUnsafe([...e.resolutions],{threadId:e.threadId,runId:e.interruptedRunId}).finally(()=>{this.activeInterruptSubmission=void 0}),n=this.takeInterruptSubmissionFailure();if(n!==void 0)throw{errors:n.errors};if(!t)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)}`}setIsLoading(e){this.isLoading=e,this.callbacksRef.current.onLoadingChange(e),this.events.loadingChanged(e)}setStatus(e){this.status=e,this.callbacksRef.current.onStatusChange(e),this.devtoolsBridge.emitSnapshot()}setIsSubscribed(e){this.isSubscribed=e,this.callbacksRef.current.onSubscriptionChange(e),this.devtoolsBridge.emitSnapshot()}setConnectionStatus(e){this.connectionStatus=e,this.callbacksRef.current.onConnectionStatusChange(e),this.devtoolsBridge.emitSnapshot()}setSessionGenerating(e){this.sessionGenerating!==e&&(this.sessionGenerating=e,this.callbacksRef.current.onSessionGeneratingChange(e),this.devtoolsBridge.emitSnapshot())}notifyResumeStateChange(e){let t=this.getResumeState(),n=this.interruptManager.getState();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){this.error=e,this.callbacksRef.current.onErrorChange(e),this.events.errorChanged(e?.message||null)}buildDevtoolsBridgeOptions(e){let t=this;return{get hookId(){return t.uniqueId},get clientId(){return t.uniqueId},get threadId(){return t.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: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);for await(let n of t){if(e.aborted)break;await this.processIncomingChunk(n)}}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.setIsLoading(!0),this.setStatus(`streaming`),(async()=>{let r=!1,i=!1,a=!1,o=setTimeout(()=>{i||n.abort()},ca);try{for await(let a of t(e,n.signal)){if(n.signal.aborted)break;i||(i=!0,clearTimeout(o)),!r&&la.has(a.type)&&(r=!0,this.dropTrailingInFlightAssistant()),await this.processIncomingChunk(a,{defer:!1})}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))}async processIncomingChunk(e,t){if(e=Un(e),e.type===`RUN_ERROR`&&this.isActiveInterruptSubmissionFailure(e)){let t=P(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`)&&(G(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),this.processor.processChunk(e),this.updateRunLifecycle(e),this.observeInterruptState(e),t?.defer!==!1&&(typeof document>`u`||!document.hidden)&&await new Promise(e=>setTimeout(e,0)),this.resolveJoinedRun(e)}isActiveInterruptSubmissionFailure(e){let t=this.activeInterruptSubmission,n=P(e)?.interruptErrors;if(!t||!Array.isArray(n)||n.length===0)return!1;let r=G(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=G(e);if(t===void 0)return;let n=this.joinedRunWaiters.get(t);n!==void 0&&(this.joinedRunWaiters.delete(t),n())}ensureSubscription(){if(!this.isSubscribed){this.subscribe();return}(!this.subscriptionAbortController||this.subscriptionAbortController.signal.aborted)&&this.subscribe({restart:!0})}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.hasBlockingInterrupts())throw Error(`ChatClient: cannot send normal input while pending interrupts exist. Use resumeInterrupts() instead.`);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}hasBlockingInterrupts(){return this.activeInterruptSubmission!==void 0||this.hasPendingInterrupts()}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.hasBlockingInterrupts())throw Error(`ChatClient: cannot append normal input while pending interrupts exist. Use resumeInterrupts() instead.`);let t=ur(e,W);if(t.role===`system`)return;let n=t;this.events.messageAppended(n);let r=this.processor.getMessages();if(this.processor.setMessages([...r,n]),this.devtoolsBridge.emitSnapshot(),this.isLoading){this.queuePostStreamAction(async()=>{await this.streamResponse()});return}await this.streamResponse()}async streamResponse(){if(this.isLoading)return!1;let e=++this.streamGeneration,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.processor.getMessages(),u=new Map(this.clientToolsRef.current),d=this.context;if(await this.callbacksRef.current.onResponse(),a.aborted)return!1;let f={...this.bodyOption,...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=Vi(this.byokProvider,f.provider);m=await Hi(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?an(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||(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 Rr&&this.byok?.request(n.provider,`missing`),n instanceof zr&&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 Rr||n instanceof zr||n instanceof Br))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.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(){let e=this.abortController!==null;this.cancelInFlightStream({setReadyStatus:!0}),this.discardPendingSends(),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.discardPendingSends(),this.persistor?.remove(),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)}async addToolResultForClientTool(e,t,n){if(t&&e.state!==`output-error`)try{e={...e,output:this.validateClientToolOutput(t,e.output)}}catch(t){e={...e,output:null,state:`output-error`,errorText:t.message}}if(this.events.toolResultAdded(e.toolCallId,e.tool,e.output,e.state||`output-available`,n),this.processor.addToolResult(e.toolCallId,e.output,e.state===`output-error`?e.errorText||`Tool execution failed`:void 0),this.devtoolsBridge.emitSnapshot(),!this.interruptManager.resolveClientToolOutput(e.toolCallId,e.state===`output-error`?{error:e.errorText||`Tool execution failed`}:e.output)){if(this.isLoading){this.queuePostStreamAction(()=>this.checkForContinuation());return}await this.checkForContinuation()}}validateClientToolOutput(e,t){return e.outputSchema&&B(e.outputSchema)?sn(e.outputSchema,t):t}async addToolApprovalResponse(e){if(this.processor.addToolApprovalResponse(e.id,e.approved),this.devtoolsBridge.emitSnapshot(),this.interruptManager.resolveToolApprovalDecision(e.id,e.approved))return;let t=this.processor.getMessages(),n;for(let r of t){let t=r.parts.find(t=>t.type===`tool-call`&&t.approval?.id===e.id);if(t){n=t.id;break}}if(n&&this.events.toolApprovalResponded(e.id,n,e.approved),this.processor.addToolApprovalResponse(e.id,e.approved),this.devtoolsBridge.emitSnapshot(),this.isLoading){this.queuePostStreamAction(()=>this.checkForContinuation());return}await this.checkForContinuation()}queuePostStreamAction(e){this.postStreamActions.push(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.hasPendingInterrupts()){if(this.continuationPending||this.isLoading){this.continuationSkipped=!0;return}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()}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=aa(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(){this.callbacksRef.current.onQueueChange(this.getQueue()),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}getError(){return this.error}setMessagesManually(e){this.processor.setMessages(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`),this.connection=di(ra({connection:e.connection,fetcher:e.fetcher})),t&&this.subscribe()}if(e.body!==void 0&&(this.bodyOption=e.body),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=new Map;for(let t of e.tools)this.clientToolsRef.current.set(t.name,t);this.devtoolsBridge.notifyToolsChanged()}e.queue!==void 0&&(this.queueConfig=ia(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.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 da=e=>`background:${e};color:#fff;border-radius:3px;padding:1px 5px`,fa=`${da(`#7c3aed`)};font-weight:600`,pa={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 ma(e){if(e)return(e,t,n)=>{console.log(`%cAstralBeam%c ${new Date().toISOString().slice(11,19)} %c${e}%c ${t}`,fa,`color:#94a3b8;font-weight:400`,da(pa[e]),``,...n===void 0?[]:[n])}}function ha(e){if(!e)return{type:`object`};if(!(`~standard`in e))return e;try{return an(e)}catch{return{type:`object`}}}async function ga(e,t){if(!e||!(`~standard`in e))return t;let n=await e[`~standard`].validate(t);return n.issues?null:n.value??{}}function _a(e,t,n,r){return[...Object.keys(e).length>0?[va(e,n)]:[],ya(),...ba(t,r)]}function va(e,t){return dr({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:
27
- `+Object.entries(e).map(([e,{description:t,parameters:n}])=>`- ${e}: ${t} Props schema: ${JSON.stringify(ha(n))}`).join(`
28
- `),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 ya(){return dr({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 ba(e,t){return Object.entries(e).map(([e,n])=>dr({name:e,description:n.description,inputSchema:ha(n.parameters),...n.metadata?{metadata:n.metadata}:{}}).client(async r=>{t?.(`tool`,`executing host tool "${e}"`,{input:r});let i=await ga(n.parameters,r??{});if(i==null)throw t?.(`error`,`input for host tool "${e}" failed schema validation`,{input:r}),Error(`Input for tool "${e}" failed schema validation`);try{let r=await n.execute(i);return t?.(`tool`,`host tool "${e}" returned`,{output:r}),r}catch(n){throw t?.(`error`,`host tool "${e}" threw`,{error:n}),n}}))}function xa(e){if(e.length>16384)throw Error(`The chat auth token is too large`);let{exp:t,iat:n,user:r}=Nt(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 Sa(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(Error(`Authentication endpoint returned HTTP ${s.status}`),{status:s.status,headers:s.headers});return(await s.json())?.token}const Ca={status:`loading`};function wa(e){return{...e,fetchAstralBeamToken:e.fetchAstralBeamToken,session:{cached:void 0,refreshPromise:void 0,abortController:new AbortController,state:Ca,listeners:new Set},fetchClient:globalThis.fetch.bind(globalThis),debug:void 0}}function Ta(e){return e.session.state}function Ea(e,t){let{listeners:n}=e.session;return n.add(t),()=>{n.delete(t)}}function Da(e,t){e.session.state=t;for(let t of e.session.listeners)t()}function Oa(e,t){e.apiUrl!==t.apiUrl&&(Na(e),e.session.abortController=new AbortController,Da(e,{status:`loading`})),e.apiUrl=t.apiUrl,e.fetchAstralBeamToken=t.fetchAstralBeamToken}function ka(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 Aa(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 Sa(e,i);if(i.throwIfAborted(),typeof s!=`string`||!s)throw Error(`${a} did not return a token`);let{expiresAt:c,refreshAt:l,tenantAdmin:u}=xa(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 Ke({apiUrl:r,astralBeamToken:s,fetchClient:e.fetchClient,signal:i,cache:`no-store`,credentials:`omit`})}catch(t){if(!o&&e.retryUnauthorized!==!1&&C(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},Da(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:Error(`Authentication failed`);throw t.cached=void 0,Da(e,{status:`error`,error:r}),r}}async function Z(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())&&Da(e,{status:`loading`});let r=Aa(e);t.refreshPromise=r;try{return await r}finally{t.refreshPromise===r&&(t.refreshPromise=void 0)}}function ja(e,t){let n=!t||e.session.cached?.value===t;return n&&(e.session.cached=void 0),Z({...e,force:n,retryUnauthorized:!1})}async function Ma(e){e.session.abortController.signal.aborted&&(e.session.abortController=new AbortController),await Z(e)}function Na({session:e}){e.abortController.abort(),e.refreshPromise=void 0,e.cached=void 0,e.state=Ca}async function Pa(e){let{input:t,init:n,session:r,fetchClient:i,debug:a}=e,o=Ta(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 ja(e,u),f=Ta(e);if(o.status!==`ready`||f.status!==`ready`||ka(o.currentUser)!==ka(f.currentUser))throw new DOMException(`Identity changed`,`AbortError`);return n?.signal?.throwIfAborted(),c.set(`authorization`,`Bearer ${d}`),await i(t,{...n,headers:c})}function Fa(e){let t,n=new AbortController,r=0,i=()=>typeof document>`u`||document.visibilityState!==`hidden`&&globalThis.navigator?.onLine!==!1,a=()=>{n.signal.aborted||!i()||Z({...e,force:!0}).catch(()=>{})},o=()=>{if(clearTimeout(t),n.signal.aborted||typeof document>`u`||!i())return;let o=Ta(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=Ea(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 Ma(e).catch(()=>{}),o(),()=>{n.abort(),clearTimeout(t),c()}}function Ia(e){return e.state===`complete`||e.state===`error`||e.output!==void 0}function La(e,t){return typeof e==`object`&&e&&t in e?e[t]:void 0}function Q(e,t){let n=La(e,t);return typeof n==`string`?n:void 0}function Ra(e,t){let n=La(e,t);return typeof n==`number`?n:void 0}function za(e){return Q(e.output,`refusal`)}function Ba(e){if(e.name!==`sandbox_write_file`)return;let t=Q(e.output,`path`)??Q(e.input,`path`);if(t===void 0)return;let n=Q(e.input,`content`)??``;return{toolCallId:e.id,path:t,label:Va(e)??t,content:n,lines:n.length===0?0:n.split(`
29
- `).length,written:e.output!=null&&za(e)===void 0}}function Va(e){let t=Q(e.output,`relativePath`);return t!==void 0&&t!==`.`?t:Q(e.output,`path`)??Q(e.input,`path`)}function Ha(e){if(e.name!==`sandbox_run_command`)return;let t=Q(e.input,`command`);if(t===void 0)return;let n=e.output;return{toolCallId:e.id,command:t,cwd:Q(e.input,`cwd`),exitCode:Ra(n,`exitCode`),stdout:Q(n,`stdout`)??``,stderr:Q(n,`stderr`)??``,durationMs:Ra(n,`durationMs`),timedOut:La(n,`timedOut`)===!0,truncated:La(n,`truncated`)===!0,finished:n!=null}}function Ua(e){let t=new Map,n=[];for(let r of e)for(let e of r.parts){if(e.type!==`tool-call`)continue;let r=Ba(e);r?.written&&t.set(r.path,r);let i=Ha(e);i&&za(e)===void 0&&n.push(i)}return{files:[...t.values()],commands:n}}function Wa(e,t){return e.length===t.length&&e.every((e,n)=>e.name===t[n]?.name&&e.title===t[n]?.title)}function Ga(e,t=!1){let n={...e},r=ma(n.debug),i=new Set,a={messages:[],status:`ready`,error:void 0,auth:{status:`loading`},capabilities:{attachments:!0},agentTools:[],sandboxStatus:void 0,sandbox:{files:[],commands:[]}},o=e=>{a={...a,...e};for(let e of i)e()},s=wa({apiUrl:n.apiUrl,scope:`tenant`,fetchAstralBeamToken:n.fetchAstralBeamToken??{url:`/api/astralbeam/token`}}),c,l,u,d=!1,f=0,p,m=async()=>{let e=++f;try{let t=await Z(s);if(e!==f)return;let i=await We(n.agentId?{agentId:n.agentId}:{},{apiUrl:s.apiUrl,astralBeamToken:t,signal:s.session.abortController.signal,fetchClient:(e,t)=>Pa({...s,input:e,init:t})});if(e!==f)return;let a=i.capabilities?.attachments!==!1;o({capabilities:{attachments:a}}),r?.(`mount`,`agent capabilities resolved`,{attachments:a})}catch(e){r?.(`error`,`agent capabilities could not be resolved; keeping the defaults`,e)}},h=new Map,g=()=>{for(let e of h.values())e();h.clear()},_=async(e,t)=>{let r=n.widgets??{};if(!Object.hasOwn(r,e.widget))throw Error(`Unknown widget "${e.widget}"`);let i=r[e.widget],a=await ga(i?.parameters,e.props??{});if(a==null)throw Error(`Props for widget "${e.widget}" failed validation`);h.get(t)?.(),h.delete(t);let o,s=n.onRenderWidget?.({widget:e.widget,props:a,toolCallId:t,release:()=>{h.get(t)===o&&h.delete(t)}});return s&&(o=s,h.set(t,s)),{widget:e.widget,rendered:n.onRenderWidget!==void 0}},v=()=>_a(n.widgets??{},n.tools??{},_,r),ee=()=>{let e=v(),t=e.map(e=>{let t=e.metadata?.title;return{name:e.name,title:typeof t==`string`&&t.length>0?t:void 0}});return Wa(a.agentTools,t)||o({agentTools:t}),e},te=()=>({...n.agentId?{agentId:n.agentId}:{},...n.debug?{debug:!0}:{}}),ne=pi(()=>ye(He(),s.apiUrl),async()=>{let e=u,t=await Z(s);if(e!==void 0&&e!==u)throw new DOMException(`Identity changed`,`AbortError`);return{fetchClient:(e,n)=>Ce(He(),{...n,apiUrl:s.apiUrl,astralBeamToken:t,fetchClient:(e,t)=>Pa({...s,input:e,init:t})})}}),re=ne.connect;ne.connect=async function*(...e){try{yield*re(...e)}catch(e){throw e instanceof Error&&C(e.cause)?e.cause:e}};let y=new ua({connection:ne,tools:ee(),forwardedProps:te(),onMessagesChange:e=>{o({messages:e,sandbox:Ua(e),error:y.getError()})},onStatusChange:e=>o({status:e,error:y.getError()}),onCustomEvent:(e,t)=>{let n=t?.state;if(e===`astralbeam.sandbox.status`&&(n===`starting`||n===`ready`||n===`error`)){r?.(`sandbox`,`sandbox ${n}`),o({sandboxStatus:n});return}r?.(`stream`,`custom event "${e}"`,t)},onChunk:e=>n.streamCallbacks?.onChunk?.(e),onResponse:e=>n.streamCallbacks?.onResponse?.(e),onFinish:e=>n.streamCallbacks?.onFinish?.(e),onError:e=>n.streamCallbacks?.onError?.(e)}),ie=()=>{for(let e of a.messages)for(let t of e.parts)t.type!==`tool-call`||Ia(t)||(t.name===`ask_questionnaire`?(r?.(`questionnaire`,`skipping pending questionnaire before send`,{id:t.id}),y.addToolResult({toolCallId:t.id,tool:t.name,output:{answers:[],skipped:!0}})):(r?.(`tool`,`settling unimplemented tool call "${t.name}" as error`,{id:t.id}),y.addToolResult({toolCallId:t.id,tool:t.name,output:null,state:`output-error`,errorText:`The application hosting this chat has no implementation for "${t.name}"`})))},ae=()=>{let e=Ta(s);if(e.status===`ready`){let t=ka(e.currentUser);u!==void 0&&u!==t&&(y.stop(),y.clear(),g(),o({messages:[],sandbox:{files:[],commands:[]},sandboxStatus:void 0})),u=t,p!==t&&(p=t,m())}o({auth:e})},oe=()=>{d||(d=!0,l=Ea(s,ae),ae(),c=Fa(s))};return t||oe(),{start:oe,getState:()=>a,subscribe:e=>(i.add(e),()=>i.delete(e)),updateOptions:e=>{let t=n.agentId,i=n.apiUrl;n={...n,...e},r=ma(n.debug),Oa(s,{apiUrl:n.apiUrl,fetchAstralBeamToken:n.fetchAstralBeamToken??{url:`/api/astralbeam/token`}}),s.debug=r,y.updateOptions({tools:ee(),forwardedProps:te()}),d&&(n.agentId!==t||n.apiUrl!==i)&&m()},sendMessage:e=>(ie(),y.sendMessage(e)),addToolResult:e=>y.addToolResult(e),stop:()=>y.stop(),retryAuthentication:()=>{Z({...s,force:!0}).catch(()=>void 0)},reload:()=>y.reload(),reset:()=>{r?.(`status`,`conversation reset`),y.clear(),g(),o({messages:[],sandbox:{files:[],commands:[]},sandboxStatus:void 0,error:void 0})},dispose:()=>{g(),y.stop(),f++,p=void 0,c?.(),l?.(),Na(s),d=!1,queueMicrotask(()=>{d||y.dispose()}),i.clear()}}}const Ka=(e,t=`algorithm.name`)=>TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function qa(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function Ja(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 Ya(e,t,n){let r=e.algorithm;if(r.name!==t.name)throw Ka(t.name);if(t.hash&&r.hash?.name!==t.hash)throw Ka(t.hash,`algorithm.hash`);if(t.namedCurve&&r.namedCurve!==t.namedCurve)throw Ka(t.namedCurve,`algorithm.namedCurve`);if(t.length!==void 0&&r.length!==t.length)throw Ka(t.length,`algorithm.length`);qa(e,n)}function Xa(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}const Za=(e,t,...n)=>Xa(`Key for the ${e} algorithm must be `,t,...n),Qa=e=>{if(e?.[Symbol.toStringTag]===`CryptoKey`)return!0;try{return e instanceof CryptoKey}catch{return!1}},$a=e=>e?.[Symbol.toStringTag]===`KeyObject`,eo=e=>Qa(e)||$a(e);function to(e,t){if(e)throw TypeError(`${t} can only be called once`)}async function no(e,t){if(t.kty===`RSA`&&`oth`in t&&t.oth!==void 0)throw new bt(`RSA JWK "oth" (Other Primes Info) Parameter value is not supported`);if(!e.kty.includes(t.kty))throw new bt(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`);let n=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,r=!!(t.d||t.priv),i={...t};return i.kty!==`AKP`&&delete i.alg,delete i.use,crypto.subtle.importKey(`jwk`,i,n,t.ext??!r,t.key_ops??e.usages[+!!r])}const ro=e=>e[Symbol.toStringTag],io=(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`)}};function ao(e,t,n){let{alg:r,secret:i}=e,a=n===`decrypt`||n===`sign`;if(i&&t instanceof Uint8Array)return[oo,t];if(Ot(t)){if(i?!jt(t):!(a?kt(t):At(t)))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`);return io(e,t,n),[lo,t]}if(!eo(t))throw TypeError(i?Za(r,t,`CryptoKey`,`KeyObject`,`JSON Web Key`,`Uint8Array`):Za(r,t,`CryptoKey`,`KeyObject`,`JSON Web Key`));if(i){if(t.type!==`secret`)throw TypeError(`${ro(t)} instances for symmetric algorithms must be of type "secret"`)}else{if(t.type===`secret`)throw TypeError(`${ro(t)} instances for asymmetric algorithms must not be of type "secret"`);let e=a?`private`:`public`;if((t.type===`public`||t.type===`private`)&&t.type!==e){let r=n===`sign`?`signing`:n===`verify`?`verifying`:`${n.slice(0,-1)}tion`;throw TypeError(`${ro(t)} instances for asymmetric algorithm ${r} must be of type "${e}"`)}}return Qa(t)?[so,t]:[co,t]}const oo=0,so=1,co=2,lo=3;let uo;const fo={__proto__:null,prime256v1:`P-256`,secp384r1:`P-384`,secp521r1:`P-521`};function po(e,t,n){uo||=new WeakMap;let r=uo.get(e);return n&&(r?r[t]=n:uo.set(e,{__proto__:null,[t]:n})),n??r?.[t]}const mo=async(e,t,n)=>po(e,n.alg)??po(e,n.alg,await no(n,{...t,alg:n.alg})),ho=(e,t)=>{let n=po(e,t.alg);if(n)return n;let r=e.type===`public`,i=t.usages[+!r],{asymmetricKeyType:a}=e,o=fo[e.asymmetricKeyDetails?.namedCurve],s=t.resolve?.({crv:o,asymmetricKeyType:a})??t.subtle;return po(e,t.alg,e.toCryptoKey(s,r,i))};async function go(e,t,n){let r=ao(e,t,n);switch(r[0]){case 0:case 1:return r[1];case 3:{let t=r[1];if(t.k)return wt(t.k);if(!Object.isFrozen(t)){let{key_ops:e}=t;Array.isArray(e)&&Object.freeze(e),Object.freeze(t)}return mo(t,t,e)}case 2:{let t=r[1];return t.type===`secret`?t.export():`toCryptoKey`in t&&typeof t.toCryptoKey==`function`?ho(t,e):mo(t,t.export({format:`jwk`}),e)}}}function _o(e){let t={__proto__:null};for(let n in e)t[n]={...e[n],alg:n};return t}const vo={__proto__:null,b64:!0};function yo(e,t){let{crit:n}=t??{};if(Array.isArray(n)&&new Set(n).size!==n.length)throw new e(`"crit" (Critical) Header Parameter MUST NOT contain duplicate values`)}function bo(e,t,n,r,i){if(i.crit!==void 0&&r?.crit===void 0)throw new e(`"crit" (Critical) Header Parameter MUST be integrity protected`);if(!r||r.crit===void 0)return[];if(!Array.isArray(r.crit)||r.crit.length===0||r.crit.some(e=>typeof e!=`string`||e.length===0))throw new e(`"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present`);let a=n===void 0?t:{__proto__:null,...n,...t};for(let t of r.crit){if(!(t in a))throw new bt(`Extension Header Parameter "${t}" is not recognized`);if(!Object.hasOwn(i,t)||i[t]===void 0)throw new e(`Extension Header Parameter "${t}" is missing`);if(a[t]&&(!Object.hasOwn(r,t)||r[t]===void 0))throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return r.crit}async function xo(e,t,n){return t instanceof Uint8Array?crypto.subtle.importKey(`raw`,t,e.subtle,!1,[n]):(Ya(t,e.subtle,n),e.minRsaBits&&Ja(e.alg,t),t)}async function So(e,t,n){let r=await xo(e,t,`sign`),i=await crypto.subtle.sign(e.signing,r,n);return new Uint8Array(i)}const Co=[[`verify`],[`sign`]];function wo(e){let t={name:`HMAC`,hash:`SHA-${e}`};return{kty:[`oct`],secret:!0,subtle:t,signing:t,usages:Co}}function $(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:Co,minRsaBits:2048}}function To(e,t){return{kty:[`EC`],crv:e,subtle:{name:`ECDSA`,namedCurve:e},signing:{name:`ECDSA`,hash:`SHA-${t}`},usages:Co}}function Eo(){let e={name:`Ed25519`};return{kty:[`OKP`],crv:`Ed25519`,subtle:e,signing:e,usages:Co}}function Do(e){let t={name:`ML-DSA-${e}`};return{kty:[`AKP`],subtle:t,signing:t,usages:Co}}const Oo=_o({HS256:wo(256),HS384:wo(384),HS512:wo(512),RS256:$(256),RS384:$(384),RS512:$(512),PS256:$(256,32),PS384:$(384,48),PS512:$(512,64),ES256:To(`P-256`,256),ES384:To(`P-384`,384),ES512:To(`P-521`,512),EdDSA:Eo(),Ed25519:Eo(),"ML-DSA-44":Do(44),"ML-DSA-65":Do(65),"ML-DSA-87":Do(87)});function ko(e){let t=typeof e==`string`?Oo[e]:void 0;if(!t)throw new bt(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}const Ao=e=>Math.floor(e.getTime()/1e3),jo={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},Mo=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function No(e){let t=Mo.exec(e);if(!t||t[4]&&t[1])throw TypeError(`Invalid time period format`);let n=parseFloat(t[2]),r=Math.round(n*jo[t[3][0].toLowerCase()]);return t[1]===`-`||t[4]===`ago`?-r:r}function Po(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}function Fo(e,t){return typeof e==`number`?Po(t,e):e instanceof Date?Po(t,Ao(e)):Ao(new Date)+No(e)}var Io=class{#e;constructor(e){if(!Et(e))throw TypeError(`JWT Claims Set MUST be an object`);this.#e=structuredClone(e)}data(){return mt.encode(JSON.stringify(this.#e))}get iss(){return this.#e.iss}set iss(e){this.#e.iss=e}get sub(){return this.#e.sub}set sub(e){this.#e.sub=e}get aud(){return this.#e.aud}set aud(e){this.#e.aud=e}set jti(e){this.#e.jti=e}set nbf(e){this.#e.nbf=Fo(e,`setNotBefore`)}set exp(e){this.#e.exp=Fo(e,`setExpirationTime`)}set iat(e){e===void 0?this.#e.iat=Ao(new Date):typeof e==`string`?this.#e.iat=Po(`setIssuedAt`,Ao(new Date)+No(e)):this.#e.iat=Fo(e,`setIssuedAt`)}};function Lo(e){return e?.b64===!1&&Array.isArray(e.crit)&&e.crit.includes(`b64`)}async function Ro(e,t){let{protectedHeader:n,unprotectedHeader:r}=e;if(!n&&!r)throw new M(`either setProtectedHeader or setUnprotectedHeader must be called before #sign()`);if(!Dt(n,r))throw new M(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let i={...n,...r};yo(M,n);let a=bo(M,vo,e.crit,n,i),o=!0;if(a.includes(`b64`)&&(o=n.b64,typeof o!=`boolean`))throw new M(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);let{alg:s}=i;if(typeof s!=`string`||!s)throw new M(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);let c=ko(s),l,u;if(o){let t=e.encoded??=[];t[0]??=Tt(e.payload),t[1]??=vt(t[0]),l=t[0],u=t[1]}else u=e.payload,l=``;let d,f;n?(d=Tt(JSON.stringify(n)),f=vt(d)):(d=``,f=new Uint8Array);let p=_t(f,vt(`.`),u),m={signature:Tt(await So(c,await go(c,t,`sign`),p)),payload:l};return n&&(m.protected=d),r&&(m.header=r),m}var zo=class{#e;#t;#n;constructor(e){if(!(e instanceof Uint8Array))throw TypeError(`payload must be an instance of Uint8Array`);this.#e=e}setProtectedHeader(e){return to(this.#t,`setProtectedHeader`),this.#t=e,this}setUnprotectedHeader(e){return to(this.#n,`setUnprotectedHeader`),this.#n=e,this}async sign(e,t){return Ro({payload:this.#e,protectedHeader:this.#t,unprotectedHeader:this.#n,crit:t?.crit},e)}},Bo=class{#e;#t;constructor(e){this.#e=new zo(e)}setProtectedHeader(e){return this.#e.setProtectedHeader(e),this.#t=e,this}async sign(e,t){if(Lo(this.#t))throw TypeError(`use the flattened module for creating JWS with b64: false`);let n=await this.#e.sign(e,t);return`${n.protected}.${n.payload}.${n.signature}`}},Vo=class{#e;#t;constructor(e={}){this.#t=new Io(e)}setIssuer(e){return this.#t.iss=e,this}setSubject(e){return this.#t.sub=e,this}setAudience(e){return this.#t.aud=e,this}setJti(e){return this.#t.jti=e,this}setNotBefore(e){return this.#t.nbf=e,this}setExpirationTime(e){return this.#t.exp=e,this}setIssuedAt(e){return this.#t.iat=e,this}setProtectedHeader(e){return this.#e=e,this}async sign(e,t){let n=new Bo(this.#t.data());if(n.setProtectedHeader(this.#e),Lo(this.#e))throw new N(`JWTs MUST NOT use unencoded payload`);return n.sign(e,t)}};const Ho=`astralbeam`,Uo=16384,Wo=8192,Go=/^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}$/,Ko=[`id`,`name`,`metadata`],qo=[`id`,`name`,`admin`,`metadata`],Jo=new TextEncoder;function Yo(e){if(!Go.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 Xo(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Zo(e){return e===null||typeof e==`string`||typeof e==`boolean`?!0:typeof e==`number`?Number.isFinite(e):Array.isArray(e)?e.every(Zo):Xo(e)&&Object.values(e).every(Zo)}function Qo(e,t,n){if(!Xo(t))throw Error(`${e} must be an object`);let r=n?qo:Ko;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&&!(Xo(s)&&Zo(s)))throw Error(`${e}.metadata must be a JSON object`)}function $o(e,t){Qo(`user`,e,!0),Qo(`tenant`,t,!1);let n=JSON.stringify({user:e,tenant:t});if(Jo.encode(n).byteLength>Wo)throw Error(`user and tenant must not exceed ${Wo} bytes`);return JSON.parse(n)}async function es(e){let t=await crypto.subtle.digest(`SHA-256`,Jo.encode(e));return Jo.encode(Tt(new Uint8Array(t)))}async function ts({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}=Yo(e);if(n!==a)throw Error(`organizationId must match the API key organization`);let s=Math.floor(Date.now()/1e3);return await new Vo({ver:1,email:t,organization_id:n}).setProtectedHeader({alg:`HS256`,typ:`astralbeam-organization+jwt`,kid:i}).setIssuer(n).setAudience(Ho).setIssuedAt(s).setExpirationTime(s+r).sign(await es(o))}async function ns({apiKey:e,user:t,tenant:n,expiresInSeconds:r=300}){if(!Number.isInteger(r)||r<60||r>600)throw Error(`chat auth tokens must live for 60-600 seconds`);let{keyId:i,organizationId:a,keySecret:o}=Yo(e),s=$o(t,n),c=Math.floor(Date.now()/1e3),l=await new Vo({ver:4,user:s.user,tenant:s.tenant}).setProtectedHeader({alg:`HS256`,typ:`astralbeam+jwt`,kid:i}).setIssuer(a).setAudience(Ho).setIssuedAt(c).setExpirationTime(c+r).sign(await es(o));if(Jo.encode(l).byteLength>Uo)throw Error(`chat auth tokens must not exceed ${Uo} bytes`);return l}function rs(e){let t=Number(e);if(!Number.isInteger(t)||t<1)throw new x(`Expected a positive integer.`);return t}function is(e){let t=Number(e);if(!Number.isInteger(t)||t<60||t>600)throw new x(`Expected a whole number of seconds from 60 to 600.`);return t}function as(e){let t;try{t=JSON.parse(e)}catch{throw new x(`Expected a JSON object.`)}if(typeof t!=`object`||!t||Array.isArray(t))throw new x(`Expected a JSON object.`);return t}function os(e){return e.requiredOption(`--tenant <external-id>`,`Tenant external ID, signed as tenant.id`).requiredOption(`--user <external-id>`,`TenantUser external ID, signed as user.id`).option(`--tenant-name <name>`,`Tenant display name`).option(`--user-name <name>`,`TenantUser display name`).option(`--admin`,`sign user.admin: true, granting Tenant admin API access`).option(`--expires-in <seconds>`,`token lifetime, 60-600 (default 300)`,is)}function ss(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 cs(e,t,n){let r=new Date(Date.now()+t*1e3).toISOString();n?qe({token:e,expires_at:r}):s.write(`${e}\n`)}function ls(e){let t=e.command(`token`).description(`Mint short-lived JWTs offline with the organization API key`);os(t.command(`chat`).description(`Mint a chat JWT for a Tenant's user, as a token endpoint would`)).action(async(e,t)=>{let{apiKey:n}=await j(),r=e.expiresIn??300;cs(await ns({apiKey:n,expiresInSeconds:r,...ss(e)}),r,k(t).json)}),t.command(`organization`).description(`Mint an organization-management JWT delegating a member's current role`).requiredOption(`--email <email>`,`email of an existing member of the organization`).option(`--expires-in <seconds>`,`token lifetime, 60-600 (default 300)`,is).action(async(e,t)=>{let{apiKey:n}=await j(),r=e.expiresIn??300;cs(await ts({apiKey:n,email:e.email,organizationId:tt(n),expiresInSeconds:r}),r,k(t).json)})}function us(e){return e.filter(e=>e.role===`assistant`).map(e=>e.parts.map(e=>e.type===`text`?e.content:``).join(``)).filter(Boolean).join(`
22
+ `)return r(),e(t.trim());if(a===``)return r(),n(Error(`Cancelled.`));t=a===``||a===`\b`?t.slice(0,-1):t+a}};o.on(`data`,i)})}async function dt(){if(o.isTTY)return await ut(`Paste an organization API key: `);let e=[];for await(let t of o)e.push(t);return Buffer.concat(e).toString(`utf8`).trim()}async function ft(e,t){let n=nt(e),{id:r,name:i,slug:a}=await He({apiKey:e,apiUrl:t});if(r!==n)throw Error(`The API returned a different organization.`);return{id:r,name:i,slug:a}}function pt(e){return`${e.slice(0,e.indexOf(`_abo_`)+5)}…${e.slice(-4)}`}function mt(e){let t=e.command(`auth`).description(`Bind organization API keys to directories, and check them`);t.command(`login`).description(`Verify an API key, read from a hidden prompt or stdin, and bind it to this directory and everything below it`).option(`--api-url <url>`,`API base URL, ending in /api (default ${$e})`).action(async(e,t)=>{let{json:r}=k(t),i=rt(e.apiUrl??n.ASTRALBEAM_API_URL??`https://app.astralbeam.ai/api`),a=await dt(),o=await ft(a,i),s=await at(),c=await D();c.bindings[s]={api_url:i,api_key:a,organization:o},await it(c),ct({apiKey:a,apiUrl:i,organization:o,directory:s}),E({directory:s,organization:o,api_url:i},r)}),t.command(`logout`).description(`Remove the binding that covers this directory`).action(async(e,t)=>{let n=await D(),r=ot(n,await at());if(!r)throw Error(`No AstralBeam login covers this directory.`);delete n.bindings[r.directory],await it(n);let{organization:i}=r.binding;E({directory:r.directory,organization:i},k(t).json)}),t.command(`status`).description(`Show which organization commands here use, and verify the key against the API`).action(async(e,t)=>{let{apiKey:n,apiUrl:r,directory:i}=await j(),a=await ft(n,r);if(O.context&&(O.context.organization=a),i){let e=await D(),t=e.bindings[i];t&&JSON.stringify(t.organization)!==JSON.stringify(a)&&(t.organization=a,await it(e))}E({organization:a,api_url:r,api_key:pt(n),source:i??`ASTRALBEAM_API_KEY`},k(t).json)}),t.command(`list`).description(`List every directory binding`).action(async(e,t)=>{let{bindings:n}=await D(),r=Object.entries(n).map(([e,t])=>({directory:e,organization:t.organization,api_url:t.api_url}));if(k(t).json)return w({items:r});if(r.length===0)return void a.write(`No bindings.
23
+ `);Xe(r.map(({directory:e,organization:t,api_url:n})=>({directory:st(e),name:t.name,slug:t.slug,organization_id:t.id,api_url:n})),[`directory`,`name`,`slug`,`organization_id`,`api_url`])})}const ht=new TextEncoder,gt=new TextDecoder,_t=new TextDecoder(`utf-8`,{fatal:!0});function vt(...e){let t=e.reduce((e,{length:t})=>e+t,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function yt(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r>127)throw TypeError(`non-ASCII string encountered in encode()`);t[n]=r}return t}var bt=class extends Error{static code=`ERR_JOSE_GENERIC`;code=`ERR_JOSE_GENERIC`;constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},xt=class extends bt{static code=`ERR_JOSE_NOT_SUPPORTED`;code=`ERR_JOSE_NOT_SUPPORTED`},M=class extends bt{static code=`ERR_JWS_INVALID`;code=`ERR_JWS_INVALID`},N=class extends bt{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`};function St(e){if(Uint8Array.prototype.toBase64)return e.toBase64();let t=32768,n=[];for(let r=0;r<e.length;r+=t)n.push(String.fromCharCode.apply(null,e.subarray(r,r+t)));return btoa(n.join(``))}function Ct(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}const wt=`The input to be decoded is not correctly encoded.`;function Tt(e){if(Uint8Array.fromBase64)try{return Uint8Array.fromBase64(typeof e==`string`?e:gt.decode(e),{alphabet:`base64url`})}catch(e){throw TypeError(wt,{cause:e})}let t=e;if(t instanceof Uint8Array&&(t=gt.decode(t)),t.includes(`+`)||t.includes(`/`))throw TypeError(wt);t=t.replace(/-/g,`+`).replace(/_/g,`/`);try{return Ct(t)}catch{throw TypeError(wt)}}function Et(e){let t=e;return typeof t==`string`&&(t=ht.encode(t)),Uint8Array.prototype.toBase64?t.toBase64({alphabet:`base64url`,omitPadding:!0}):St(t).replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}function Dt(e){if(typeof e!=`object`||!e||Object.prototype.toString.call(e)!==`[object Object]`)return!1;let t=Object.getPrototypeOf(e);if(t===null)return!0;let n=t;for(;Object.getPrototypeOf(n)!==null;)n=Object.getPrototypeOf(n);return t===n}function Ot(...e){let t=new Set;for(let n of e)if(n)for(let e of Object.keys(n)){if(t.has(e))return!1;t.add(e)}return!0}const kt=e=>Dt(e)&&typeof e.kty==`string`,At=e=>e.kty!==`oct`&&(e.kty===`AKP`&&typeof e.priv==`string`||typeof e.d==`string`),jt=e=>e.kty!==`oct`&&e.d===void 0&&e.priv===void 0,Mt=e=>e.kty===`oct`&&typeof e.k==`string`;var Nt=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports);function Pt(e){if(typeof e!=`string`)throw new N(`JWTs must use Compact JWS serialization, JWT must be a string`);let{1:t,length:n}=e.split(`.`);if(n===5)throw new N(`Only JWTs using Compact JWS serialization can be decoded`);if(n!==3)throw new N(`Invalid JWT`);if(!t)throw new N(`JWTs must contain a payload`);let r;try{r=Tt(t)}catch{throw new N(`Failed to base64url decode the payload`)}let i;try{i=JSON.parse(_t.decode(r))}catch{throw new N(`Failed to parse the decoded payload as JSON`)}if(!Dt(i))throw new N(`Invalid JWT Claims Set`);return i}var Ft=class extends Error{missingFeature;constructor(e){super(It(e)),this.name=`UnsupportedResponseStreamError`,this.missingFeature=e}};function It(e){return`Streaming fetch responses are not supported in this runtime because ${e} is unavailable. React Native users need a compatible fetch/stream/TextDecoder polyfill, or should use a fetch, XHR, or custom transport that can deliver streaming chunks.`}function Lt(e){if(!e.body)throw new Ft(`Response.body`);if(typeof e.body.getReader!=`function`)throw new Ft(`Response.body.getReader`);return e.body.getReader()}function Rt(){if(typeof globalThis.TextDecoder!=`function`)throw new Ft(`TextDecoder`);return new globalThis.TextDecoder}function zt(e){if(!e.startsWith(`data:`))return e;let t=e.slice(5);return t.startsWith(` `)?t.slice(1):t}function Bt(e){return Object.keys(e).length>0?e:void 0}function Vt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&`promptTokens`in e}function Ht(e,t){return Vt(e)?e:Ut(Array.isArray(e)?e:void 0,t)}function Ut(e,t){let n=e?.[0];if(n==null&&t==null)return;let{promptTokensDetails:r,completionTokensDetails:i,...a}=t??{},o=Bt({...n?.cachedInputTokens===void 0?{}:{cachedTokens:n.cachedInputTokens},...r}),s=Bt({...n?.reasoningTokens===void 0?{}:{reasoningTokens:n.reasoningTokens},...i});return{promptTokens:n?.inputTokens??0,completionTokens:n?.outputTokens??0,totalTokens:n?.totalTokens??0,...a,...o===void 0?{}:{promptTokensDetails:o},...s===void 0?{}:{completionTokensDetails:s}}}function Wt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Gt(e,t){if(t==null)return e;if(e==null)return{...t};let n={...e,...t};return Wt(e.tanstack)&&Wt(t.tanstack)&&(n.tanstack={...e.tanstack,...t.tanstack}),n}function P(e){if(e==null)return;let t=`metadata`in e?e.metadata:void 0,n=(typeof t==`object`&&t&&!Array.isArray(t)?t:e).tanstack;if(!(typeof n!=`object`||!n||Array.isArray(n)))return n}function Kt(e,t){let n=e.metadata,r=P(e)??{};return{...e,metadata:{...n??{},tanstack:{...r,...t}}}}let qt=function(e){return e.TEXT_MESSAGE_START=`TEXT_MESSAGE_START`,e.TEXT_MESSAGE_CONTENT=`TEXT_MESSAGE_CONTENT`,e.TEXT_MESSAGE_END=`TEXT_MESSAGE_END`,e.TEXT_MESSAGE_CHUNK=`TEXT_MESSAGE_CHUNK`,e.TOOL_CALL_START=`TOOL_CALL_START`,e.TOOL_CALL_ARGS=`TOOL_CALL_ARGS`,e.TOOL_CALL_END=`TOOL_CALL_END`,e.TOOL_CALL_CHUNK=`TOOL_CALL_CHUNK`,e.TOOL_CALL_RESULT=`TOOL_CALL_RESULT`,e.THINKING_START=`THINKING_START`,e.THINKING_END=`THINKING_END`,e.THINKING_TEXT_MESSAGE_START=`THINKING_TEXT_MESSAGE_START`,e.THINKING_TEXT_MESSAGE_CONTENT=`THINKING_TEXT_MESSAGE_CONTENT`,e.THINKING_TEXT_MESSAGE_END=`THINKING_TEXT_MESSAGE_END`,e.STATE_SNAPSHOT=`STATE_SNAPSHOT`,e.STATE_DELTA=`STATE_DELTA`,e.MESSAGES_SNAPSHOT=`MESSAGES_SNAPSHOT`,e.ACTIVITY_SNAPSHOT=`ACTIVITY_SNAPSHOT`,e.ACTIVITY_DELTA=`ACTIVITY_DELTA`,e.RAW=`RAW`,e.CUSTOM=`CUSTOM`,e.RUN_STARTED=`RUN_STARTED`,e.RUN_FINISHED=`RUN_FINISHED`,e.RUN_ERROR=`RUN_ERROR`,e.STEP_STARTED=`STEP_STARTED`,e.STEP_FINISHED=`STEP_FINISHED`,e.REASONING_START=`REASONING_START`,e.REASONING_MESSAGE_START=`REASONING_MESSAGE_START`,e.REASONING_MESSAGE_CONTENT=`REASONING_MESSAGE_CONTENT`,e.REASONING_MESSAGE_END=`REASONING_MESSAGE_END`,e.REASONING_MESSAGE_CHUNK=`REASONING_MESSAGE_CHUNK`,e.REASONING_END=`REASONING_END`,e.REASONING_ENCRYPTED_VALUE=`REASONING_ENCRYPTED_VALUE`,e}({});var Jt=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function F(e,t){return e>>>t|e<<32-t}function Yt(e){let t=new TextEncoder().encode(e),n=t.length*8,r=t.length+1,i=r+(56-r%64+64)%64+8,a=new Uint8Array(i);a.set(t),a[t.length]=128;let o=new DataView(a.buffer);o.setUint32(i-8,Math.floor(n/4294967296)),o.setUint32(i-4,n>>>0);let s=1779033703,c=3144134277,l=1013904242,u=2773480762,d=1359893119,f=2600822924,p=528734635,m=1541459225,h=new Uint32Array(64);for(let e=0;e<i;e+=64){for(let t=0;t<16;t++)h[t]=o.getUint32(e+t*4);for(let e=16;e<64;e++){let t=h[e-15]??0,n=h[e-2]??0,r=F(t,7)^F(t,18)^t>>>3,i=F(n,17)^F(n,19)^n>>>10;h[e]=(h[e-16]??0)+r+(h[e-7]??0)+i>>>0}let t=s,n=c,r=l,i=u,a=d,g=f,_=p,v=m;for(let e=0;e<64;e++){let o=F(a,6)^F(a,11)^F(a,25),s=a&g^~a&_,c=v+o+s+(Jt[e]??0)+(h[e]??0)>>>0,l=(F(t,2)^F(t,13)^F(t,22))+(t&n^t&r^n&r)>>>0;v=_,_=g,g=a,a=i+c>>>0,i=r,r=n,n=t,t=c+l>>>0}s=s+t>>>0,c=c+n>>>0,l=l+r>>>0,u=u+i>>>0,d=d+a>>>0,f=f+g>>>0,p=p+_>>>0,m=m+v>>>0}let g=e=>(e>>>0).toString(16).padStart(8,`0`);return g(s)+g(c)+g(l)+g(u)+g(d)+g(f)+g(p)+g(m)}function Xt(e){return`sha256:${Yt(e)}`}function Zt(e,t){if(e===null)return`null`;if(typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return JSON.stringify(e);if(typeof e!=`object`)throw TypeError(`Interrupt values must be JSON-compatible.`);if(t.has(e))throw TypeError(`Interrupt values must not cycle.`);if(!Array.isArray(e)&&Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw TypeError(`Interrupt values must use plain JSON objects.`);t.add(e);let n;if(Array.isArray(e)){let r=[];for(let n=0;n<e.length;n++)r.push(Zt(e[n],t));n=`[${r.join(`,`)}]`}else{let r=e;n=`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${Zt(r[e],t)}`).join(`,`)}}`}return t.delete(e),n}function I(e){return Zt(e,new WeakSet)}function L(e,t=Xt){if(typeof e!=`string`)throw TypeError(`Interrupt digests require canonical JSON text.`);return t(e)}function Qt(e){typeof e!=`object`||!e||Object.isFrozen(e)||(Object.values(e).forEach(Qt),Object.freeze(e))}function R(e){let t=JSON.parse(I(e));return Qt(t),t}function $t(e){let t=R([...e].sort((e,t)=>e.interruptId.localeCompare(t.interruptId))),n=I(t);return Object.freeze({resolutions:t,canonicalResolutions:n,fingerprint:L(n)})}function en(e){let t={};for(let[n,r]of Object.entries(e))n!==`$schema`&&(t[n]=r);return t}function tn(e){return(typeof e==`object`||typeof e==`function`)&&e!==null}function z(e){if(!tn(e)||!(`~standard`in e))return!1;let t=e[`~standard`];return typeof t!=`object`||!t||!(`version`in t)||t.version!==1||!(`jsonSchema`in t)||typeof t.jsonSchema!=`object`||t.jsonSchema===null||!(`input`in t.jsonSchema)?!1:typeof t.jsonSchema.input==`function`}function B(e){return tn(e)&&`~standard`in e&&typeof e[`~standard`]==`object`&&e[`~standard`]!==null&&`version`in e[`~standard`]&&e[`~standard`].version===1&&`validate`in e[`~standard`]&&typeof e[`~standard`].validate==`function`}function nn(e){return Object.keys(e).length>0?e:void 0}function rn(e,t=[]){let n={...e},r={};if(n.type===`object`&&n.properties){let e={...n.properties},i=Object.keys(e),a={};for(let n of i){let r=e[n];if(!r)continue;let i=!t.includes(n),o=!1,s;if(r.type===`object`&&r.properties){let t=rn(r,r.required||[]);e[n]=i?{...t.schema,type:[`object`,`null`]}:t.schema,o=i,s=t.nullWidening}else if(r.type===`array`&&r.items){let t=Array.isArray(r.items)?r.items[0]:r.items,a=t?rn(t,t.required||[]):void 0;e[n]={...r,items:a?a.schema:r.items,...i?{type:[`array`,`null`]}:{}},o=i,s=a?.nullWidening?{items:a.nullWidening}:void 0}else i&&(r.type&&!Array.isArray(r.type)?(e[n]={...r,type:[r.type,`null`]},o=!0):Array.isArray(r.type)&&!r.type.includes(`null`)&&(e[n]={...r,type:[...r.type,`null`]},o=!0));(o||s)&&(a[n]={...s??{},...o?{widened:!0}:{}})}n.properties=e,n.required=i,n.additionalProperties=!1,Object.keys(a).length>0&&(r.properties=a)}if(n.type===`array`&&n.items){let e=Array.isArray(n.items)?n.items[0]:n.items;if(e){let t=rn(e,e.required||[]);n.items=t.schema,t.nullWidening&&(r.items=t.nullWidening)}}return{schema:n,nullWidening:nn(r)}}function an(e){if(z(e)){let t=en(e[`~standard`].jsonSchema.input({target:`draft-07`}));return`properties`in t&&!t.type&&(t.type=`object`),t.type===`object`&&!(`properties`in t)&&(t.properties={}),t.type===`object`&&!(`required`in t)&&(t.required=[]),t}if(B(e))throw Error("Schema is a Standard Schema validator but does not expose a JSON Schema converter on `~standard.jsonSchema`. Use Zod v4.2+, ArkType v2.1.28+, or wrap a Valibot schema with `toStandardJsonSchema()` from `@valibot/to-json-schema` before passing it as `outputSchema`.");return typeof e==`object`?en(e):e}function on(e,t={}){if(!e)return;let{forStructuredOutput:n=!1}=t;if(!n&&!z(e)&&!B(e))return e;let r=an(e);return!r||typeof r!=`object`||!n?r:rn(r,r.required||[]).schema}var sn=class extends Error{name=`StandardSchemaValidationError`;issues;constructor(e){super(`Validation failed: ${e.map(e=>e.message||`Validation failed`).join(`, `)}`),this.issues=e}};function cn(e,t){if(!B(e))return t;let n=e[`~standard`].validate(t);if(n instanceof Promise)throw Error(`Schema validation returned a Promise. Use validateWithStandardSchema for async validation.`);if(!n.issues)return n.value;throw new sn(n.issues)}var ln=new Set([`$schema`,`$id`,`$ref`,`$defs`,`type`,`properties`,`required`,`additionalProperties`,`items`,`oneOf`,`anyOf`,`allOf`,`enum`,`const`,`format`,`minimum`,`maximum`,`minLength`,`maxLength`,`pattern`]);function un(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null)}function dn(e){return un(e)&&Object.keys(e).some(e=>ln.has(e))}function fn(e){return B(e)||z(e)||dn(e)}function pn(e){if(!un(e))return!1;let t=Object.keys(e);return t.length>0&&t.every(e=>e===`approve`||e===`reject`)&&t.every(t=>fn(e[t]))}function mn(e){let t={};for(let[n,r]of Object.entries(e))t[n]=r;return t}function V(e){if(B(e)){let t=z(e)?mn(e[`~standard`].jsonSchema.input({target:`draft-2020-12`})):void 0;return{source:e,validator:e,...t!==void 0&&{jsonSchema:t}}}if(dn(e))return{source:e,jsonSchema:e};throw TypeError(`Expected a supported SchemaInput.`)}function hn(e){let t={approved:{const:e.approved}},n=[`approved`];return e.approved&&e.inputSchema&&(t.editedArgs=e.inputSchema.jsonSchema??{}),e.payload&&(t.payload=e.payload.jsonSchema??{},n.push(`payload`)),{type:`object`,properties:t,required:n,additionalProperties:!1}}function gn(e,t){let n=t===void 0?null:V(t),r=null,i=null;if(e!==void 0)if(B(e)||dn(e))r=V(e),i=r;else if(pn(e))r=e.approve===void 0?null:V(e.approve),i=e.reject===void 0?null:V(e.reject);else throw TypeError(`approvalSchema must be a SchemaInput or a nonempty map containing approve or reject.`);let a={oneOf:[hn({approved:!0,payload:r,inputSchema:n}),hn({approved:!1,payload:i,inputSchema:null})]},o=I(a),s=I({approve:r?.jsonSchema??null,reject:i?.jsonSchema??null});return{branches:{approve:r,reject:i},responseSchema:a,responseSchemaHash:L(o),approvalSchemaHash:L(s)}}function _n(e){return L(e===void 0?`undefined`:I(V(e).jsonSchema??{standardValidator:`unserialized`}))}var vn=`tanstack:interruptBinding`,yn=vn;function bn(e){return e&&typeof e==`object`?e:null}function H(e,t){return typeof e[t]==`string`?e[t]:void 0}function xn(e){let t=e.v;return t===void 0||t===1}function Sn(e){let t=bn(e.metadata),n=t?bn(t[yn]):null;if(!n||H(n,`interruptId`)!==e.id||!xn(n))return;let r=H(n,`kind`),i=H(n,`interruptId`),a=H(n,`responseSchemaHash`),o=H(n,`expiresAt`);if(!i||a===``||o!==void 0&&!Number.isFinite(Date.parse(o)))return;if(r===`generic`){let e=H(n,`definitionId`),t=H(n,`key`),s=n.batchIndex,c=H(n,`payloadSchemaHash`);return(e!==void 0||t!==void 0||s!==void 0||c!==void 0)&&(!e||!t||typeof s!=`number`||!Number.isInteger(s)||s<0)?void 0:{v:1,kind:r,interruptId:i,...a?{responseSchemaHash:a}:{},...o?{expiresAt:o}:{},...e?{definitionId:e}:{},...t?{key:t}:{},...typeof s==`number`?{batchIndex:s}:{},...c?{payloadSchemaHash:c}:{}}}if(!a)return;let s=H(n,`toolName`),c=H(n,`toolCallId`);if(!(!s||!c)){if(r===`client-tool-execution`){let e=H(n,`outputSchemaHash`);return e?{v:1,kind:r,interruptId:i,toolName:s,toolCallId:c,outputSchemaHash:e,responseSchemaHash:a,...o?{expiresAt:o}:{}}:void 0}if(r===`tool-approval`){let e=H(n,`inputSchemaHash`),t=H(n,`approvalSchemaHash`);return!e||!t?void 0:{v:1,kind:r,interruptId:i,toolName:s,toolCallId:c,originalArgs:n.originalArgs,inputSchemaHash:e,approvalSchemaHash:t,responseSchemaHash:a,...o?{expiresAt:o}:{}}}}}function Cn(e){let t=Sn(e);if(!t)return;let n=bn(e.metadata),r=n?bn(n[yn]):null;if(!r)return;let i=H(r,`interruptedRunId`),a=r.generation;if(!(!i||typeof a!=`number`||!Number.isInteger(a)||a<0))return{...t,interruptedRunId:i,generation:a}}var wn=`tanstack:interruptPayload`;function Tn(e,t){if(!z(e))throw TypeError(`${t} must be a Standard Schema with a JSON Schema converter.`);try{let t=e[`~standard`].jsonSchema.input({target:`draft-07`});if(t===void 0)throw TypeError(`The exported schema is undefined.`);if(typeof t==`function`)throw TypeError(`The exported schema must not be a function.`);if(Array.isArray(t)||!t||typeof t!=`object`||![Object.prototype,null].includes(Object.getPrototypeOf(t)))throw TypeError(`The exported schema must be a plain JSON object.`);let n={};for(let[e,r]of Object.entries(t))e!==`$schema`&&(n[e]=r);return{json:n,canonicalJson:I(n)}}catch(e){throw TypeError(`${t} could not export compatible JSON Schema: ${e instanceof Error?e.message:String(e)}`)}}function En(e){return L(Tn(e,`Interrupt schema`).canonicalJson)}var Dn=`tanstack:interruptContinuation`;function On(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function kn(e){return{[Dn]:e}}function An(e){let t=Sn(e);if(t?.kind!==`generic`||t.definitionId===void 0||t.key===void 0||t.batchIndex===void 0)return;let n=On(e.metadata)?e.metadata:void 0,r=n!==void 0&&Object.prototype.hasOwnProperty.call(n,`tanstack:interruptPayload`);return{v:1,definitionId:t.definitionId,key:t.key,batchIndex:t.batchIndex,reason:e.reason,message:e.message??``,...e.expiresAt===void 0?{}:{expiresAt:e.expiresAt},...t.responseSchemaHash===void 0?{}:{responseSchemaHash:t.responseSchemaHash},...t.payloadSchemaHash===void 0?{}:{payloadSchemaHash:t.payloadSchemaHash},...r?{payload:n[wn]}:{}}}function jn(e){let t=[];for(let n of e){let e=n.parts??[];if(n.role===`system`){t.push(Mn(n,{content:e.length>0?In(e):n.content??``},e));continue}if(n.role===`user`){t.push(Mn(n,{content:e.length>0?Ln(e):n.content??``},e));continue}for(let r of e)if(r.type===`thinking`){let e={role:`reasoning`,id:Bn(n.id,r),content:r.content};r.signature&&(e.encryptedValue=r.signature),t.push(e)}let r=In(e),i=zn(e);t.push(Mn(n,{...r!==``&&{content:r},...i&&{toolCalls:i}},e));for(let n of e)n.type===`tool-result`&&t.push({role:`tool`,id:Vn(n.toolCallId),toolCallId:n.toolCallId,content:typeof n.content==`string`?n.content:JSON.stringify(n.content),...n.error!==void 0&&{error:n.error}})}return t}function Mn(e,t,n){let r=Nn(e,n),i=e.name;return{id:e.id,role:e.role,...i!==void 0&&{name:i},...t,...r!==void 0&&{metadata:r}}}function Nn(e,t){let n={...e.metadata??{}},r={...P(e)??{}};e.createdAt&&(r.createdAt=e.createdAt.toISOString());let i=Pn(t);i&&(r.structuredOutput=i);let a={};for(let e of t)e.type===`tool-call`&&e.metadata!==void 0&&(a[e.id]=e.metadata);Object.keys(a).length>0&&(r.toolCallMetadata=a);let o=t.filter(e=>e.type===`ui-resource`);return o.length>0&&(r.uiResources=o),Object.keys(r).length>0&&(n.tanstack=r),Object.keys(n).length>0?n:void 0}function Pn(e){for(let t of e)if(t.type===`structured-output`&&t.status!==`complete`)return Fn(t)}function Fn(e){return{status:e.status,raw:e.raw,...e.errorMessage!==void 0&&{errorMessage:e.errorMessage}}}function In(e){let t=[];for(let n of e)n.type===`text`?t.push(n.content):n.type===`structured-output`&&n.status===`complete`&&n.raw!==``&&t.push(n.raw);return t.join(``)}function Ln(e){if(!e.some(e=>e.type===`image`||e.type===`audio`||e.type===`video`||e.type===`document`))return In(e);let t=[];for(let n of e)n.type===`text`?t.push({type:`text`,text:n.content}):(n.type===`image`||n.type===`audio`||n.type===`video`||n.type===`document`)&&t.push(n);return t}function Rn(e){if(typeof e!=`object`||!e||Array.isArray(e)||!(`thoughtSignature`in e))return;let t=e.thoughtSignature;return typeof t==`string`&&t!==``?t:void 0}function zn(e){let t=[];for(let n of e)if(n.type===`tool-call`){let e=Rn(n.metadata);t.push({id:n.id,type:`function`,function:{name:n.name,arguments:n.arguments},...e===void 0?{}:{encryptedValue:e}})}return t.length>0?t:void 0}function Bn(e,t){return`${e}-reasoning-${t.id??Hn(t.content)}`}function Vn(e){return`tool-${e}`}function Hn(e){let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)|0;return Math.abs(t).toString(36)}function Un(e){if((e.type===qt.RUN_FINISHED||e.type===qt.RUN_ERROR)&&(Array.isArray(e.usage)||Vt(e.usage))){let t=Ht(e.usage,P(e)?.usage);t!==void 0&&(e.usage=t)}if(e.type===qt.TOOL_CALL_START&&e.toolName===void 0&&e.toolCallName&&(e.toolName=e.toolCallName),e.type===qt.TOOL_CALL_END&&e.input===void 0){let t=P(e)?.input;t!==void 0&&(e.input=t)}return e}function Wn(e){Un(e);let t=P(e),n=e;if(t==null)return n;for(let[e,r]of Object.entries(t))e===`usage`||e===`interruptErrors`||n[e]===void 0&&r!==void 0&&(n[e]=r);return t.interruptErrors!==void 0&&(n[`tanstack:interruptErrors`]=t.interruptErrors),n}var Gn=new Set([`text`,`image`,`audio`,`video`,`document`]);function Kn(e){if(typeof e!=`object`||!e)return!1;let t=e;if(typeof t.type!=`string`||!Gn.has(t.type))return!1;if(t.type===`text`)return typeof t.content==`string`;let n=t.source;if(typeof n!=`object`||!n)return!1;let r=n;return typeof r.value==`string`?r.type===`data`?typeof r.mimeType==`string`:r.type===`url`:!1}function qn(e){return Array.isArray(e)&&e.length>0&&e.every(Kn)}function Jn(e){return typeof e==`string`||qn(e)?e:JSON.stringify(e)}function Yn(e){let t=e?.metadata;return typeof t==`object`&&t&&t.providerExecuted===!0?t:null}function Xn(e){return Yn(e)!==null}function Zn(e){return e.type===`text`||e.type===`image`||e.type===`audio`||e.type===`video`||e.type===`document`}function Qn(e){try{return JSON.stringify(e)??``}catch{return``}}function $n(e){return typeof e==`string`&&e!==``?e:void 0}function er(e){if(`encryptedValue`in e){let t=$n(e.encryptedValue);if(t!==void 0)return t}return $n(P(e)?.signature)}function tr(e){return e.length===0?null:e.every(e=>e.type===`text`)?e.map(e=>e.content).join(``)||null:e}function nr(e){return e==null?``:typeof e==`string`?e:e.filter(e=>e.type===`text`).map(e=>e.content).join(``)}function rr(e){return e.role===`system`?[]:e.role===`assistant`?sr(e):[ir(e)]}function ir(e){let t=[];for(let n of e.parts)Zn(n)&&t.push(n);return{id:e.id,role:e.role,content:tr(t),...e.createdAt!==void 0&&{createdAt:e.createdAt}}}function ar(){return{contentParts:[],toolCalls:[]}}function or(e){return e.state===`input-complete`||e.state===`complete`||e.state===`approval-requested`||e.state===`approval-responded`||e.state===`error`||e.output!==void 0}function sr(e){let t=[],n=ar(),r=[],i=new Set;function a(){let i=tr(n.contentParts),a=i!==null,o=n.toolCalls.length>0,s=r.length>0;(a||o||s)&&(t.push({id:e.id,role:`assistant`,content:i,...o&&{toolCalls:n.toolCalls},...s&&{thinking:r},...n.structuredOutput&&{structuredOutput:n.structuredOutput},...e.createdAt!==void 0&&{createdAt:e.createdAt}}),r=[]),n=ar()}for(let o of e.parts)switch(o.type){case`text`:case`image`:case`audio`:case`video`:case`document`:n.contentParts.push(o);break;case`tool-call`:or(o)&&n.toolCalls.push({id:o.id,type:`function`,function:{name:o.name,arguments:o.arguments},...o.metadata!==void 0&&{metadata:o.metadata}});break;case`tool-result`:a(),(o.state===`complete`||o.state===`error`)&&!i.has(o.toolCallId)&&(t.push({id:e.id,role:`tool`,content:o.content,toolCallId:o.toolCallId,...e.createdAt!==void 0&&{createdAt:e.createdAt}}),i.add(o.toolCallId));break;case`thinking`:o.content&&(n.toolCalls.some(Xn)&&a(),r.push({content:o.content,...o.signature&&{signature:o.signature}}));break;case`structured-output`:if(o.status===`complete`){let e=o.raw===``?o.data===void 0?``:Qn(o.data):o.raw;e!==``&&(n.contentParts.push({type:`text`,content:e}),n.structuredOutput=o)}}a();for(let n of e.parts)if(n.type===`tool-call`&&(n.output!==void 0&&!i.has(n.id)&&(t.push({id:e.id,role:`tool`,content:Jn(n.output),toolCallId:n.id,...e.createdAt!==void 0&&{createdAt:e.createdAt}}),i.add(n.id)),n.output===void 0&&n.state===`approval-responded`&&n.approval?.approved!==void 0&&!i.has(n.id))){let r=n.approval.approved;t.push({id:e.id,role:`tool`,content:JSON.stringify({approved:r,...r&&{pendingExecution:!0},message:r?`User approved this action`:`User denied this action`}),toolCallId:n.id,...e.createdAt!==void 0&&{createdAt:e.createdAt}}),i.add(n.id)}return t.length===0&&t.push({id:e.id,role:`assistant`,content:null,...e.createdAt!==void 0&&{createdAt:e.createdAt}}),t}function cr(e,t){let n=[];if(e.role===`assistant`&&e.thinking?.length)for(let t of e.thinking)t.content&&n.push({type:`thinking`,content:t.content,...t.signature&&{signature:t.signature}});if(e.role===`assistant`&&e.structuredOutput)n.push(e.structuredOutput);else if(e.role===`tool`&&e.toolCallId)n.push({type:`tool-result`,toolCallId:e.toolCallId,content:nr(e.content),state:`complete`});else if(Array.isArray(e.content))for(let t of e.content)n.push(t);else{let t=nr(e.content);t&&n.push({type:`text`,content:t})}if(e.toolCalls&&e.toolCalls.length>0)for(let t of e.toolCalls){let e;try{e=JSON.parse(t.function.arguments)}catch{e=void 0}n.push({type:`tool-call`,id:t.id,name:t.function.name,arguments:t.function.arguments,state:`input-complete`,...e!==void 0&&{input:e},...t.metadata!==void 0&&{metadata:t.metadata}})}return{id:t||W(),role:e.role===`tool`?`assistant`:e.role,parts:n,...e.createdAt!==void 0&&{createdAt:e.createdAt}}}function lr(e){if(`parts`in e)return U(e,{...e,id:e.id||W()});let t=e.id||W();switch(e.role){case`user`:return U(e,{id:t,role:`user`,parts:ur(e.content)});case`assistant`:{let n=P(e)?.toolCallMetadata,r=e.toolCalls?.map(e=>{let t=typeof n==`object`&&n?n[e.id]:void 0;return t===void 0?e:{...e,metadata:t}});return U(e,cr({role:`assistant`,content:e.content??null,...r&&{toolCalls:r}},t))}case`tool`:return U(e,cr({role:`tool`,content:e.content,toolCallId:e.toolCallId},t));case`system`:case`developer`:return U(e,{id:t,role:`system`,parts:e.content?[{type:`text`,content:e.content}]:[]});case`reasoning`:{let n=er(e);return U(e,{id:t,role:`assistant`,parts:e.content?[{type:`thinking`,content:e.content,...n===void 0?{}:{signature:n}}]:[]})}default:return U(e,{id:t,role:`assistant`,parts:[]})}}function U(e,t){if(!(`metadata`in e))return t;let n=e.metadata;if(typeof n!=`object`||!n||Array.isArray(n))return t;let r=n,i=P(r)?.createdAt,a=typeof i==`string`?new Date(i):void 0,o=a!==void 0&&!Number.isNaN(a.getTime());return{...t,metadata:r,...o?{createdAt:a}:{}}}function ur(e){if(typeof e==`string`)return e?[{type:`text`,content:e}]:[];let t=[];for(let n of e)n.type===`text`?t.push({type:`text`,content:n.text}):n.type!==`binary`&&t.push(n);return t}function dr(e,t){return`parts`in e?{...e,id:e.id||t(),createdAt:e.createdAt||new Date}:{...cr(e,t()),createdAt:e.createdAt??new Date}}function W(){return`msg-${Date.now()}-${Math.random().toString(36).substring(7)}`}function fr(e){if(e.approvalSchema!==void 0&&e.needsApproval!==!0)throw TypeError(`approvalSchema requires needsApproval: true.`);let t=e.inputSchema,n=e.outputSchema,r=e.approvalSchema,i=e.needsApproval;return{__toolSide:`definition`,...e,inputSchema:t,outputSchema:n,approvalSchema:r,needsApproval:i,server(a){return{__toolSide:`server`,...e,inputSchema:t,outputSchema:n,approvalSchema:r,needsApproval:i,execute:a}},client(a){return{__toolSide:`client`,...e,inputSchema:t,outputSchema:n,approvalSchema:r,needsApproval:i,...a!==void 0&&{execute:a}}}}}function pr(e){return typeof e==`string`&&e!==``?e:void 0}function mr(e){if(`runId`in e){let t=pr(e.runId);if(t!==void 0)return t}return pr(P(e)?.runId)}var hr=Nt((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.ALL=e.COLLECTION=e.ATOM=e.SPECIAL=e.INF=e._INFINITY=e.INFINITY=e.NAN=e.BOOL=e.NULL=e.OBJ=e.ARR=e.NUM=e.STR=void 0,e.STR=1,e.NUM=2,e.ARR=4,e.OBJ=8,e.NULL=16,e.BOOL=32,e.NAN=64,e.INFINITY=128,e._INFINITY=256,e.INF=e.INFINITY|e._INFINITY,e.SPECIAL=e.NULL|e.BOOL|e.INF|e.NAN,e.ATOM=e.STR|e.NUM|e.SPECIAL,e.COLLECTION=e.ARR|e.OBJ,e.ALL=e.ATOM|e.COLLECTION,e.Allow={STR:e.STR,NUM:e.NUM,ARR:e.ARR,OBJ:e.OBJ,NULL:e.NULL,BOOL:e.BOOL,NAN:e.NAN,INFINITY:e.INFINITY,_INFINITY:e._INFINITY,INF:e.INF,SPECIAL:e.SPECIAL,ATOM:e.ATOM,COLLECTION:e.COLLECTION,ALL:e.ALL},e.default=e.Allow})),gr=Nt((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__exportStar||function(e,n){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(n,r)&&t(n,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.MalformedJSON=e.PartialJSON=e.parseJSON=e.parse=void 0;let r=hr();Object.defineProperty(e,"Allow",{enumerable:!0,get:function(){return r.Allow}}),n(hr(),e);var i=class extends Error{};e.PartialJSON=i;var a=class extends Error{};e.MalformedJSON=a;function o(e,t=r.Allow.ALL){if(typeof e!=`string`)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return s(e.trim(),t)}e.parseJSON=o;let s=(e,t)=>{let n=e.length,o=0,s=e=>{throw new i(`${e} at position ${o}`)},c=e=>{throw new a(`${e} at position ${o}`)},l=()=>(m(),o>=n&&s(`Unexpected end of input`),e[o]===`"`?u():e[o]===`{`?d():e[o]===`[`?f():e.substring(o,o+4)===`null`||r.Allow.NULL&t&&n-o<4&&`null`.startsWith(e.substring(o))?(o+=4,null):e.substring(o,o+4)===`true`||r.Allow.BOOL&t&&n-o<4&&`true`.startsWith(e.substring(o))?(o+=4,!0):e.substring(o,o+5)===`false`||r.Allow.BOOL&t&&n-o<5&&`false`.startsWith(e.substring(o))?(o+=5,!1):e.substring(o,o+8)===`Infinity`||r.Allow.INFINITY&t&&n-o<8&&`Infinity`.startsWith(e.substring(o))?(o+=8,1/0):e.substring(o,o+9)===`-Infinity`||r.Allow._INFINITY&t&&1<n-o&&n-o<9&&`-Infinity`.startsWith(e.substring(o))?(o+=9,-1/0):e.substring(o,o+3)===`NaN`||r.Allow.NAN&t&&n-o<3&&`NaN`.startsWith(e.substring(o))?(o+=3,NaN):p()),u=()=>{let i=o,a=!1;for(o++;o<n&&(e[o]!==`"`||a&&e[o-1]===`\\`);)a=e[o]===`\\`&&!a,o++;if(e.charAt(o)==`"`)try{return JSON.parse(e.substring(i,++o-Number(a)))}catch(e){c(String(e))}else if(r.Allow.STR&t)try{return JSON.parse(e.substring(i,o-Number(a))+`"`)}catch{return JSON.parse(e.substring(i,e.lastIndexOf(`\\`))+`"`)}s(`Unterminated string literal`)},d=()=>{o++,m();let i={};try{for(;e[o]!==`}`;){if(m(),o>=n&&r.Allow.OBJ&t)return i;let a=u();m(),o++;try{i[a]=l()}catch(e){if(r.Allow.OBJ&t)return i;throw e}m(),e[o]===`,`&&o++}}catch{if(r.Allow.OBJ&t)return i;s(`Expected '}' at end of object`)}return o++,i},f=()=>{o++;let n=[];try{for(;e[o]!==`]`;)n.push(l()),m(),e[o]===`,`&&o++}catch{if(r.Allow.ARR&t)return n;s(`Expected ']' at end of array`)}return o++,n},p=()=>{if(o===0){e===`-`&&c(`Not sure what '-' is`);try{return JSON.parse(e)}catch(n){if(r.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf(`e`)))}catch{}c(String(n))}}let i=o;for(e[o]===`-`&&o++;e[o]&&`,]}`.indexOf(e[o])===-1;)o++;o==n&&!(r.Allow.NUM&t)&&s(`Unterminated number literal`);try{return JSON.parse(e.substring(i,o))}catch{e.substring(i,o)===`-`&&s(`Not sure what '-' is`);try{return JSON.parse(e.substring(i,e.lastIndexOf(`e`)))}catch(e){c(String(e))}}},m=()=>{for(;o<n&&`
24
+ \r `.includes(e[o]);)o++};return l()};e.parse=o}))(),_r=new class{parse(e){if(!(!e||e.trim()===``))try{return(0,gr.parse)(e)}catch{return}}};function vr(e){return _r.parse(e)}var yr=class{shouldEmit(e,t){return!0}};function br(e){let t=Error(e.message||e.error?.message||`An error occurred`),n=e.code??e.error?.code;return n!==void 0&&Object.assign(t,{code:n}),e.rawEvent!==void 0&&Object.assign(t,{rawEvent:e.rawEvent}),t}function xr(e,t,n){return e.map(e=>{if(e.id!==t)return e;let r=[...e.parts],i=r.length>0?r[r.length-1]:null;return i&&i.type===`text`?r[r.length-1]={type:`text`,content:n}:r.push({type:`text`,content:n}),{...e,parts:r}})}function Sr(e,t,n){return e.map(e=>{if(e.id!==t)return e;let r=[...e.parts],i=r.find(e=>e.type===`tool-call`&&e.id===n.id),a=n.metadata??i?.metadata,o=n.input??i?.input,s={type:`tool-call`,id:n.id,name:n.name,arguments:n.arguments,state:n.state,...i?.approval&&{approval:{...i.approval}},...i?.output!==void 0&&{output:i.output},...o!==void 0&&{input:o},...a!==void 0&&{metadata:a}};return i?r[r.indexOf(i)]=s:r.push(s),{...e,parts:r}})}function Cr(e,t,n,r,i,a){return e.map(e=>{if(e.id!==t)return e;let o=[...e.parts],s=o.findIndex(e=>e.type===`tool-result`&&e.toolCallId===n),c={type:`tool-result`,toolCallId:n,content:r,state:i,...a&&{error:a}};return s>=0?o[s]=c:o.push(c),{...e,parts:o}})}function wr(e,t,n,r){return e.map(e=>{if(e.id!==t)return e;let i=[...e.parts],a=i.find(e=>e.type===`tool-call`&&e.id===n);if(a){let e=i.indexOf(a);i[e]={...a,state:`approval-requested`,approval:{id:r,needsApproval:!0}}}return{...e,parts:i}})}function Tr(e,t,n,r,i){return e.map(e=>{let a=[...e.parts],o=a.find(e=>e.type===`tool-call`&&e.id===t);if(o){let e=a.indexOf(o);a[e]={...o,output:i?{error:i}:n,state:r??(i?`error`:`complete`)}}return{...e,parts:a}})}function Er(e,t,n){return e.map(e=>{let r=[...e.parts],i=r.find(e=>e.type===`tool-call`&&e.approval?.id===t);if(i&&i.approval){let e=r.indexOf(i);r[e]={...i,approval:{...i.approval,approved:n},state:`approval-responded`}}return{...e,parts:r}})}function Dr(e,t,n){return e.map(e=>{if(e.id!==t)return e;let r=[...e.parts],i=r.findIndex(e=>e.type===`structured-output`),a=i>=0?r[i]:null,o=(a?.raw??``)+n,s=vr(o)??a?.partial,c={type:`structured-output`,status:`streaming`,raw:o,...s===void 0?{}:{partial:s},...a?.reasoning===void 0?{}:{reasoning:a.reasoning}};return i>=0?r[i]=c:r.push(c),{...e,parts:r}})}function Or(e,t,n,r,i){return e.map(e=>{if(e.id!==t)return e;let a=[...e.parts],o=a.findIndex(e=>e.type===`structured-output`),s=o>=0?a[o].raw:``,c=r||s;if(c===``&&n!==void 0)try{c=JSON.stringify(n)}catch{}let l={type:`structured-output`,status:`complete`,data:n,partial:n,raw:c,...i===void 0?{}:{reasoning:i}};return o>=0?a[o]=l:a.push(l),{...e,parts:a}})}function kr(e,t,n){return e.map(e=>{if(e.id!==t)return e;let r=[...e.parts],i=r.findIndex(e=>e.type===`structured-output`);if(i<0)return r.push({type:`structured-output`,status:`error`,raw:``,errorMessage:n}),{...e,parts:r};let a=r[i];return a.status===`complete`?e:(r[i]={...a,status:`error`,errorMessage:n},{...e,parts:r})})}function Ar(e,t,n,r,i){return e.map(e=>{if(e.id!==t)return e;let a=[...e.parts],o=a.findIndex(e=>e.type===`thinking`&&e.stepId===n),s={type:`thinking`,content:r,stepId:n,...i&&{signature:i}};return o>=0?a[o]=s:a.push(s),{...e,parts:a}})}var jr=12;function Mr(e){return e.some(e=>{let t=e.metadata;if(!t||typeof t!=`object`||Array.isArray(t))return!1;let n=t[vn];return typeof n==`object`&&!!n&&!Array.isArray(n)&&n.kind===`generic`})}var Nr=class e{chunkStrategy;events;jsonParser;recordingEnabled;messages=[];messageStates=new Map;activeMessageIds=new Set;toolCallToMessage=new Map;pendingManualMessageId=null;pendingThinkingStepId=null;structuredMessageIds=new Set;structuredOutputUpdateBatches=new Map;activeRuns=new Set;finishReason=null;hasError=!1;isDone=!1;recording=null;recordingStartTime=0;constructor(e={}){this.chunkStrategy=e.chunkStrategy||new yr,this.events=e.events||{},this.jsonParser=e.jsonParser||_r,this.recordingEnabled=e.recording??!1,e.initialMessages&&(this.messages=[...e.initialMessages])}setMessages(e){this.messages=[...e],this.emitMessagesChange()}addUserMessage(e,t,n){let r=typeof e==`string`?[{type:`text`,content:e}]:e.map(e=>e),i={id:t??W(),role:`user`,parts:r,createdAt:new Date,...n==null?{}:{metadata:n}};return this.messages=[...this.messages,i],this.emitMessagesChange(),i}prepareAssistantMessage(){this.resetStreamState()}startAssistantMessage(e){this.prepareAssistantMessage();let{messageId:t}=this.ensureAssistantMessage(e);return this.pendingManualMessageId=t,t}getCurrentAssistantMessageId(){let e=null;for(let[t,n]of this.messageStates)n.role===`assistant`&&(e=t);return e}addToolResult(e,t,n){let r=this.messages.find(t=>t.parts.some(t=>t.type===`tool-call`&&t.id===e));if(!r){console.warn(`[StreamProcessor] Could not find message with tool call ${e}`);return}let i=Tr(this.messages,e,t,n?`error`:void 0,n),a=Jn(t),o=n?`error`:`complete`;i=Cr(i,r.id,e,a,o,n),this.messages=i,this.emitMessagesChange()}addToolApprovalResponse(e,t){this.messages=Er(this.messages,e,t),this.emitMessagesChange()}toModelMessages(){let e=[];for(let t of this.messages)e.push(...rr(t));return e}getMessages(){return this.messages}areAllToolsComplete(){let e=this.messages.findLast(e=>e.role===`assistant`);if(!e)return!0;let t=e.parts.filter(e=>e.type===`tool-call`);if(t.length===0)return!0;let n=new Set(e.parts.filter(e=>e.type===`tool-result`).map(e=>e.toolCallId));return t.every(e=>e.state===`complete`||e.state===`approval-responded`||e.output!==void 0&&!e.approval||n.has(e.id)||Xn(e))}removeMessagesAfter(e){let t=new Set(this.messages.slice(0,e+1).map(e=>e.id));for(let e of this.structuredMessageIds)t.has(e)||this.structuredMessageIds.delete(e);for(let e of this.structuredOutputUpdateBatches.keys())t.has(e)||this.structuredOutputUpdateBatches.delete(e);for(let e of this.messageStates.keys())t.has(e)||this.messageStates.delete(e);for(let[e,n]of this.toolCallToMessage)t.has(n)||this.toolCallToMessage.delete(e);for(let e of this.activeMessageIds)t.has(e)||this.activeMessageIds.delete(e);this.messages=this.messages.slice(0,e+1),this.emitMessagesChange()}clearMessages(){this.messages=[],this.messageStates.clear(),this.activeMessageIds.clear(),this.toolCallToMessage.clear(),this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.pendingManualMessageId=null,this.emitMessagesChange()}async process(e){this.resetStreamState(),this.recordingEnabled&&this.startRecording();for await(let t of e)this.processChunk(t);return this.finalizeStream(),this.recording&&(this.recording.result=this.getResult()),this.getResult()}processChunk(e){switch(this.recording&&this.recording.chunks.push({chunk:e,timestamp:Date.now(),index:this.recording.chunks.length}),e.type){case`TEXT_MESSAGE_START`:this.handleTextMessageStartEvent(e);break;case`TEXT_MESSAGE_CONTENT`:this.handleTextMessageContentEvent(e);break;case`TEXT_MESSAGE_END`:this.handleTextMessageEndEvent(e);break;case`TOOL_CALL_START`:this.handleToolCallStartEvent(e);break;case`TOOL_CALL_ARGS`:this.handleToolCallArgsEvent(e);break;case`TOOL_CALL_END`:this.handleToolCallEndEvent(e);break;case`RUN_FINISHED`:this.handleRunFinishedEvent(e);break;case`RUN_ERROR`:this.handleRunErrorEvent(e);break;case`STEP_FINISHED`:this.handleStepFinishedEvent(e);break;case`MESSAGES_SNAPSHOT`:this.handleMessagesSnapshotEvent(e);break;case`CUSTOM`:this.handleCustomEvent(e);break;case`RUN_STARTED`:this.handleRunStartedEvent(e);break;case`REASONING_START`:case`REASONING_MESSAGE_START`:case`REASONING_MESSAGE_END`:case`REASONING_END`:break;case`REASONING_MESSAGE_CONTENT`:this.handleReasoningMessageContentEvent(e);break;case`REASONING_ENCRYPTED_VALUE`:this.handleReasoningEncryptedValueEvent(e);break;case`TOOL_CALL_RESULT`:this.handleToolCallResultEvent(e);break;case`STEP_STARTED`:this.handleStepStartedEvent(e)}}createMessageState(e,t){let n={id:e,role:t,totalTextContent:``,currentSegmentText:``,lastEmittedText:``,hasSeenReasoningEvents:!1,thinkingSteps:new Map,thinkingStepSignatures:new Map,thinkingStepOrder:[],currentThinkingStepId:null,toolCalls:new Map,toolCallOrder:[],hasToolCallsSinceTextStart:!1,isComplete:!1};return this.messageStates.set(e,n),n}getMessageState(e){return this.messageStates.get(e)}consumePendingThinkingStep(e){if(!this.pendingThinkingStepId)return;let t=this.pendingThinkingStepId;e.currentThinkingStepId=t,e.thinkingSteps.has(t)||(e.thinkingSteps.set(t,``),e.thinkingStepOrder.push(t)),this.pendingThinkingStepId=null}getActiveAssistantMessageId(){let e=Array.from(this.activeMessageIds).reverse();for(let t of e){let e=this.messageStates.get(t);if(e&&e.role===`assistant`)return t}return null}ensureAssistantMessage(e){if(e){let t=this.getMessageState(e);if(t)return{messageId:e,state:t}}let t=this.getActiveAssistantMessageId();if(t){let e=this.getMessageState(t);if(e)return{messageId:t,state:e}}if(e){let t=this.messages.find(t=>t.id===e);if(t){let n=this.createMessageState(e,t.role);this.activeMessageIds.add(e);let r=t.parts.length>0?t.parts[t.parts.length-1]:null;return r&&r.type===`text`&&(n.currentSegmentText=r.content,n.lastEmittedText=r.content,n.totalTextContent=r.content),{messageId:e,state:n}}}let n=e||W(),r={id:n,role:`assistant`,parts:[],createdAt:new Date};this.messages=[...this.messages,r];let i=this.createMessageState(n,`assistant`);return this.activeMessageIds.add(n),this.pendingManualMessageId=n,this.events.onStreamStart?.(),this.emitMessagesChange(),{messageId:n,state:i}}mergeMessageMetadata(e,t){if(typeof t!=`object`||!t||Array.isArray(t))return;let n=this.messages.find(t=>t.id===e);if(!n)return;let r=t,i=P(r),a=i!=null&&(`content`in i||`args`in i)?{...r,tanstack:Object.fromEntries(Object.entries(i).filter(([e])=>e!==`content`&&e!==`args`))}:r,o=Gt(n.metadata,a),s=P(r)?.createdAt,c=typeof s==`string`?new Date(s):void 0,l=c!==void 0&&!Number.isNaN(c.getTime());this.messages=this.messages.map(t=>t.id===e?{...t,...o===void 0?{}:{metadata:o},...l?{createdAt:c}:{}}:t),this.emitMessagesChange()}handleTextMessageStartEvent(e){let{messageId:t,role:n}=e,r=n===`user`||n===`system`?n:`assistant`;if(this.pendingManualMessageId){let n=this.pendingManualMessageId;if(this.pendingManualMessageId=null,n!==t){this.messages=this.messages.map(e=>e.id===n?{...e,id:t}:e);let e=this.messageStates.get(n);e&&(e.id=t,this.messageStates.delete(n),this.messageStates.set(t,e)),this.activeMessageIds.delete(n),this.activeMessageIds.add(t);for(let[e,r]of this.toolCallToMessage)r===n&&this.toolCallToMessage.set(e,t)}this.messageStates.has(t)||(this.createMessageState(t,r),this.activeMessageIds.add(t)),this.mergeMessageMetadata(t,e.metadata),this.emitMessagesChange();return}if(this.messages.find(e=>e.id===t)){this.activeMessageIds.add(t);let n=this.messageStates.get(t);n?n.hasToolCallsSinceTextStart&&=(n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(t),n.currentSegmentText=``,n.lastEmittedText=``,!1):this.createMessageState(t,r),this.mergeMessageMetadata(t,e.metadata);return}let i={id:t,role:r,parts:[],createdAt:new Date};this.messages=[...this.messages,i],this.createMessageState(t,r),this.activeMessageIds.add(t),this.mergeMessageMetadata(t,e.metadata),this.events.onStreamStart?.(),this.emitMessagesChange()}handleTextMessageEndEvent(e){let{messageId:t}=e;this.mergeMessageMetadata(t,e.metadata);let n=this.getMessageState(t);n&&(n.isComplete||n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(t))}handleMessagesSnapshotEvent(e){this.resetStreamState();let t=this.messages,n=new Map(t.map(e=>[e.id,e])),r=this.mergeReasoningFanOut(e.messages.map(lr));this.messages=this.reconcileSnapshotToolCalls(r,t).map(e=>{if(e.metadata!=null)return e;let t=n.get(e.id);return t?.metadata==null?e:{...e,metadata:t.metadata}}),this.emitMessagesChange()}mergeReasoningFanOut(e){let t=[],n=[],r=e=>e.parts.filter(e=>e.type===`thinking`),i=e=>e.role===`assistant`&&e.parts.length>0&&e.parts.every(e=>e.type===`thinking`),a=e=>e.role===`assistant`&&e.parts.length===1&&e.parts[0]?.type===`tool-result`,o=()=>{t.push(...n),n=[]};for(let s of e){if(i(s)){n.push(s);continue}if(s.role===`assistant`&&n.length>0&&!a(s)){t.push({...s,parts:[...n.flatMap(r),...s.parts]}),n=[];continue}o(),t.push(s)}return o(),t}reconcileSnapshotToolCalls(e,t){let n=new Map;for(let e of t)for(let t of e.parts)t.type===`tool-call`&&n.set(t.id,t);let r=new Set;for(let t of e)for(let e of t.parts)e.type===`tool-call`&&r.add(e.id);let i=[];for(let t of e){let e=t.role===`assistant`&&t.parts.length===1?t.parts.find(e=>e.type===`tool-result`):void 0;if(!e){i.push(t);continue}let a=i.findLast(t=>t.parts.some(t=>t.type===`tool-call`&&t.id===e.toolCallId))??i.findLast(e=>e.role===`assistant`&&!(e.parts.length===1&&e.parts[0]?.type===`tool-result`));if(!a){r.has(e.toolCallId)||console.warn(`[StreamProcessor] MESSAGES_SNAPSHOT contains a tool-result for "${e.toolCallId}" but no matching tool-call exists in the snapshot, and there is no assistant message to anchor into; addToolResult("${e.toolCallId}") will not be able to locate this call`),i.push(t);continue}let o=[...a.parts];if(!r.has(e.toolCallId)&&!o.some(t=>t.type===`tool-call`&&t.id===e.toolCallId)){let t=n.get(e.toolCallId);t?(o.push({...t}),r.add(t.id)):console.warn(`[StreamProcessor] MESSAGES_SNAPSHOT contains a tool-result for "${e.toolCallId}" but no matching tool-call exists in the snapshot or the pre-snapshot state; addToolResult("${e.toolCallId}") will not be able to locate this call`)}o.push(e),a.parts=o}return this.enrichSnapshotToolCallsFromResults(i,n)}enrichSnapshotToolCallsFromResults(e,t){let n=new Map;for(let t of e)for(let e of t.parts)e.type===`tool-result`&&n.set(e.toolCallId,e);return e.map(e=>{let r=e.parts.map(e=>{if(e.type!==`tool-call`)return e;let r=t.get(e.id),i=n.get(e.id),a=e;if(r&&(r.output!==void 0||r.state===`complete`||r.state===`error`)&&(e.output===void 0||e.state===`input-complete`||e.state===`input-streaming`||e.state===`awaiting-input`)&&(a={...e,...r.output===void 0?{}:{output:r.output},state:r.state,...r.approval===void 0?{}:{approval:r.approval},...r.metadata===void 0?{}:{metadata:r.metadata}}),i&&a.output===void 0){let e;if(Array.isArray(i.content))e=i.content;else try{e=JSON.parse(i.content)}catch{e=i.content}let t=i.state===`error`?this.extractToolResultError(e):void 0;a={...a,output:t?{error:t}:e,state:i.state===`error`?`error`:`complete`}}return a});return r.some((t,n)=>t!==e.parts[n])?{...e,parts:r}:e})}handleTextMessageContentEvent(e){let{messageId:t,state:n}=this.ensureAssistantMessage(e.messageId);if(this.mergeMessageMetadata(t,e.metadata),this.structuredMessageIds.has(t)){let r=e.delta||``;r!==``&&(this.messages=Dr(this.messages,t,r),n.totalTextContent+=r,this.queueStructuredOutputUpdate(t,r),this.emitMessagesChange());return}let r=n.currentSegmentText;n.hasToolCallsSinceTextStart&&r.length>0&&this.isNewTextSegment(e,r)&&(r!==n.lastEmittedText&&this.emitTextUpdateForMessage(t),n.currentSegmentText=``,n.lastEmittedText=``,n.hasToolCallsSinceTextStart=!1);let i=n.currentSegmentText,a=e.delta||``,o=a===``?i:i+a,s=o.slice(i.length);n.currentSegmentText=o,n.totalTextContent+=s;let c=e.delta||``;this.chunkStrategy.shouldEmit(c,n.currentSegmentText)&&n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(t)}handleToolCallStartEvent(e){let t=e.parentMessageId??this.getActiveAssistantMessageId(),{messageId:n,state:r}=this.ensureAssistantMessage(t??void 0);r.hasToolCallsSinceTextStart=!0;let i=e.toolCallId;if(!r.toolCalls.get(i)){let t=`awaiting-input`,a=e.toolCallName,o=e.metadata,s={id:e.toolCallId,name:a,arguments:``,state:t,parsedArguments:void 0,index:r.toolCalls.size,...o!==void 0&&{metadata:o}};r.toolCalls.set(i,s),r.toolCallOrder.push(i),this.toolCallToMessage.set(i,n),this.messages=Sr(this.messages,n,{id:e.toolCallId,name:a,arguments:``,state:t,...o!==void 0&&{metadata:o}}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(n,e.toolCallId,t,``)}}handleToolCallArgsEvent(e){let t=e.toolCallId,n=this.toolCallToMessage.get(t);if(!n)return;let r=this.getMessageState(n);if(!r)return;let i=r.toolCalls.get(t);if(!i)return;let a=i.state===`awaiting-input`;i.arguments+=e.delta||``,a&&e.delta&&(i.state=`input-streaming`),i.parsedArguments=this.jsonParser.parse(i.arguments),this.messages=Sr(this.messages,n,{id:i.id,name:i.name,arguments:i.arguments,state:i.state}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(n,i.id,i.state,i.arguments)}handleToolCallEndEvent(e){let t=this.toolCallToMessage.get(e.toolCallId);if(!t)return;let n=this.getMessageState(t);if(!n)return;let r=e.input===void 0?P(e)?.input:e.input,i=n.toolCalls.get(e.toolCallId);if(i&&i.state!==`input-complete`){if(r!==void 0&&!i.arguments)try{i.arguments=JSON.stringify(r)}catch{}let a=n.toolCallOrder.indexOf(e.toolCallId);this.completeToolCall(t,a,i),r!==void 0&&(i.parsedArguments=r,this.messages=Sr(this.messages,t,{id:i.id,name:i.name,arguments:i.arguments,state:`input-complete`,input:r,...i.metadata!==void 0&&{metadata:i.metadata}}),this.emitMessagesChange())}}extractToolResultError(e){return e&&typeof e==`object`&&`error`in e&&typeof e.error==`string`?e.error:typeof e==`string`?e:`Tool execution failed`}handleToolCallResultEvent(e){let t=this.toolCallToMessage.get(e.toolCallId)??this.messages.find(t=>t.parts.some(t=>t.type===`tool-call`&&t.id===e.toolCallId))?.id;if(!t)return;let n=e.state===`output-error`||P(e)?.state===`output-error`,r;try{r=JSON.parse(e.content)}catch{r=e.content}this.messages=Tr(this.messages,e.toolCallId,r,n?`error`:void 0);let i=n?`error`:`complete`;this.messages=Cr(this.messages,t,e.toolCallId,e.content,i,i===`error`?this.extractToolResultError(r):void 0),this.emitMessagesChange()}handleRunStartedEvent(e){this.activeRuns.add(e.runId)}handleRunFinishedEvent(e){let t=e;this.finishReason=t.finishReason===void 0?P(e)?.finishReason??null:t.finishReason,this.activeRuns.delete(e.runId),e.outcome?.type===`interrupt`&&this.handleInterrupts(e.outcome.interrupts),this.activeRuns.size===0&&(this.isDone=!0,this.completeAllToolCalls(),this.finalizeStream())}handleInterrupts(e){let t=Mr(e);for(let n of e){let e=n.metadata&&typeof n.metadata==`object`?n.metadata:{},r=typeof e.kind==`string`?e.kind:void 0,i=n.toolCallId;if(!i)continue;let a=typeof e.toolName==`string`?e.toolName:this.findToolCallName(i),o=Object.hasOwn(e,`input`)?e.input:{};if(r===`approval`||n.reason===`approval_required`){let e=this.getActiveAssistantMessageId()??this.toolCallToMessage.get(i)??this.messages.find(e=>e.role===`assistant`&&e.parts.some(e=>e.type===`tool-call`&&e.id===i))?.id;e&&(this.messages=wr(this.messages,e,i,n.id),this.emitMessagesChange()),this.events.onApprovalRequest?.({toolCallId:i,toolName:a,input:o,approvalId:n.id});continue}if(r===`client_tool`||n.reason===`client_tool_input`){if(t)continue;this.events.onToolCall?.({toolCallId:i,toolName:a,input:o})}}}findToolCallName(e){for(let t of this.messageStates.values()){let n=t.toolCalls.get(e);if(n)return n.name}return``}handleRunErrorEvent(e){this.hasError=!0;let t=mr(e);t?this.activeRuns.delete(t):this.activeRuns.clear();let{messageId:n}=this.ensureAssistantMessage(),r=e.message||`An error occurred`;e.message||console.error(`[StreamProcessor] RUN_ERROR with no message; original chunk:`,e),this.structuredMessageIds.has(n)&&(this.flushStructuredOutputUpdate(n),this.messages=kr(this.messages,n,r),this.structuredMessageIds.delete(n),this.emitStructuredOutputChange(n,`error`),this.emitMessagesChange()),this.events.onError?.(br(e))}handleStepStartedEvent(e){let t=e.stepName||W(),n=this.getActiveAssistantMessageId();if(n){let e=this.getMessageState(n);if(e){e.currentThinkingStepId=t,e.thinkingSteps.has(t)||(e.thinkingSteps.set(t,``),e.thinkingStepOrder.push(t)),this.pendingThinkingStepId=null;return}}this.pendingThinkingStepId=t}handleStepFinishedEvent(e){let t=e,n=t.signature;if(!n)return;let{messageId:r,state:i}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0),a=i.currentThinkingStepId??t.stepId;if(!a)return;let o=i.thinkingSteps.get(a);o!==void 0&&(i.thinkingStepSignatures.set(a,n),this.messages=Ar(this.messages,r,a,o,n),this.emitMessagesChange())}handleReasoningMessageContentEvent(e){let{messageId:t,state:n}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0);n.hasSeenReasoningEvents=!0;let r=e.delta||``;this.consumePendingThinkingStep(n);let i=n.currentThinkingStepId??e.messageId;n.thinkingSteps.has(i)||(n.thinkingSteps.set(i,``),n.thinkingStepOrder.push(i),n.currentThinkingStepId=i);let a=(n.thinkingSteps.get(i)??``)+r;n.thinkingSteps.set(i,a),this.messages=Ar(this.messages,t,i,a,n.thinkingStepSignatures.get(i)),this.emitMessagesChange(),this.events.onThinkingUpdate?.(t,i,a)}handleReasoningEncryptedValueEvent(e){let t=e.encryptedValue;if(typeof t!=`string`||t===``)return;if(e.subtype===`tool-call`){this.attachToolCallSignature(e.entityId,t);return}let{messageId:n,state:r}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0),i=r.currentThinkingStepId??e.entityId;r.thinkingStepSignatures.set(i,t);let a=r.thinkingSteps.get(i)??``;r.thinkingSteps.has(i)||(r.thinkingSteps.set(i,a),r.thinkingStepOrder.push(i)),this.messages=Ar(this.messages,n,i,a,t),this.emitMessagesChange()}attachToolCallSignature(e,t){this.messages=this.messages.map(n=>{let r=!1,i=n.parts.map(n=>n.type!==`tool-call`||n.id!==e?n:(r=!0,{...n,metadata:{...n.metadata!=null&&typeof n.metadata==`object`?n.metadata:{},thoughtSignature:t}}));return r?{...n,parts:i}:n});for(let n of this.messageStates.values()){let r=n.toolCalls.get(e);r&&(r.metadata={...r.metadata??{},thoughtSignature:t})}this.emitMessagesChange()}handleCustomEvent(e){let t=this.getActiveAssistantMessageId();if(e.name===`structured-output.start`&&e.value){let n=e.value,{messageId:r}=this.ensureAssistantMessage(n.messageId??t??void 0);r&&(this.structuredMessageIds.add(r),this.structuredOutputUpdateBatches.delete(r),this.events.onStructuredOutputChange?.({phase:`start`,messageId:r,status:`streaming`,raw:``}));return}if(e.name===`structured-output.complete`&&e.value){let n=e.value,{messageId:r}=this.ensureAssistantMessage(n.messageId??t??void 0);r&&(this.flushStructuredOutputUpdate(r),this.messages=Or(this.messages,r,n.object,n.raw??``,n.reasoning),this.structuredMessageIds.delete(r),this.emitStructuredOutputChange(r,`complete`),this.emitMessagesChange())}if(e.name===`tool-input-available`&&e.value){let{toolCallId:t,toolName:n,input:r}=e.value;this.events.onToolCall?.({toolCallId:t,toolName:n,input:r});return}if(e.name===`approval-requested`&&e.value){let{toolCallId:n,toolName:r,input:i,approval:a}=e.value,o=t??this.toolCallToMessage.get(n);o&&(this.messages=wr(this.messages,o,n,a.id),this.emitMessagesChange()),this.events.onApprovalRequest?.({toolCallId:n,toolName:r,input:i,approvalId:a.id});return}if(e.name===`ui-resource`&&e.value){let n=e.value,r=this.toolCallToMessage.get(n.toolCallId)??t;if(r){let e={type:`ui-resource`,resource:n.resource,toolCallId:n.toolCallId,toolName:n.toolName,...n.serverId!==void 0&&{serverId:n.serverId},...n.meta!==void 0&&{meta:n.meta}};this.messages=this.messages.map(t=>t.id===r?{...t,parts:[...t.parts,e]}:t),this.emitMessagesChange()}else console.warn(`[mcp-apps] dropped ui-resource: no target message for toolCallId "${n.toolCallId}" (toolName "${n.toolName}")`);return}if(this.events.onCustomEvent){let t=e.value&&typeof e.value==`object`?e.value.toolCallId:void 0;this.events.onCustomEvent(e.name,e.value,{toolCallId:t})}}isNewTextSegment(e,t){return!0}completeAllToolCalls(){for(let e of this.activeMessageIds)this.completeAllToolCallsForMessage(e)}completeAllToolCallsForMessage(e){let t=this.getMessageState(e);t&&t.toolCalls.forEach((n,r)=>{if(n.state!==`input-complete`){let i=t.toolCallOrder.indexOf(r);this.completeToolCall(e,i,n)}})}completeToolCall(e,t,n){n.state=`input-complete`;let r=!1;try{n.parsedArguments=JSON.parse(n.arguments),r=!0}catch{n.parsedArguments=void 0}this.isToolCallPartErrored(n.id)||this.isToolCallPartAwaitingUserAction(n.id)||(this.messages=Sr(this.messages,e,{id:n.id,name:n.name,arguments:n.arguments,state:`input-complete`,...r&&{input:n.parsedArguments},...n.metadata!==void 0&&{metadata:n.metadata}}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(e,n.id,`input-complete`,n.arguments))}isToolCallPartAwaitingUserAction(e){return this.messages.some(t=>t.parts?.some(t=>t.type===`tool-call`&&t.id===e&&(t.state===`approval-requested`||t.state===`approval-responded`)))}isToolCallPartErrored(e){return this.messages.some(t=>t.parts?.some(t=>t.type===`tool-call`&&t.id===e&&t.state===`error`))}emitTextUpdateForMessage(e){let t=this.getMessageState(e);t&&(t.lastEmittedText=t.currentSegmentText,this.messages=xr(this.messages,e,t.currentSegmentText),this.emitMessagesChange(),this.events.onTextUpdate?.(e,t.currentSegmentText))}queueStructuredOutputUpdate(e,t){let n=this.structuredOutputUpdateBatches.get(e),r={delta:`${n?.delta??``}${t}`,chunkCount:(n?.chunkCount??0)+1};this.structuredOutputUpdateBatches.set(e,r),r.chunkCount>=jr&&this.flushStructuredOutputUpdate(e)}flushStructuredOutputUpdate(e){let t=this.structuredOutputUpdateBatches.get(e);!t||t.chunkCount===0||(this.structuredOutputUpdateBatches.delete(e),this.emitStructuredOutputChange(e,`update`,t.delta))}emitStructuredOutputChange(e,t,n){let r=this.messages.find(t=>t.id===e)?.parts.find(e=>e.type===`structured-output`);r&&this.events.onStructuredOutputChange?.({phase:t,messageId:e,status:r.status,raw:r.raw,...r.partial===void 0?{}:{partial:r.partial},...r.data===void 0?{}:{data:r.data},...r.reasoning===void 0?{}:{reasoning:r.reasoning},...r.errorMessage===void 0?{}:{errorMessage:r.errorMessage},...n===void 0?{}:{delta:n}})}emitMessagesChange(){this.events.onMessagesChange?.([...this.messages])}finalizeStream(){let e;for(let t of this.activeMessageIds){let n=this.getMessageState(t);if(!n)continue;this.completeAllToolCallsForMessage(t),n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(t),n.isComplete=!0;let r=this.messages.find(e=>e.id===t);r&&r.role===`assistant`&&(e=r)}for(let e of this.structuredMessageIds)this.flushStructuredOutputUpdate(e),this.messages=kr(this.messages,e,`Stream ended without structured-output.complete`),this.emitStructuredOutputChange(e,`error`);if(this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.activeMessageIds.clear(),e&&!this.hasError&&this.isWhitespaceOnlyMessage(e)){this.messages=this.messages.filter(t=>t.id!==e.id),this.emitMessagesChange();return}e&&this.events.onStreamEnd?.(e)}getCompletedToolCalls(){let e=[];for(let t of this.messageStates.values())for(let n of t.toolCalls.values())n.state===`input-complete`&&e.push({id:n.id,type:`function`,function:{name:n.name,arguments:n.arguments},...n.metadata!==void 0&&{metadata:n.metadata}});return e}getResult(){let e=this.getCompletedToolCalls(),t=``,n=``;for(let e of this.messageStates.values()){t+=e.totalTextContent;for(let t of e.thinkingStepOrder)n+=e.thinkingSteps.get(t)??``}return{content:t,thinking:n||void 0,toolCalls:e.length>0?e:void 0,finishReason:this.finishReason}}getState(){let e=``,t=``,n=new Map,r=[];for(let i of this.messageStates.values()){e+=i.totalTextContent;for(let e of i.thinkingStepOrder)t+=i.thinkingSteps.get(e)??``;for(let[e,t]of i.toolCalls)n.set(e,t);r.push(...i.toolCallOrder)}return{content:e,thinking:t,toolCalls:n,toolCallOrder:r,finishReason:this.finishReason,done:this.isDone}}startRecording(){this.recordingEnabled=!0,this.recordingStartTime=Date.now(),this.recording={version:`1.0`,timestamp:this.recordingStartTime,chunks:[]}}getRecording(){return this.recording}resetStreamState(){this.messageStates.clear(),this.activeMessageIds.clear(),this.activeRuns.clear(),this.toolCallToMessage.clear(),this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.pendingManualMessageId=null,this.pendingThinkingStepId=null,this.finishReason=null,this.hasError=!1,this.isDone=!1,this.chunkStrategy.reset?.()}reset(){this.resetStreamState(),this.messages=[]}isWhitespaceOnlyMessage(e){return e.parts.length!==0&&e.parts.every(e=>e.type===`text`&&e.content.trim()===``)}static async replay(t,n){return new e(n).process(Pr(t))}};function Pr(e){return{async*[Symbol.asyncIterator](){for(let{chunk:t}of e.chunks)yield t}}}var Fr=function(e){return e.TEXT_MESSAGE_START=`TEXT_MESSAGE_START`,e.TEXT_MESSAGE_CONTENT=`TEXT_MESSAGE_CONTENT`,e.TEXT_MESSAGE_END=`TEXT_MESSAGE_END`,e.TEXT_MESSAGE_CHUNK=`TEXT_MESSAGE_CHUNK`,e.TOOL_CALL_START=`TOOL_CALL_START`,e.TOOL_CALL_ARGS=`TOOL_CALL_ARGS`,e.TOOL_CALL_END=`TOOL_CALL_END`,e.TOOL_CALL_CHUNK=`TOOL_CALL_CHUNK`,e.TOOL_CALL_RESULT=`TOOL_CALL_RESULT`,e.THINKING_START=`THINKING_START`,e.THINKING_END=`THINKING_END`,e.THINKING_TEXT_MESSAGE_START=`THINKING_TEXT_MESSAGE_START`,e.THINKING_TEXT_MESSAGE_CONTENT=`THINKING_TEXT_MESSAGE_CONTENT`,e.THINKING_TEXT_MESSAGE_END=`THINKING_TEXT_MESSAGE_END`,e.STATE_SNAPSHOT=`STATE_SNAPSHOT`,e.STATE_DELTA=`STATE_DELTA`,e.MESSAGES_SNAPSHOT=`MESSAGES_SNAPSHOT`,e.ACTIVITY_SNAPSHOT=`ACTIVITY_SNAPSHOT`,e.ACTIVITY_DELTA=`ACTIVITY_DELTA`,e.RAW=`RAW`,e.CUSTOM=`CUSTOM`,e.RUN_STARTED=`RUN_STARTED`,e.RUN_FINISHED=`RUN_FINISHED`,e.RUN_ERROR=`RUN_ERROR`,e.STEP_STARTED=`STEP_STARTED`,e.STEP_FINISHED=`STEP_FINISHED`,e.REASONING_START=`REASONING_START`,e.REASONING_MESSAGE_START=`REASONING_MESSAGE_START`,e.REASONING_MESSAGE_CONTENT=`REASONING_MESSAGE_CONTENT`,e.REASONING_MESSAGE_END=`REASONING_MESSAGE_END`,e.REASONING_MESSAGE_CHUNK=`REASONING_MESSAGE_CHUNK`,e.REASONING_END=`REASONING_END`,e.REASONING_ENCRYPTED_VALUE=`REASONING_ENCRYPTED_VALUE`,e}({}),Ir=/^[a-z][a-z0-9-]{0,63}$/;function Lr(e){return typeof e==`string`&&Ir.test(e)}function Rr(e){if(typeof e!=`object`||!e||!(`error`in e))return!1;let t=e.error;return!(typeof t!=`object`||!t||!(`type`in t)||t.type!==`byok_missing`||!(`provider`in t)||typeof t.provider!=`string`||!Lr(t.provider)||!(`message`in t)||typeof t.message!=`string`)}var zr=class extends Error{provider;constructor(e){super(`Missing ${e} API key`),this.name=`ByokMissingError`,this.provider=e}},Br=class extends Error{provider;reason;constructor(e,t){super(t===`locked`?`${e} key is locked`:`Missing ${e} API key`),this.name=`ByokBlockedError`,this.provider=e,this.reason=t}},Vr=class extends Error{constructor(){super(`BYOK is enabled but no provider slug was resolved. Pass byokProvider or forwardedProps.provider.`),this.name=`ByokUnresolvedProviderError`}},Hr=new WeakMap;function G(e){return Hr.get(e)??mr(e)}var Ur=class extends Error{constructor(){super(`Stream ended with unterminated trailing data — connection was likely cut short.`),this.name=`StreamTruncatedError`}},Wr=class extends Error{constructor(e){super(`Stream response body read failed`,{cause:e}),this.name=`StreamReadError`}},Gr=class extends Error{constructor(){super(`Durable run ended without a terminal event and could not resume — the run did not complete.`),this.name=`DurableStreamIncompleteError`}},Kr=class extends Error{constructor(e){super(`Durable run exceeded its reconnect ceiling of ${e} attempts — giving up.`),this.name=`StreamReconnectLimitError`}};function qr(e){let t=e?.maxAttempts??5,n=e?.delayMs??250;if(!Number.isInteger(t)||t<0)throw Error(`Invalid reconnect.maxAttempts: ${t}. Must be a non-negative integer.`);if(!Number.isFinite(n)||n<0)throw Error(`Invalid reconnect.delayMs: ${n}. Must be a non-negative finite number.`);return{maxAttempts:t,delayMs:n}}function Jr(e){let t=qr(e),n=new Set,r,i=0;return{get lastEventId(){return r},note(e){return e===void 0?`new`:e===``?(r=void 0,n.clear(),`reset`):n.has(e)?`duplicate`:(n.add(e),r=e,`new`)},async waitBeforeReconnect(e,n){if(e)i=0;else if(i+=1,i>t.maxAttempts)throw new Kr(t.maxAttempts);await Yr(t.delayMs,n)}}}function Yr(e,t){return e<=0||t?.aborted?Promise.resolve():new Promise(n=>{let r=()=>{clearTimeout(i),n()},i=setTimeout(()=>{t?.removeEventListener(`abort`,r),n()},e);t?.addEventListener(`abort`,r,{once:!0})})}function Xr(e){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function Zr(e,t){if(!e)throw Error(`Cannot synthesize terminal event: ${t} not supplied via runContext and not observed in the upstream stream.`);return e}function K(e){if(!e)return{};if(e instanceof Headers){let t={};return e.forEach((e,n)=>{t[n]=e}),t}return e}var Qr=`X-Run-Id`;function $r(e){return e===void 0?{}:{[Qr]:e}}function ei(e,t){let n=e.indexOf(`#`),r=n===-1?``:e.slice(n),i=n===-1?e:e.slice(0,n),a=i.indexOf(`?`),o=a===-1?i:i.slice(0,a),s=new URLSearchParams(a===-1?``:i.slice(a+1));for(let[e,n]of Object.entries(t))s.set(e,n);let c=s.toString();return`${o}${c.length===0?``:`?${c}`}${r}`}async function*ti(e,t){try{let n=Rt(),r=``;for(;!t?.aborted;){let i;try{i=await e.read()}catch(e){if(t?.aborted)return;throw new Wr(e)}let{done:a,value:o}=i;if(a)break;r+=n.decode(o,{stream:!0});let s=r.split(`
25
+ `);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 Ur}finally{e.releaseLock()}}function ni(e){return Wn(e)}function ri(e){let t=P(e)?.model;if(typeof t==`string`)return t;let n=`usage`in e?e.usage:void 0;if(Array.isArray(n)){let e=n[0]?.model;if(typeof e==`string`)return e}}async function*ii(e,t){let n,r,i,a;for await(let o of e){if(o===`id`||o.startsWith(`id:`)){let e=o===`id`?``:o.slice(3);a=e.startsWith(` `)?e.slice(1):e;continue}if(o.startsWith(`:`)||o.startsWith(`event:`)||o.startsWith(`retry:`))continue;let e=zt(o);if(e===`[DONE]`){yield{chunk:Kt({type:Fr.RUN_FINISHED,threadId:n??t?.threadId??``,runId:r??t?.runId??``,timestamp:Date.now()},{finishReason:`stop`,...i===void 0?{}:{model:i}})};return}let s=ni(JSON.parse(e));`threadId`in s&&typeof s.threadId==`string`&&(n=s.threadId),`runId`in s&&typeof s.runId==`string`&&(r=s.runId);let c=ri(s);c!==void 0&&(i=c);let l=a;a=void 0,yield{chunk:s,...l===void 0?{}:{id:l}}}}async function ai(e){if(!e.ok){if(e.status===401){let t=await e.clone().json().catch(()=>null);if(Rr(t))throw new zr(t.error.provider)}throw Error(`HTTP error! status: ${e.status} ${e.statusText}`)}}async function oi(e,t,n,r,i){let a=await e(ei(t,{threadId:i}),{method:`GET`,headers:{Accept:`application/json`,...n},credentials:r});await ai(a);let o=await a.json(),s=o.activeRun&&typeof o.activeRun.runId==`string`?{runId:o.activeRun.runId}:null,c=o.interrupts&&typeof o.interrupts.runId==`string`&&Array.isArray(o.interrupts.pending)&&o.interrupts.pending.length>0?{runId:o.interrupts.runId,pending:o.interrupts.pending}:null;return{messages:Array.isArray(o.messages)?o.messages:[],activeRun:s,interrupts:c}}async function si(e,t,n,r,i){let a=await e(ei(t,{threadId:i}),{method:`GET`,headers:{Accept:`application/json`,...n},credentials:r});await ai(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*ci(e,t,n){await ai(e),yield*ii(ti(Lt(e),t),n)}async function*li(e,t){for await(let{chunk:n}of ci(e,t))yield n}function ui(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 Wr(e)}yield*r(o,a)}}async function*di(e,t,n){let r=Jr(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 Ur||e instanceof Wr)&&r.lastEventId!==void 0){await r.waitBeforeReconnect(a,t);continue}throw e}if(t?.aborted||i)return;if(r.lastEventId!==void 0){if(a){await r.waitBeforeReconnect(!0,t);continue}throw new Gr}return}}function fi(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=[];function o(e,t){t&&Hr.set(e,t);let n=a.shift();n?n(e):i.push(e)}return{subscribe(e){let t=i.splice(0),n=[];return i=t,a=n,(async function*(){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)}})()},async send(t,n,r,i){let a=!1,s,c;try{let l=e.connect(t,n,r,i);for await(let e of l)`threadId`in e&&typeof e.threadId==`string`&&(s=e.threadId),`runId`in e&&typeof e.runId==`string`&&(c=e.runId),(e.type===`RUN_FINISHED`||e.type===`RUN_ERROR`)&&(a=!0),o(e,i?.runId);!r?.aborted&&!a&&o(Kt({type:Fr.RUN_FINISHED,threadId:Zr(s??i?.threadId,`threadId`),runId:Zr(c??i?.runId,`runId`),timestamp:Date.now()},{finishReason:`stop`,model:`connect-wrapper`}),i?.runId)}catch(e){if(!r?.aborted&&!a)try{let t=e instanceof Error?e.message:`Unknown error in connect()`;o({type:Fr.RUN_ERROR,threadId:Zr(s??i?.threadId,`threadId`),runId:Zr(c??i?.runId,`runId`),timestamp:Date.now(),message:t},i?.runId)}catch{}throw e}},...typeof e.joinRun==`function`?{joinRun:(t,n)=>e.joinRun(t,n)}:{},...(()=>{let t=e.hydrate;return typeof t==`function`?{hydrate:e=>t(e)}:{}})()}}function pi(e,t,n,r){let i=jn(e),a={...r.body,...n?.forwardedProps??{},...t};return{threadId:n?.threadId??Xr(`thread`),runId:n?.runId??Xr(`run`),...n?.parentRunId!==void 0&&{parentRunId:n.parentRunId},...n?.resume!==void 0&&{resume:n.resume},state:{},messages:i,tools:n?.clientTools??[],context:[],forwardedProps:a,data:{...a}}}function mi(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`,...K(s.headers),...K(a?.headers),...$r(a?.runId)},l=pi(n,r,a,s),u=s.fetchClient??fetch,d=i||s.signal;yield*di(ui(u,o,{method:`POST`,headers:c,body:JSON.stringify(l),credentials:s.credentials||`same-origin`},(e,t)=>ci(e,t,{...a?.threadId===void 0?{}:{threadId:a.threadId},...a?.runId===void 0?{}:{runId:a.runId}})),d,s.reconnect)},async*joinRun(n,r){let i=typeof e==`function`?e():e,a=typeof t==`function`?await t():t,o=ei(i,{offset:`-1`,runId:n}),s={...K(a.headers)},c=a.fetchClient??fetch,l=r||a.signal;yield*di(ui(c,o,{method:`GET`,headers:s,credentials:a.credentials||`same-origin`},(e,t)=>ci(e,t,{runId:n})),l,a.reconnect)},async hydrate(n){let r=typeof e==`function`?e():e,i=typeof t==`function`?await t():t;return oi(i.fetchClient??fetch,r,K(i.headers),i.credentials||`same-origin`,n)},async hydrateGeneration(n){let r=typeof e==`function`?e():e,i=typeof t==`function`?await t():t;return si(i.fetchClient??fetch,r,K(i.headers),i.credentials||`same-origin`,n)}}}function hi(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*li(a,r):yield*gi(a,r)}}}async function*gi(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 q(e){return e.resumable}function _i(e,t){let n=An(e.descriptor);return n?{...t,metadata:kn(n)}:t}function vi(e){return`cancel`in e&&`clearResolution`in e}var yi=new Set([`invalid-payload`,`invalid-edited-args`,`invalid-tool-output`,`invalid-response-schema`,`unknown-interrupt`,`expired`,`stale`,`conflict`,`legacy-unsupported`]),bi=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`,`legacy-submit-failed`]);function J(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function xi(e){return J(e)&&e.kind===`approval`&&typeof e.toolName==`string`&&`input`in e}function Si(e){return J(e)&&e.kind===`client_tool`&&typeof e.toolName==`string`&&`input`in e}function Ci(e){return xi(e.metadata)||Si(e.metadata)}function wi(e){return Cn(e)}function Ti(e){if(!J(e.metadata))return!1;let t=e.metadata[vn];return!J(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 Ei(e){if(!J(e.metadata))return!1;let t=e.metadata[vn];return!J(t)||t.kind!==`generic`?!1:`definitionId`in t||`key`in t||`batchIndex`in t||`payloadSchemaHash`in t}function Di(e){return e.metadata?.[`tanstack:interruptPayload`]}function Oi(e){return e===`tanstack:client_tool_execution`||e===`client_tool_input`}function Y(e){if(e.responseSchema!==void 0)try{return L(I(e.responseSchema))}catch{return}}function ki(e){if(e!==void 0)try{return En(e)}catch{return}}function X(e){return e!==null&&(typeof e==`object`||typeof e==`function`)&&`then`in e&&typeof e.then==`function`}function Ai(e,t,n){if(e===void 0)return{valid:!0,payload:t};if(B(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 X(r)?Promise.resolve(r).then(i):i(r)}return{valid:!0,payload:t}}function ji(e){for(let t of yi)if(t===e)return!0;return!1}function Mi(e){for(let t of bi)if(t===e)return!0;return!1}function Ni(e){if(!J(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`?t===`item`?ji(n)&&typeof e.interruptId==`string`&&(e.source===`client`||e.source===`server`):t===`batch`&&Mi(n)&&Array.isArray(e.interruptIds)&&e.interruptIds.every(e=>typeof e==`string`)&&(e.source===`client`||e.source===`server`||e.source===`transport`):!1}function Pi(e){return Ni(e)?[e]:!J(e)||!Array.isArray(e.errors)?[]:e.errors.every(Ni)?e.errors:[]}function Fi(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 Ii(e,t){return e.threadId===t.threadId&&e.interruptedRunId===t.interruptedRunId&&e.generation===t.generation&&Fi(e.interruptIds,t.interruptIds)}function Li(e,t,n){let r=n.filter(e=>e.source!==`transport`),i=e=>t.includes(e)&&r.some(t=>Ii(e,t)),a=e.filter(e=>!i(e)),o=t.filter(e=>!r.some(t=>Ii(e,t)));return Object.freeze({rootErrors:Object.freeze([...a,...n]),submissionRootErrors:Object.freeze([...o,...r])})}function Ri(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):Fi(e.interruptIds,n)}function zi(e,t,n){let r=Y(e)??n?.responseSchemaHash;return R({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 Bi(e,t){let n=R(e.descriptor),r=e.error===void 0?Object.freeze([]):Object.freeze([R(e.error)]),i=r[0];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,...i===void 0?{}:{error:i},canResolve:e.canResolve}}var Vi=class{options;hydration;items=[];snapshot=Object.freeze([]);rootErrors=Object.freeze([]);submissionRootErrors=Object.freeze([]);state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:!1});activeTransaction;activeSubmissionOperation;retrySubmission;resuming=!1;tools;interruptDefinitions;constructor(e){this.options=e,this.tools=e.tools;let t=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:R(e.interrupts)};let n=new Map;for(let t of e.interrupts){let e=wi(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,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:!1}),this.options.onChange?.(e?.source??`live`)}getInterruptErrors(){return this.rootErrors}getResuming(){return this.resuming}resolve(e){if(this.assertRootMutable(),typeof e==`boolean`){this.resolveBooleanBulk(e);return}this.resolveTransaction(e)}cancel(){this.assertRootMutable(),this.invalidateRetry();for(let e of this.items)q(e)&&(e.validationGeneration++,e.resolution=Object.freeze(_i(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;if(!e){this.addRootError(`transport`,`There is no retryable interrupt submission.`,!1);return}this.submitBatch(e)}resolveClientToolOutput(e,t){let n=this.items.find(t=>t.kind===`client-tool-execution`&&t.binding?.kind===`client-tool-execution`&&t.binding.toolCallId===e||t.kind===`generic`&&Oi(t.descriptor.reason)&&t.descriptor.toolCallId===e&&Si(t.descriptor.metadata));return n?(this.resolveItem(n.descriptor.id,t),!0):!1}resolveToolApprovalDecision(e,t){let n=this.items.find(t=>t.descriptor.id===e&&(t.kind===`tool-approval`||t.kind===`generic`&&t.descriptor.reason===`approval_required`&&xi(t.descriptor.metadata)));return n?(this.resolveItem(n.descriptor.id,{approved:t}),!0):!1}hydrateInterrupt(e,t,n){let r=R(e),i=wi(r),a=i===void 0&&Ci(r);if(i===void 0&&!a)return Ti(r)?{descriptor:r,binding:zi(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 o=i!==void 0&&i.interruptId===r.id&&i.interruptedRunId===t.interruptedRunId&&i.generation===t.generation&&Y(r)===i.responseSchemaHash,s=i!==void 0&&i.interruptId===r.id&&i.interruptedRunId===t.interruptedRunId&&i.generation===t.generation&&i.responseSchemaHash===(Y(r)??i.responseSchemaHash);if(i!==void 0&&Ei(r)&&(!s||i.kind!==`generic`||i.definitionId===void 0||i.key===void 0||i.batchIndex===void 0))return{descriptor:r,binding:zi(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(s&&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=gn(e.approvalSchema,e.inputSchema);if(_n(e.inputSchema)===i.inputSchemaHash&&t.approvalSchemaHash===i.approvalSchemaHash&&t.responseSchemaHash===i.responseSchemaHash)return{descriptor:r,binding:R(i),kind:`tool-approval`,status:`pending`,canResolve:!0,resumable:!0,tool:e,validationGeneration:0}}catch{}}if(s&&i.kind===`client-tool-execution`){let e=this.tools?.find(e=>e.name===i.toolName);if(e!==void 0&&r.toolCallId===i.toolCallId&&_n(e.outputSchema)===i.outputSchemaHash)return{descriptor:r,binding:R(i),kind:`client-tool-execution`,status:`pending`,canResolve:!0,resumable:!0,tool:e,validationGeneration:0}}if(i!==void 0&&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:R(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(o&&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&&ki(e.responseSchema)===i.responseSchemaHash&&(e.payloadSchema===void 0?i.payloadSchemaHash===void 0:i.payloadSchemaHash===ki(e.payloadSchema))){let t=Di(r);return{descriptor:r,binding:R(i),definition:e,kind:`generic`,status:`pending`,canResolve:!0,resumable:!0,...t===void 0?{}:{payload:R(t)},validationGeneration:0}}}let c=a||i!==void 0&&i.interruptId===r.id&&i.interruptedRunId===t.interruptedRunId&&i.generation===t.generation&&(i.kind!==`generic`||Y(r)===void 0||i.responseSchemaHash===Y(r));return{descriptor:r,binding:zi(r,t,i),kind:`generic`,status:`pending`,canResolve:c,resumable:c,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=Bi(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=R(n.binding),i={...r,kind:`tool-approval`,binding:t,toolName:n.binding.toolName,toolCallId:n.binding.toolCallId,originalArgs:R(n.binding.originalArgs),cancel:()=>this.cancelItem(n.descriptor.id,e),clearResolution:()=>this.clearItem(n.descriptor.id,e),resolveInterrupt:(t,r)=>{let i=J(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`?R(n.binding):R({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`){if(!this.hydration){this.snapshot=Object.freeze([]),this.state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:this.resuming}),this.options.onChange?.(e);return}this.snapshot=this.buildSnapshot(),this.state=Object.freeze({interrupts:this.snapshot,pendingInterrupts: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);if(X(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)});return}this.applyValidation(r,a,n)}cancelItem(e,t){this.assertItemMutable(t);let n=this.findItem(e);this.invalidateRetry(),n.validationGeneration++,n.resolution=Object.freeze(_i(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=>q(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=$t(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.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();return}e.resolution=R(_i(e,{interruptId:e.descriptor.id,status:`resolved`,payload:t.payload})),e.status=`staged`,e.error=void 0,n||(this.publish(),this.maybeSubmit())}validateCandidate(e,t){if(e.kind===`generic`){let n=Ai(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 X(n)?Promise.resolve(n).then(r):r(n)}return e.kind===`client-tool-execution`?Ai(e.tool?.outputSchema,t,`invalid-tool-output`):this.validateApprovalCandidate(e,t)}validateApprovalCandidate(e,t){if(!J(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=Ai(e.tool?.inputSchema,r,`invalid-edited-args`);return X(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=Ai(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 X(o)?Promise.resolve(o).then(s):s(o)}approvalBranchSchema(e,t){let n=e?.approvalSchema;return!J(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=>q(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);return}this.invalidateRetry();for(let n of t)n.validationGeneration++,n.resolution=R({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(vi),i;try{for(let t of r){let n=e(t);if(n!==void 0){i={code:X(n)?`async-resolver`:`inactive-transaction`,message:X(n)?`Interrupt transaction resolvers must be synchronous.`:`Interrupt transaction resolvers must return literal undefined.`};break}}i===void 0&&this.items.some(e=>q(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}if(i){this.restoreCheckpoints(t),this.addRootError(i.code,i.message,!1);return}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)q(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=Pi(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)q(e)&&(e.status=`error`);return}let r=n.filter(e=>Ri(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=>q(t)&&t.descriptor.id===e.interruptId);t&&(t.status=`error`,t.error=R(e))}else o.push(R(e));let s=Li(this.rootErrors,this.submissionRootErrors,o);this.rootErrors=s.rootErrors,this.submissionRootErrors=s.submissionRootErrors;for(let e of this.items)q(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(q).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})}};function Hi(e,...t){let n=e?.();if(Lr(n))return n;for(let e of t)if(Lr(e))return e}async function Ui(e,t){if(!t)throw new Vr;return await e.prepare(t),e.headers(t)}var Wi=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})}toolApprovalResponded(e,t,n,r){this.emitEvent(`tools:approval:responded`,{approvalId:e,toolCallId:t,approved:n,...r})}toolFixtureApplied(e){this.emitEvent(`devtools:tool-fixture:applied`,{...e})}},Gi=class extends Wi{emitEvent(){}},Ki=class{events;constructor(e){this.events=new Gi(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){}beginRun(e,t){}getCurrentRunEventContext(){}getCurrentOrLastRunEventContext(){}findToolCallContext(e){return{toolCallId:e}}async applyFixture(e){}},qi=e=>new Ki(e);function Ji(e){if(Array.isArray(e))return{messages:e};if(e&&Array.isArray(e.messages))return e}function Yi(e){return`toolCallId`in e&&typeof e.toolCallId==`string`?e.toolCallId:void 0}function Xi(e){return`messageId`in e&&typeof e.messageId==`string`?e.messageId:void 0}function Zi(e){return`parentMessageId`in e&&typeof e.parentMessageId==`string`?e.parentMessageId:void 0}var Qi=class{adapter;id;applyMessages;applyResume;skipNextPersist=!1;generation=0;queue=Promise.resolve();queuePending=!1;messagesGeneration=0;lastMessages=[];lastResume=null;clearedMessageIds=new Set;clearedRunIds=new Set;ignoredActiveRunIds=new Set;clearedToolCallIds=new Set;currentRunlessRunId=null;constructor(e,t,n,r){this.adapter=e,this.id=t,this.applyMessages=n,this.applyResume=r}writeState(){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)})}readInitial(){try{let e=this.adapter.getItem(this.id);if(e instanceof Promise)return e.then(Ji).catch(()=>void 0);let t=Ji(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;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){if(this.messagesGeneration++,this.lastMessages=[...e],this.skipNextPersist){this.skipNextPersist=!1;return}this.writeState()}persistResumeSnapshot(e){this.lastResume=e,!this.skipNextPersist&&this.writeState()}remove(){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)});return}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=G(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=Yi(e);if(n&&this.clearedToolCallIds.has(n))return!0;let r=Zi(e);if(r&&this.clearedMessageIds.has(r))return n&&this.clearedToolCallIds.add(n),!0;let i=Xi(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=Xi(e);t&&this.clearedMessageIds.add(t);let n=Yi(e);n&&this.clearedToolCallIds.add(n)}isRunlessChunkFromIgnoredRun(e){return G(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===`TOOL_CALL_START`||e.type===`TOOL_CALL_ARGS`||e.type===`TOOL_CALL_END`||e.type===`TOOL_CALL_RESULT`||e.type===`MESSAGES_SNAPSHOT`||e.type===`RUN_ERROR`}};function $i(e){return`toolCallId`in e&&typeof e.toolCallId==`string`?e.toolCallId:void 0}function ea(e){return`messageId`in e&&typeof e.messageId==`string`?e.messageId:void 0}function ta(e){return`parentMessageId`in e&&typeof e.parentMessageId==`string`?e.parentMessageId:void 0}var na=class{clearedMessageIds=new Set;clearedRunIds=new Set;ignoredActiveRunIds=new Set;clearedToolCallIds=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=G(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=$i(e);if(n&&this.clearedToolCallIds.has(n))return!0;let r=ta(e);if(r&&this.clearedMessageIds.has(r))return n&&this.clearedToolCallIds.add(n),!0;let i=ea(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=ea(e);t&&this.clearedMessageIds.add(t);let n=$i(e);n&&this.clearedToolCallIds.add(n)}isRunlessChunkFromIgnoredRun(e){return G(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===`TOOL_CALL_START`||e.type===`TOOL_CALL_ARGS`||e.type===`TOOL_CALL_END`||e.type===`TOOL_CALL_RESULT`||e.type===`MESSAGES_SNAPSHOT`||e.type===`RUN_ERROR`}};function ra(e){let t=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 ia(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 hi(n);throw Error("ChatClient: either `connection` or `fetcher` is required.")}function aa(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 oa(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(`
26
+ `),...t===void 0?{}:{body:t}};let r=[],i;for(let t of e){if(typeof t.content==`string`){r.push({type:`text`,content:t.content});continue}typeof t.content.content==`string`?r.push({type:`text`,content:t.content.content}):r.push(...t.content.content),i=Gt(i,t.content.metadata)}return{content:{content:r,...i===void 0?{}:{metadata:i}},...t===void 0?{}:{body:t}}}function sa(e){if(!(typeof e!=`object`||!e||Array.isArray(e))&&!(!(`approved`in e)||typeof e.approved!=`boolean`))return e.approved}function ca(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 la=2e3,ua=new Set([`TEXT_MESSAGE_START`,`TEXT_MESSAGE_CONTENT`,`TOOL_CALL_START`,`MESSAGES_SNAPSHOT`]),da=class{processor;connection;uniqueId;threadId;persistor;clearedStreamTracker=new na;currentRunId=null;lastResume=null;rejoinedRunId=null;interruptManager;activeInterruptSubmission;interruptSubmissionFailure;joinedRunWaiters=new Map;pendingResumeParentRunId=null;pendingResumeThreadId=null;pendingResumeItems=null;activeResumeThreadId=null;activeResumeRunId=null;bodyOption={};forwardedPropsOption={};byok;byokProvider;context=void 0;pendingMessageBody=void 0;queueConfig;messageQueue=[];sendInFlight=!1;messageQueueDraining=!1;stopMessageQueueDrain=!1;deliverClaim=!1;isLoading=!1;isSubscribed=!1;error=void 0;status=`ready`;connectionStatus=`disconnected`;abortController=null;clientToolsRef;devtoolsBridge;events;currentStreamId=null;currentMessageId=null;postStreamActions=[];pendingToolExecutions=new Map;activeClientTools=null;activeContext=void 0;continuationPending=!1;subscriptionAbortController=null;processingResolve=null;errorReportedGeneration=null;streamGeneration=0;continuationSkipped=!1;draining=!1;sessionGenerating=!1;activeRunIds=new Set;disposed=!1;tailing=!1;rejoinRunId;cachesMessages;devtoolsMounted=!1;callbacksRef;constructor(e){ra(e.interrupts),this.threadId=e.threadId||``,this.uniqueId=this.threadId;let t=!0;if(e.persistence===!0){if(!e.threadId)throw Error("[TanStack AI] persistence needs a stable `threadId` to key on. Pass a threadId from your app (for example support-42).");t=!1}else if(e.persistence){if(!e.threadId)throw Error("[TanStack AI] persistence needs a stable `threadId` to key on. Pass a threadId from your app (for example support-42).");this.persistor=new Qi(e.persistence,e.threadId,e=>this.processor.setMessages(e),e=>this.applyPersistedResume(e))}if(this.bodyOption=e.body||{},this.forwardedPropsOption=e.forwardedProps||{},this.byok=e.byok,this.byokProvider=e.byokProvider,this.context=e.context,this.queueConfig=aa(e.queue),this.connection=fi(ia(e)),this.clientToolsRef={current:new Map},e.tools)for(let t of e.tools)this.clientToolsRef.current.set(t.name,t);this.devtoolsBridge=(e.devtoolsBridgeFactory??qi)(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||(()=>{}),onQueueChange:e.onQueueChange||(()=>{}),onResumeStateChange:e.onResumeStateChange||(()=>{}),onRunIdChange:e.onRunIdChange||(()=>{}),onInterruptStateChange:e.onInterruptStateChange||(()=>{}),onCustomEvent:e.onCustomEvent||(()=>{})}},this.interruptManager=new Vi({...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 n=this.persistor?.readInitial(),r=n instanceof Promise?void 0:n,i=r?r.messages:e.initialMessages,a=null;if(r?.resume){let e=r.resume;Array.isArray(e.pendingInterrupts)&&e.pendingInterrupts.length>0?this.applyResumeSnapshot(e):e.resumeState.runId&&(a=e.resumeState.runId)}if(!a&&e.initialResumeSnapshot){let t=e.initialResumeSnapshot;!(Array.isArray(t.pendingInterrupts)&&t.pendingInterrupts.length>0)&&t.resumeState.runId&&(a=t.resumeState.runId)}this.processor=new Nr({...e.streamProcessor?.chunkStrategy?{chunkStrategy:e.streamProcessor.chunkStrategy}:{},...i?{initialMessages:i}:{},events:{onMessagesChange:e=>{this.persistor?.notifyMessagesChanged(e),this.callbacksRef.current.onMessagesChange(e)},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(n){let r=this.devtoolsBridge.getCurrentRunEventContext(),i=(async()=>{try{let i=this.activeClientTools===null?this.context:this.activeContext,a=await n(e.input,{toolCallId:e.toolCallId,context:i,emitCustomEvent:()=>{}});await this.addToolResultForClientTool({toolCallId:e.toolCallId,tool:e.toolName,output:a,state:`output-available`},t,r)}catch(n){await this.addToolResultForClientTool({toolCallId:e.toolCallId,tool:e.toolName,output:null,state:`output-error`,errorText:n.message},t,r)}finally{this.pendingToolExecutions.delete(e.toolCallId)}})();this.pendingToolExecutions.set(e.toolCallId,i)}},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),this.callbacksRef.current.onCustomEvent(e,t,n)}}}),this.persistor?.hydrateAsync(n),this.rejoinRunId=a,this.cachesMessages=t}attach(){this.disposed||this.tailing||(this.ensureThreadId(),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=ca(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;e&&(this.isLoading||this.abortController||this.disposed||(async()=>{let t;try{t=await e(this.threadId)}catch{return}this.disposed||!this.tailing||this.isLoading||this.abortController||(t.messages.length>0&&this.processor.setMessages(t.messages),t.interrupts&&t.interrupts.pending.length>0?this.applyResumeSnapshot({resumeState:{threadId:this.threadId,runId:t.interrupts.runId},pendingInterrupts:t.interrupts.pending}):t.activeRun?.runId&&this.maybeRejoinInFlight(t.activeRun.runId))})())}mountDevtools(){this.ensureThreadId(),!this.devtoolsMounted&&(this.devtoolsMounted=!0,this.devtoolsBridge.mountWithTools(this.processor.getMessages().length))}ensureThreadId(){return this.threadId||=this.generateUniqueId(`thread`),this.uniqueId=this.threadId,this.threadId}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=G(e)??this.clearedStreamTracker.takeRunlessRunId();t&&(this.activeRunIds.delete(t),this.setSessionGenerating(this.activeRunIds.size>0),G(e)||this.resolveProcessing())}updateRunLifecycle(e,t){if(e.type===`RUN_STARTED`){let t=G(e)??e.runId;this.activeResumeThreadId=`threadId`in e&&typeof e.threadId==`string`?e.threadId:this.activeResumeThreadId,this.activeResumeRunId=t,this.activeRunIds.add(t),this.clearedStreamTracker.onRunStarted(t),this.setSessionGenerating(!0),this.persistor&&this.connection.joinRun&&!this.lastResume&&this.persistResumeSnapshot({threadId:this.activeResumeThreadId??this.threadId,runId:t});return}if(e.type!==`RUN_FINISHED`&&e.type!==`RUN_ERROR`)return;let n=G(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),t?.resolveProcessing!==!1&&this.resolveProcessing()}observeInterruptState(e){if(e.type!==`RUN_FINISHED`&&e.type!==`RUN_ERROR`||this.activeInterruptSubmission&&e.type===`RUN_ERROR`)return;let t=G(e),n=`threadId`in e&&typeof e.threadId==`string`?e.threadId:this.activeResumeThreadId;if(e.type===`RUN_FINISHED`&&e.outcome?.type===`interrupt`){let r=this.currentRunId??t??this.activeResumeRunId??``;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`);if(r||i||a||o||s||c){this.lastResume=null,this.persistor?.persistResumeSnapshot(null),this.interruptManager.reset();return}this.notifyResumeStateChange(`live`)}getResumeState(){return this.lastResume?{...this.lastResume}:null}getCurrentRunId(){return this.currentRunId}setCurrentRunId(e){this.currentRunId!==e&&(this.currentRunId=e,this.callbacksRef.current.onRunIdChange(e))}getInterruptState(){return this.interruptManager.getState()}getInterrupts(){return this.interruptManager.getInterrupts()}getPendingInterrupts(){return this.interruptManager.getInterrupts()}resolveInterrupts(e){if(typeof e==`boolean`){this.interruptManager.resolve(e);return}this.interruptManager.resolve(e)}cancelInterrupts(){this.interruptManager.cancel()}retryInterrupts(){this.interruptManager.retry()}resumeInterruptsUnsafe(e,t){let n=t??this.lastResume;return n?this.isLoading?new Promise((t,r)=>{this.queuePostStreamAction(async()=>{try{t(await this.resumeInterruptsUnsafe(e,n))}catch(e){r(e)}})}):(this.pendingResumeThreadId=n.threadId,this.pendingResumeParentRunId=n.runId,this.pendingResumeItems=[...e],this.streamResponse()):Promise.resolve(!1)}resumeInterrupts(e,t){return this.resumeInterruptsUnsafe(e,t)}async submitInterruptBatch(e){this.activeInterruptSubmission=e,this.interruptSubmissionFailure=void 0;for(let t of e.resolutions){let e=sa(t.payload);if(e===void 0)continue;let n=t.interruptId;this.processor.addToolApprovalResponse(n,e)}let t=await this.resumeInterruptsUnsafe([...e.resolutions],{threadId:e.threadId,runId:e.interruptedRunId}).finally(()=>{this.activeInterruptSubmission=void 0}),n=this.takeInterruptSubmissionFailure();if(n!==void 0)throw{errors:n.errors};if(!t)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)}`}setIsLoading(e){this.isLoading=e,this.callbacksRef.current.onLoadingChange(e),this.events.loadingChanged(e)}setStatus(e){this.status=e,this.callbacksRef.current.onStatusChange(e),this.devtoolsBridge.emitSnapshot()}setIsSubscribed(e){this.isSubscribed=e,this.callbacksRef.current.onSubscriptionChange(e),this.devtoolsBridge.emitSnapshot()}setConnectionStatus(e){this.connectionStatus=e,this.callbacksRef.current.onConnectionStatusChange(e),this.devtoolsBridge.emitSnapshot()}setSessionGenerating(e){this.sessionGenerating!==e&&(this.sessionGenerating=e,this.callbacksRef.current.onSessionGeneratingChange(e),this.devtoolsBridge.emitSnapshot())}notifyResumeStateChange(e){let t=this.getResumeState(),n=this.interruptManager.getState();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){this.error=e,this.callbacksRef.current.onErrorChange(e),this.events.errorChanged(e?.message||null)}buildDevtoolsBridgeOptions(e){let t=this;return{get hookId(){return t.uniqueId},get clientId(){return t.uniqueId},get threadId(){return t.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: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);for await(let n of t){if(e.aborted)break;await this.processIncomingChunk(n)}}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.setIsLoading(!0),this.setStatus(`streaming`),(async()=>{let r=!1,i=!1,a=!1,o=setTimeout(()=>{i||n.abort()},la);try{for await(let a of t(e,n.signal)){if(n.signal.aborted)break;i||(i=!0,clearTimeout(o)),!r&&ua.has(a.type)&&(r=!0,this.dropTrailingInFlightAssistant()),await this.processIncomingChunk(a,{defer:!1})}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))}async processIncomingChunk(e,t){if(e=Wn(e),e.type===`RUN_ERROR`&&this.isActiveInterruptSubmissionFailure(e)){let t=P(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`)&&(G(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),this.processor.processChunk(e),this.updateRunLifecycle(e),this.observeInterruptState(e),t?.defer!==!1&&(typeof document>`u`||!document.hidden)&&await new Promise(e=>setTimeout(e,0)),this.resolveJoinedRun(e)}isActiveInterruptSubmissionFailure(e){let t=this.activeInterruptSubmission,n=P(e)?.interruptErrors;if(!t||!Array.isArray(n)||n.length===0)return!1;let r=G(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=G(e);if(t===void 0)return;let n=this.joinedRunWaiters.get(t);n!==void 0&&(this.joinedRunWaiters.delete(t),n())}ensureSubscription(){if(!this.isSubscribed){this.subscribe();return}(!this.subscriptionAbortController||this.subscriptionAbortController.signal.aborted)&&this.subscribe({restart:!0})}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.hasBlockingInterrupts())throw Error(`ChatClient: cannot send normal input while pending interrupts exist. Use resumeInterrupts() instead.`);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}hasBlockingInterrupts(){return this.activeInterruptSubmission!==void 0||this.hasPendingInterrupts()}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.hasBlockingInterrupts())throw Error(`ChatClient: cannot append normal input while pending interrupts exist. Use resumeInterrupts() instead.`);let t=dr(e,W);if(t.role===`system`)return;let n=t;this.events.messageAppended(n);let r=this.processor.getMessages();if(this.processor.setMessages([...r,n]),this.devtoolsBridge.emitSnapshot(),this.isLoading){this.queuePostStreamAction(async()=>{await this.streamResponse()});return}await this.streamResponse()}async streamResponse(){if(this.isLoading)return!1;let e=++this.streamGeneration,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.processor.getMessages(),u=new Map(this.clientToolsRef.current),d=this.context;if(await this.callbacksRef.current.onResponse(),a.aborted)return!1;let f={...this.bodyOption,...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=Hi(this.byokProvider,f.provider);m=await Ui(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?on(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||(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 zr&&this.byok?.request(n.provider,`missing`),n instanceof Br&&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 zr||n instanceof Br||n instanceof Vr))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.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(){let e=this.abortController!==null;this.cancelInFlightStream({setReadyStatus:!0}),this.discardPendingSends(),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.discardPendingSends(),this.persistor?.remove(),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)}async addToolResultForClientTool(e,t,n){if(t&&e.state!==`output-error`)try{e={...e,output:this.validateClientToolOutput(t,e.output)}}catch(t){e={...e,output:null,state:`output-error`,errorText:t.message}}if(this.events.toolResultAdded(e.toolCallId,e.tool,e.output,e.state||`output-available`,n),this.processor.addToolResult(e.toolCallId,e.output,e.state===`output-error`?e.errorText||`Tool execution failed`:void 0),this.devtoolsBridge.emitSnapshot(),!this.interruptManager.resolveClientToolOutput(e.toolCallId,e.state===`output-error`?{error:e.errorText||`Tool execution failed`}:e.output)){if(this.isLoading){this.queuePostStreamAction(()=>this.checkForContinuation());return}await this.checkForContinuation()}}validateClientToolOutput(e,t){return e.outputSchema&&B(e.outputSchema)?cn(e.outputSchema,t):t}async addToolApprovalResponse(e){if(this.processor.addToolApprovalResponse(e.id,e.approved),this.devtoolsBridge.emitSnapshot(),this.interruptManager.resolveToolApprovalDecision(e.id,e.approved))return;let t=this.processor.getMessages(),n;for(let r of t){let t=r.parts.find(t=>t.type===`tool-call`&&t.approval?.id===e.id);if(t){n=t.id;break}}if(n&&this.events.toolApprovalResponded(e.id,n,e.approved),this.processor.addToolApprovalResponse(e.id,e.approved),this.devtoolsBridge.emitSnapshot(),this.isLoading){this.queuePostStreamAction(()=>this.checkForContinuation());return}await this.checkForContinuation()}queuePostStreamAction(e){this.postStreamActions.push(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.hasPendingInterrupts()){if(this.continuationPending||this.isLoading){this.continuationSkipped=!0;return}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()}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=oa(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(){this.callbacksRef.current.onQueueChange(this.getQueue()),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}getError(){return this.error}setMessagesManually(e){this.processor.setMessages(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`),this.connection=fi(ia({connection:e.connection,fetcher:e.fetcher})),t&&this.subscribe()}if(e.body!==void 0&&(this.bodyOption=e.body),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=new Map;for(let t of e.tools)this.clientToolsRef.current.set(t.name,t);this.devtoolsBridge.notifyToolsChanged()}e.queue!==void 0&&(this.queueConfig=aa(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.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 fa=e=>`background:${e};color:#fff;border-radius:3px;padding:1px 5px`,pa=`${fa(`#7c3aed`)};font-weight:600`,ma={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 ha(e){if(e)return(e,t,n)=>{console.log(`%cAstralBeam%c ${new Date().toISOString().slice(11,19)} %c${e}%c ${t}`,pa,`color:#94a3b8;font-weight:400`,fa(ma[e]),``,...n===void 0?[]:[n])}}function ga(e){if(!e)return{type:`object`};if(!(`~standard`in e))return e;try{return on(e)}catch{return{type:`object`}}}async function _a(e,t){if(!e||!(`~standard`in e))return t;let n=await e[`~standard`].validate(t);return n.issues?null:n.value??{}}function va(e,t,n,r){return[...Object.keys(e).length>0?[ya(e,n)]:[],ba(),...xa(t,r)]}function ya(e,t){return fr({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:
27
+ `+Object.entries(e).map(([e,{description:t,parameters:n}])=>`- ${e}: ${t} Props schema: ${JSON.stringify(ga(n))}`).join(`
28
+ `),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 ba(){return fr({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 xa(e,t){return Object.entries(e).map(([e,n])=>fr({name:e,description:n.description,inputSchema:ga(n.parameters),...n.metadata?{metadata:n.metadata}:{}}).client(async r=>{t?.(`tool`,`executing host tool "${e}"`,{input:r});let i=await _a(n.parameters,r??{});if(i==null)throw t?.(`error`,`input for host tool "${e}" failed schema validation`,{input:r}),Error(`Input for tool "${e}" failed schema validation`);try{let r=await n.execute(i);return t?.(`tool`,`host tool "${e}" returned`,{output:r}),r}catch(n){throw t?.(`error`,`host tool "${e}" threw`,{error:n}),n}}))}function Sa(e){if(e.length>16384)throw Error(`The chat auth token is too large`);let{exp:t,iat:n,user:r}=Pt(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 Ca(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(Error(`Authentication endpoint returned HTTP ${s.status}`),{status:s.status,headers:s.headers});return(await s.json())?.token}const wa={status:`loading`};function Ta(e){return{...e,fetchAstralBeamToken:e.fetchAstralBeamToken,session:{cached:void 0,refreshPromise:void 0,abortController:new AbortController,state:wa,listeners:new Set},fetchClient:globalThis.fetch.bind(globalThis),debug:void 0}}function Ea(e){return e.session.state}function Da(e,t){let{listeners:n}=e.session;return n.add(t),()=>{n.delete(t)}}function Oa(e,t){e.session.state=t;for(let t of e.session.listeners)t()}function ka(e,t){e.apiUrl!==t.apiUrl&&(Pa(e),e.session.abortController=new AbortController,Oa(e,{status:`loading`})),e.apiUrl=t.apiUrl,e.fetchAstralBeamToken=t.fetchAstralBeamToken}function Aa(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 ja(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 Ca(e,i);if(i.throwIfAborted(),typeof s!=`string`||!s)throw Error(`${a} did not return a token`);let{expiresAt:c,refreshAt:l,tenantAdmin:u}=Sa(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 qe({apiUrl:r,astralBeamToken:s,fetchClient:e.fetchClient,signal:i,cache:`no-store`,credentials:`omit`})}catch(t){if(!o&&e.retryUnauthorized!==!1&&ye(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},Oa(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:Error(`Authentication failed`);throw t.cached=void 0,Oa(e,{status:`error`,error:r}),r}}async function Z(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())&&Oa(e,{status:`loading`});let r=ja(e);t.refreshPromise=r;try{return await r}finally{t.refreshPromise===r&&(t.refreshPromise=void 0)}}function Ma(e,t){let n=!t||e.session.cached?.value===t;return n&&(e.session.cached=void 0),Z({...e,force:n,retryUnauthorized:!1})}async function Na(e){e.session.abortController.signal.aborted&&(e.session.abortController=new AbortController),await Z(e)}function Pa({session:e}){e.abortController.abort(),e.refreshPromise=void 0,e.cached=void 0,e.state=wa}async function Fa(e){let{input:t,init:n,session:r,fetchClient:i,debug:a}=e,o=Ea(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 Ma(e,u),f=Ea(e);if(o.status!==`ready`||f.status!==`ready`||Aa(o.currentUser)!==Aa(f.currentUser))throw new DOMException(`Identity changed`,`AbortError`);return n?.signal?.throwIfAborted(),c.set(`authorization`,`Bearer ${d}`),await i(t,{...n,headers:c})}function Ia(e){let t,n=new AbortController,r=0,i=()=>typeof document>`u`||document.visibilityState!==`hidden`&&globalThis.navigator?.onLine!==!1,a=()=>{n.signal.aborted||!i()||Z({...e,force:!0}).catch(()=>{})},o=()=>{if(clearTimeout(t),n.signal.aborted||typeof document>`u`||!i())return;let o=Ea(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=Da(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 Na(e).catch(()=>{}),o(),()=>{n.abort(),clearTimeout(t),c()}}function La(e){return e.state===`complete`||e.state===`error`||e.output!==void 0}function Ra(e,t){return typeof e==`object`&&e&&t in e?e[t]:void 0}function Q(e,t){let n=Ra(e,t);return typeof n==`string`?n:void 0}function za(e,t){let n=Ra(e,t);return typeof n==`number`?n:void 0}function Ba(e){return Q(e.output,`refusal`)}function Va(e){if(e.name!==`sandbox_write_file`)return;let t=Q(e.output,`path`)??Q(e.input,`path`);if(t===void 0)return;let n=Q(e.input,`content`)??``;return{toolCallId:e.id,path:t,label:Ha(e)??t,content:n,lines:n.length===0?0:n.split(`
29
+ `).length,written:e.output!=null&&Ba(e)===void 0}}function Ha(e){let t=Q(e.output,`relativePath`);return t!==void 0&&t!==`.`?t:Q(e.output,`path`)??Q(e.input,`path`)}function Ua(e){if(e.name!==`sandbox_run_command`)return;let t=Q(e.input,`command`);if(t===void 0)return;let n=e.output;return{toolCallId:e.id,command:t,cwd:Q(e.input,`cwd`),exitCode:za(n,`exitCode`),stdout:Q(n,`stdout`)??``,stderr:Q(n,`stderr`)??``,durationMs:za(n,`durationMs`),timedOut:Ra(n,`timedOut`)===!0,truncated:Ra(n,`truncated`)===!0,finished:n!=null}}function Wa(e){let t=new Map,n=[];for(let r of e)for(let e of r.parts){if(e.type!==`tool-call`)continue;let r=Va(e);r?.written&&t.set(r.path,r);let i=Ua(e);i&&Ba(e)===void 0&&n.push(i)}return{files:[...t.values()],commands:n}}function Ga(e,t){return e.length===t.length&&e.every((e,n)=>e.name===t[n]?.name&&e.title===t[n]?.title)}function Ka(e,t=!1){let n={...e},r=ha(n.debug),i=new Set,a={messages:[],status:`ready`,error:void 0,auth:{status:`loading`},capabilities:{attachments:!0},agentTools:[],sandboxStatus:void 0,sandbox:{files:[],commands:[]}},o=e=>{a={...a,...e};for(let e of i)e()},s=Ta({apiUrl:n.apiUrl,scope:`tenant`,fetchAstralBeamToken:n.fetchAstralBeamToken??{url:`/api/astralbeam/token`}}),c,l,u,d=!1,f=0,p,m=async()=>{let e=++f;try{let t=await Z(s);if(e!==f)return;let i=await Ge(n.agentId?{agentId:n.agentId}:{},{apiUrl:s.apiUrl,astralBeamToken:t,signal:s.session.abortController.signal,fetchClient:(e,t)=>Fa({...s,input:e,init:t})});if(e!==f)return;let a=i.capabilities?.attachments!==!1;o({capabilities:{attachments:a}}),r?.(`mount`,`agent capabilities resolved`,{attachments:a})}catch(e){r?.(`error`,`agent capabilities could not be resolved; keeping the defaults`,e)}},h=new Map,g=()=>{for(let e of h.values())e();h.clear()},_=async(e,t)=>{let r=n.widgets??{};if(!Object.hasOwn(r,e.widget))throw Error(`Unknown widget "${e.widget}"`);let i=r[e.widget],a=await _a(i?.parameters,e.props??{});if(a==null)throw Error(`Props for widget "${e.widget}" failed validation`);h.get(t)?.(),h.delete(t);let o,s=n.onRenderWidget?.({widget:e.widget,props:a,toolCallId:t,release:()=>{h.get(t)===o&&h.delete(t)}});return s&&(o=s,h.set(t,s)),{widget:e.widget,rendered:n.onRenderWidget!==void 0}},v=()=>va(n.widgets??{},n.tools??{},_,r),ee=()=>{let e=v(),t=e.map(e=>{let t=e.metadata?.title;return{name:e.name,title:typeof t==`string`&&t.length>0?t:void 0}});return Ga(a.agentTools,t)||o({agentTools:t}),e},te=()=>({...n.agentId?{agentId:n.agentId}:{},...n.debug?{debug:!0}:{}}),ne=mi(()=>be(Ue(),s.apiUrl),async()=>{let e=u,t=await Z(s);if(e!==void 0&&e!==u)throw new DOMException(`Identity changed`,`AbortError`);return{fetchClient:(e,n)=>we(Ue(),{...n,apiUrl:s.apiUrl,astralBeamToken:t,fetchClient:(e,t)=>Fa({...s,input:e,init:t})})}}),re=ne.connect;ne.connect=async function*(...e){try{yield*re(...e)}catch(e){throw e instanceof Error&&ye(e.cause)?e.cause:e}};let y=new da({connection:ne,tools:ee(),forwardedProps:te(),onMessagesChange:e=>{o({messages:e,sandbox:Wa(e),error:y.getError()})},onStatusChange:e=>o({status:e,error:y.getError()}),onCustomEvent:(e,t)=>{let n=t?.state;if(e===`astralbeam.sandbox.status`&&(n===`starting`||n===`ready`||n===`error`)){r?.(`sandbox`,`sandbox ${n}`),o({sandboxStatus:n});return}r?.(`stream`,`custom event "${e}"`,t)},onChunk:e=>n.streamCallbacks?.onChunk?.(e),onResponse:e=>n.streamCallbacks?.onResponse?.(e),onFinish:e=>n.streamCallbacks?.onFinish?.(e),onError:e=>n.streamCallbacks?.onError?.(e)}),ie=()=>{for(let e of a.messages)for(let t of e.parts)t.type!==`tool-call`||La(t)||(t.name===`ask_questionnaire`?(r?.(`questionnaire`,`skipping pending questionnaire before send`,{id:t.id}),y.addToolResult({toolCallId:t.id,tool:t.name,output:{answers:[],skipped:!0}})):(r?.(`tool`,`settling unimplemented tool call "${t.name}" as error`,{id:t.id}),y.addToolResult({toolCallId:t.id,tool:t.name,output:null,state:`output-error`,errorText:`The application hosting this chat has no implementation for "${t.name}"`})))},ae=()=>{let e=Ea(s);if(e.status===`ready`){let t=Aa(e.currentUser);u!==void 0&&u!==t&&(y.stop(),y.clear(),g(),o({messages:[],sandbox:{files:[],commands:[]},sandboxStatus:void 0})),u=t,p!==t&&(p=t,m())}o({auth:e})},oe=()=>{d||(d=!0,l=Da(s,ae),ae(),c=Ia(s))};return t||oe(),{start:oe,getState:()=>a,subscribe:e=>(i.add(e),()=>i.delete(e)),updateOptions:e=>{let t=n.agentId,i=n.apiUrl;n={...n,...e},r=ha(n.debug),ka(s,{apiUrl:n.apiUrl,fetchAstralBeamToken:n.fetchAstralBeamToken??{url:`/api/astralbeam/token`}}),s.debug=r,y.updateOptions({tools:ee(),forwardedProps:te()}),d&&(n.agentId!==t||n.apiUrl!==i)&&m()},sendMessage:e=>(ie(),y.sendMessage(e)),addToolResult:e=>y.addToolResult(e),stop:()=>y.stop(),retryAuthentication:()=>{Z({...s,force:!0}).catch(()=>void 0)},reload:()=>y.reload(),reset:()=>{r?.(`status`,`conversation reset`),y.clear(),g(),o({messages:[],sandbox:{files:[],commands:[]},sandboxStatus:void 0,error:void 0})},dispose:()=>{g(),y.stop(),f++,p=void 0,c?.(),l?.(),Pa(s),d=!1,queueMicrotask(()=>{d||y.dispose()}),i.clear()}}}const qa=(e,t=`algorithm.name`)=>TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function Ja(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function Ya(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 Xa(e,t,n){let r=e.algorithm;if(r.name!==t.name)throw qa(t.name);if(t.hash&&r.hash?.name!==t.hash)throw qa(t.hash,`algorithm.hash`);if(t.namedCurve&&r.namedCurve!==t.namedCurve)throw qa(t.namedCurve,`algorithm.namedCurve`);if(t.length!==void 0&&r.length!==t.length)throw qa(t.length,`algorithm.length`);Ja(e,n)}function Za(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}const Qa=(e,t,...n)=>Za(`Key for the ${e} algorithm must be `,t,...n),$a=e=>{if(e?.[Symbol.toStringTag]===`CryptoKey`)return!0;try{return e instanceof CryptoKey}catch{return!1}},eo=e=>e?.[Symbol.toStringTag]===`KeyObject`,to=e=>$a(e)||eo(e);function no(e,t){if(e)throw TypeError(`${t} can only be called once`)}async function ro(e,t){if(t.kty===`RSA`&&`oth`in t&&t.oth!==void 0)throw new xt(`RSA JWK "oth" (Other Primes Info) Parameter value is not supported`);if(!e.kty.includes(t.kty))throw new xt(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`);let n=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,r=!!(t.d||t.priv),i={...t};return i.kty!==`AKP`&&delete i.alg,delete i.use,crypto.subtle.importKey(`jwk`,i,n,t.ext??!r,t.key_ops??e.usages[+!!r])}const io=e=>e[Symbol.toStringTag],ao=(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`)}};function oo(e,t,n){let{alg:r,secret:i}=e,a=n===`decrypt`||n===`sign`;if(i&&t instanceof Uint8Array)return[so,t];if(kt(t)){if(i?!Mt(t):!(a?At(t):jt(t)))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`);return ao(e,t,n),[uo,t]}if(!to(t))throw TypeError(i?Qa(r,t,`CryptoKey`,`KeyObject`,`JSON Web Key`,`Uint8Array`):Qa(r,t,`CryptoKey`,`KeyObject`,`JSON Web Key`));if(i){if(t.type!==`secret`)throw TypeError(`${io(t)} instances for symmetric algorithms must be of type "secret"`)}else{if(t.type===`secret`)throw TypeError(`${io(t)} instances for asymmetric algorithms must not be of type "secret"`);let e=a?`private`:`public`;if((t.type===`public`||t.type===`private`)&&t.type!==e){let r=n===`sign`?`signing`:n===`verify`?`verifying`:`${n.slice(0,-1)}tion`;throw TypeError(`${io(t)} instances for asymmetric algorithm ${r} must be of type "${e}"`)}}return $a(t)?[co,t]:[lo,t]}const so=0,co=1,lo=2,uo=3;let fo;const po={__proto__:null,prime256v1:`P-256`,secp384r1:`P-384`,secp521r1:`P-521`};function mo(e,t,n){fo||=new WeakMap;let r=fo.get(e);return n&&(r?r[t]=n:fo.set(e,{__proto__:null,[t]:n})),n??r?.[t]}const ho=async(e,t,n)=>mo(e,n.alg)??mo(e,n.alg,await ro(n,{...t,alg:n.alg})),go=(e,t)=>{let n=mo(e,t.alg);if(n)return n;let r=e.type===`public`,i=t.usages[+!r],{asymmetricKeyType:a}=e,o=po[e.asymmetricKeyDetails?.namedCurve],s=t.resolve?.({crv:o,asymmetricKeyType:a})??t.subtle;return mo(e,t.alg,e.toCryptoKey(s,r,i))};async function _o(e,t,n){let r=oo(e,t,n);switch(r[0]){case 0:case 1:return r[1];case 3:{let t=r[1];if(t.k)return Tt(t.k);if(!Object.isFrozen(t)){let{key_ops:e}=t;Array.isArray(e)&&Object.freeze(e),Object.freeze(t)}return ho(t,t,e)}case 2:{let t=r[1];return t.type===`secret`?t.export():`toCryptoKey`in t&&typeof t.toCryptoKey==`function`?go(t,e):ho(t,t.export({format:`jwk`}),e)}}}function vo(e){let t={__proto__:null};for(let n in e)t[n]={...e[n],alg:n};return t}const yo={__proto__:null,b64:!0};function bo(e,t){let{crit:n}=t??{};if(Array.isArray(n)&&new Set(n).size!==n.length)throw new e(`"crit" (Critical) Header Parameter MUST NOT contain duplicate values`)}function xo(e,t,n,r,i){if(i.crit!==void 0&&r?.crit===void 0)throw new e(`"crit" (Critical) Header Parameter MUST be integrity protected`);if(!r||r.crit===void 0)return[];if(!Array.isArray(r.crit)||r.crit.length===0||r.crit.some(e=>typeof e!=`string`||e.length===0))throw new e(`"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present`);let a=n===void 0?t:{__proto__:null,...n,...t};for(let t of r.crit){if(!(t in a))throw new xt(`Extension Header Parameter "${t}" is not recognized`);if(!Object.hasOwn(i,t)||i[t]===void 0)throw new e(`Extension Header Parameter "${t}" is missing`);if(a[t]&&(!Object.hasOwn(r,t)||r[t]===void 0))throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return r.crit}async function So(e,t,n){return t instanceof Uint8Array?crypto.subtle.importKey(`raw`,t,e.subtle,!1,[n]):(Xa(t,e.subtle,n),e.minRsaBits&&Ya(e.alg,t),t)}async function Co(e,t,n){let r=await So(e,t,`sign`),i=await crypto.subtle.sign(e.signing,r,n);return new Uint8Array(i)}const wo=[[`verify`],[`sign`]];function To(e){let t={name:`HMAC`,hash:`SHA-${e}`};return{kty:[`oct`],secret:!0,subtle:t,signing:t,usages:wo}}function $(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:wo,minRsaBits:2048}}function Eo(e,t){return{kty:[`EC`],crv:e,subtle:{name:`ECDSA`,namedCurve:e},signing:{name:`ECDSA`,hash:`SHA-${t}`},usages:wo}}function Do(){let e={name:`Ed25519`};return{kty:[`OKP`],crv:`Ed25519`,subtle:e,signing:e,usages:wo}}function Oo(e){let t={name:`ML-DSA-${e}`};return{kty:[`AKP`],subtle:t,signing:t,usages:wo}}const ko=vo({HS256:To(256),HS384:To(384),HS512:To(512),RS256:$(256),RS384:$(384),RS512:$(512),PS256:$(256,32),PS384:$(384,48),PS512:$(512,64),ES256:Eo(`P-256`,256),ES384:Eo(`P-384`,384),ES512:Eo(`P-521`,512),EdDSA:Do(),Ed25519:Do(),"ML-DSA-44":Oo(44),"ML-DSA-65":Oo(65),"ML-DSA-87":Oo(87)});function Ao(e){let t=typeof e==`string`?ko[e]:void 0;if(!t)throw new xt(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}const jo=e=>Math.floor(e.getTime()/1e3),Mo={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},No=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function Po(e){let t=No.exec(e);if(!t||t[4]&&t[1])throw TypeError(`Invalid time period format`);let n=parseFloat(t[2]),r=Math.round(n*Mo[t[3][0].toLowerCase()]);return t[1]===`-`||t[4]===`ago`?-r:r}function Fo(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}function Io(e,t){return typeof e==`number`?Fo(t,e):e instanceof Date?Fo(t,jo(e)):jo(new Date)+Po(e)}var Lo=class{#e;constructor(e){if(!Dt(e))throw TypeError(`JWT Claims Set MUST be an object`);this.#e=structuredClone(e)}data(){return ht.encode(JSON.stringify(this.#e))}get iss(){return this.#e.iss}set iss(e){this.#e.iss=e}get sub(){return this.#e.sub}set sub(e){this.#e.sub=e}get aud(){return this.#e.aud}set aud(e){this.#e.aud=e}set jti(e){this.#e.jti=e}set nbf(e){this.#e.nbf=Io(e,`setNotBefore`)}set exp(e){this.#e.exp=Io(e,`setExpirationTime`)}set iat(e){e===void 0?this.#e.iat=jo(new Date):typeof e==`string`?this.#e.iat=Fo(`setIssuedAt`,jo(new Date)+Po(e)):this.#e.iat=Io(e,`setIssuedAt`)}};function Ro(e){return e?.b64===!1&&Array.isArray(e.crit)&&e.crit.includes(`b64`)}async function zo(e,t){let{protectedHeader:n,unprotectedHeader:r}=e;if(!n&&!r)throw new M(`either setProtectedHeader or setUnprotectedHeader must be called before #sign()`);if(!Ot(n,r))throw new M(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let i={...n,...r};bo(M,n);let a=xo(M,yo,e.crit,n,i),o=!0;if(a.includes(`b64`)&&(o=n.b64,typeof o!=`boolean`))throw new M(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);let{alg:s}=i;if(typeof s!=`string`||!s)throw new M(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);let c=Ao(s),l,u;if(o){let t=e.encoded??=[];t[0]??=Et(e.payload),t[1]??=yt(t[0]),l=t[0],u=t[1]}else u=e.payload,l=``;let d,f;n?(d=Et(JSON.stringify(n)),f=yt(d)):(d=``,f=new Uint8Array);let p=vt(f,yt(`.`),u),m={signature:Et(await Co(c,await _o(c,t,`sign`),p)),payload:l};return n&&(m.protected=d),r&&(m.header=r),m}var Bo=class{#e;#t;#n;constructor(e){if(!(e instanceof Uint8Array))throw TypeError(`payload must be an instance of Uint8Array`);this.#e=e}setProtectedHeader(e){return no(this.#t,`setProtectedHeader`),this.#t=e,this}setUnprotectedHeader(e){return no(this.#n,`setUnprotectedHeader`),this.#n=e,this}async sign(e,t){return zo({payload:this.#e,protectedHeader:this.#t,unprotectedHeader:this.#n,crit:t?.crit},e)}},Vo=class{#e;#t;constructor(e){this.#e=new Bo(e)}setProtectedHeader(e){return this.#e.setProtectedHeader(e),this.#t=e,this}async sign(e,t){if(Ro(this.#t))throw TypeError(`use the flattened module for creating JWS with b64: false`);let n=await this.#e.sign(e,t);return`${n.protected}.${n.payload}.${n.signature}`}},Ho=class{#e;#t;constructor(e={}){this.#t=new Lo(e)}setIssuer(e){return this.#t.iss=e,this}setSubject(e){return this.#t.sub=e,this}setAudience(e){return this.#t.aud=e,this}setJti(e){return this.#t.jti=e,this}setNotBefore(e){return this.#t.nbf=e,this}setExpirationTime(e){return this.#t.exp=e,this}setIssuedAt(e){return this.#t.iat=e,this}setProtectedHeader(e){return this.#e=e,this}async sign(e,t){let n=new Vo(this.#t.data());if(n.setProtectedHeader(this.#e),Ro(this.#e))throw new N(`JWTs MUST NOT use unencoded payload`);return n.sign(e,t)}};const Uo=`astralbeam`,Wo=16384,Go=8192,Ko=/^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}$/,qo=[`id`,`name`,`metadata`],Jo=[`id`,`name`,`admin`,`metadata`],Yo=new TextEncoder;function Xo(e){if(!Ko.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 Zo(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Qo(e){return e===null||typeof e==`string`||typeof e==`boolean`?!0:typeof e==`number`?Number.isFinite(e):Array.isArray(e)?e.every(Qo):Zo(e)&&Object.values(e).every(Qo)}function $o(e,t,n){if(!Zo(t))throw Error(`${e} must be an object`);let r=n?Jo:qo;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&&!(Zo(s)&&Qo(s)))throw Error(`${e}.metadata must be a JSON object`)}function es(e,t){$o(`user`,e,!0),$o(`tenant`,t,!1);let n=JSON.stringify({user:e,tenant:t});if(Yo.encode(n).byteLength>Go)throw Error(`user and tenant must not exceed ${Go} bytes`);return JSON.parse(n)}async function ts(e){let t=await crypto.subtle.digest(`SHA-256`,Yo.encode(e));return Yo.encode(Et(new Uint8Array(t)))}async function ns({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}=Xo(e);if(n!==a)throw Error(`organizationId must match the API key organization`);let s=Math.floor(Date.now()/1e3);return await new Ho({ver:1,email:t,organization_id:n}).setProtectedHeader({alg:`HS256`,typ:`astralbeam-organization+jwt`,kid:i}).setIssuer(n).setAudience(Uo).setIssuedAt(s).setExpirationTime(s+r).sign(await ts(o))}async function rs({apiKey:e,user:t,tenant:n,expiresInSeconds:r=300}){if(!Number.isInteger(r)||r<60||r>600)throw Error(`chat auth tokens must live for 60-600 seconds`);let{keyId:i,organizationId:a,keySecret:o}=Xo(e),s=es(t,n),c=Math.floor(Date.now()/1e3),l=await new Ho({ver:4,user:s.user,tenant:s.tenant}).setProtectedHeader({alg:`HS256`,typ:`astralbeam+jwt`,kid:i}).setIssuer(a).setAudience(Uo).setIssuedAt(c).setExpirationTime(c+r).sign(await ts(o));if(Yo.encode(l).byteLength>Wo)throw Error(`chat auth tokens must not exceed ${Wo} bytes`);return l}function is(e){let t=Number(e);if(!Number.isInteger(t)||t<1)throw new x(`Expected a positive integer.`);return t}function as(e){let t=Number(e);if(!Number.isInteger(t)||t<60||t>600)throw new x(`Expected a whole number of seconds from 60 to 600.`);return t}function os(e){let t;try{t=JSON.parse(e)}catch{throw new x(`Expected a JSON object.`)}if(typeof t!=`object`||!t||Array.isArray(t))throw new x(`Expected a JSON object.`);return t}function ss(e){return e.requiredOption(`--tenant <external-id>`,`Tenant external ID, signed as tenant.id`).requiredOption(`--user <external-id>`,`TenantUser external ID, signed as user.id`).option(`--tenant-name <name>`,`Tenant display name`).option(`--user-name <name>`,`TenantUser display name`).option(`--admin`,`sign user.admin: true, granting Tenant admin API access`).option(`--expires-in <seconds>`,`token lifetime, 60-600 (default 300)`,as)}function cs(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 ls(e,t,n){let r=new Date(Date.now()+t*1e3).toISOString();n?w({token:e,expires_at:r}):s.write(`${e}\n`)}function us(e){let t=e.command(`token`).description(`Mint short-lived JWTs offline with the organization API key`);ss(t.command(`chat`).description(`Mint a chat JWT for a Tenant's user, as a token endpoint would`)).action(async(e,t)=>{let{apiKey:n}=await j(),r=e.expiresIn??300;ls(await rs({apiKey:n,expiresInSeconds:r,...cs(e)}),r,k(t).json)}),t.command(`organization`).description(`Mint an organization-management JWT delegating a member's current role`).requiredOption(`--email <email>`,`email of an existing member of the organization`).option(`--expires-in <seconds>`,`token lifetime, 60-600 (default 300)`,as).action(async(e,t)=>{let{apiKey:n}=await j(),r=e.expiresIn??300;ls(await ns({apiKey:n,email:e.email,organizationId:nt(n),expiresInSeconds:r}),r,k(t).json)})}function ds(e){return e.filter(e=>e.role===`assistant`).map(e=>e.parts.map(e=>e.type===`text`?e.content:``).join(``)).filter(Boolean).join(`
30
30
 
31
- `)}async function ds(e,t,n){let r=e.getState().messages.length,i=``,o=new Set,c=e.subscribe(()=>{if(n)return;let t=e.getState().messages.slice(r),c=us(t);c.startsWith(i)&&(s.write(T(c.slice(i.length),`
32
- `)),i=c);for(let e of t.flatMap(e=>e.parts))e.type!==`tool-call`||o.has(e.id)||(o.add(e.id),a.write(`[tool ${T(e.name)}]\n`))});try{await e.sendMessage(t)}finally{c()}let{error:l,messages:u}=e.getState();if(l)throw l;n?qe({messages:u.slice(r)}):i.endsWith(`
31
+ `)}async function fs(e,t,n){let r=e.getState().messages.length,i=``,o=new Set,c=e.subscribe(()=>{if(n)return;let t=e.getState().messages.slice(r),c=ds(t);c.startsWith(i)&&(s.write(T(c.slice(i.length),`
32
+ `)),i=c);for(let e of t.flatMap(e=>e.parts))e.type!==`tool-call`||o.has(e.id)||(o.add(e.id),a.write(`[tool ${T(e.name)}]\n`))});try{await e.sendMessage(t)}finally{c()}let{error:l,messages:u}=e.getState();if(l)throw l;n?w({messages:u.slice(r)}):i.endsWith(`
33
33
  `)||s.write(`
34
- `)}async function fs(){let e=[];for await(let t of o)e.push(t);return Buffer.concat(e).toString(`utf8`).trim()}async function ps(e){let t=ae({input:o,output:s});a.write(`Type a message, or /exit to quit.
35
- `);try{for(;;){let n=(await t.question(`> `).catch(()=>`/exit`)).trim();if(n===`/exit`)return;n&&await ds(e,n,!1)}}finally{t.close()}}function ms(e){os(e.command(`chat`).description(`Chat with an agent as one of a Tenant's users, like the embedded widget`).argument(`[message]`,`message to send (default: stdin when piped, else an interactive prompt)`).option(`--agent <id>`,`public agent ID (default: the organization's default agent)`)).action(async(e,t,n)=>{let{json:r}=k(n),{apiKey:i,apiUrl:a}=await j(),s=t.expiresIn??300,c=ss(t),l=Ga({apiUrl:a,...t.agent===void 0?{}:{agentId:t.agent},fetchAstralBeamToken:async()=>({token:await ns({apiKey:i,expiresInSeconds:s,...c})})});try{e===void 0?o.isTTY?r?n.error(`Pass a message or pipe one on stdin with --json.`):await ps(l):await ds(l,await fs(),r):await ds(l,e,r)}finally{l.dispose()}})}const hs=new URL(`../skills/astralbeam/SKILL.md`,import.meta.url);function gs(e){e.command(`skill`).description(`Print or install the Agent Skill that teaches coding agents this CLI`).action(async(e,t)=>{let n=await v(oe(hs),`utf8`);k(t).json?E({content:n},!0):s.write(n)}).command(`install`).description(`Write the skill to <dir>/astralbeam/SKILL.md`).option(`--dir <path>`,`skills directory, such as ~/.claude/skills or .agents/skills`,`.claude/skills`).action(async(e,t)=>{let n=p(e.dir,`astralbeam`);await _(n,{recursive:!0});let r=f(n,`SKILL.md`);await re(r,await v(oe(hs),`utf8`));let{json:i}=k(t);i||a.write(`Restart your agent session to load the skill.
36
- `),E({path:r},i)})}function _s(e){return e.option(`-q, --search <text>`,`case-insensitive substring of the name or external ID`).option(`--external-id <id>`,`exact external ID, returning zero or one item`).option(`--page-size <count>`,`items per page, capped at 100 (default 20)`,rs).option(`--page-after <cursor>`,`continue after a previous page's page_after`).option(`--page-before <cursor>`,`go back from a previous page's page_before`).addOption(new S(`--all`,`follow page_after to the last page and return every item`).conflicts(`pageBefore`))}function vs(e){let t={};return e.search!==void 0&&(t.q=e.search),e.externalId!==void 0&&(t[`filter[external_id]`]=e.externalId),e.pageSize===void 0?e.all&&(t.page_size=100):t.page_size=e.pageSize,e.pageAfter!==void 0&&(t.page_after=e.pageAfter),e.pageBefore!==void 0&&(t.page_before=e.pageBefore),t}async function ys(e,t,n){let r=await n(e);if(!t)return r;let i=[...r.items],a=r.page_after;for(;a!==null;){let t=await n({...e,page_after:a});i.push(...t.items),a=t.page_after}return{items:i,page_after:null,page_before:r.page_before}}function bs(e,t,n){if(n)return qe(e);e.items.length===0?a.write(`No results.
37
- `):Xe(e.items,t),e.page_after!==null&&a.write(`More results: --page-after ${e.page_after}\n`)}function xs(e){let t={};return e.name!==void 0&&(t.name=e.name),e.clearName&&(t.name=null),e.metadata!==void 0&&(t.metadata=e.metadata),t}function Ss(e,t){return e.option(`--name <name>`,`display name`),t&&e.addOption(new S(`--clear-name`,`remove the name`).conflicts(`name`)),e.option(`--metadata <json>`,t?`JSON object replacing the stored metadata`:`JSON object stored with the record`,as)}function Cs(e){let t=e.command(`tenants`).description(`Manage Tenants, the customers of your application`);_s(t.command(`list`).description(`List Tenants in internal ID order`)).action(async(e,t)=>{let n=await A();bs(await ys(vs(e),e.all,e=>Te(e,n)),[`id`,`external_id`,`name`,`created_at`],k(t).json)}),t.command(`get`).description(`Show one Tenant by its internal ID`).argument(`<id>`,`internal Tenant ID`).action(async(e,t,n)=>{E(await ke(e,await A()),k(n).json)}),Ss(t.command(`create`).description(`Create a Tenant. An external ID already in use returns HTTP 409.`).requiredOption(`--external-id <id>`,`your stable, immutable identity for the customer`),!1).action(async(e,t)=>{E(await De({external_id:e.externalId,...xs(e)},await A()),k(t).json)}),Ss(t.command(`update`).description(`Update a Tenant. Omitted fields stay unchanged.`).argument(`<id>`,`internal Tenant ID`),!0).action(async(e,t,n)=>{let r=xs(t);Object.keys(r).length===0&&n.error(`Pass --name, --clear-name, or --metadata.`),E(await je(e,r,await A()),k(n).json)})}function ws(e){let t=xs(e);return e.admin!==void 0&&(t.admin=e.admin),t}function Ts(e,t){return e.addOption(new S(`--admin`,t)).addOption(new S(`--no-admin`,`the opposite of --admin`))}function Es(e){let t=e.command(`tenant-users`).description(`Manage TenantUsers, the users of one Tenant`);Ts(_s(t.command(`list`).description(`List a Tenant's users in internal ID order`).argument(`<tenant-id>`,`internal Tenant ID`)),`only stored admins (--no-admin: only non-admins)`).action(async(e,t,n)=>{let r=await A(),i=vs(t);t.admin!==void 0&&(i[`filter[admin]`]=t.admin?`true`:`false`),bs(await ys(i,t.all,t=>Ne(e,t,r)),[`id`,`external_id`,`name`,`admin`,`created_at`],k(n).json)}),t.command(`get`).description(`Show one TenantUser by its internal ID`).argument(`<tenant-id>`,`internal Tenant ID`).argument(`<id>`,`internal TenantUser ID`).action(async(e,t,n,r)=>{E(await Le(e,t,await A()),k(r).json)}),Ts(Ss(t.command(`create`).description(`Create a TenantUser. An external ID already in the Tenant returns HTTP 409.`).argument(`<tenant-id>`,`internal Tenant ID`).requiredOption(`--external-id <id>`,`your stable, immutable identity for the user`),!1),`store the user as a Tenant admin (default false)`).action(async(e,t,n)=>{E(await Fe(e,{external_id:t.externalId,...ws(t)},await A()),k(n).json)}),Ts(Ss(t.command(`update`).description(`Update a TenantUser. Omitted fields stay unchanged.`).argument(`<tenant-id>`,`internal Tenant ID`).argument(`<id>`,`internal TenantUser ID`),!0),`store the user as a Tenant admin`).action(async(e,t,n,r)=>{let i=ws(n);Object.keys(i).length===0&&r.error(`Pass --name, --clear-name, --metadata, --admin, or --no-admin.`),E(await ze(e,t,i,await A()),k(r).json)})}const Ds=`
34
+ `)}async function ps(){let e=[];for await(let t of o)e.push(t);return Buffer.concat(e).toString(`utf8`).trim()}async function ms(e){let t=ae({input:o,output:s});a.write(`Type a message, or /exit to quit.
35
+ `);try{for(;;){let n=(await t.question(`> `).catch(()=>`/exit`)).trim();if(n===`/exit`)return;n&&await fs(e,n,!1)}}finally{t.close()}}function hs(e){ss(e.command(`chat`).description(`Chat with an agent as one of a Tenant's users, like the embedded widget`).argument(`[message]`,`message to send (default: stdin when piped, else an interactive prompt)`).option(`--agent <id>`,`public agent ID (default: the organization's default agent)`)).action(async(e,t,n)=>{let{json:r}=k(n),{apiKey:i,apiUrl:a}=await j(),s=t.expiresIn??300,c=cs(t),l=Ka({apiUrl:a,...t.agent===void 0?{}:{agentId:t.agent},fetchAstralBeamToken:async()=>({token:await rs({apiKey:i,expiresInSeconds:s,...c})})});try{e===void 0?o.isTTY?r?n.error(`Pass a message or pipe one on stdin with --json.`):await ms(l):await fs(l,await ps(),r):await fs(l,e,r)}finally{l.dispose()}})}const gs=new URL(`../skills/astralbeam/SKILL.md`,import.meta.url);function _s(e){e.command(`skill`).description(`Print or install the Agent Skill that teaches coding agents this CLI`).action(async(e,t)=>{let n=await v(oe(gs),`utf8`);k(t).json?E({content:n},!0):s.write(n)}).command(`install`).description(`Write the skill to <dir>/astralbeam/SKILL.md`).option(`--dir <path>`,`skills directory, such as ~/.claude/skills or .agents/skills`,`.claude/skills`).action(async(e,t)=>{let n=p(e.dir,`astralbeam`);await _(n,{recursive:!0});let r=f(n,`SKILL.md`);await re(r,await v(oe(gs),`utf8`));let{json:i}=k(t);i||a.write(`Restart your agent session to load the skill.
36
+ `),E({path:r},i)})}function vs(e){return e.option(`-q, --search <text>`,`case-insensitive substring of the name or external ID`).option(`--external-id <id>`,`exact external ID, returning zero or one item`).option(`--page-size <count>`,`items per page, capped at 100 (default 20)`,is).option(`--page-after <cursor>`,`continue after a previous page's page_after`).option(`--page-before <cursor>`,`go back from a previous page's page_before`).addOption(new S(`--all`,`follow page_after to the last page and return every item`).conflicts(`pageBefore`))}function ys(e){let t={};return e.search!==void 0&&(t.q=e.search),e.externalId!==void 0&&(t[`filter[external_id]`]=e.externalId),e.pageSize===void 0?e.all&&(t.page_size=100):t.page_size=e.pageSize,e.pageAfter!==void 0&&(t.page_after=e.pageAfter),e.pageBefore!==void 0&&(t.page_before=e.pageBefore),t}async function bs(e,t,n){let r=await n(e);if(!t)return r;let i=[...r.items],a=r.page_after;for(;a!==null;){let t=await n({...e,page_after:a});i.push(...t.items),a=t.page_after}return{items:i,page_after:null,page_before:r.page_before}}function xs(e,t,n){if(n)return w(e);e.items.length===0?a.write(`No results.
37
+ `):Xe(e.items,t),e.page_after!==null&&a.write(`More results: --page-after ${e.page_after}\n`)}function Ss(e){let t={};return e.name!==void 0&&(t.name=e.name),e.clearName&&(t.name=null),e.metadata!==void 0&&(t.metadata=e.metadata),t}function Cs(e,t){return e.option(`--name <name>`,`display name`),t&&e.addOption(new S(`--clear-name`,`remove the name`).conflicts(`name`)),e.option(`--metadata <json>`,t?`JSON object replacing the stored metadata`:`JSON object stored with the record`,os)}function ws(e){let t=e.command(`tenants`).description(`Manage Tenants, the customers of your application`);vs(t.command(`list`).description(`List Tenants in internal ID order`)).action(async(e,t)=>{let n=await A();xs(await bs(ys(e),e.all,e=>Ee(e,n)),[`id`,`external_id`,`name`,`created_at`],k(t).json)}),t.command(`get`).description(`Show one Tenant by its internal ID`).argument(`<id>`,`internal Tenant ID`).action(async(e,t,n)=>{E(await Ae(e,await A()),k(n).json)}),Cs(t.command(`create`).description(`Create a Tenant. An external ID already in use returns HTTP 409.`).requiredOption(`--external-id <id>`,`your stable, immutable identity for the customer`),!1).action(async(e,t)=>{E(await Oe({external_id:e.externalId,...Ss(e)},await A()),k(t).json)}),Cs(t.command(`update`).description(`Update a Tenant. Omitted fields stay unchanged.`).argument(`<id>`,`internal Tenant ID`),!0).action(async(e,t,n)=>{let r=Ss(t);Object.keys(r).length===0&&n.error(`Pass --name, --clear-name, or --metadata.`),E(await Me(e,r,await A()),k(n).json)})}function Ts(e){let t=Ss(e);return e.admin!==void 0&&(t.admin=e.admin),t}function Es(e,t){return e.addOption(new S(`--admin`,t)).addOption(new S(`--no-admin`,`the opposite of --admin`))}function Ds(e){let t=e.command(`tenant-users`).description(`Manage TenantUsers, the users of one Tenant`);Es(vs(t.command(`list`).description(`List a Tenant's users in internal ID order`).argument(`<tenant-id>`,`internal Tenant ID`)),`only stored admins (--no-admin: only non-admins)`).action(async(e,t,n)=>{let r=await A(),i=ys(t);t.admin!==void 0&&(i[`filter[admin]`]=t.admin?`true`:`false`),xs(await bs(i,t.all,t=>Pe(e,t,r)),[`id`,`external_id`,`name`,`admin`,`created_at`],k(n).json)}),t.command(`get`).description(`Show one TenantUser by its internal ID`).argument(`<tenant-id>`,`internal Tenant ID`).argument(`<id>`,`internal TenantUser ID`).action(async(e,t,n,r)=>{E(await Re(e,t,await A()),k(r).json)}),Es(Cs(t.command(`create`).description(`Create a TenantUser. An external ID already in the Tenant returns HTTP 409.`).argument(`<tenant-id>`,`internal Tenant ID`).requiredOption(`--external-id <id>`,`your stable, immutable identity for the user`),!1),`store the user as a Tenant admin (default false)`).action(async(e,t,n)=>{E(await Ie(e,{external_id:t.externalId,...Ts(t)},await A()),k(n).json)}),Es(Cs(t.command(`update`).description(`Update a TenantUser. Omitted fields stay unchanged.`).argument(`<tenant-id>`,`internal Tenant ID`).argument(`<id>`,`internal TenantUser ID`),!0),`store the user as a Tenant admin`).action(async(e,t,n,r)=>{let i=Ts(n);Object.keys(i).length===0&&r.error(`Pass --name, --clear-name, --metadata, --admin, or --no-admin.`),E(await Be(e,t,i,await A()),k(r).json)})}const Os=`
38
38
  Environment:
39
39
  ASTRALBEAM_API_KEY organization API key, used instead of directory logins
40
- ASTRALBEAM_API_URL API base URL for ASTRALBEAM_API_KEY and login (default ${Qe})
40
+ ASTRALBEAM_API_URL API base URL for ASTRALBEAM_API_KEY and login (default ${$e})
41
41
  ASTRALBEAM_CONFIG_DIR directory holding config.json
42
42
 
43
43
  Exit codes: 0 success, 1 API or runtime failure, 2 invalid usage.
44
- Docs: https://app.astralbeam.ai/docs/cli/getting-started`;async function Os(e){let t=e.includes(`--json`),n=new he(`astralbeam`).description(`Manage an AstralBeam organization's Tenants, TenantUsers, tokens, and agent chats.`).version(ve).option(`--json`,`print JSON to stdout, and failures as JSON to stderr`).addHelpText(`after`,Ds).showHelpAfterError().exitOverride();t&&n.configureOutput({writeErr:()=>void 0}),pt(n),Cs(n),Es(n),ls(n),ms(n),gs(n),Object.assign(O,{json:t,context:void 0});try{return await n.parseAsync(e),t&&a.write(`${JSON.stringify({context:O.context??null})}\n`),0}catch(e){if(!(e instanceof b))return Ze(e,t,O.context),1;if(e.exitCode===0)return 0;if(t){let t=e.code===`commander.help`?`Missing subcommand.`:e.message.replace(/^error: /,``);Ze(Error(t),!0,O.context)}return 2}}e.exitCode=await Os(e.argv);export{};
44
+ Docs: https://app.astralbeam.ai/docs/cli/getting-started`;async function ks(e){let t=e.includes(`--json`),n=e.includes(`--debug`),r=new he(`astralbeam`).description(`Manage an AstralBeam organization's Tenants, TenantUsers, tokens, and agent chats.`).version(ve).option(`--json`,`print JSON to stdout, and failures as JSON to stderr`).option(`--debug`,`log HTTP requests and failure stack traces to stderr, never headers`).addHelpText(`after`,Os).showHelpAfterError().exitOverride();t&&r.configureOutput({writeErr:()=>void 0}),mt(r),ws(r),Ds(r),us(r),hs(r),_s(r),Object.assign(O,{json:t,context:void 0,failedRequest:void 0});let i=globalThis.fetch;globalThis.fetch=As(i,n);try{return await r.parseAsync(e),t&&a.write(`${JSON.stringify({context:O.context??null})}\n`),0}catch(e){if(!(e instanceof b))return n&&e instanceof Error&&a.write(`[debug] ${e.stack}\n`),Qe(e,t,O.context,O.failedRequest),1;if(e.exitCode===0)return 0;if(t){let t=e.code===`commander.help`?`Missing subcommand.`:e.message.replace(/^error: /,``);Qe(Error(t),!0,O.context)}return 2}finally{globalThis.fetch=i}}function As(e,t){return async(n,r)=>{let i=r?.method??(n instanceof Request?n.method:`GET`),o=n instanceof Request?n.url:String(n),s=performance.now();t&&a.write(`[debug] → ${i} ${o}\n`);let c;try{c=await e(n,r)}catch(e){if(!(e instanceof TypeError))throw e;let t=e.cause instanceof Error?e.cause.message:e.message;throw Error(`Could not reach ${o}: ${t}`,{cause:e})}let l=Math.round(performance.now()-s);return t&&a.write(`[debug] ← ${c.status} ${c.statusText} (${l} ms)\n`),c.ok||(O.failedRequest=`${i} ${o}`),c}}e.exitCode=await ks(e.argv);export{};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astralbeam/cli",
3
- "version": "0.12.0",
3
+ "version": "0.13.0",
4
4
  "description": "Command-line interface for AstralBeam organization admins and their coding agents",
5
5
  "homepage": "https://app.astralbeam.ai/docs/cli/getting-started",
6
6
  "bugs": "https://github.com/AstralBeamAI/astralbeam/issues",
@@ -12,7 +12,7 @@ If `astralbeam` is not on the PATH, run it as `npx -y @astralbeam/cli` instead.
12
12
  ## Rules
13
13
 
14
14
  - Pass `--json` on every command whose output you will read. Records and pages go to stdout. Stderr then holds exactly one JSON object: `{"context": {...}}` on success, or `{"error": {...}, "context": {...}}` on failure, where `error` carries the API's `status`, `detail`, and optional `issues`. `context` is `{"organization": {"id", "name", "slug"}, "bound_directory": <path or null>}`, or `null` when the command uses no credentials or failed before resolving them.
15
- - Exit code 0 means success, 1 means the API or runtime failed, and 2 means the command line was invalid. Read `astralbeam <command> --help` before guessing flags.
15
+ - Exit code 0 means success, 1 means the API or runtime failed, and 2 means the command line was invalid. Read `astralbeam <command> --help` before guessing flags. To diagnose an unexpected failure, rerun it without `--json` and with `--debug`, which logs each HTTP request and the stack trace to stderr.
16
16
  - Never print, log, or echo an API key. Never pass a key as a command-line argument. Credentials come from `ASTRALBEAM_API_KEY`, or from the nearest directory at or above the working directory where someone ran `astralbeam auth login`. Run commands from the project directory the user means, because a different directory can select a different organization.
17
17
  - Before any write, run `astralbeam auth status --json` from the same directory and confirm `organization` is the one the user means. Stop if it is not. Without `--json`, keyed commands print the organization first on stderr as `▸ Acme (acme) · org <id> · bound at ~/work/acme`.
18
18
  - Never run `astralbeam auth login` yourself unless the user supplies the key through stdin or the environment. It prompts for a secret.