@copilotkitnext/core 1.51.4 → 1.51.5-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.umd.js CHANGED
@@ -1,2 +1,1841 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@ag-ui/client"),require("@copilotkitnext/shared"),require("rxjs")):"function"==typeof define&&define.amd?define(["exports","@ag-ui/client","@copilotkitnext/shared","rxjs"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).CopilotKitNextCore={},e.AgUIClient,e.CopilotKitNextShared,e.rxjs)}(this,function(e,t,n,r){"use strict";function i(e){return"function"==typeof e}function o(e){return function(t){if(function(e){return i(null==e?void 0:e.lift)}(t))return t.lift(function(t){try{return e(t,this)}catch(e){this.error(e)}});throw new TypeError("Unable to lift unknown Observable type")}}var s=function(e,t){return s=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},s(e,t)};function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}s(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function u(e,t,n,r){return new(n||(n=Promise))(function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(s,a)}u((r=r.apply(e,t||[])).next())})}function c(e,t){var n,r,i,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},s=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return s.next=a(0),s.throw=a(1),s.return=a(2),"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(a){return function(u){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;s&&(s=0,a[0]&&(o=0)),o;)try{if(n=1,r&&(i=2&a[0]?r.return:a[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,a[1])).done)return i;switch(r=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,r=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!(i=o.trys,(i=i.length>0&&i[i.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]<i[3])){o.label=a[1];break}if(6===a[0]&&o.label<i[1]){o.label=i[1],i=a;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(a);break}i[2]&&o.ops.pop(),o.trys.pop();continue}a=t.call(e,o)}catch(e){a=[6,e],r=0}finally{n=i=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,u])}}}function l(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function d(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,i,o=n.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s}function g(e,t,n){if(n||2===arguments.length)for(var r,i=0,o=t.length;i<o;i++)!r&&i in t||(r||(r=Array.prototype.slice.call(t,0,i)),r[i]=t[i]);return e.concat(r||Array.prototype.slice.call(t))}function h(e){return this instanceof h?(this.v=e,this):new h(e)}function f(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,i=n.apply(e,t||[]),o=[];return r=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),s("next"),s("throw"),s("return",function(e){return function(t){return Promise.resolve(t).then(e,c)}}),r[Symbol.asyncIterator]=function(){return this},r;function s(e,t){i[e]&&(r[e]=function(t){return new Promise(function(n,r){o.push([e,t,n,r])>1||a(e,t)})},t&&(r[e]=t(r[e])))}function a(e,t){try{(n=i[e](t)).value instanceof h?Promise.resolve(n.value.v).then(u,c):l(o[0][2],n)}catch(e){l(o[0][3],e)}var n}function u(e){a("next",e)}function c(e){a("throw",e)}function l(e,t){e(t),o.shift(),o.length&&a(o[0][0],o[0][1])}}function p(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=l(e),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(n){t[n]=e[n]&&function(t){return new Promise(function(r,i){(function(e,t,n,r){Promise.resolve(r).then(function(t){e({value:t,done:n})},t)})(r,i,(t=e[n](t)).done,t.value)})}}}"function"==typeof SuppressedError&&SuppressedError;var m,y=((m=function(e){return function(t){e(this),this.message=t?t.length+" errors occurred during unsubscription:\n"+t.map(function(e,t){return t+1+") "+e.toString()}).join("\n "):"",this.name="UnsubscriptionError",this.errors=t}}(function(e){Error.call(e),e.stack=(new Error).stack})).prototype=Object.create(Error.prototype),m.prototype.constructor=m,m);function v(e,t){if(e){var n=e.indexOf(t);0<=n&&e.splice(n,1)}}var b=function(){function e(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}var t;return e.prototype.unsubscribe=function(){var e,t,n,r,o;if(!this.closed){this.closed=!0;var s=this._parentage;if(s)if(this._parentage=null,Array.isArray(s))try{for(var a=l(s),u=a.next();!u.done;u=a.next()){u.value.remove(this)}}catch(t){e={error:t}}finally{try{u&&!u.done&&(t=a.return)&&t.call(a)}finally{if(e)throw e.error}}else s.remove(this);var c=this.initialTeardown;if(i(c))try{c()}catch(e){o=e instanceof y?e.errors:[e]}var h=this._finalizers;if(h){this._finalizers=null;try{for(var f=l(h),p=f.next();!p.done;p=f.next()){var m=p.value;try{S(m)}catch(e){o=null!=o?o:[],e instanceof y?o=g(g([],d(o)),d(e.errors)):o.push(e)}}}catch(e){n={error:e}}finally{try{p&&!p.done&&(r=f.return)&&r.call(f)}finally{if(n)throw n.error}}}if(o)throw new y(o)}},e.prototype.add=function(t){var n;if(t&&t!==this)if(this.closed)S(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(n=this._finalizers)&&void 0!==n?n:[]).push(t)}},e.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},e.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},e.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&v(t,e)},e.prototype.remove=function(t){var n=this._finalizers;n&&v(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}();function _(e){return e instanceof b||e&&"closed"in e&&i(e.remove)&&i(e.add)&&i(e.unsubscribe)}function S(e){i(e)?e():e.unsubscribe()}b.EMPTY;var A={Promise:void 0},w=function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];return setTimeout.apply(void 0,g([e,t],d(n)))};function C(e){w(function(){throw e})}function I(){}var E=function(e){function t(t){var n=e.call(this)||this;return n.isStopped=!1,t?(n.destination=t,_(t)&&t.add(n)):n.destination=P,n}return a(t,e),t.create=function(e,t,n){return new R(e,t,n)},t.prototype.next=function(e){this.isStopped||this._next(e)},t.prototype.error=function(e){this.isStopped||(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t}(b),T=function(){function e(e){this.partialObserver=e}return e.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(e){x(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){x(e)}else x(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){x(e)}},e}(),R=function(e){function t(t,n,r){var o,s=e.call(this)||this;return o=i(t)||!t?{next:null!=t?t:void 0,error:null!=n?n:void 0,complete:null!=r?r:void 0}:t,s.destination=new T(o),s}return a(t,e),t}(E);function x(e){C(e)}var P={closed:!0,next:I,error:function(e){throw e},complete:I},Z="function"==typeof Symbol&&Symbol.observable||"@@observable";function O(e){return e}var N=function(){function e(e){e&&(this._subscribe=e)}return e.prototype.lift=function(t){var n=new e;return n.source=this,n.operator=t,n},e.prototype.subscribe=function(e,t,n){var r,o=this,s=(r=e)&&r instanceof E||function(e){return e&&i(e.next)&&i(e.error)&&i(e.complete)}(r)&&_(r)?e:new R(e,t,n);return function(){var e=o,t=e.operator,n=e.source;s.add(t?t.call(s,n):n?o._subscribe(s):o._trySubscribe(s))}(),s},e.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},e.prototype.forEach=function(e,t){var n=this;return new(t=k(t))(function(t,r){var i=new R({next:function(t){try{e(t)}catch(e){r(e),i.unsubscribe()}},error:r,complete:t});n.subscribe(i)})},e.prototype._subscribe=function(e){var t;return null===(t=this.source)||void 0===t?void 0:t.subscribe(e)},e.prototype[Z]=function(){return this},e.prototype.pipe=function(){for(var e,t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return(0===(e=t).length?O:1===e.length?e[0]:function(t){return e.reduce(function(e,t){return t(e)},t)})(this)},e.prototype.toPromise=function(e){var t=this;return new(e=k(e))(function(e,n){var r;t.subscribe(function(e){return r=e},function(e){return n(e)},function(){return e(r)})})},e.create=function(t){return new e(t)},e}();function k(e){var t;return null!==(t=null!=e?e:A.Promise)&&void 0!==t?t:Promise}var U="function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator";function j(e){if(e instanceof N)return e;if(null!=e){if(function(e){return i(e[Z])}(e))return a=e,new N(function(e){var t=a[Z]();if(i(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")});if((s=e)&&"number"==typeof s.length&&"function"!=typeof s)return o=e,new N(function(e){for(var t=0;t<o.length&&!e.closed;t++)e.next(o[t]);e.complete()});if(i(null==(r=e)?void 0:r.then))return n=e,new N(function(e){n.then(function(t){e.closed||(e.next(t),e.complete())},function(t){return e.error(t)}).then(null,C)});if(function(e){return Symbol.asyncIterator&&i(null==e?void 0:e[Symbol.asyncIterator])}(e))return M(e);if(function(e){return i(null==e?void 0:e[U])}(e))return t=e,new N(function(e){var n,r;try{for(var i=l(t),o=i.next();!o.done;o=i.next()){var s=o.value;if(e.next(s),e.closed)return}}catch(e){n={error:e}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}e.complete()});if(function(e){return i(null==e?void 0:e.getReader)}(e))return M(function(e){return f(this,arguments,function(){var t,n,r;return c(this,function(i){switch(i.label){case 0:t=e.getReader(),i.label=1;case 1:i.trys.push([1,,9,10]),i.label=2;case 2:return[4,h(t.read())];case 3:return n=i.sent(),r=n.value,n.done?[4,h(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,h(r)];case 6:return[4,i.sent()];case 7:return i.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}(e))}var t,n,r,o,s,a;throw function(e){return new TypeError("You provided "+(null!==e&&"object"==typeof e?"an invalid object":"'"+e+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}(e)}function M(e){return new N(function(t){(function(e,t){var n,r,i,o;return u(this,void 0,void 0,function(){var s,a;return c(this,function(u){switch(u.label){case 0:u.trys.push([0,5,6,11]),n=p(e),u.label=1;case 1:return[4,n.next()];case 2:if((r=u.sent()).done)return[3,4];if(s=r.value,t.next(s),t.closed)return[2];u.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=u.sent(),i={error:a},[3,11];case 6:return u.trys.push([6,,9,10]),r&&!r.done&&(o=n.return)?[4,o.call(n)]:[3,8];case 7:u.sent(),u.label=8;case 8:return[3,10];case 9:if(i)throw i.error;return[7];case 10:return[7];case 11:return t.complete(),[2]}})})})(e,t).catch(function(e){return t.error(e)})})}var F=function(e){function t(t,n,r,i,o,s){var a=e.call(this,t)||this;return a.onFinalize=o,a.shouldUnsubscribe=s,a._next=n?function(e){try{n(e)}catch(e){t.error(e)}}:e.prototype._next,a._error=i?function(e){try{i(e)}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._error,a._complete=r?function(){try{r()}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._complete,a}return a(t,e),t.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var n=this.closed;e.prototype.unsubscribe.call(this),!n&&(null===(t=this.onFinalize)||void 0===t||t.call(this))}},t}(E);function L(e){return o(function(t,n){var r,i,o=null,s=!1;o=t.subscribe(new F(n,void 0,void 0,function(i){r=j(e(i,L(e)(t))),o?(o.unsubscribe(),o=null,r.subscribe(n)):s=!0},i)),s&&(o.unsubscribe(),o=null,r.subscribe(n))})}function $(e){return e.pipe(L(e=>{if(function(e){return null!==e&&"object"==typeof e&&"name"in e&&"ZodError"===e.name}(e))return r.EMPTY;throw e}))}class D extends t.HttpAgent{constructor(e){var t,n,r;const i=e.runtimeUrl?e.runtimeUrl.replace(/\/$/,""):void 0,o=null!==(t=e.transport)&&void 0!==t?t:"rest",s="single"===o?null!==(n=null!=i?i:e.runtimeUrl)&&void 0!==n?n:"":`${null!=i?i:e.runtimeUrl}/agent/${encodeURIComponent(null!==(r=e.agentId)&&void 0!==r?r:"")}/run`;if(!s)throw new Error("ProxiedCopilotRuntimeAgent requires a runtimeUrl when transport is set to 'single'.");super({...e,url:s}),this.runtimeUrl=null!=i?i:e.runtimeUrl,this.credentials=e.credentials,this.transport=o,"single"===this.transport&&(this.singleEndpointUrl=this.runtimeUrl)}abortRun(){if(!this.agentId||!this.threadId)return;if("undefined"==typeof fetch)return;if("single"===this.transport){if(!this.singleEndpointUrl)return;const e=new Headers({...this.headers,"Content-Type":"application/json"});return void fetch(this.singleEndpointUrl,{method:"POST",headers:e,body:JSON.stringify({method:"agent/stop",params:{agentId:this.agentId,threadId:this.threadId}}),...this.credentials?{credentials:this.credentials}:{}}).catch(e=>{console.error("ProxiedCopilotRuntimeAgent: stop request failed",e)})}if(!this.runtimeUrl)return;const e=`${this.runtimeUrl}/agent/${encodeURIComponent(this.agentId)}/stop/${encodeURIComponent(this.threadId)}`,t="undefined"!=typeof window&&window.location?window.location.origin:"http://localhost",n=new URL(this.runtimeUrl,t),r=new URL(e,n);fetch(r.toString(),{method:"POST",headers:{"Content-Type":"application/json",...this.headers},...this.credentials?{credentials:this.credentials}:{}}).catch(e=>{console.error("ProxiedCopilotRuntimeAgent: stop request failed",e)})}connect(e){if("single"===this.transport){if(!this.singleEndpointUrl)throw new Error("Single endpoint transport requires a runtimeUrl");const n=this.createSingleRouteRequestInit(e,"agent/connect",{agentId:this.agentId}),r=t.runHttpRequest(this.singleEndpointUrl,n);return $(t.transformHttpEventStream(r))}const n=t.runHttpRequest(`${this.runtimeUrl}/agent/${this.agentId}/connect`,this.requestInit(e));return $(t.transformHttpEventStream(n))}run(e){if("single"===this.transport){if(!this.singleEndpointUrl)throw new Error("Single endpoint transport requires a runtimeUrl");const n=this.createSingleRouteRequestInit(e,"agent/run",{agentId:this.agentId}),r=t.runHttpRequest(this.singleEndpointUrl,n);return $(t.transformHttpEventStream(r))}return $(super.run(e))}clone(){const e=super.clone();return e.runtimeUrl=this.runtimeUrl,e.credentials=this.credentials,e.transport=this.transport,e.singleEndpointUrl=this.singleEndpointUrl,e}createSingleRouteRequestInit(e,t,n){var r,i;if(!this.agentId)throw new Error("ProxiedCopilotRuntimeAgent requires agentId to make runtime requests");const o=super.requestInit(e),s=new Headers(null!==(r=o.headers)&&void 0!==r?r:{});let a;if(s.set("Content-Type","application/json"),s.set("Accept",null!==(i=s.get("Accept"))&&void 0!==i?i:"text/event-stream"),"string"==typeof o.body)try{a=JSON.parse(o.body)}catch(e){console.warn("ProxiedCopilotRuntimeAgent: failed to parse request body for single route transport",e),a=void 0}const u={method:t};return n&&Object.keys(n).length>0&&(u.params=n),void 0!==a&&(u.body=a),{...o,headers:s,body:JSON.stringify(u),...this.credentials?{credentials:this.credentials}:{}}}}class z{constructor(t){this.core=t,this._agents={},this.localAgents={},this.remoteAgents={},this._runtimeConnectionStatus=e.CopilotKitCoreRuntimeConnectionStatus.Disconnected,this._runtimeTransport="rest",this._audioFileTranscriptionEnabled=!1}get agents(){return this._agents}get runtimeUrl(){return this._runtimeUrl}get runtimeVersion(){return this._runtimeVersion}get runtimeConnectionStatus(){return this._runtimeConnectionStatus}get runtimeTransport(){return this._runtimeTransport}get audioFileTranscriptionEnabled(){return this._audioFileTranscriptionEnabled}initialize(e){this.localAgents=this.assignAgentIds(e),this.applyHeadersToAgents(this.localAgents),this._agents=this.localAgents}setRuntimeUrl(e){const t=e?e.replace(/\/$/,""):void 0;this._runtimeUrl!==t&&(this._runtimeUrl=t,this.updateRuntimeConnection())}setRuntimeTransport(e){this._runtimeTransport!==e&&(this._runtimeTransport=e,this.updateRuntimeConnection())}setAgents__unsafe_dev_only(e){Object.entries(e).forEach(([e,t])=>{t&&this.validateAndAssignAgentId(e,t)}),this.localAgents=e,this._agents={...this.localAgents,...this.remoteAgents},this.applyHeadersToAgents(this._agents),this.notifyAgentsChanged()}addAgent__unsafe_dev_only({id:e,agent:t}){this.validateAndAssignAgentId(e,t),this.localAgents[e]=t,this.applyHeadersToAgent(t),this._agents={...this.localAgents,...this.remoteAgents},this.notifyAgentsChanged()}removeAgent__unsafe_dev_only(e){delete this.localAgents[e],this._agents={...this.localAgents,...this.remoteAgents},this.notifyAgentsChanged()}getAgent(t){if(t in this._agents)return this._agents[t];(void 0===this.runtimeUrl||this.runtimeConnectionStatus!==e.CopilotKitCoreRuntimeConnectionStatus.Disconnected&&this.runtimeConnectionStatus!==e.CopilotKitCoreRuntimeConnectionStatus.Connecting)&&console.warn(`Agent ${t} not found`)}applyHeadersToAgent(e){e instanceof t.HttpAgent&&(e.headers={...this.core.headers})}applyHeadersToAgents(e){Object.values(e).forEach(e=>{this.applyHeadersToAgent(e)})}applyCredentialsToAgent(e){e instanceof D&&(e.credentials=this.core.credentials)}applyCredentialsToAgents(e){Object.values(e).forEach(e=>{this.applyCredentialsToAgent(e)})}async updateRuntimeConnection(){var t;if("undefined"!=typeof window){if(!this.runtimeUrl)return this._runtimeConnectionStatus=e.CopilotKitCoreRuntimeConnectionStatus.Disconnected,this._runtimeVersion=void 0,this._audioFileTranscriptionEnabled=!1,this.remoteAgents={},this._agents=this.localAgents,await this.notifyRuntimeStatusChanged(e.CopilotKitCoreRuntimeConnectionStatus.Disconnected),void await this.notifyAgentsChanged();this._runtimeConnectionStatus=e.CopilotKitCoreRuntimeConnectionStatus.Connecting,await this.notifyRuntimeStatusChanged(e.CopilotKitCoreRuntimeConnectionStatus.Connecting);try{const n=await this.fetchRuntimeInfo(),{version:r,...i}=n,o=this.core.credentials,s=Object.fromEntries(Object.entries(i.agents).map(([e,{description:t}])=>{const n=new D({runtimeUrl:this.runtimeUrl,agentId:e,description:t,transport:this._runtimeTransport,credentials:o});return this.applyHeadersToAgent(n),[e,n]}));this.remoteAgents=s,this._agents={...this.localAgents,...this.remoteAgents},this._runtimeConnectionStatus=e.CopilotKitCoreRuntimeConnectionStatus.Connected,this._runtimeVersion=r,this._audioFileTranscriptionEnabled=null!==(t=n.audioFileTranscriptionEnabled)&&void 0!==t&&t,await this.notifyRuntimeStatusChanged(e.CopilotKitCoreRuntimeConnectionStatus.Connected),await this.notifyAgentsChanged()}catch(t){this._runtimeConnectionStatus=e.CopilotKitCoreRuntimeConnectionStatus.Error,this._runtimeVersion=void 0,this._audioFileTranscriptionEnabled=!1,this.remoteAgents={},this._agents=this.localAgents,await this.notifyRuntimeStatusChanged(e.CopilotKitCoreRuntimeConnectionStatus.Error),await this.notifyAgentsChanged();const r=t instanceof Error?t.message:JSON.stringify(t);n.logger.warn(`Failed to load runtime info (${this.runtimeUrl}/info): ${r}`);const i=t instanceof Error?t:new Error(String(t));await this.core.emitError({error:i,code:e.CopilotKitCoreErrorCode.RUNTIME_INFO_FETCH_FAILED,context:{runtimeUrl:this.runtimeUrl}})}}}async fetchRuntimeInfo(){if(!this.runtimeUrl)throw new Error("Runtime URL is not set");const e=this.core.headers,t=this.core.credentials,n={...e};if("single"===this._runtimeTransport){n["Content-Type"]||(n["Content-Type"]="application/json");const e=await fetch(this.runtimeUrl,{method:"POST",headers:n,body:JSON.stringify({method:"info"}),...t?{credentials:t}:{}});if("ok"in e&&!e.ok)throw new Error(`Runtime info request failed with status ${e.status}`);return await e.json()}const r=await fetch(`${this.runtimeUrl}/info`,{headers:n,...t?{credentials:t}:{}});if("ok"in r&&!r.ok)throw new Error(`Runtime info request failed with status ${r.status}`);return await r.json()}assignAgentIds(e){return Object.entries(e).forEach(([e,t])=>{t&&this.validateAndAssignAgentId(e,t)}),e}validateAndAssignAgentId(e,t){if(t.agentId&&t.agentId!==e)throw new Error(`Agent registration mismatch: Agent with ID "${t.agentId}" cannot be registered under key "${e}". The agent ID must match the registration key or be undefined.`);t.agentId||(t.agentId=e)}async notifyRuntimeStatusChanged(e){await this.core.notifySubscribers(t=>{var n;return null===(n=t.onRuntimeConnectionStatusChanged)||void 0===n?void 0:n.call(t,{copilotkit:this.core,status:e})},"Error in CopilotKitCore subscriber (onRuntimeConnectionStatusChanged):")}async notifyAgentsChanged(){await this.core.notifySubscribers(e=>{var t;return null===(t=e.onAgentsChanged)||void 0===t?void 0:t.call(e,{copilotkit:this.core,agents:this._agents})},"Subscriber onAgentsChanged error:")}}class H{constructor(e){this.core=e,this._context={}}get context(){return this._context}addContext({description:e,value:t}){const r=n.randomUUID();return this._context[r]={description:e,value:t},this.notifySubscribers(),r}removeContext(e){delete this._context[e],this.notifySubscribers()}async notifySubscribers(){await this.core.notifySubscribers(e=>{var t;return null===(t=e.onContextChanged)||void 0===t?void 0:t.call(e,{copilotkit:this.core,context:this._context})},"Subscriber onContextChanged error:")}}class K{constructor(e){this.core=e,this._suggestionsConfig={},this._suggestions={},this._runningSuggestions={}}initialize(e){for(const t of e)this._suggestionsConfig[n.randomUUID()]=t}addSuggestionsConfig(e){const t=n.randomUUID();return this._suggestionsConfig[t]=e,this.notifySuggestionsConfigChanged(),t}removeSuggestionsConfig(e){delete this._suggestionsConfig[e],this.notifySuggestionsConfigChanged()}reloadSuggestions(e){var t,r;this.clearSuggestions(e);const i=this.core.getAgent(e);if(!i)return;const o=null!==(r=null===(t=i.messages)||void 0===t?void 0:t.length)&&void 0!==r?r:0;let s=!1;for(const t of Object.values(this._suggestionsConfig)){if(void 0!==t.consumerAgentId&&"*"!==t.consumerAgentId&&t.consumerAgentId!==e)continue;if(!this.shouldShowSuggestions(t,o))continue;const r=n.randomUUID();q(t)?(s||(s=!0,this.notifySuggestionsStartedLoading(e)),this.generateSuggestions(r,t,e)):B(t)&&this.addStaticSuggestions(r,t,e)}}clearSuggestions(e){const t=this._runningSuggestions[e];if(t){for(const e of t)e.abortRun();delete this._runningSuggestions[e]}this._suggestions[e]={},this.notifySuggestionsChanged(e,[])}getSuggestions(e){var t,n,r;return{suggestions:Object.values(null!==(t=this._suggestions[e])&&void 0!==t?t:{}).flat(),isLoading:(null!==(r=null===(n=this._runningSuggestions[e])||void 0===n?void 0:n.length)&&void 0!==r?r:0)>0}}async generateSuggestions(e,t,n){var r,i,o,s,a;let u;try{const c=this.core.getAgent(null!==(r=t.providerAgentId)&&void 0!==r?r:"default");if(!c)throw new Error(`Suggestions provider agent not found: ${t.providerAgentId}`);const l=this.core.getAgent(n);if(!l)throw new Error(`Suggestions consumer agent not found: ${n}`);const d=c.clone();u=d,u.threadId=e,u.messages=JSON.parse(JSON.stringify(l.messages)),u.state=JSON.parse(JSON.stringify(l.state)),this._suggestions[n]={...null!==(i=this._suggestions[n])&&void 0!==i?i:{},[e]:[]},this._runningSuggestions[n]=[...null!==(o=this._runningSuggestions[n])&&void 0!==o?o:[],u],u.addMessage({id:e,role:"user",content:["Suggest what the user could say next. Provide clear, highly relevant suggestions by calling the `copilotkitSuggest` tool.",`Provide at least ${null!==(s=t.minSuggestions)&&void 0!==s?s:1} and at most ${null!==(a=t.maxSuggestions)&&void 0!==a?a:3} suggestions.`,`The user has the following tools available: ${JSON.stringify(this.core.buildFrontendTools(n))}.`,` ${t.instructions}`].join("\n")}),await u.runAgent({context:Object.values(this.core.context),forwardedProps:{...this.core.properties,toolChoice:{type:"function",function:{name:"copilotkitSuggest"}}},tools:[J]},{onMessagesChanged:({messages:t})=>{this.extractSuggestions(t,e,n,!0)}})}catch(e){console.warn("Error generating suggestions:",e)}finally{this.finalizeSuggestions(e,n);const t=this._runningSuggestions[n];if(u&&t){const e=t.filter(e=>e!==u);this._runningSuggestions[n]=e,0===e.length&&(delete this._runningSuggestions[n],await this.notifySuggestionsFinishedLoading(n))}}}finalizeSuggestions(e,t){var n;const r=this._suggestions[t],i=null==r?void 0:r[e];if(r&&i&&i.length>0){const o=i.filter(e=>""!==e.title||""!==e.message).map(e=>({...e,isLoading:!1}));o.length>0?r[e]=o:delete r[e];const s=Object.values(null!==(n=this._suggestions[t])&&void 0!==n?n:{}).flat();this.notifySuggestionsChanged(t,s,"finalized")}}extractSuggestions(e,t,r,i){var o,s,a;const u=e.findIndex(e=>e.id===t);if(-1==u)return;const c=[],l=e.slice(u+1);for(const e of l)if("assistant"===e.role&&e.toolCalls)for(const t of e.toolCalls)if("copilotkitSuggest"===t.function.name){const e=Array.isArray(t.function.arguments)?t.function.arguments.join(""):t.function.arguments,r=n.partialJSONParse(e);if(r&&"object"==typeof r&&"suggestions"in r){const e=r.suggestions;if(Array.isArray(e))for(const t of e)t&&"object"==typeof t&&"title"in t&&c.push({title:null!==(o=t.title)&&void 0!==o?o:"",message:null!==(s=t.message)&&void 0!==s?s:"",isLoading:!1})}}i&&c.length>0&&(c[c.length-1].isLoading=!0);const d=this._suggestions[r];if(d){d[t]=c;const e=Object.values(null!==(a=this._suggestions[r])&&void 0!==a?a:{}).flat();this.notifySuggestionsChanged(r,e,"suggestions changed")}}async notifySuggestionsConfigChanged(){await this.core.notifySubscribers(e=>{var t;return null===(t=e.onSuggestionsConfigChanged)||void 0===t?void 0:t.call(e,{copilotkit:this.core,suggestionsConfig:this._suggestionsConfig})},"Subscriber onSuggestionsConfigChanged error:")}async notifySuggestionsChanged(e,t,n=""){await this.core.notifySubscribers(n=>{var r;return null===(r=n.onSuggestionsChanged)||void 0===r?void 0:r.call(n,{copilotkit:this.core,agentId:e,suggestions:t})},`Subscriber onSuggestionsChanged error: ${n}`)}async notifySuggestionsStartedLoading(e){await this.core.notifySubscribers(t=>{var n;return null===(n=t.onSuggestionsStartedLoading)||void 0===n?void 0:n.call(t,{copilotkit:this.core,agentId:e})},"Subscriber onSuggestionsStartedLoading error:")}async notifySuggestionsFinishedLoading(e){await this.core.notifySubscribers(t=>{var n;return null===(n=t.onSuggestionsFinishedLoading)||void 0===n?void 0:n.call(t,{copilotkit:this.core,agentId:e})},"Subscriber onSuggestionsFinishedLoading error:")}shouldShowSuggestions(e,t){const n=e.available;if(!n)return q(e)?t>0:0===t;switch(n){case"disabled":default:return!1;case"before-first-message":return 0===t;case"after-first-message":return t>0;case"always":return!0}}addStaticSuggestions(e,t,n){var r,i;const o=t.suggestions.map(e=>({...e,isLoading:!1}));this._suggestions[n]={...null!==(r=this._suggestions[n])&&void 0!==r?r:{},[e]:o};const s=Object.values(null!==(i=this._suggestions[n])&&void 0!==i?i:{}).flat();this.notifySuggestionsChanged(n,s,"static suggestions added")}}function q(e){return"instructions"in e}function B(e){return"suggestions"in e}const J={name:"copilotkitSuggest",description:"Suggest what the user could say next",parameters:{type:"object",properties:{suggestions:{type:"array",description:"List of suggestions shown to the user as buttons.",items:{type:"object",properties:{title:{type:"string",description:"The title of the suggestion. This is shown as a button and should be short."},message:{type:"string",description:"The message to send when the suggestion is clicked. This should be a clear, complete sentence and will be sent as an instruction to the AI."}},required:["title","message"]}}},required:["suggestions"]}},V=Symbol("Let zodToJsonSchema decide on which parser to use"),G={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},W=e=>{const t=(e=>"string"==typeof e?{...G,name:e}:{...G,...e})(e),n=void 0!==t.name?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function Y(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function Q(e,t,n,r,i){e[t]=n,Y(e,t,r,i)}const X=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join("/")};var ee;function te(e){if("openAi"!==e.target)return{};const t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:"relative"===e.$refStrategy?X(t,e.currentPath):t.join("/")}}function ne(e,t){return xe(e.type._def,t)}!function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(ee||(ee={}));function re(e,t,n){const r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>re(e,t,n))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return ie(e,t)}}const ie=(e,t)=>{const n={type:"integer",format:"unix-time"};if("openApi3"===t.target)return n;for(const r of e.checks)switch(r.kind){case"min":Q(n,"minimum",r.value,r.message,t);break;case"max":Q(n,"maximum",r.value,r.message,t)}return n};let oe;const se=/^[cC][^\s-]{8,}$/,ae=/^[0-9a-z]+$/,ue=/^[0-9A-HJKMNP-TV-Z]{26}$/,ce=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,le=()=>(void 0===oe&&(oe=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),oe),de=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ge=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,he=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,fe=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,pe=/^[a-zA-Z0-9_-]{21}$/,me=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;function ye(e,t){const n={type:"string"};if(e.checks)for(const r of e.checks)switch(r.kind){case"min":Q(n,"minLength","number"==typeof n.minLength?Math.max(n.minLength,r.value):r.value,r.message,t);break;case"max":Q(n,"maxLength","number"==typeof n.maxLength?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case"email":switch(t.emailStrategy){case"format:email":_e(n,"email",r.message,t);break;case"format:idn-email":_e(n,"idn-email",r.message,t);break;case"pattern:zod":Se(n,ce,r.message,t)}break;case"url":_e(n,"uri",r.message,t);break;case"uuid":_e(n,"uuid",r.message,t);break;case"regex":Se(n,r.regex,r.message,t);break;case"cuid":Se(n,se,r.message,t);break;case"cuid2":Se(n,ae,r.message,t);break;case"startsWith":Se(n,RegExp(`^${ve(r.value,t)}`),r.message,t);break;case"endsWith":Se(n,RegExp(`${ve(r.value,t)}$`),r.message,t);break;case"datetime":_e(n,"date-time",r.message,t);break;case"date":_e(n,"date",r.message,t);break;case"time":_e(n,"time",r.message,t);break;case"duration":_e(n,"duration",r.message,t);break;case"length":Q(n,"minLength","number"==typeof n.minLength?Math.max(n.minLength,r.value):r.value,r.message,t),Q(n,"maxLength","number"==typeof n.maxLength?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case"includes":Se(n,RegExp(ve(r.value,t)),r.message,t);break;case"ip":"v6"!==r.version&&_e(n,"ipv4",r.message,t),"v4"!==r.version&&_e(n,"ipv6",r.message,t);break;case"base64url":Se(n,fe,r.message,t);break;case"jwt":Se(n,me,r.message,t);break;case"cidr":"v6"!==r.version&&Se(n,de,r.message,t),"v4"!==r.version&&Se(n,ge,r.message,t);break;case"emoji":Se(n,le(),r.message,t);break;case"ulid":Se(n,ue,r.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":_e(n,"binary",r.message,t);break;case"contentEncoding:base64":Q(n,"contentEncoding","base64",r.message,t);break;case"pattern:zod":Se(n,he,r.message,t)}break;case"nanoid":Se(n,pe,r.message,t)}return n}function ve(e,t){return"escape"===t.patternStrategy?function(e){let t="";for(let n=0;n<e.length;n++)be.has(e[n])||(t+="\\"),t+=e[n];return t}(e):e}const be=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function _e(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):Q(e,"format",t,n,r)}function Se(e,t,n,r){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.allOf.push({pattern:Ae(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):Q(e,"pattern",Ae(t,r),n,r)}function Ae(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;const n=e.flags.includes("i"),r=e.flags.includes("m"),i=e.flags.includes("s"),o=n?e.source.toLowerCase():e.source;let s="",a=!1,u=!1,c=!1;for(let e=0;e<o.length;e++)if(a)s+=o[e],a=!1;else{if(n)if(u){if(o[e].match(/[a-z]/)){c?(s+=o[e],s+=`${o[e-2]}-${o[e]}`.toUpperCase(),c=!1):"-"===o[e+1]&&o[e+2]?.match(/[a-z]/)?(s+=o[e],c=!0):s+=`${o[e]}${o[e].toUpperCase()}`;continue}}else if(o[e].match(/[a-z]/)){s+=`[${o[e]}${o[e].toUpperCase()}]`;continue}if(r){if("^"===o[e]){s+="(^|(?<=[\r\n]))";continue}if("$"===o[e]){s+="($|(?=[\r\n]))";continue}}i&&"."===o[e]?s+=u?`${o[e]}\r\n`:`[${o[e]}\r\n]`:(s+=o[e],"\\"===o[e]?a=!0:u&&"]"===o[e]?u=!1:u||"["!==o[e]||(u=!0))}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return s}function we(e,t){if("openAi"===t.target&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),"openApi3"===t.target&&e.keyType?._def.typeName===ee.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:xe(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",r]})??te(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const n={type:"object",additionalProperties:xe(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if("openApi3"===t.target)return n;if(e.keyType?._def.typeName===ee.ZodString&&e.keyType._def.checks?.length){const{type:r,...i}=ye(e.keyType._def,t);return{...n,propertyNames:i}}if(e.keyType?._def.typeName===ee.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===ee.ZodBranded&&e.keyType._def.type._def.typeName===ee.ZodString&&e.keyType._def.type._def.checks?.length){const{type:r,...i}=ne(e.keyType._def,t);return{...n,propertyNames:i}}return n}const Ce={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};const Ie=(e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>xe(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${n}`]})).filter(e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function Ee(e,t){const n="openAi"===t.target,r={type:"object",properties:{}},i=[],o=e.shape();for(const e in o){let s=o[e];if(void 0===s||void 0===s._def)continue;let a=Te(s);a&&n&&("ZodOptional"===s._def.typeName&&(s=s._def.innerType),s.isNullable()||(s=s.nullable()),a=!1);const u=xe(s._def,{...t,currentPath:[...t.currentPath,"properties",e],propertyPath:[...t.currentPath,"properties",e]});void 0!==u&&(r.properties[e]=u,a||i.push(e))}i.length&&(r.required=i);const s=function(e,t){if("ZodNever"!==e.catchall._def.typeName)return xe(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return"strict"===t.removeAdditionalStrategy?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}(e,t);return void 0!==s&&(r.additionalProperties=s),r}function Te(e){try{return e.isOptional()}catch{return!0}}const Re=(e,t,n)=>{switch(t){case ee.ZodString:return ye(e,n);case ee.ZodNumber:return function(e,t){const n={type:"number"};if(!e.checks)return n;for(const r of e.checks)switch(r.kind){case"int":n.type="integer",Y(n,"type",r.message,t);break;case"min":"jsonSchema7"===t.target?r.inclusive?Q(n,"minimum",r.value,r.message,t):Q(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),Q(n,"minimum",r.value,r.message,t));break;case"max":"jsonSchema7"===t.target?r.inclusive?Q(n,"maximum",r.value,r.message,t):Q(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),Q(n,"maximum",r.value,r.message,t));break;case"multipleOf":Q(n,"multipleOf",r.value,r.message,t)}return n}(e,n);case ee.ZodObject:return Ee(e,n);case ee.ZodBigInt:return function(e,t){const n={type:"integer",format:"int64"};if(!e.checks)return n;for(const r of e.checks)switch(r.kind){case"min":"jsonSchema7"===t.target?r.inclusive?Q(n,"minimum",r.value,r.message,t):Q(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),Q(n,"minimum",r.value,r.message,t));break;case"max":"jsonSchema7"===t.target?r.inclusive?Q(n,"maximum",r.value,r.message,t):Q(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),Q(n,"maximum",r.value,r.message,t));break;case"multipleOf":Q(n,"multipleOf",r.value,r.message,t)}return n}(e,n);case ee.ZodBoolean:return{type:"boolean"};case ee.ZodDate:return re(e,n);case ee.ZodUndefined:return function(e){return{not:te(e)}}(n);case ee.ZodNull:return function(e){return"openApi3"===e.target?{enum:["null"],nullable:!0}:{type:"null"}}(n);case ee.ZodArray:return function(e,t){const n={type:"array"};return e.type?._def&&e.type?._def?.typeName!==ee.ZodAny&&(n.items=xe(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&Q(n,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&Q(n,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(Q(n,"minItems",e.exactLength.value,e.exactLength.message,t),Q(n,"maxItems",e.exactLength.value,e.exactLength.message,t)),n}(e,n);case ee.ZodUnion:case ee.ZodDiscriminatedUnion:return function(e,t){if("openApi3"===t.target)return Ie(e,t);const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in Ce&&(!e._def.checks||!e._def.checks.length))){const e=n.reduce((e,t)=>{const n=Ce[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}if(n.every(e=>"ZodLiteral"===e._def.typeName&&!e.description)){const e=n.reduce((e,t)=>{const n=typeof t._def.value;switch(n){case"string":case"number":case"boolean":return[...e,n];case"bigint":return[...e,"integer"];case"object":if(null===t._def.value)return[...e,"null"];default:return e}},[]);if(e.length===n.length){const t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>"ZodEnum"===e._def.typeName))return{type:"string",enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return Ie(e,t)}(e,n);case ee.ZodIntersection:return function(e,t){const n=[xe(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),xe(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(e=>!!e);let r="jsonSchema2019-09"===t.target?{unevaluatedProperties:!1}:void 0;const i=[];return n.forEach(e=>{if("type"in(t=e)&&"string"===t.type||!("allOf"in t)){let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){const{additionalProperties:n,...r}=e;t=r}else r=void 0;i.push(t)}else i.push(...e.allOf),void 0===e.unevaluatedProperties&&(r=void 0);var t}),i.length?{allOf:i,...r}:void 0}(e,n);case ee.ZodTuple:return function(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((e,n)=>xe(e._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[]),additionalItems:xe(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>xe(e._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[])}}(e,n);case ee.ZodRecord:return we(e,n);case ee.ZodLiteral:return function(e,t){const n=typeof e.value;return"bigint"!==n&&"number"!==n&&"boolean"!==n&&"string"!==n?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===t.target?{type:"bigint"===n?"integer":n,enum:[e.value]}:{type:"bigint"===n?"integer":n,const:e.value}}(e,n);case ee.ZodEnum:return function(e){return{type:"string",enum:Array.from(e.values)}}(e);case ee.ZodNativeEnum:return function(e){const t=e.values,n=Object.keys(e.values).filter(e=>"number"!=typeof t[t[e]]).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:1===r.length?"string"===r[0]?"string":"number":["string","number"],enum:n}}(e);case ee.ZodNullable:return function(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return"openApi3"===t.target?{type:Ce[e.innerType._def.typeName],nullable:!0}:{type:[Ce[e.innerType._def.typeName],"null"]};if("openApi3"===t.target){const n=xe(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const n=xe(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}(e,n);case ee.ZodOptional:return((e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return xe(e.innerType._def,t);const n=xe(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:te(t)},n]}:te(t)})(e,n);case ee.ZodMap:return function(e,t){return"record"===t.mapStrategy?we(e,t):{type:"array",maxItems:125,items:{type:"array",items:[xe(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||te(t),xe(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||te(t)],minItems:2,maxItems:2}}}(e,n);case ee.ZodSet:return function(e,t){const n={type:"array",uniqueItems:!0,items:xe(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&Q(n,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&Q(n,"maxItems",e.maxSize.value,e.maxSize.message,t),n}(e,n);case ee.ZodLazy:return()=>e.getter()._def;case ee.ZodPromise:return function(e,t){return xe(e.type._def,t)}(e,n);case ee.ZodNaN:case ee.ZodNever:return function(e){return"openAi"===e.target?void 0:{not:te({...e,currentPath:[...e.currentPath,"not"]})}}(n);case ee.ZodEffects:return function(e,t){return"input"===t.effectStrategy?xe(e.schema._def,t):te(t)}(e,n);case ee.ZodAny:return te(n);case ee.ZodUnknown:return function(e){return te(e)}(n);case ee.ZodDefault:return function(e,t){return{...xe(e.innerType._def,t),default:e.defaultValue()}}(e,n);case ee.ZodBranded:return ne(e,n);case ee.ZodReadonly:case ee.ZodCatch:return((e,t)=>xe(e.innerType._def,t))(e,n);case ee.ZodPipeline:return((e,t)=>{if("input"===t.pipeStrategy)return xe(e.in._def,t);if("output"===t.pipeStrategy)return xe(e.out._def,t);const n=xe(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]});return{allOf:[n,xe(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]})].filter(e=>void 0!==e)}})(e,n);case ee.ZodFunction:case ee.ZodVoid:case ee.ZodSymbol:default:return}};function xe(e,t,n=!1){const r=t.seen.get(e);if(t.override){const i=t.override?.(e,t,r,n);if(i!==V)return i}if(r&&!n){const e=Pe(r,t);if(void 0!==e)return e}const i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);const o=Re(e,e.typeName,t),s="function"==typeof o?xe(o(),t):o;if(s&&Ze(e,t,s),t.postProcess){const n=t.postProcess(s,e,t);return i.jsonSchema=s,n}return i.jsonSchema=s,s}const Pe=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:X(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),te(t)):"seen"===t.$refStrategy?te(t):void 0}},Ze=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n);class Oe{constructor(e){this.core=e,this._tools=[]}get tools(){return this._tools}initialize(e){this._tools=e}addTool(e){-1===this._tools.findIndex(t=>t.name===e.name&&t.agentId===e.agentId)?this._tools.push(e):n.logger.warn(`Tool already exists: '${e.name}' for agent '${e.agentId||"global"}', skipping.`)}removeTool(e,t){this._tools=this._tools.filter(n=>void 0!==t?!(n.name===e&&n.agentId===t):!(n.name===e&&!n.agentId))}getTool(e){const{toolName:t,agentId:n}=e;if(n){const e=this._tools.find(e=>e.name===t&&e.agentId===n);if(e)return e}return this._tools.find(e=>e.name===t&&!e.agentId)}setTools(e){this._tools=[...e]}async connectAgent({agent:n}){try{await n.detachActiveRun(),n.setMessages([]),n.setState({}),n instanceof t.HttpAgent&&(n.headers={...this.core.headers});const e=await n.connectAgent({forwardedProps:this.core.properties,tools:this.buildFrontendTools(n.agentId)},this.createAgentErrorSubscriber(n));return this.processAgentResult({runAgentResult:e,agent:n})}catch(t){const r=t instanceof Error?t:new Error(String(t)),i={};throw n.agentId&&(i.agentId=n.agentId),await this.core.emitError({error:r,code:e.CopilotKitCoreErrorCode.AGENT_CONNECT_FAILED,context:i}),t}}async runAgent({agent:n}){n.agentId&&this.core.suggestionEngine.clearSuggestions(n.agentId),n instanceof t.HttpAgent&&(n.headers={...this.core.headers});try{const e=await n.runAgent({forwardedProps:this.core.properties,tools:this.buildFrontendTools(n.agentId),context:Object.values(this.core.context)},this.createAgentErrorSubscriber(n));return this.processAgentResult({runAgentResult:e,agent:n})}catch(t){const r=t instanceof Error?t:new Error(String(t)),i={};throw n.agentId&&(i.agentId=n.agentId),await this.core.emitError({error:r,code:e.CopilotKitCoreErrorCode.AGENT_RUN_FAILED,context:i}),t}}async processAgentResult({runAgentResult:e,agent:t}){const{newMessages:n}=e,r=t.agentId;let i=!1;for(const e of n)if("assistant"===e.role)for(const o of e.toolCalls||[])if(-1===n.findIndex(e=>"tool"===e.role&&e.toolCallId===o.id)){const n=this.getTool({toolName:o.function.name,agentId:t.agentId});if(n){await this.executeSpecificTool(n,o,e,t,r)&&(i=!0)}else{const n=this.getTool({toolName:"*",agentId:t.agentId});if(n){await this.executeWildcardTool(n,o,e,t,r)&&(i=!0)}}}return i?await this.runAgent({agent:t}):(this.core.suggestionEngine.reloadSuggestions(r),e)}async executeSpecificTool(t,r,i,o,s){if((null==t?void 0:t.agentId)&&t.agentId!==o.agentId)return!1;let a,u="",c=!1;if(null==t?void 0:t.handler){let n;try{n=JSON.parse(r.function.arguments)}catch(t){const n=t instanceof Error?t:new Error(String(t));a=n.message,c=!0,await this.core.emitError({error:n,code:e.CopilotKitCoreErrorCode.TOOL_ARGUMENT_PARSE_FAILED,context:{agentId:s,toolCallId:r.id,toolName:r.function.name,rawArguments:r.function.arguments,toolType:"specific",messageId:i.id}})}if(await this.core.notifySubscribers(e=>{var t;return null===(t=e.onToolExecutionStart)||void 0===t?void 0:t.call(e,{copilotkit:this.core,toolCallId:r.id,agentId:s,toolName:r.function.name,args:n})},"Subscriber onToolExecutionStart error:"),!a)try{const e=await t.handler(n,{toolCall:r,agent:o});u=null==e?"":"string"==typeof e?e:JSON.stringify(e)}catch(t){const o=t instanceof Error?t:new Error(String(t));a=o.message,await this.core.emitError({error:o,code:e.CopilotKitCoreErrorCode.TOOL_HANDLER_FAILED,context:{agentId:s,toolCallId:r.id,toolName:r.function.name,parsedArgs:n,toolType:"specific",messageId:i.id}})}if(a&&(u=`Error: ${a}`),await this.core.notifySubscribers(e=>{var t;return null===(t=e.onToolExecutionEnd)||void 0===t?void 0:t.call(e,{copilotkit:this.core,toolCallId:r.id,agentId:s,toolName:r.function.name,result:a?"":u,error:a})},"Subscriber onToolExecutionEnd error:"),c)throw new Error(null!=a?a:"Tool execution failed")}if(!a||!c){const e=o.messages.findIndex(e=>e.id===i.id);if(-1===e)return!1;const s={id:n.randomUUID(),role:"tool",toolCallId:r.id,content:u};if(o.messages.splice(e+1,0,s),!a&&!1!==(null==t?void 0:t.followUp))return!0}return!1}async executeWildcardTool(t,r,i,o,s){if((null==t?void 0:t.agentId)&&t.agentId!==o.agentId)return!1;let a,u="",c=!1;if(null==t?void 0:t.handler){let n;try{n=JSON.parse(r.function.arguments)}catch(t){const n=t instanceof Error?t:new Error(String(t));a=n.message,c=!0,await this.core.emitError({error:n,code:e.CopilotKitCoreErrorCode.TOOL_ARGUMENT_PARSE_FAILED,context:{agentId:s,toolCallId:r.id,toolName:r.function.name,rawArguments:r.function.arguments,toolType:"wildcard",messageId:i.id}})}const l={toolName:r.function.name,args:n};if(await this.core.notifySubscribers(e=>{var t;return null===(t=e.onToolExecutionStart)||void 0===t?void 0:t.call(e,{copilotkit:this.core,toolCallId:r.id,agentId:s,toolName:r.function.name,args:l})},"Subscriber onToolExecutionStart error:"),!a)try{const e=await t.handler(l,{toolCall:r,agent:o});u=null==e?"":"string"==typeof e?e:JSON.stringify(e)}catch(t){const n=t instanceof Error?t:new Error(String(t));a=n.message,await this.core.emitError({error:n,code:e.CopilotKitCoreErrorCode.TOOL_HANDLER_FAILED,context:{agentId:s,toolCallId:r.id,toolName:r.function.name,parsedArgs:l,toolType:"wildcard",messageId:i.id}})}if(a&&(u=`Error: ${a}`),await this.core.notifySubscribers(e=>{var t;return null===(t=e.onToolExecutionEnd)||void 0===t?void 0:t.call(e,{copilotkit:this.core,toolCallId:r.id,agentId:s,toolName:r.function.name,result:a?"":u,error:a})},"Subscriber onToolExecutionEnd error:"),c)throw new Error(null!=a?a:"Tool execution failed")}if(!a||!c){const e=o.messages.findIndex(e=>e.id===i.id);if(-1===e)return!1;const s={id:n.randomUUID(),role:"tool",toolCallId:r.id,content:u};if(o.messages.splice(e+1,0,s),!a&&!1!==(null==t?void 0:t.followUp))return!0}return!1}buildFrontendTools(e){return this._tools.filter(t=>!t.agentId||t.agentId===e).map(e=>{var t;return{name:e.name,description:null!==(t=e.description)&&void 0!==t?t:"",parameters:ke(e)}})}createAgentErrorSubscriber(t){const n=async(e,n,r={})=>{const i={...r};t.agentId&&(i.agentId=t.agentId),await this.core.emitError({error:e,code:n,context:i})};return{onRunFailed:async({error:t})=>{await n(t,e.CopilotKitCoreErrorCode.AGENT_RUN_FAILED_EVENT,{source:"onRunFailed"})},onRunErrorEvent:async({event:t})=>{var r,i,o;const s=(null==t?void 0:t.rawEvent)instanceof Error?t.rawEvent:(null===(r=null==t?void 0:t.rawEvent)||void 0===r?void 0:r.error)instanceof Error?t.rawEvent.error:void 0,a="string"==typeof(null===(i=null==t?void 0:t.rawEvent)||void 0===i?void 0:i.error)?t.rawEvent.error:null!==(o=null==t?void 0:t.message)&&void 0!==o?o:"Agent run error",u=null!=s?s:new Error(a);(null==t?void 0:t.code)&&!u.code&&(u.code=t.code),await n(u,e.CopilotKitCoreErrorCode.AGENT_RUN_ERROR_EVENT,{source:"onRunErrorEvent",event:t,runtimeErrorCode:null==t?void 0:t.code})}}}}const Ne={type:"object",properties:{}};function ke(e){if(!e.parameters)return{...Ne};const t=((e,t)=>{const n=W(t);let r="object"==typeof t&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:xe(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??te(n)}),{}):void 0;const i="string"==typeof t?t:"title"===t?.nameStrategy?void 0:t?.name,o=xe(e._def,void 0===i?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??te(n),s="object"==typeof t&&void 0!==t.name&&"title"===t.nameStrategy?t.name:void 0;void 0!==s&&(o.title=s),n.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:"relative"===n.$refStrategy?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));const a=void 0===i?r?{...o,[n.definitionPath]:r}:o:{$ref:[..."relative"===n.$refStrategy?[]:n.basePath,n.definitionPath,i].join("/"),[n.definitionPath]:{...r,[i]:o}};return"jsonSchema7"===n.target?a.$schema="http://json-schema.org/draft-07/schema#":"jsonSchema2019-09"!==n.target&&"openAi"!==n.target||(a.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===n.target&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a})(e.parameters,{$refStrategy:"none"});if(!t||"object"!=typeof t)return{...Ne};const{$schema:n,...r}=t;return"string"!=typeof r.type&&(r.type="object"),"object"==typeof r.properties&&null!==r.properties||(r.properties={}),Ue(r),r}function Ue(e){if(!e||"object"!=typeof e)return;if(Array.isArray(e))return void e.forEach(Ue);const t=e;void 0!==t.additionalProperties&&delete t.additionalProperties;for(const e of Object.values(t))Ue(e)}class je{constructor(e){this.core=e,this.stateByRun=new Map,this.messageToRun=new Map,this.agentSubscriptions=new Map}initialize(){}subscribeToAgent(e){if(!e.agentId)return;const t=e.agentId;this.unsubscribeFromAgent(t);const{unsubscribe:n}=e.subscribe({onRunStartedEvent:({event:t,state:n})=>{this.handleRunStarted(e,t,n)},onRunFinishedEvent:({event:t,state:n})=>{this.handleRunFinished(e,t,n)},onStateSnapshotEvent:({event:t,input:n,state:r})=>{this.handleStateSnapshot(e,t,n,r)},onStateDeltaEvent:({event:t,input:n,state:r})=>{this.handleStateDelta(e,t,n,r)},onMessagesSnapshotEvent:({event:t,input:n,messages:r})=>{this.handleMessagesSnapshot(e,t,n,r)},onNewMessage:({message:t,input:n})=>{this.handleNewMessage(e,t,n)}});this.agentSubscriptions.set(t,n)}unsubscribeFromAgent(e){const t=this.agentSubscriptions.get(e);t&&(t(),this.agentSubscriptions.delete(e))}getStateByRun(e,t,n){var r,i;const o=null===(i=null===(r=this.stateByRun.get(e))||void 0===r?void 0:r.get(t))||void 0===i?void 0:i.get(n);if(o)return JSON.parse(JSON.stringify(o))}getRunIdForMessage(e,t,n){var r,i;return null===(i=null===(r=this.messageToRun.get(e))||void 0===r?void 0:r.get(t))||void 0===i?void 0:i.get(n)}getStatesForThread(e,t){var n,r;return null!==(r=null===(n=this.stateByRun.get(e))||void 0===n?void 0:n.get(t))&&void 0!==r?r:new Map}getRunIdsForThread(e,t){var n;const r=null===(n=this.stateByRun.get(e))||void 0===n?void 0:n.get(t);return r?Array.from(r.keys()):[]}handleRunStarted(e,t,n){if(!e.agentId)return;const{threadId:r,runId:i}=t;this.saveState(e.agentId,r,i,n)}handleRunFinished(e,t,n){if(!e.agentId)return;const{threadId:r,runId:i}=t;this.saveState(e.agentId,r,i,n)}handleStateSnapshot(e,t,n,r){if(!e.agentId)return;const{threadId:i,runId:o}=n,s={...r,...t.snapshot};this.saveState(e.agentId,i,o,s)}handleStateDelta(e,t,n,r){if(!e.agentId)return;const{threadId:i,runId:o}=n;this.saveState(e.agentId,i,o,r)}handleMessagesSnapshot(e,t,n,r){if(!e.agentId)return;const{threadId:i,runId:o}=n;for(const n of t.messages)this.associateMessageWithRun(e.agentId,i,n.id,o)}handleNewMessage(e,t,n){if(!e.agentId||!n)return;const{threadId:r,runId:i}=n;this.associateMessageWithRun(e.agentId,r,t.id,i)}saveState(e,t,n,r){this.stateByRun.has(e)||this.stateByRun.set(e,new Map);const i=this.stateByRun.get(e);i.has(t)||i.set(t,new Map);i.get(t).set(n,JSON.parse(JSON.stringify(r)))}associateMessageWithRun(e,t,n,r){this.messageToRun.has(e)||this.messageToRun.set(e,new Map);const i=this.messageToRun.get(e);i.has(t)||i.set(t,new Map);i.get(t).set(n,r)}clearAgentState(e){this.stateByRun.delete(e),this.messageToRun.delete(e)}clearThreadState(e,t){var n,r;null===(n=this.stateByRun.get(e))||void 0===n||n.delete(t),null===(r=this.messageToRun.get(e))||void 0===r||r.delete(t)}}var Me,Fe,Le;e.CopilotKitCoreErrorCode=void 0,(Me=e.CopilotKitCoreErrorCode||(e.CopilotKitCoreErrorCode={})).RUNTIME_INFO_FETCH_FAILED="runtime_info_fetch_failed",Me.AGENT_CONNECT_FAILED="agent_connect_failed",Me.AGENT_RUN_FAILED="agent_run_failed",Me.AGENT_RUN_FAILED_EVENT="agent_run_failed_event",Me.AGENT_RUN_ERROR_EVENT="agent_run_error_event",Me.TOOL_ARGUMENT_PARSE_FAILED="tool_argument_parse_failed",Me.TOOL_HANDLER_FAILED="tool_handler_failed",Me.TRANSCRIPTION_FAILED="transcription_failed",Me.TRANSCRIPTION_SERVICE_NOT_CONFIGURED="transcription_service_not_configured",Me.TRANSCRIPTION_INVALID_AUDIO="transcription_invalid_audio",Me.TRANSCRIPTION_RATE_LIMITED="transcription_rate_limited",Me.TRANSCRIPTION_AUTH_FAILED="transcription_auth_failed",Me.TRANSCRIPTION_NETWORK_ERROR="transcription_network_error",e.CopilotKitCoreRuntimeConnectionStatus=void 0,(Fe=e.CopilotKitCoreRuntimeConnectionStatus||(e.CopilotKitCoreRuntimeConnectionStatus={})).Disconnected="disconnected",Fe.Connected="connected",Fe.Connecting="connecting",Fe.Error="error";e.ToolCallStatus=void 0,(Le=e.ToolCallStatus||(e.ToolCallStatus={})).InProgress="inProgress",Le.Executing="executing",Le.Complete="complete",e.AgentRegistry=z,e.ContextStore=H,e.CopilotKitCore=class{constructor({runtimeUrl:e,runtimeTransport:t="rest",headers:n={},credentials:r,properties:i={},agents__unsafe_dev_only:o={},tools:s=[],suggestionsConfig:a=[]}){this.subscribers=new Set,this._headers=n,this._credentials=r,this._properties=i,this.agentRegistry=new z(this),this.contextStore=new H(this),this.suggestionEngine=new K(this),this.runHandler=new Oe(this),this.stateManager=new je(this),this.agentRegistry.initialize(o),this.runHandler.initialize(s),this.suggestionEngine.initialize(a),this.stateManager.initialize(),this.agentRegistry.setRuntimeTransport(t),this.agentRegistry.setRuntimeUrl(e),this.subscribe({onAgentsChanged:({agents:e})=>{Object.values(e).forEach(e=>{e.agentId&&this.stateManager.subscribeToAgent(e)})}})}async notifySubscribers(e,t){await Promise.all(Array.from(this.subscribers).map(async n=>{try{await e(n)}catch(e){console.error(t,e)}}))}async emitError({error:e,code:t,context:n={}}){await this.notifySubscribers(r=>{var i;return null===(i=r.onError)||void 0===i?void 0:i.call(r,{copilotkit:this,error:e,code:t,context:n})},"Subscriber onError error:")}get context(){return this.contextStore.context}get agents(){return this.agentRegistry.agents}get tools(){return this.runHandler.tools}get runtimeUrl(){return this.agentRegistry.runtimeUrl}setRuntimeUrl(e){this.agentRegistry.setRuntimeUrl(e)}get runtimeTransport(){return this.agentRegistry.runtimeTransport}setRuntimeTransport(e){this.agentRegistry.setRuntimeTransport(e)}get runtimeVersion(){return this.agentRegistry.runtimeVersion}get headers(){return this._headers}get credentials(){return this._credentials}get properties(){return this._properties}get runtimeConnectionStatus(){return this.agentRegistry.runtimeConnectionStatus}get audioFileTranscriptionEnabled(){return this.agentRegistry.audioFileTranscriptionEnabled}setHeaders(e){this._headers=e,this.agentRegistry.applyHeadersToAgents(this.agentRegistry.agents),this.notifySubscribers(e=>{var t;return null===(t=e.onHeadersChanged)||void 0===t?void 0:t.call(e,{copilotkit:this,headers:this.headers})},"Subscriber onHeadersChanged error:")}setCredentials(e){this._credentials=e,this.agentRegistry.applyCredentialsToAgents(this.agentRegistry.agents)}setProperties(e){this._properties=e,this.notifySubscribers(e=>{var t;return null===(t=e.onPropertiesChanged)||void 0===t?void 0:t.call(e,{copilotkit:this,properties:this.properties})},"Subscriber onPropertiesChanged error:")}setAgents__unsafe_dev_only(e){this.agentRegistry.setAgents__unsafe_dev_only(e)}addAgent__unsafe_dev_only(e){this.agentRegistry.addAgent__unsafe_dev_only(e)}removeAgent__unsafe_dev_only(e){this.agentRegistry.removeAgent__unsafe_dev_only(e)}getAgent(e){return this.agentRegistry.getAgent(e)}addContext(e){return this.contextStore.addContext(e)}removeContext(e){this.contextStore.removeContext(e)}addSuggestionsConfig(e){return this.suggestionEngine.addSuggestionsConfig(e)}removeSuggestionsConfig(e){this.suggestionEngine.removeSuggestionsConfig(e)}reloadSuggestions(e){this.suggestionEngine.reloadSuggestions(e)}clearSuggestions(e){this.suggestionEngine.clearSuggestions(e)}getSuggestions(e){return this.suggestionEngine.getSuggestions(e)}addTool(e){this.runHandler.addTool(e)}removeTool(e,t){this.runHandler.removeTool(e,t)}getTool(e){return this.runHandler.getTool(e)}setTools(e){this.runHandler.setTools(e)}subscribe(e){return this.subscribers.add(e),{unsubscribe:()=>{this.subscribers.delete(e)}}}async connectAgent(e){return this.runHandler.connectAgent(e)}stopAgent(e){e.agent.abortRun()}async runAgent(e){return this.runHandler.runAgent(e)}getStateByRun(e,t,n){return this.stateManager.getStateByRun(e,t,n)}getRunIdForMessage(e,t,n){return this.stateManager.getRunIdForMessage(e,t,n)}getRunIdsForThread(e,t){return this.stateManager.getRunIdsForThread(e,t)}buildFrontendTools(e){return this.runHandler.buildFrontendTools(e)}},e.ProxiedCopilotRuntimeAgent=D,e.RunHandler=Oe,e.StateManager=je,e.SuggestionEngine=K,e.completePartialMarkdown=function(e){let t=e;const n=Array.from(t.matchAll(/^(\s*)(`{3,}|~{3,})/gm));if(n.length%2==1){const[,e,r]=n[0];t+=`\n${e}${r}`}t.match(/\[([^\]]*)\]\(([^)]*)$/)&&(t+=")");const r=[],i=Array.from(t),o=[],s=[];let a=0,u=-1;for(let e=0;e<i.length;e++)if(0===e||"\n"===i[e-1]){const n=t.substring(e).match(/^(\s*)(`{3,}|~{3,})/);n&&(a++,a%2==1?u=e:-1!==u&&(o.push({start:u,end:e+n[0].length}),u=-1),e+=n[0].length-1)}for(let e=0;e<i.length;e++)if("`"===i[e]){let t=0;for(let n=e-1;n>=0&&"\\"===i[n];n--)t++;if(t%2==0)for(let t=e+1;t<i.length;t++)if("`"===i[t]){let n=0;for(let e=t-1;e>=0&&"\\"===i[e];e--)n++;if(n%2==0){s.push({start:e,end:t+1}),e=t;break}}}const c=e=>o.some(t=>e>=t.start&&e<t.end)||s.some(t=>e>=t.start&&e<t.end);for(let e=0;e<i.length;e++){const t=i[e],n=i[e+1],o=i[e-1];if(!c(e))if("["===t){let t=!1,n=1,o=e+1;for(;o<i.length&&n>0;)"["!==i[o]||c(o)||n++,"]"!==i[o]||c(o)||n--,o++;if(0===n&&"("===i[o]){let n=1;for(o++;o<i.length&&n>0;)"("!==i[o]||c(o)||n++,")"!==i[o]||c(o)||n--,o++;if(0===n){t=!0,e=o-1;continue}}if(!t){const t=r.findIndex(e=>"bracket"===e.type);-1!==t?r.splice(t,1):r.push({type:"bracket",marker:"[",position:e})}}else if("*"===t&&"*"===n){const t=r.findIndex(e=>"bold_star"===e.type);-1!==t?r.splice(t,1):r.push({type:"bold_star",marker:"**",position:e}),e++}else if("_"===t&&"_"===n){const t=r.findIndex(e=>"bold_underscore"===e.type);-1!==t?r.splice(t,1):r.push({type:"bold_underscore",marker:"__",position:e}),e++}else if("~"===t&&"~"===n){const t=r.findIndex(e=>"strike"===e.type);-1!==t?r.splice(t,1):r.push({type:"strike",marker:"~~",position:e}),e++}else if("*"===t&&"*"!==o&&"*"!==n){const t=r.findIndex(e=>"italic_star"===e.type);-1!==t?r.splice(t,1):r.push({type:"italic_star",marker:"*",position:e})}else if("_"===t&&"_"!==o&&"_"!==n){const t=r.findIndex(e=>"italic_underscore"===e.type);-1!==t?r.splice(t,1):r.push({type:"italic_underscore",marker:"_",position:e})}}let l=0;for(let e=0;e<i.length;e++)"`"!==i[e]||c(e)||l++;l%2==1&&(t+="`"),r.sort((e,t)=>t.position-e.position);let d=t+r.map(e=>{switch(e.type){case"bracket":return"]";case"bold_star":return"**";case"bold_underscore":return"__";case"strike":return"~~";case"italic_star":return"*";case"italic_underscore":return"_";default:return""}}).join("");const g=Array.from(d.matchAll(/^(\s*)(`{3,}|~{3,})/gm)),h=(d.match(/`/g)||[]).length%2==1,f=g.length%2==1;let p=!h&&!f;if(p){const e=d.lastIndexOf("(");if(-1!==e){(d.substring(0,e).match(/`/g)||[]).length%2==1&&(p=!1)}}if(p){const e=(d.match(/\(/g)||[]).length,t=(d.match(/\)/g)||[]).length;e>t&&(d+=")".repeat(e-t))}return d}});
2
- //# sourceMappingURL=index.umd.js.map
1
+ (function(global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@ag-ui/client'), require('@copilotkitnext/shared'), require('rxjs'), require('rxjs/operators'), require('zod-to-json-schema')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', '@ag-ui/client', '@copilotkitnext/shared', 'rxjs', 'rxjs/operators', 'zod-to-json-schema'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.CopilotKitNextCore = {}), global.AgUIClient,global.CopilotKitNextShared,global.rxjs,global.rxjs.operators,global.zodToJsonSchema));
5
+ })(this, function(exports, _ag_ui_client, _copilotkitnext_shared, rxjs, rxjs_operators, zod_to_json_schema) {
6
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
7
+
8
+ //#region \0@oxc-project+runtime@0.112.0/helpers/typeof.js
9
+ function _typeof(o) {
10
+ "@babel/helpers - typeof";
11
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
12
+ return typeof o;
13
+ } : function(o) {
14
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
15
+ }, _typeof(o);
16
+ }
17
+
18
+ //#endregion
19
+ //#region \0@oxc-project+runtime@0.112.0/helpers/toPrimitive.js
20
+ function toPrimitive(t, r) {
21
+ if ("object" != _typeof(t) || !t) return t;
22
+ var e = t[Symbol.toPrimitive];
23
+ if (void 0 !== e) {
24
+ var i = e.call(t, r || "default");
25
+ if ("object" != _typeof(i)) return i;
26
+ throw new TypeError("@@toPrimitive must return a primitive value.");
27
+ }
28
+ return ("string" === r ? String : Number)(t);
29
+ }
30
+
31
+ //#endregion
32
+ //#region \0@oxc-project+runtime@0.112.0/helpers/toPropertyKey.js
33
+ function toPropertyKey(t) {
34
+ var i = toPrimitive(t, "string");
35
+ return "symbol" == _typeof(i) ? i : i + "";
36
+ }
37
+
38
+ //#endregion
39
+ //#region \0@oxc-project+runtime@0.112.0/helpers/defineProperty.js
40
+ function _defineProperty(e, r, t) {
41
+ return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
42
+ value: t,
43
+ enumerable: !0,
44
+ configurable: !0,
45
+ writable: !0
46
+ }) : e[r] = t, e;
47
+ }
48
+
49
+ //#endregion
50
+ //#region src/agent.ts
51
+ /**
52
+ * Check if an error is a ZodError (validation error).
53
+ * These can occur when the SSE stream is aborted/truncated mid-event.
54
+ */
55
+ function isZodError(error) {
56
+ return error !== null && typeof error === "object" && "name" in error && error.name === "ZodError";
57
+ }
58
+ /**
59
+ * Wrap an Observable to catch and suppress ZodErrors that occur during stream abort.
60
+ * These errors are expected when the connection is cancelled mid-stream.
61
+ */
62
+ function withAbortErrorHandling(observable) {
63
+ return observable.pipe((0, rxjs_operators.catchError)((error) => {
64
+ if (isZodError(error)) return rxjs.EMPTY;
65
+ throw error;
66
+ }));
67
+ }
68
+ var ProxiedCopilotRuntimeAgent = class extends _ag_ui_client.HttpAgent {
69
+ constructor(config) {
70
+ var _config$transport, _ref, _config$agentId;
71
+ const normalizedRuntimeUrl = config.runtimeUrl ? config.runtimeUrl.replace(/\/$/, "") : void 0;
72
+ const transport = (_config$transport = config.transport) !== null && _config$transport !== void 0 ? _config$transport : "rest";
73
+ const runUrl = transport === "single" ? (_ref = normalizedRuntimeUrl !== null && normalizedRuntimeUrl !== void 0 ? normalizedRuntimeUrl : config.runtimeUrl) !== null && _ref !== void 0 ? _ref : "" : `${normalizedRuntimeUrl !== null && normalizedRuntimeUrl !== void 0 ? normalizedRuntimeUrl : config.runtimeUrl}/agent/${encodeURIComponent((_config$agentId = config.agentId) !== null && _config$agentId !== void 0 ? _config$agentId : "")}/run`;
74
+ if (!runUrl) throw new Error("ProxiedCopilotRuntimeAgent requires a runtimeUrl when transport is set to 'single'.");
75
+ super({
76
+ ...config,
77
+ url: runUrl
78
+ });
79
+ _defineProperty(this, "runtimeUrl", void 0);
80
+ _defineProperty(this, "credentials", void 0);
81
+ _defineProperty(this, "transport", void 0);
82
+ _defineProperty(this, "singleEndpointUrl", void 0);
83
+ this.runtimeUrl = normalizedRuntimeUrl !== null && normalizedRuntimeUrl !== void 0 ? normalizedRuntimeUrl : config.runtimeUrl;
84
+ this.credentials = config.credentials;
85
+ this.transport = transport;
86
+ if (this.transport === "single") this.singleEndpointUrl = this.runtimeUrl;
87
+ }
88
+ abortRun() {
89
+ if (!this.agentId || !this.threadId) return;
90
+ if (typeof fetch === "undefined") return;
91
+ if (this.transport === "single") {
92
+ if (!this.singleEndpointUrl) return;
93
+ const headers = new Headers({
94
+ ...this.headers,
95
+ "Content-Type": "application/json"
96
+ });
97
+ fetch(this.singleEndpointUrl, {
98
+ method: "POST",
99
+ headers,
100
+ body: JSON.stringify({
101
+ method: "agent/stop",
102
+ params: {
103
+ agentId: this.agentId,
104
+ threadId: this.threadId
105
+ }
106
+ }),
107
+ ...this.credentials ? { credentials: this.credentials } : {}
108
+ }).catch((error) => {
109
+ console.error("ProxiedCopilotRuntimeAgent: stop request failed", error);
110
+ });
111
+ return;
112
+ }
113
+ if (!this.runtimeUrl) return;
114
+ const stopPath = `${this.runtimeUrl}/agent/${encodeURIComponent(this.agentId)}/stop/${encodeURIComponent(this.threadId)}`;
115
+ const origin = typeof window !== "undefined" && window.location ? window.location.origin : "http://localhost";
116
+ const base = new URL(this.runtimeUrl, origin);
117
+ const stopUrl = new URL(stopPath, base);
118
+ fetch(stopUrl.toString(), {
119
+ method: "POST",
120
+ headers: {
121
+ "Content-Type": "application/json",
122
+ ...this.headers
123
+ },
124
+ ...this.credentials ? { credentials: this.credentials } : {}
125
+ }).catch((error) => {
126
+ console.error("ProxiedCopilotRuntimeAgent: stop request failed", error);
127
+ });
128
+ }
129
+ connect(input) {
130
+ if (this.transport === "single") {
131
+ if (!this.singleEndpointUrl) throw new Error("Single endpoint transport requires a runtimeUrl");
132
+ const requestInit = this.createSingleRouteRequestInit(input, "agent/connect", { agentId: this.agentId });
133
+ return withAbortErrorHandling((0, _ag_ui_client.transformHttpEventStream)((0, _ag_ui_client.runHttpRequest)(this.singleEndpointUrl, requestInit)));
134
+ }
135
+ return withAbortErrorHandling((0, _ag_ui_client.transformHttpEventStream)((0, _ag_ui_client.runHttpRequest)(`${this.runtimeUrl}/agent/${this.agentId}/connect`, this.requestInit(input))));
136
+ }
137
+ run(input) {
138
+ if (this.transport === "single") {
139
+ if (!this.singleEndpointUrl) throw new Error("Single endpoint transport requires a runtimeUrl");
140
+ const requestInit = this.createSingleRouteRequestInit(input, "agent/run", { agentId: this.agentId });
141
+ return withAbortErrorHandling((0, _ag_ui_client.transformHttpEventStream)((0, _ag_ui_client.runHttpRequest)(this.singleEndpointUrl, requestInit)));
142
+ }
143
+ return withAbortErrorHandling(super.run(input));
144
+ }
145
+ clone() {
146
+ const cloned = super.clone();
147
+ cloned.runtimeUrl = this.runtimeUrl;
148
+ cloned.credentials = this.credentials;
149
+ cloned.transport = this.transport;
150
+ cloned.singleEndpointUrl = this.singleEndpointUrl;
151
+ return cloned;
152
+ }
153
+ createSingleRouteRequestInit(input, method, params) {
154
+ var _baseInit$headers, _headers$get;
155
+ if (!this.agentId) throw new Error("ProxiedCopilotRuntimeAgent requires agentId to make runtime requests");
156
+ const baseInit = super.requestInit(input);
157
+ const headers = new Headers((_baseInit$headers = baseInit.headers) !== null && _baseInit$headers !== void 0 ? _baseInit$headers : {});
158
+ headers.set("Content-Type", "application/json");
159
+ headers.set("Accept", (_headers$get = headers.get("Accept")) !== null && _headers$get !== void 0 ? _headers$get : "text/event-stream");
160
+ let originalBody = void 0;
161
+ if (typeof baseInit.body === "string") try {
162
+ originalBody = JSON.parse(baseInit.body);
163
+ } catch (error) {
164
+ console.warn("ProxiedCopilotRuntimeAgent: failed to parse request body for single route transport", error);
165
+ originalBody = void 0;
166
+ }
167
+ const envelope = { method };
168
+ if (params && Object.keys(params).length > 0) envelope.params = params;
169
+ if (originalBody !== void 0) envelope.body = originalBody;
170
+ return {
171
+ ...baseInit,
172
+ headers,
173
+ body: JSON.stringify(envelope),
174
+ ...this.credentials ? { credentials: this.credentials } : {}
175
+ };
176
+ }
177
+ };
178
+
179
+ //#endregion
180
+ //#region src/core/agent-registry.ts
181
+ /**
182
+ * Manages agent registration, lifecycle, and runtime connectivity for CopilotKitCore.
183
+ * Handles both local development agents and remote runtime agents.
184
+ */
185
+ var AgentRegistry = class {
186
+ constructor(core) {
187
+ this.core = core;
188
+ _defineProperty(this, "_agents", {});
189
+ _defineProperty(this, "localAgents", {});
190
+ _defineProperty(this, "remoteAgents", {});
191
+ _defineProperty(this, "_runtimeUrl", void 0);
192
+ _defineProperty(this, "_runtimeVersion", void 0);
193
+ _defineProperty(this, "_runtimeConnectionStatus", CopilotKitCoreRuntimeConnectionStatus.Disconnected);
194
+ _defineProperty(this, "_runtimeTransport", "rest");
195
+ _defineProperty(this, "_audioFileTranscriptionEnabled", false);
196
+ }
197
+ /**
198
+ * Get all agents as a readonly record
199
+ */
200
+ get agents() {
201
+ return this._agents;
202
+ }
203
+ get runtimeUrl() {
204
+ return this._runtimeUrl;
205
+ }
206
+ get runtimeVersion() {
207
+ return this._runtimeVersion;
208
+ }
209
+ get runtimeConnectionStatus() {
210
+ return this._runtimeConnectionStatus;
211
+ }
212
+ get runtimeTransport() {
213
+ return this._runtimeTransport;
214
+ }
215
+ get audioFileTranscriptionEnabled() {
216
+ return this._audioFileTranscriptionEnabled;
217
+ }
218
+ /**
219
+ * Initialize agents from configuration
220
+ */
221
+ initialize(agents) {
222
+ this.localAgents = this.assignAgentIds(agents);
223
+ this.applyHeadersToAgents(this.localAgents);
224
+ this._agents = this.localAgents;
225
+ }
226
+ /**
227
+ * Set the runtime URL and update connection
228
+ */
229
+ setRuntimeUrl(runtimeUrl) {
230
+ const normalizedRuntimeUrl = runtimeUrl ? runtimeUrl.replace(/\/$/, "") : void 0;
231
+ if (this._runtimeUrl === normalizedRuntimeUrl) return;
232
+ this._runtimeUrl = normalizedRuntimeUrl;
233
+ this.updateRuntimeConnection();
234
+ }
235
+ setRuntimeTransport(runtimeTransport) {
236
+ if (this._runtimeTransport === runtimeTransport) return;
237
+ this._runtimeTransport = runtimeTransport;
238
+ this.updateRuntimeConnection();
239
+ }
240
+ /**
241
+ * Set all agents at once (for development use)
242
+ */
243
+ setAgents__unsafe_dev_only(agents) {
244
+ Object.entries(agents).forEach(([id, agent]) => {
245
+ if (agent) this.validateAndAssignAgentId(id, agent);
246
+ });
247
+ this.localAgents = agents;
248
+ this._agents = {
249
+ ...this.localAgents,
250
+ ...this.remoteAgents
251
+ };
252
+ this.applyHeadersToAgents(this._agents);
253
+ this.notifyAgentsChanged();
254
+ }
255
+ /**
256
+ * Add a single agent (for development use)
257
+ */
258
+ addAgent__unsafe_dev_only({ id, agent }) {
259
+ this.validateAndAssignAgentId(id, agent);
260
+ this.localAgents[id] = agent;
261
+ this.applyHeadersToAgent(agent);
262
+ this._agents = {
263
+ ...this.localAgents,
264
+ ...this.remoteAgents
265
+ };
266
+ this.notifyAgentsChanged();
267
+ }
268
+ /**
269
+ * Remove an agent by ID (for development use)
270
+ */
271
+ removeAgent__unsafe_dev_only(id) {
272
+ delete this.localAgents[id];
273
+ this._agents = {
274
+ ...this.localAgents,
275
+ ...this.remoteAgents
276
+ };
277
+ this.notifyAgentsChanged();
278
+ }
279
+ /**
280
+ * Get an agent by ID
281
+ */
282
+ getAgent(id) {
283
+ if (id in this._agents) return this._agents[id];
284
+ if (this.runtimeUrl !== void 0 && (this.runtimeConnectionStatus === CopilotKitCoreRuntimeConnectionStatus.Disconnected || this.runtimeConnectionStatus === CopilotKitCoreRuntimeConnectionStatus.Connecting)) return;
285
+ console.warn(`Agent ${id} not found`);
286
+ }
287
+ /**
288
+ * Apply current headers to an agent
289
+ */
290
+ applyHeadersToAgent(agent) {
291
+ if (agent instanceof _ag_ui_client.HttpAgent) agent.headers = { ...this.core.headers };
292
+ }
293
+ /**
294
+ * Apply current headers to all agents
295
+ */
296
+ applyHeadersToAgents(agents) {
297
+ Object.values(agents).forEach((agent) => {
298
+ this.applyHeadersToAgent(agent);
299
+ });
300
+ }
301
+ /**
302
+ * Apply current credentials to an agent
303
+ */
304
+ applyCredentialsToAgent(agent) {
305
+ if (agent instanceof ProxiedCopilotRuntimeAgent) agent.credentials = this.core.credentials;
306
+ }
307
+ /**
308
+ * Apply current credentials to all agents
309
+ */
310
+ applyCredentialsToAgents(agents) {
311
+ Object.values(agents).forEach((agent) => {
312
+ this.applyCredentialsToAgent(agent);
313
+ });
314
+ }
315
+ /**
316
+ * Update runtime connection and fetch remote agents
317
+ */
318
+ async updateRuntimeConnection() {
319
+ if (typeof window === "undefined") return;
320
+ if (!this.runtimeUrl) {
321
+ this._runtimeConnectionStatus = CopilotKitCoreRuntimeConnectionStatus.Disconnected;
322
+ this._runtimeVersion = void 0;
323
+ this._audioFileTranscriptionEnabled = false;
324
+ this.remoteAgents = {};
325
+ this._agents = this.localAgents;
326
+ await this.notifyRuntimeStatusChanged(CopilotKitCoreRuntimeConnectionStatus.Disconnected);
327
+ await this.notifyAgentsChanged();
328
+ return;
329
+ }
330
+ this._runtimeConnectionStatus = CopilotKitCoreRuntimeConnectionStatus.Connecting;
331
+ await this.notifyRuntimeStatusChanged(CopilotKitCoreRuntimeConnectionStatus.Connecting);
332
+ try {
333
+ var _runtimeInfoResponse$;
334
+ const runtimeInfoResponse = await this.fetchRuntimeInfo();
335
+ const { version, ...runtimeInfo } = runtimeInfoResponse;
336
+ const credentials = this.core.credentials;
337
+ this.remoteAgents = Object.fromEntries(Object.entries(runtimeInfo.agents).map(([id, { description }]) => {
338
+ const agent = new ProxiedCopilotRuntimeAgent({
339
+ runtimeUrl: this.runtimeUrl,
340
+ agentId: id,
341
+ description,
342
+ transport: this._runtimeTransport,
343
+ credentials
344
+ });
345
+ this.applyHeadersToAgent(agent);
346
+ return [id, agent];
347
+ }));
348
+ this._agents = {
349
+ ...this.localAgents,
350
+ ...this.remoteAgents
351
+ };
352
+ this._runtimeConnectionStatus = CopilotKitCoreRuntimeConnectionStatus.Connected;
353
+ this._runtimeVersion = version;
354
+ this._audioFileTranscriptionEnabled = (_runtimeInfoResponse$ = runtimeInfoResponse.audioFileTranscriptionEnabled) !== null && _runtimeInfoResponse$ !== void 0 ? _runtimeInfoResponse$ : false;
355
+ await this.notifyRuntimeStatusChanged(CopilotKitCoreRuntimeConnectionStatus.Connected);
356
+ await this.notifyAgentsChanged();
357
+ } catch (error) {
358
+ this._runtimeConnectionStatus = CopilotKitCoreRuntimeConnectionStatus.Error;
359
+ this._runtimeVersion = void 0;
360
+ this._audioFileTranscriptionEnabled = false;
361
+ this.remoteAgents = {};
362
+ this._agents = this.localAgents;
363
+ await this.notifyRuntimeStatusChanged(CopilotKitCoreRuntimeConnectionStatus.Error);
364
+ await this.notifyAgentsChanged();
365
+ const message = error instanceof Error ? error.message : JSON.stringify(error);
366
+ _copilotkitnext_shared.logger.warn(`Failed to load runtime info (${this.runtimeUrl}/info): ${message}`);
367
+ const runtimeError = error instanceof Error ? error : new Error(String(error));
368
+ await this.core.emitError({
369
+ error: runtimeError,
370
+ code: CopilotKitCoreErrorCode.RUNTIME_INFO_FETCH_FAILED,
371
+ context: { runtimeUrl: this.runtimeUrl }
372
+ });
373
+ }
374
+ }
375
+ async fetchRuntimeInfo() {
376
+ if (!this.runtimeUrl) throw new Error("Runtime URL is not set");
377
+ const baseHeaders = this.core.headers;
378
+ const credentials = this.core.credentials;
379
+ const headers = { ...baseHeaders };
380
+ if (this._runtimeTransport === "single") {
381
+ if (!headers["Content-Type"]) headers["Content-Type"] = "application/json";
382
+ const response = await fetch(this.runtimeUrl, {
383
+ method: "POST",
384
+ headers,
385
+ body: JSON.stringify({ method: "info" }),
386
+ ...credentials ? { credentials } : {}
387
+ });
388
+ if ("ok" in response && !response.ok) throw new Error(`Runtime info request failed with status ${response.status}`);
389
+ return await response.json();
390
+ }
391
+ const response = await fetch(`${this.runtimeUrl}/info`, {
392
+ headers,
393
+ ...credentials ? { credentials } : {}
394
+ });
395
+ if ("ok" in response && !response.ok) throw new Error(`Runtime info request failed with status ${response.status}`);
396
+ return await response.json();
397
+ }
398
+ /**
399
+ * Assign agent IDs to a record of agents
400
+ */
401
+ assignAgentIds(agents) {
402
+ Object.entries(agents).forEach(([id, agent]) => {
403
+ if (agent) this.validateAndAssignAgentId(id, agent);
404
+ });
405
+ return agents;
406
+ }
407
+ /**
408
+ * Validate and assign an agent ID
409
+ */
410
+ validateAndAssignAgentId(registrationId, agent) {
411
+ if (agent.agentId && agent.agentId !== registrationId) throw new Error(`Agent registration mismatch: Agent with ID "${agent.agentId}" cannot be registered under key "${registrationId}". The agent ID must match the registration key or be undefined.`);
412
+ if (!agent.agentId) agent.agentId = registrationId;
413
+ }
414
+ /**
415
+ * Notify subscribers of runtime status changes
416
+ */
417
+ async notifyRuntimeStatusChanged(status) {
418
+ await this.core.notifySubscribers((subscriber) => {
419
+ var _subscriber$onRuntime;
420
+ return (_subscriber$onRuntime = subscriber.onRuntimeConnectionStatusChanged) === null || _subscriber$onRuntime === void 0 ? void 0 : _subscriber$onRuntime.call(subscriber, {
421
+ copilotkit: this.core,
422
+ status
423
+ });
424
+ }, "Error in CopilotKitCore subscriber (onRuntimeConnectionStatusChanged):");
425
+ }
426
+ /**
427
+ * Notify subscribers of agent changes
428
+ */
429
+ async notifyAgentsChanged() {
430
+ await this.core.notifySubscribers((subscriber) => {
431
+ var _subscriber$onAgentsC;
432
+ return (_subscriber$onAgentsC = subscriber.onAgentsChanged) === null || _subscriber$onAgentsC === void 0 ? void 0 : _subscriber$onAgentsC.call(subscriber, {
433
+ copilotkit: this.core,
434
+ agents: this._agents
435
+ });
436
+ }, "Subscriber onAgentsChanged error:");
437
+ }
438
+ };
439
+
440
+ //#endregion
441
+ //#region src/core/context-store.ts
442
+ /**
443
+ * Manages context storage and lifecycle for CopilotKitCore.
444
+ * Context represents additional information available to agents during execution.
445
+ */
446
+ var ContextStore = class {
447
+ constructor(core) {
448
+ this.core = core;
449
+ _defineProperty(this, "_context", {});
450
+ }
451
+ /**
452
+ * Get all context entries as a readonly record
453
+ */
454
+ get context() {
455
+ return this._context;
456
+ }
457
+ /**
458
+ * Add a new context entry
459
+ * @returns The ID of the created context entry
460
+ */
461
+ addContext({ description, value }) {
462
+ const id = (0, _copilotkitnext_shared.randomUUID)();
463
+ this._context[id] = {
464
+ description,
465
+ value
466
+ };
467
+ this.notifySubscribers();
468
+ return id;
469
+ }
470
+ /**
471
+ * Remove a context entry by ID
472
+ */
473
+ removeContext(id) {
474
+ delete this._context[id];
475
+ this.notifySubscribers();
476
+ }
477
+ /**
478
+ * Notify all subscribers of context changes
479
+ */
480
+ async notifySubscribers() {
481
+ await this.core.notifySubscribers((subscriber) => {
482
+ var _subscriber$onContext;
483
+ return (_subscriber$onContext = subscriber.onContextChanged) === null || _subscriber$onContext === void 0 ? void 0 : _subscriber$onContext.call(subscriber, {
484
+ copilotkit: this.core,
485
+ context: this._context
486
+ });
487
+ }, "Subscriber onContextChanged error:");
488
+ }
489
+ };
490
+
491
+ //#endregion
492
+ //#region src/core/suggestion-engine.ts
493
+ /**
494
+ * Manages suggestion generation, streaming, and lifecycle for CopilotKitCore.
495
+ * Handles both dynamic (AI-generated) and static suggestions.
496
+ */
497
+ var SuggestionEngine = class {
498
+ constructor(core) {
499
+ this.core = core;
500
+ _defineProperty(this, "_suggestionsConfig", {});
501
+ _defineProperty(this, "_suggestions", {});
502
+ _defineProperty(this, "_runningSuggestions", {});
503
+ }
504
+ /**
505
+ * Initialize with suggestion configs
506
+ */
507
+ initialize(suggestionsConfig) {
508
+ for (const config of suggestionsConfig) this._suggestionsConfig[(0, _copilotkitnext_shared.randomUUID)()] = config;
509
+ }
510
+ /**
511
+ * Add a suggestion configuration
512
+ * @returns The ID of the created config
513
+ */
514
+ addSuggestionsConfig(config) {
515
+ const id = (0, _copilotkitnext_shared.randomUUID)();
516
+ this._suggestionsConfig[id] = config;
517
+ this.notifySuggestionsConfigChanged();
518
+ return id;
519
+ }
520
+ /**
521
+ * Remove a suggestion configuration by ID
522
+ */
523
+ removeSuggestionsConfig(id) {
524
+ delete this._suggestionsConfig[id];
525
+ this.notifySuggestionsConfigChanged();
526
+ }
527
+ /**
528
+ * Reload suggestions for a specific agent
529
+ * This triggers generation of new suggestions based on current configs
530
+ */
531
+ reloadSuggestions(agentId) {
532
+ var _agent$messages$lengt, _agent$messages;
533
+ this.clearSuggestions(agentId);
534
+ const agent = this.core.getAgent(agentId);
535
+ if (!agent) return;
536
+ const messageCount = (_agent$messages$lengt = (_agent$messages = agent.messages) === null || _agent$messages === void 0 ? void 0 : _agent$messages.length) !== null && _agent$messages$lengt !== void 0 ? _agent$messages$lengt : 0;
537
+ let hasAnySuggestions = false;
538
+ for (const config of Object.values(this._suggestionsConfig)) {
539
+ if (config.consumerAgentId !== void 0 && config.consumerAgentId !== "*" && config.consumerAgentId !== agentId) continue;
540
+ if (!this.shouldShowSuggestions(config, messageCount)) continue;
541
+ const suggestionId = (0, _copilotkitnext_shared.randomUUID)();
542
+ if (isDynamicSuggestionsConfig(config)) {
543
+ if (!hasAnySuggestions) {
544
+ hasAnySuggestions = true;
545
+ this.notifySuggestionsStartedLoading(agentId);
546
+ }
547
+ this.generateSuggestions(suggestionId, config, agentId);
548
+ } else if (isStaticSuggestionsConfig(config)) this.addStaticSuggestions(suggestionId, config, agentId);
549
+ }
550
+ }
551
+ /**
552
+ * Clear all suggestions for a specific agent
553
+ */
554
+ clearSuggestions(agentId) {
555
+ const runningAgents = this._runningSuggestions[agentId];
556
+ if (runningAgents) {
557
+ for (const agent of runningAgents) agent.abortRun();
558
+ delete this._runningSuggestions[agentId];
559
+ }
560
+ this._suggestions[agentId] = {};
561
+ this.notifySuggestionsChanged(agentId, []);
562
+ }
563
+ /**
564
+ * Get current suggestions for an agent
565
+ */
566
+ getSuggestions(agentId) {
567
+ var _this$_suggestions$ag, _this$_runningSuggest, _this$_runningSuggest2;
568
+ return {
569
+ suggestions: Object.values((_this$_suggestions$ag = this._suggestions[agentId]) !== null && _this$_suggestions$ag !== void 0 ? _this$_suggestions$ag : {}).flat(),
570
+ isLoading: ((_this$_runningSuggest = (_this$_runningSuggest2 = this._runningSuggestions[agentId]) === null || _this$_runningSuggest2 === void 0 ? void 0 : _this$_runningSuggest2.length) !== null && _this$_runningSuggest !== void 0 ? _this$_runningSuggest : 0) > 0
571
+ };
572
+ }
573
+ /**
574
+ * Generate suggestions using a provider agent
575
+ */
576
+ async generateSuggestions(suggestionId, config, consumerAgentId) {
577
+ let agent = void 0;
578
+ try {
579
+ var _config$providerAgent, _this$_suggestions$co, _this$_runningSuggest3, _config$minSuggestion, _config$maxSuggestion;
580
+ const suggestionsProviderAgent = this.core.getAgent((_config$providerAgent = config.providerAgentId) !== null && _config$providerAgent !== void 0 ? _config$providerAgent : "default");
581
+ if (!suggestionsProviderAgent) throw new Error(`Suggestions provider agent not found: ${config.providerAgentId}`);
582
+ const suggestionsConsumerAgent = this.core.getAgent(consumerAgentId);
583
+ if (!suggestionsConsumerAgent) throw new Error(`Suggestions consumer agent not found: ${consumerAgentId}`);
584
+ agent = suggestionsProviderAgent.clone();
585
+ agent.threadId = suggestionId;
586
+ agent.messages = JSON.parse(JSON.stringify(suggestionsConsumerAgent.messages));
587
+ agent.state = JSON.parse(JSON.stringify(suggestionsConsumerAgent.state));
588
+ this._suggestions[consumerAgentId] = {
589
+ ...(_this$_suggestions$co = this._suggestions[consumerAgentId]) !== null && _this$_suggestions$co !== void 0 ? _this$_suggestions$co : {},
590
+ [suggestionId]: []
591
+ };
592
+ this._runningSuggestions[consumerAgentId] = [...(_this$_runningSuggest3 = this._runningSuggestions[consumerAgentId]) !== null && _this$_runningSuggest3 !== void 0 ? _this$_runningSuggest3 : [], agent];
593
+ agent.addMessage({
594
+ id: suggestionId,
595
+ role: "user",
596
+ content: [
597
+ `Suggest what the user could say next. Provide clear, highly relevant suggestions by calling the \`copilotkitSuggest\` tool.`,
598
+ `Provide at least ${(_config$minSuggestion = config.minSuggestions) !== null && _config$minSuggestion !== void 0 ? _config$minSuggestion : 1} and at most ${(_config$maxSuggestion = config.maxSuggestions) !== null && _config$maxSuggestion !== void 0 ? _config$maxSuggestion : 3} suggestions.`,
599
+ `The user has the following tools available: ${JSON.stringify(this.core.buildFrontendTools(consumerAgentId))}.`,
600
+ ` ${config.instructions}`
601
+ ].join("\n")
602
+ });
603
+ await agent.runAgent({
604
+ context: Object.values(this.core.context),
605
+ forwardedProps: {
606
+ ...this.core.properties,
607
+ toolChoice: {
608
+ type: "function",
609
+ function: { name: "copilotkitSuggest" }
610
+ }
611
+ },
612
+ tools: [SUGGEST_TOOL]
613
+ }, { onMessagesChanged: ({ messages }) => {
614
+ this.extractSuggestions(messages, suggestionId, consumerAgentId, true);
615
+ } });
616
+ } catch (error) {
617
+ console.warn("Error generating suggestions:", error);
618
+ } finally {
619
+ this.finalizeSuggestions(suggestionId, consumerAgentId);
620
+ const runningAgents = this._runningSuggestions[consumerAgentId];
621
+ if (agent && runningAgents) {
622
+ const filteredAgents = runningAgents.filter((a) => a !== agent);
623
+ this._runningSuggestions[consumerAgentId] = filteredAgents;
624
+ if (filteredAgents.length === 0) {
625
+ delete this._runningSuggestions[consumerAgentId];
626
+ await this.notifySuggestionsFinishedLoading(consumerAgentId);
627
+ }
628
+ }
629
+ }
630
+ }
631
+ /**
632
+ * Finalize suggestions by marking them as no longer loading
633
+ */
634
+ finalizeSuggestions(suggestionId, consumerAgentId) {
635
+ const agentSuggestions = this._suggestions[consumerAgentId];
636
+ const currentSuggestions = agentSuggestions === null || agentSuggestions === void 0 ? void 0 : agentSuggestions[suggestionId];
637
+ if (agentSuggestions && currentSuggestions && currentSuggestions.length > 0) {
638
+ var _this$_suggestions$co2;
639
+ const finalizedSuggestions = currentSuggestions.filter((suggestion) => suggestion.title !== "" || suggestion.message !== "").map((suggestion) => ({
640
+ ...suggestion,
641
+ isLoading: false
642
+ }));
643
+ if (finalizedSuggestions.length > 0) agentSuggestions[suggestionId] = finalizedSuggestions;
644
+ else delete agentSuggestions[suggestionId];
645
+ const allSuggestions = Object.values((_this$_suggestions$co2 = this._suggestions[consumerAgentId]) !== null && _this$_suggestions$co2 !== void 0 ? _this$_suggestions$co2 : {}).flat();
646
+ this.notifySuggestionsChanged(consumerAgentId, allSuggestions, "finalized");
647
+ }
648
+ }
649
+ /**
650
+ * Extract suggestions from messages (called during streaming)
651
+ */
652
+ extractSuggestions(messages, suggestionId, consumerAgentId, isRunning) {
653
+ const idx = messages.findIndex((message) => message.id === suggestionId);
654
+ if (idx == -1) return;
655
+ const suggestions = [];
656
+ const newMessages = messages.slice(idx + 1);
657
+ for (const message of newMessages) if (message.role === "assistant" && message.toolCalls) {
658
+ for (const toolCall of message.toolCalls) if (toolCall.function.name === "copilotkitSuggest") {
659
+ const parsed = (0, _copilotkitnext_shared.partialJSONParse)(Array.isArray(toolCall.function.arguments) ? toolCall.function.arguments.join("") : toolCall.function.arguments);
660
+ if (parsed && typeof parsed === "object" && "suggestions" in parsed) {
661
+ const parsedSuggestions = parsed.suggestions;
662
+ if (Array.isArray(parsedSuggestions)) {
663
+ for (const item of parsedSuggestions) if (item && typeof item === "object" && "title" in item) {
664
+ var _item$title, _item$message;
665
+ suggestions.push({
666
+ title: (_item$title = item.title) !== null && _item$title !== void 0 ? _item$title : "",
667
+ message: (_item$message = item.message) !== null && _item$message !== void 0 ? _item$message : "",
668
+ isLoading: false
669
+ });
670
+ }
671
+ }
672
+ }
673
+ }
674
+ }
675
+ if (isRunning && suggestions.length > 0) suggestions[suggestions.length - 1].isLoading = true;
676
+ const agentSuggestions = this._suggestions[consumerAgentId];
677
+ if (agentSuggestions) {
678
+ var _this$_suggestions$co3;
679
+ agentSuggestions[suggestionId] = suggestions;
680
+ const allSuggestions = Object.values((_this$_suggestions$co3 = this._suggestions[consumerAgentId]) !== null && _this$_suggestions$co3 !== void 0 ? _this$_suggestions$co3 : {}).flat();
681
+ this.notifySuggestionsChanged(consumerAgentId, allSuggestions, "suggestions changed");
682
+ }
683
+ }
684
+ /**
685
+ * Notify subscribers of suggestions config changes
686
+ */
687
+ async notifySuggestionsConfigChanged() {
688
+ await this.core.notifySubscribers((subscriber) => {
689
+ var _subscriber$onSuggest;
690
+ return (_subscriber$onSuggest = subscriber.onSuggestionsConfigChanged) === null || _subscriber$onSuggest === void 0 ? void 0 : _subscriber$onSuggest.call(subscriber, {
691
+ copilotkit: this.core,
692
+ suggestionsConfig: this._suggestionsConfig
693
+ });
694
+ }, "Subscriber onSuggestionsConfigChanged error:");
695
+ }
696
+ /**
697
+ * Notify subscribers of suggestions changes
698
+ */
699
+ async notifySuggestionsChanged(agentId, suggestions, context = "") {
700
+ await this.core.notifySubscribers((subscriber) => {
701
+ var _subscriber$onSuggest2;
702
+ return (_subscriber$onSuggest2 = subscriber.onSuggestionsChanged) === null || _subscriber$onSuggest2 === void 0 ? void 0 : _subscriber$onSuggest2.call(subscriber, {
703
+ copilotkit: this.core,
704
+ agentId,
705
+ suggestions
706
+ });
707
+ }, `Subscriber onSuggestionsChanged error: ${context}`);
708
+ }
709
+ /**
710
+ * Notify subscribers that suggestions started loading
711
+ */
712
+ async notifySuggestionsStartedLoading(agentId) {
713
+ await this.core.notifySubscribers((subscriber) => {
714
+ var _subscriber$onSuggest3;
715
+ return (_subscriber$onSuggest3 = subscriber.onSuggestionsStartedLoading) === null || _subscriber$onSuggest3 === void 0 ? void 0 : _subscriber$onSuggest3.call(subscriber, {
716
+ copilotkit: this.core,
717
+ agentId
718
+ });
719
+ }, "Subscriber onSuggestionsStartedLoading error:");
720
+ }
721
+ /**
722
+ * Notify subscribers that suggestions finished loading
723
+ */
724
+ async notifySuggestionsFinishedLoading(agentId) {
725
+ await this.core.notifySubscribers((subscriber) => {
726
+ var _subscriber$onSuggest4;
727
+ return (_subscriber$onSuggest4 = subscriber.onSuggestionsFinishedLoading) === null || _subscriber$onSuggest4 === void 0 ? void 0 : _subscriber$onSuggest4.call(subscriber, {
728
+ copilotkit: this.core,
729
+ agentId
730
+ });
731
+ }, "Subscriber onSuggestionsFinishedLoading error:");
732
+ }
733
+ /**
734
+ * Check if suggestions should be shown based on availability and message count
735
+ */
736
+ shouldShowSuggestions(config, messageCount) {
737
+ const availability = config.available;
738
+ if (!availability) if (isDynamicSuggestionsConfig(config)) return messageCount > 0;
739
+ else return messageCount === 0;
740
+ switch (availability) {
741
+ case "disabled": return false;
742
+ case "before-first-message": return messageCount === 0;
743
+ case "after-first-message": return messageCount > 0;
744
+ case "always": return true;
745
+ default: return false;
746
+ }
747
+ }
748
+ /**
749
+ * Add static suggestions directly without AI generation
750
+ */
751
+ addStaticSuggestions(suggestionId, config, consumerAgentId) {
752
+ var _this$_suggestions$co4, _this$_suggestions$co5;
753
+ const suggestions = config.suggestions.map((s) => ({
754
+ ...s,
755
+ isLoading: false
756
+ }));
757
+ this._suggestions[consumerAgentId] = {
758
+ ...(_this$_suggestions$co4 = this._suggestions[consumerAgentId]) !== null && _this$_suggestions$co4 !== void 0 ? _this$_suggestions$co4 : {},
759
+ [suggestionId]: suggestions
760
+ };
761
+ const allSuggestions = Object.values((_this$_suggestions$co5 = this._suggestions[consumerAgentId]) !== null && _this$_suggestions$co5 !== void 0 ? _this$_suggestions$co5 : {}).flat();
762
+ this.notifySuggestionsChanged(consumerAgentId, allSuggestions, "static suggestions added");
763
+ }
764
+ };
765
+ /**
766
+ * Type guard for dynamic suggestions config
767
+ */
768
+ function isDynamicSuggestionsConfig(config) {
769
+ return "instructions" in config;
770
+ }
771
+ /**
772
+ * Type guard for static suggestions config
773
+ */
774
+ function isStaticSuggestionsConfig(config) {
775
+ return "suggestions" in config;
776
+ }
777
+ /**
778
+ * The tool definition for AI-generated suggestions
779
+ */
780
+ const SUGGEST_TOOL = {
781
+ name: "copilotkitSuggest",
782
+ description: "Suggest what the user could say next",
783
+ parameters: {
784
+ type: "object",
785
+ properties: { suggestions: {
786
+ type: "array",
787
+ description: "List of suggestions shown to the user as buttons.",
788
+ items: {
789
+ type: "object",
790
+ properties: {
791
+ title: {
792
+ type: "string",
793
+ description: "The title of the suggestion. This is shown as a button and should be short."
794
+ },
795
+ message: {
796
+ type: "string",
797
+ description: "The message to send when the suggestion is clicked. This should be a clear, complete sentence and will be sent as an instruction to the AI."
798
+ }
799
+ },
800
+ required: ["title", "message"]
801
+ }
802
+ } },
803
+ required: ["suggestions"]
804
+ }
805
+ };
806
+
807
+ //#endregion
808
+ //#region src/core/run-handler.ts
809
+ /**
810
+ * Handles agent execution, tool calling, and agent connectivity for CopilotKitCore.
811
+ * Manages the complete lifecycle of agent runs including tool execution and follow-ups.
812
+ */
813
+ var RunHandler = class {
814
+ constructor(core) {
815
+ this.core = core;
816
+ _defineProperty(this, "_tools", []);
817
+ }
818
+ /**
819
+ * Get all tools as a readonly array
820
+ */
821
+ get tools() {
822
+ return this._tools;
823
+ }
824
+ /**
825
+ * Initialize with tools
826
+ */
827
+ initialize(tools) {
828
+ this._tools = tools;
829
+ }
830
+ /**
831
+ * Add a tool to the registry
832
+ */
833
+ addTool(tool) {
834
+ if (this._tools.findIndex((t) => t.name === tool.name && t.agentId === tool.agentId) !== -1) {
835
+ _copilotkitnext_shared.logger.warn(`Tool already exists: '${tool.name}' for agent '${tool.agentId || "global"}', skipping.`);
836
+ return;
837
+ }
838
+ this._tools.push(tool);
839
+ }
840
+ /**
841
+ * Remove a tool by name and optionally by agentId
842
+ */
843
+ removeTool(id, agentId) {
844
+ this._tools = this._tools.filter((tool) => {
845
+ if (agentId !== void 0) return !(tool.name === id && tool.agentId === agentId);
846
+ return !(tool.name === id && !tool.agentId);
847
+ });
848
+ }
849
+ /**
850
+ * Get a tool by name and optionally by agentId.
851
+ * If agentId is provided, it will first look for an agent-specific tool,
852
+ * then fall back to a global tool with the same name.
853
+ */
854
+ getTool(params) {
855
+ const { toolName, agentId } = params;
856
+ if (agentId) {
857
+ const agentTool = this._tools.find((tool) => tool.name === toolName && tool.agentId === agentId);
858
+ if (agentTool) return agentTool;
859
+ }
860
+ return this._tools.find((tool) => tool.name === toolName && !tool.agentId);
861
+ }
862
+ /**
863
+ * Set all tools at once. Replaces existing tools.
864
+ */
865
+ setTools(tools) {
866
+ this._tools = [...tools];
867
+ }
868
+ /**
869
+ * Connect an agent (establish initial connection)
870
+ */
871
+ async connectAgent({ agent }) {
872
+ try {
873
+ await agent.detachActiveRun();
874
+ agent.setMessages([]);
875
+ agent.setState({});
876
+ if (agent instanceof _ag_ui_client.HttpAgent) agent.headers = { ...this.core.headers };
877
+ const runAgentResult = await agent.connectAgent({
878
+ forwardedProps: this.core.properties,
879
+ tools: this.buildFrontendTools(agent.agentId)
880
+ }, this.createAgentErrorSubscriber(agent));
881
+ return this.processAgentResult({
882
+ runAgentResult,
883
+ agent
884
+ });
885
+ } catch (error) {
886
+ const connectError = error instanceof Error ? error : new Error(String(error));
887
+ const context = {};
888
+ if (agent.agentId) context.agentId = agent.agentId;
889
+ await this.core.emitError({
890
+ error: connectError,
891
+ code: CopilotKitCoreErrorCode.AGENT_CONNECT_FAILED,
892
+ context
893
+ });
894
+ throw error;
895
+ }
896
+ }
897
+ /**
898
+ * Run an agent
899
+ */
900
+ async runAgent({ agent }) {
901
+ if (agent.agentId) this.core.suggestionEngine.clearSuggestions(agent.agentId);
902
+ if (agent instanceof _ag_ui_client.HttpAgent) agent.headers = { ...this.core.headers };
903
+ try {
904
+ const runAgentResult = await agent.runAgent({
905
+ forwardedProps: this.core.properties,
906
+ tools: this.buildFrontendTools(agent.agentId),
907
+ context: Object.values(this.core.context)
908
+ }, this.createAgentErrorSubscriber(agent));
909
+ return this.processAgentResult({
910
+ runAgentResult,
911
+ agent
912
+ });
913
+ } catch (error) {
914
+ const runError = error instanceof Error ? error : new Error(String(error));
915
+ const context = {};
916
+ if (agent.agentId) context.agentId = agent.agentId;
917
+ await this.core.emitError({
918
+ error: runError,
919
+ code: CopilotKitCoreErrorCode.AGENT_RUN_FAILED,
920
+ context
921
+ });
922
+ throw error;
923
+ }
924
+ }
925
+ /**
926
+ * Process agent result and execute tools
927
+ */
928
+ async processAgentResult({ runAgentResult, agent }) {
929
+ const { newMessages } = runAgentResult;
930
+ const agentId = agent.agentId;
931
+ let needsFollowUp = false;
932
+ for (const message of newMessages) if (message.role === "assistant") {
933
+ for (const toolCall of message.toolCalls || []) if (newMessages.findIndex((m) => m.role === "tool" && m.toolCallId === toolCall.id) === -1) {
934
+ const tool = this.getTool({
935
+ toolName: toolCall.function.name,
936
+ agentId: agent.agentId
937
+ });
938
+ if (tool) {
939
+ if (await this.executeSpecificTool(tool, toolCall, message, agent, agentId)) needsFollowUp = true;
940
+ } else {
941
+ const wildcardTool = this.getTool({
942
+ toolName: "*",
943
+ agentId: agent.agentId
944
+ });
945
+ if (wildcardTool) {
946
+ if (await this.executeWildcardTool(wildcardTool, toolCall, message, agent, agentId)) needsFollowUp = true;
947
+ }
948
+ }
949
+ }
950
+ }
951
+ if (needsFollowUp) return await this.runAgent({ agent });
952
+ this.core.suggestionEngine.reloadSuggestions(agentId);
953
+ return runAgentResult;
954
+ }
955
+ /**
956
+ * Execute a specific tool
957
+ */
958
+ async executeSpecificTool(tool, toolCall, message, agent, agentId) {
959
+ if ((tool === null || tool === void 0 ? void 0 : tool.agentId) && tool.agentId !== agent.agentId) return false;
960
+ let toolCallResult = "";
961
+ let errorMessage;
962
+ let isArgumentError = false;
963
+ if (tool === null || tool === void 0 ? void 0 : tool.handler) {
964
+ let parsedArgs;
965
+ try {
966
+ parsedArgs = JSON.parse(toolCall.function.arguments);
967
+ } catch (error) {
968
+ const parseError = error instanceof Error ? error : new Error(String(error));
969
+ errorMessage = parseError.message;
970
+ isArgumentError = true;
971
+ await this.core.emitError({
972
+ error: parseError,
973
+ code: CopilotKitCoreErrorCode.TOOL_ARGUMENT_PARSE_FAILED,
974
+ context: {
975
+ agentId,
976
+ toolCallId: toolCall.id,
977
+ toolName: toolCall.function.name,
978
+ rawArguments: toolCall.function.arguments,
979
+ toolType: "specific",
980
+ messageId: message.id
981
+ }
982
+ });
983
+ }
984
+ await this.core.notifySubscribers((subscriber) => {
985
+ var _subscriber$onToolExe;
986
+ return (_subscriber$onToolExe = subscriber.onToolExecutionStart) === null || _subscriber$onToolExe === void 0 ? void 0 : _subscriber$onToolExe.call(subscriber, {
987
+ copilotkit: this.core,
988
+ toolCallId: toolCall.id,
989
+ agentId,
990
+ toolName: toolCall.function.name,
991
+ args: parsedArgs
992
+ });
993
+ }, "Subscriber onToolExecutionStart error:");
994
+ if (!errorMessage) try {
995
+ const result = await tool.handler(parsedArgs, {
996
+ toolCall,
997
+ agent
998
+ });
999
+ if (result === void 0 || result === null) toolCallResult = "";
1000
+ else if (typeof result === "string") toolCallResult = result;
1001
+ else toolCallResult = JSON.stringify(result);
1002
+ } catch (error) {
1003
+ const handlerError = error instanceof Error ? error : new Error(String(error));
1004
+ errorMessage = handlerError.message;
1005
+ await this.core.emitError({
1006
+ error: handlerError,
1007
+ code: CopilotKitCoreErrorCode.TOOL_HANDLER_FAILED,
1008
+ context: {
1009
+ agentId,
1010
+ toolCallId: toolCall.id,
1011
+ toolName: toolCall.function.name,
1012
+ parsedArgs,
1013
+ toolType: "specific",
1014
+ messageId: message.id
1015
+ }
1016
+ });
1017
+ }
1018
+ if (errorMessage) toolCallResult = `Error: ${errorMessage}`;
1019
+ await this.core.notifySubscribers((subscriber) => {
1020
+ var _subscriber$onToolExe2;
1021
+ return (_subscriber$onToolExe2 = subscriber.onToolExecutionEnd) === null || _subscriber$onToolExe2 === void 0 ? void 0 : _subscriber$onToolExe2.call(subscriber, {
1022
+ copilotkit: this.core,
1023
+ toolCallId: toolCall.id,
1024
+ agentId,
1025
+ toolName: toolCall.function.name,
1026
+ result: errorMessage ? "" : toolCallResult,
1027
+ error: errorMessage
1028
+ });
1029
+ }, "Subscriber onToolExecutionEnd error:");
1030
+ if (isArgumentError) {
1031
+ var _errorMessage;
1032
+ throw new Error((_errorMessage = errorMessage) !== null && _errorMessage !== void 0 ? _errorMessage : "Tool execution failed");
1033
+ }
1034
+ }
1035
+ if (!errorMessage || !isArgumentError) {
1036
+ const messageIndex = agent.messages.findIndex((m) => m.id === message.id);
1037
+ if (messageIndex === -1) return false;
1038
+ const toolMessage = {
1039
+ id: (0, _copilotkitnext_shared.randomUUID)(),
1040
+ role: "tool",
1041
+ toolCallId: toolCall.id,
1042
+ content: toolCallResult
1043
+ };
1044
+ agent.messages.splice(messageIndex + 1, 0, toolMessage);
1045
+ if (!errorMessage && (tool === null || tool === void 0 ? void 0 : tool.followUp) !== false) return true;
1046
+ }
1047
+ return false;
1048
+ }
1049
+ /**
1050
+ * Execute a wildcard tool
1051
+ */
1052
+ async executeWildcardTool(wildcardTool, toolCall, message, agent, agentId) {
1053
+ if ((wildcardTool === null || wildcardTool === void 0 ? void 0 : wildcardTool.agentId) && wildcardTool.agentId !== agent.agentId) return false;
1054
+ let toolCallResult = "";
1055
+ let errorMessage;
1056
+ let isArgumentError = false;
1057
+ if (wildcardTool === null || wildcardTool === void 0 ? void 0 : wildcardTool.handler) {
1058
+ let parsedArgs;
1059
+ try {
1060
+ parsedArgs = JSON.parse(toolCall.function.arguments);
1061
+ } catch (error) {
1062
+ const parseError = error instanceof Error ? error : new Error(String(error));
1063
+ errorMessage = parseError.message;
1064
+ isArgumentError = true;
1065
+ await this.core.emitError({
1066
+ error: parseError,
1067
+ code: CopilotKitCoreErrorCode.TOOL_ARGUMENT_PARSE_FAILED,
1068
+ context: {
1069
+ agentId,
1070
+ toolCallId: toolCall.id,
1071
+ toolName: toolCall.function.name,
1072
+ rawArguments: toolCall.function.arguments,
1073
+ toolType: "wildcard",
1074
+ messageId: message.id
1075
+ }
1076
+ });
1077
+ }
1078
+ const wildcardArgs = {
1079
+ toolName: toolCall.function.name,
1080
+ args: parsedArgs
1081
+ };
1082
+ await this.core.notifySubscribers((subscriber) => {
1083
+ var _subscriber$onToolExe3;
1084
+ return (_subscriber$onToolExe3 = subscriber.onToolExecutionStart) === null || _subscriber$onToolExe3 === void 0 ? void 0 : _subscriber$onToolExe3.call(subscriber, {
1085
+ copilotkit: this.core,
1086
+ toolCallId: toolCall.id,
1087
+ agentId,
1088
+ toolName: toolCall.function.name,
1089
+ args: wildcardArgs
1090
+ });
1091
+ }, "Subscriber onToolExecutionStart error:");
1092
+ if (!errorMessage) try {
1093
+ const result = await wildcardTool.handler(wildcardArgs, {
1094
+ toolCall,
1095
+ agent
1096
+ });
1097
+ if (result === void 0 || result === null) toolCallResult = "";
1098
+ else if (typeof result === "string") toolCallResult = result;
1099
+ else toolCallResult = JSON.stringify(result);
1100
+ } catch (error) {
1101
+ const handlerError = error instanceof Error ? error : new Error(String(error));
1102
+ errorMessage = handlerError.message;
1103
+ await this.core.emitError({
1104
+ error: handlerError,
1105
+ code: CopilotKitCoreErrorCode.TOOL_HANDLER_FAILED,
1106
+ context: {
1107
+ agentId,
1108
+ toolCallId: toolCall.id,
1109
+ toolName: toolCall.function.name,
1110
+ parsedArgs: wildcardArgs,
1111
+ toolType: "wildcard",
1112
+ messageId: message.id
1113
+ }
1114
+ });
1115
+ }
1116
+ if (errorMessage) toolCallResult = `Error: ${errorMessage}`;
1117
+ await this.core.notifySubscribers((subscriber) => {
1118
+ var _subscriber$onToolExe4;
1119
+ return (_subscriber$onToolExe4 = subscriber.onToolExecutionEnd) === null || _subscriber$onToolExe4 === void 0 ? void 0 : _subscriber$onToolExe4.call(subscriber, {
1120
+ copilotkit: this.core,
1121
+ toolCallId: toolCall.id,
1122
+ agentId,
1123
+ toolName: toolCall.function.name,
1124
+ result: errorMessage ? "" : toolCallResult,
1125
+ error: errorMessage
1126
+ });
1127
+ }, "Subscriber onToolExecutionEnd error:");
1128
+ if (isArgumentError) {
1129
+ var _errorMessage2;
1130
+ throw new Error((_errorMessage2 = errorMessage) !== null && _errorMessage2 !== void 0 ? _errorMessage2 : "Tool execution failed");
1131
+ }
1132
+ }
1133
+ if (!errorMessage || !isArgumentError) {
1134
+ const messageIndex = agent.messages.findIndex((m) => m.id === message.id);
1135
+ if (messageIndex === -1) return false;
1136
+ const toolMessage = {
1137
+ id: (0, _copilotkitnext_shared.randomUUID)(),
1138
+ role: "tool",
1139
+ toolCallId: toolCall.id,
1140
+ content: toolCallResult
1141
+ };
1142
+ agent.messages.splice(messageIndex + 1, 0, toolMessage);
1143
+ if (!errorMessage && (wildcardTool === null || wildcardTool === void 0 ? void 0 : wildcardTool.followUp) !== false) return true;
1144
+ }
1145
+ return false;
1146
+ }
1147
+ /**
1148
+ * Build frontend tools for an agent
1149
+ */
1150
+ buildFrontendTools(agentId) {
1151
+ return this._tools.filter((tool) => tool.available !== false && (!tool.agentId || tool.agentId === agentId)).map((tool) => {
1152
+ var _tool$description;
1153
+ return {
1154
+ name: tool.name,
1155
+ description: (_tool$description = tool.description) !== null && _tool$description !== void 0 ? _tool$description : "",
1156
+ parameters: createToolSchema(tool)
1157
+ };
1158
+ });
1159
+ }
1160
+ /**
1161
+ * Create an agent error subscriber
1162
+ */
1163
+ createAgentErrorSubscriber(agent) {
1164
+ const emitAgentError = async (error, code, extraContext = {}) => {
1165
+ const context = { ...extraContext };
1166
+ if (agent.agentId) context.agentId = agent.agentId;
1167
+ await this.core.emitError({
1168
+ error,
1169
+ code,
1170
+ context
1171
+ });
1172
+ };
1173
+ return {
1174
+ onRunFailed: async ({ error }) => {
1175
+ await emitAgentError(error, CopilotKitCoreErrorCode.AGENT_RUN_FAILED_EVENT, { source: "onRunFailed" });
1176
+ },
1177
+ onRunErrorEvent: async ({ event }) => {
1178
+ var _event$rawEvent, _event$rawEvent2, _event$message;
1179
+ const eventError = (event === null || event === void 0 ? void 0 : event.rawEvent) instanceof Error ? event.rawEvent : (event === null || event === void 0 || (_event$rawEvent = event.rawEvent) === null || _event$rawEvent === void 0 ? void 0 : _event$rawEvent.error) instanceof Error ? event.rawEvent.error : void 0;
1180
+ const errorMessage = typeof (event === null || event === void 0 || (_event$rawEvent2 = event.rawEvent) === null || _event$rawEvent2 === void 0 ? void 0 : _event$rawEvent2.error) === "string" ? event.rawEvent.error : (_event$message = event === null || event === void 0 ? void 0 : event.message) !== null && _event$message !== void 0 ? _event$message : "Agent run error";
1181
+ const rawError = eventError !== null && eventError !== void 0 ? eventError : new Error(errorMessage);
1182
+ if ((event === null || event === void 0 ? void 0 : event.code) && !rawError.code) rawError.code = event.code;
1183
+ await emitAgentError(rawError, CopilotKitCoreErrorCode.AGENT_RUN_ERROR_EVENT, {
1184
+ source: "onRunErrorEvent",
1185
+ event,
1186
+ runtimeErrorCode: event === null || event === void 0 ? void 0 : event.code
1187
+ });
1188
+ }
1189
+ };
1190
+ }
1191
+ };
1192
+ /**
1193
+ * Empty tool schema constant
1194
+ */
1195
+ const EMPTY_TOOL_SCHEMA = {
1196
+ type: "object",
1197
+ properties: {}
1198
+ };
1199
+ /**
1200
+ * Create a JSON schema from a tool's parameters
1201
+ */
1202
+ function createToolSchema(tool) {
1203
+ if (!tool.parameters) return { ...EMPTY_TOOL_SCHEMA };
1204
+ const rawSchema = (0, zod_to_json_schema.zodToJsonSchema)(tool.parameters, { $refStrategy: "none" });
1205
+ if (!rawSchema || typeof rawSchema !== "object") return { ...EMPTY_TOOL_SCHEMA };
1206
+ const { $schema, ...schema } = rawSchema;
1207
+ if (typeof schema.type !== "string") schema.type = "object";
1208
+ if (typeof schema.properties !== "object" || schema.properties === null) schema.properties = {};
1209
+ stripAdditionalProperties(schema);
1210
+ return schema;
1211
+ }
1212
+ function stripAdditionalProperties(schema) {
1213
+ if (!schema || typeof schema !== "object") return;
1214
+ if (Array.isArray(schema)) {
1215
+ schema.forEach(stripAdditionalProperties);
1216
+ return;
1217
+ }
1218
+ const record = schema;
1219
+ if (record.additionalProperties !== void 0) delete record.additionalProperties;
1220
+ for (const value of Object.values(record)) stripAdditionalProperties(value);
1221
+ }
1222
+
1223
+ //#endregion
1224
+ //#region src/core/state-manager.ts
1225
+ /**
1226
+ * Manages state and message tracking by run for CopilotKitCore.
1227
+ * Tracks agent state snapshots and message-to-run associations.
1228
+ */
1229
+ var StateManager = class {
1230
+ constructor(core) {
1231
+ this.core = core;
1232
+ _defineProperty(this, "stateByRun", /* @__PURE__ */ new Map());
1233
+ _defineProperty(this, "messageToRun", /* @__PURE__ */ new Map());
1234
+ _defineProperty(this, "agentSubscriptions", /* @__PURE__ */ new Map());
1235
+ }
1236
+ /**
1237
+ * Initialize state tracking for an agent
1238
+ */
1239
+ initialize() {}
1240
+ /**
1241
+ * Subscribe to an agent's events to track state and messages
1242
+ */
1243
+ subscribeToAgent(agent) {
1244
+ if (!agent.agentId) return;
1245
+ const agentId = agent.agentId;
1246
+ this.unsubscribeFromAgent(agentId);
1247
+ const { unsubscribe } = agent.subscribe({
1248
+ onRunStartedEvent: ({ event, state }) => {
1249
+ this.handleRunStarted(agent, event, state);
1250
+ },
1251
+ onRunFinishedEvent: ({ event, state }) => {
1252
+ this.handleRunFinished(agent, event, state);
1253
+ },
1254
+ onStateSnapshotEvent: ({ event, input, state }) => {
1255
+ this.handleStateSnapshot(agent, event, input, state);
1256
+ },
1257
+ onStateDeltaEvent: ({ event, input, state }) => {
1258
+ this.handleStateDelta(agent, event, input, state);
1259
+ },
1260
+ onMessagesSnapshotEvent: ({ event, input, messages }) => {
1261
+ this.handleMessagesSnapshot(agent, event, input, messages);
1262
+ },
1263
+ onNewMessage: ({ message, input }) => {
1264
+ this.handleNewMessage(agent, message, input);
1265
+ }
1266
+ });
1267
+ this.agentSubscriptions.set(agentId, unsubscribe);
1268
+ }
1269
+ /**
1270
+ * Unsubscribe from an agent's events
1271
+ */
1272
+ unsubscribeFromAgent(agentId) {
1273
+ const unsubscribe = this.agentSubscriptions.get(agentId);
1274
+ if (unsubscribe) {
1275
+ unsubscribe();
1276
+ this.agentSubscriptions.delete(agentId);
1277
+ }
1278
+ }
1279
+ /**
1280
+ * Get state for a specific run
1281
+ * Returns a deep copy to prevent external mutations
1282
+ */
1283
+ getStateByRun(agentId, threadId, runId) {
1284
+ var _this$stateByRun$get;
1285
+ const state = (_this$stateByRun$get = this.stateByRun.get(agentId)) === null || _this$stateByRun$get === void 0 || (_this$stateByRun$get = _this$stateByRun$get.get(threadId)) === null || _this$stateByRun$get === void 0 ? void 0 : _this$stateByRun$get.get(runId);
1286
+ if (!state) return void 0;
1287
+ return JSON.parse(JSON.stringify(state));
1288
+ }
1289
+ /**
1290
+ * Get runId associated with a message
1291
+ */
1292
+ getRunIdForMessage(agentId, threadId, messageId) {
1293
+ var _this$messageToRun$ge;
1294
+ return (_this$messageToRun$ge = this.messageToRun.get(agentId)) === null || _this$messageToRun$ge === void 0 || (_this$messageToRun$ge = _this$messageToRun$ge.get(threadId)) === null || _this$messageToRun$ge === void 0 ? void 0 : _this$messageToRun$ge.get(messageId);
1295
+ }
1296
+ /**
1297
+ * Get all states for an agent's thread
1298
+ */
1299
+ getStatesForThread(agentId, threadId) {
1300
+ var _this$stateByRun$get$, _this$stateByRun$get2;
1301
+ return (_this$stateByRun$get$ = (_this$stateByRun$get2 = this.stateByRun.get(agentId)) === null || _this$stateByRun$get2 === void 0 ? void 0 : _this$stateByRun$get2.get(threadId)) !== null && _this$stateByRun$get$ !== void 0 ? _this$stateByRun$get$ : /* @__PURE__ */ new Map();
1302
+ }
1303
+ /**
1304
+ * Get all run IDs for an agent's thread
1305
+ */
1306
+ getRunIdsForThread(agentId, threadId) {
1307
+ var _this$stateByRun$get3;
1308
+ const threadStates = (_this$stateByRun$get3 = this.stateByRun.get(agentId)) === null || _this$stateByRun$get3 === void 0 ? void 0 : _this$stateByRun$get3.get(threadId);
1309
+ return threadStates ? Array.from(threadStates.keys()) : [];
1310
+ }
1311
+ /**
1312
+ * Handle run started event
1313
+ */
1314
+ handleRunStarted(agent, event, state) {
1315
+ if (!agent.agentId) return;
1316
+ const { threadId, runId } = event;
1317
+ this.saveState(agent.agentId, threadId, runId, state);
1318
+ }
1319
+ /**
1320
+ * Handle run finished event
1321
+ */
1322
+ handleRunFinished(agent, event, state) {
1323
+ if (!agent.agentId) return;
1324
+ const { threadId, runId } = event;
1325
+ this.saveState(agent.agentId, threadId, runId, state);
1326
+ }
1327
+ /**
1328
+ * Handle state snapshot event
1329
+ */
1330
+ handleStateSnapshot(agent, event, input, state) {
1331
+ if (!agent.agentId) return;
1332
+ const { threadId, runId } = input;
1333
+ const mergedState = {
1334
+ ...state,
1335
+ ...event.snapshot
1336
+ };
1337
+ this.saveState(agent.agentId, threadId, runId, mergedState);
1338
+ }
1339
+ /**
1340
+ * Handle state delta event
1341
+ */
1342
+ handleStateDelta(agent, event, input, state) {
1343
+ if (!agent.agentId) return;
1344
+ const { threadId, runId } = input;
1345
+ this.saveState(agent.agentId, threadId, runId, state);
1346
+ }
1347
+ /**
1348
+ * Handle messages snapshot event
1349
+ */
1350
+ handleMessagesSnapshot(agent, event, input, messages) {
1351
+ if (!agent.agentId) return;
1352
+ const { threadId, runId } = input;
1353
+ for (const message of event.messages) this.associateMessageWithRun(agent.agentId, threadId, message.id, runId);
1354
+ }
1355
+ /**
1356
+ * Handle new message event
1357
+ */
1358
+ handleNewMessage(agent, message, input) {
1359
+ if (!agent.agentId || !input) return;
1360
+ const { threadId, runId } = input;
1361
+ this.associateMessageWithRun(agent.agentId, threadId, message.id, runId);
1362
+ }
1363
+ /**
1364
+ * Save state for a specific run
1365
+ */
1366
+ saveState(agentId, threadId, runId, state) {
1367
+ if (!this.stateByRun.has(agentId)) this.stateByRun.set(agentId, /* @__PURE__ */ new Map());
1368
+ const agentStates = this.stateByRun.get(agentId);
1369
+ if (!agentStates.has(threadId)) agentStates.set(threadId, /* @__PURE__ */ new Map());
1370
+ agentStates.get(threadId).set(runId, JSON.parse(JSON.stringify(state)));
1371
+ }
1372
+ /**
1373
+ * Associate a message with a run
1374
+ */
1375
+ associateMessageWithRun(agentId, threadId, messageId, runId) {
1376
+ if (!this.messageToRun.has(agentId)) this.messageToRun.set(agentId, /* @__PURE__ */ new Map());
1377
+ const agentMessages = this.messageToRun.get(agentId);
1378
+ if (!agentMessages.has(threadId)) agentMessages.set(threadId, /* @__PURE__ */ new Map());
1379
+ agentMessages.get(threadId).set(messageId, runId);
1380
+ }
1381
+ /**
1382
+ * Clear all state for an agent
1383
+ */
1384
+ clearAgentState(agentId) {
1385
+ this.stateByRun.delete(agentId);
1386
+ this.messageToRun.delete(agentId);
1387
+ }
1388
+ /**
1389
+ * Clear all state for a thread
1390
+ */
1391
+ clearThreadState(agentId, threadId) {
1392
+ var _this$stateByRun$get4, _this$messageToRun$ge2;
1393
+ (_this$stateByRun$get4 = this.stateByRun.get(agentId)) === null || _this$stateByRun$get4 === void 0 || _this$stateByRun$get4.delete(threadId);
1394
+ (_this$messageToRun$ge2 = this.messageToRun.get(agentId)) === null || _this$messageToRun$ge2 === void 0 || _this$messageToRun$ge2.delete(threadId);
1395
+ }
1396
+ };
1397
+
1398
+ //#endregion
1399
+ //#region src/core/core.ts
1400
+ let CopilotKitCoreErrorCode = /* @__PURE__ */ function(CopilotKitCoreErrorCode) {
1401
+ CopilotKitCoreErrorCode["RUNTIME_INFO_FETCH_FAILED"] = "runtime_info_fetch_failed";
1402
+ CopilotKitCoreErrorCode["AGENT_CONNECT_FAILED"] = "agent_connect_failed";
1403
+ CopilotKitCoreErrorCode["AGENT_RUN_FAILED"] = "agent_run_failed";
1404
+ CopilotKitCoreErrorCode["AGENT_RUN_FAILED_EVENT"] = "agent_run_failed_event";
1405
+ CopilotKitCoreErrorCode["AGENT_RUN_ERROR_EVENT"] = "agent_run_error_event";
1406
+ CopilotKitCoreErrorCode["TOOL_ARGUMENT_PARSE_FAILED"] = "tool_argument_parse_failed";
1407
+ CopilotKitCoreErrorCode["TOOL_HANDLER_FAILED"] = "tool_handler_failed";
1408
+ CopilotKitCoreErrorCode["TRANSCRIPTION_FAILED"] = "transcription_failed";
1409
+ CopilotKitCoreErrorCode["TRANSCRIPTION_SERVICE_NOT_CONFIGURED"] = "transcription_service_not_configured";
1410
+ CopilotKitCoreErrorCode["TRANSCRIPTION_INVALID_AUDIO"] = "transcription_invalid_audio";
1411
+ CopilotKitCoreErrorCode["TRANSCRIPTION_RATE_LIMITED"] = "transcription_rate_limited";
1412
+ CopilotKitCoreErrorCode["TRANSCRIPTION_AUTH_FAILED"] = "transcription_auth_failed";
1413
+ CopilotKitCoreErrorCode["TRANSCRIPTION_NETWORK_ERROR"] = "transcription_network_error";
1414
+ return CopilotKitCoreErrorCode;
1415
+ }({});
1416
+ let CopilotKitCoreRuntimeConnectionStatus = /* @__PURE__ */ function(CopilotKitCoreRuntimeConnectionStatus) {
1417
+ CopilotKitCoreRuntimeConnectionStatus["Disconnected"] = "disconnected";
1418
+ CopilotKitCoreRuntimeConnectionStatus["Connected"] = "connected";
1419
+ CopilotKitCoreRuntimeConnectionStatus["Connecting"] = "connecting";
1420
+ CopilotKitCoreRuntimeConnectionStatus["Error"] = "error";
1421
+ return CopilotKitCoreRuntimeConnectionStatus;
1422
+ }({});
1423
+ var CopilotKitCore = class {
1424
+ constructor({ runtimeUrl, runtimeTransport = "rest", headers = {}, credentials, properties = {}, agents__unsafe_dev_only = {}, tools = [], suggestionsConfig = [] }) {
1425
+ _defineProperty(this, "_headers", void 0);
1426
+ _defineProperty(this, "_credentials", void 0);
1427
+ _defineProperty(this, "_properties", void 0);
1428
+ _defineProperty(this, "subscribers", /* @__PURE__ */ new Set());
1429
+ _defineProperty(this, "agentRegistry", void 0);
1430
+ _defineProperty(this, "contextStore", void 0);
1431
+ _defineProperty(this, "suggestionEngine", void 0);
1432
+ _defineProperty(this, "runHandler", void 0);
1433
+ _defineProperty(this, "stateManager", void 0);
1434
+ this._headers = headers;
1435
+ this._credentials = credentials;
1436
+ this._properties = properties;
1437
+ this.agentRegistry = new AgentRegistry(this);
1438
+ this.contextStore = new ContextStore(this);
1439
+ this.suggestionEngine = new SuggestionEngine(this);
1440
+ this.runHandler = new RunHandler(this);
1441
+ this.stateManager = new StateManager(this);
1442
+ this.agentRegistry.initialize(agents__unsafe_dev_only);
1443
+ this.runHandler.initialize(tools);
1444
+ this.suggestionEngine.initialize(suggestionsConfig);
1445
+ this.stateManager.initialize();
1446
+ this.agentRegistry.setRuntimeTransport(runtimeTransport);
1447
+ this.agentRegistry.setRuntimeUrl(runtimeUrl);
1448
+ this.subscribe({ onAgentsChanged: ({ agents }) => {
1449
+ Object.values(agents).forEach((agent) => {
1450
+ if (agent.agentId) this.stateManager.subscribeToAgent(agent);
1451
+ });
1452
+ } });
1453
+ }
1454
+ /**
1455
+ * Internal method used by delegate classes and subclasses to notify subscribers
1456
+ */
1457
+ async notifySubscribers(handler, errorMessage) {
1458
+ await Promise.all(Array.from(this.subscribers).map(async (subscriber) => {
1459
+ try {
1460
+ await handler(subscriber);
1461
+ } catch (error) {
1462
+ console.error(errorMessage, error);
1463
+ }
1464
+ }));
1465
+ }
1466
+ /**
1467
+ * Internal method used by delegate classes to emit errors
1468
+ */
1469
+ async emitError({ error, code, context = {} }) {
1470
+ await this.notifySubscribers((subscriber) => {
1471
+ var _subscriber$onError;
1472
+ return (_subscriber$onError = subscriber.onError) === null || _subscriber$onError === void 0 ? void 0 : _subscriber$onError.call(subscriber, {
1473
+ copilotkit: this,
1474
+ error,
1475
+ code,
1476
+ context
1477
+ });
1478
+ }, "Subscriber onError error:");
1479
+ }
1480
+ /**
1481
+ * Snapshot accessors
1482
+ */
1483
+ get context() {
1484
+ return this.contextStore.context;
1485
+ }
1486
+ get agents() {
1487
+ return this.agentRegistry.agents;
1488
+ }
1489
+ get tools() {
1490
+ return this.runHandler.tools;
1491
+ }
1492
+ get runtimeUrl() {
1493
+ return this.agentRegistry.runtimeUrl;
1494
+ }
1495
+ setRuntimeUrl(runtimeUrl) {
1496
+ this.agentRegistry.setRuntimeUrl(runtimeUrl);
1497
+ }
1498
+ get runtimeTransport() {
1499
+ return this.agentRegistry.runtimeTransport;
1500
+ }
1501
+ setRuntimeTransport(runtimeTransport) {
1502
+ this.agentRegistry.setRuntimeTransport(runtimeTransport);
1503
+ }
1504
+ get runtimeVersion() {
1505
+ return this.agentRegistry.runtimeVersion;
1506
+ }
1507
+ get headers() {
1508
+ return this._headers;
1509
+ }
1510
+ get credentials() {
1511
+ return this._credentials;
1512
+ }
1513
+ get properties() {
1514
+ return this._properties;
1515
+ }
1516
+ get runtimeConnectionStatus() {
1517
+ return this.agentRegistry.runtimeConnectionStatus;
1518
+ }
1519
+ get audioFileTranscriptionEnabled() {
1520
+ return this.agentRegistry.audioFileTranscriptionEnabled;
1521
+ }
1522
+ /**
1523
+ * Configuration updates
1524
+ */
1525
+ setHeaders(headers) {
1526
+ this._headers = headers;
1527
+ this.agentRegistry.applyHeadersToAgents(this.agentRegistry.agents);
1528
+ this.notifySubscribers((subscriber) => {
1529
+ var _subscriber$onHeaders;
1530
+ return (_subscriber$onHeaders = subscriber.onHeadersChanged) === null || _subscriber$onHeaders === void 0 ? void 0 : _subscriber$onHeaders.call(subscriber, {
1531
+ copilotkit: this,
1532
+ headers: this.headers
1533
+ });
1534
+ }, "Subscriber onHeadersChanged error:");
1535
+ }
1536
+ setCredentials(credentials) {
1537
+ this._credentials = credentials;
1538
+ this.agentRegistry.applyCredentialsToAgents(this.agentRegistry.agents);
1539
+ }
1540
+ setProperties(properties) {
1541
+ this._properties = properties;
1542
+ this.notifySubscribers((subscriber) => {
1543
+ var _subscriber$onPropert;
1544
+ return (_subscriber$onPropert = subscriber.onPropertiesChanged) === null || _subscriber$onPropert === void 0 ? void 0 : _subscriber$onPropert.call(subscriber, {
1545
+ copilotkit: this,
1546
+ properties: this.properties
1547
+ });
1548
+ }, "Subscriber onPropertiesChanged error:");
1549
+ }
1550
+ /**
1551
+ * Agent management (delegated to AgentRegistry)
1552
+ */
1553
+ setAgents__unsafe_dev_only(agents) {
1554
+ this.agentRegistry.setAgents__unsafe_dev_only(agents);
1555
+ }
1556
+ addAgent__unsafe_dev_only(params) {
1557
+ this.agentRegistry.addAgent__unsafe_dev_only(params);
1558
+ }
1559
+ removeAgent__unsafe_dev_only(id) {
1560
+ this.agentRegistry.removeAgent__unsafe_dev_only(id);
1561
+ }
1562
+ getAgent(id) {
1563
+ return this.agentRegistry.getAgent(id);
1564
+ }
1565
+ /**
1566
+ * Context management (delegated to ContextStore)
1567
+ */
1568
+ addContext(context) {
1569
+ return this.contextStore.addContext(context);
1570
+ }
1571
+ removeContext(id) {
1572
+ this.contextStore.removeContext(id);
1573
+ }
1574
+ /**
1575
+ * Suggestions management (delegated to SuggestionEngine)
1576
+ */
1577
+ addSuggestionsConfig(config) {
1578
+ return this.suggestionEngine.addSuggestionsConfig(config);
1579
+ }
1580
+ removeSuggestionsConfig(id) {
1581
+ this.suggestionEngine.removeSuggestionsConfig(id);
1582
+ }
1583
+ reloadSuggestions(agentId) {
1584
+ this.suggestionEngine.reloadSuggestions(agentId);
1585
+ }
1586
+ clearSuggestions(agentId) {
1587
+ this.suggestionEngine.clearSuggestions(agentId);
1588
+ }
1589
+ getSuggestions(agentId) {
1590
+ return this.suggestionEngine.getSuggestions(agentId);
1591
+ }
1592
+ /**
1593
+ * Tool management (delegated to RunHandler)
1594
+ */
1595
+ addTool(tool) {
1596
+ this.runHandler.addTool(tool);
1597
+ }
1598
+ removeTool(id, agentId) {
1599
+ this.runHandler.removeTool(id, agentId);
1600
+ }
1601
+ getTool(params) {
1602
+ return this.runHandler.getTool(params);
1603
+ }
1604
+ setTools(tools) {
1605
+ this.runHandler.setTools(tools);
1606
+ }
1607
+ /**
1608
+ * Subscription lifecycle
1609
+ */
1610
+ subscribe(subscriber) {
1611
+ this.subscribers.add(subscriber);
1612
+ return { unsubscribe: () => {
1613
+ this.subscribers.delete(subscriber);
1614
+ } };
1615
+ }
1616
+ /**
1617
+ * Agent connectivity (delegated to RunHandler)
1618
+ */
1619
+ async connectAgent(params) {
1620
+ return this.runHandler.connectAgent(params);
1621
+ }
1622
+ stopAgent(params) {
1623
+ params.agent.abortRun();
1624
+ }
1625
+ async runAgent(params) {
1626
+ return this.runHandler.runAgent(params);
1627
+ }
1628
+ /**
1629
+ * State management (delegated to StateManager)
1630
+ */
1631
+ getStateByRun(agentId, threadId, runId) {
1632
+ return this.stateManager.getStateByRun(agentId, threadId, runId);
1633
+ }
1634
+ getRunIdForMessage(agentId, threadId, messageId) {
1635
+ return this.stateManager.getRunIdForMessage(agentId, threadId, messageId);
1636
+ }
1637
+ getRunIdsForThread(agentId, threadId) {
1638
+ return this.stateManager.getRunIdsForThread(agentId, threadId);
1639
+ }
1640
+ /**
1641
+ * Internal method used by RunHandler to build frontend tools
1642
+ */
1643
+ buildFrontendTools(agentId) {
1644
+ return this.runHandler.buildFrontendTools(agentId);
1645
+ }
1646
+ };
1647
+
1648
+ //#endregion
1649
+ //#region src/types.ts
1650
+ /**
1651
+ * Status of a tool call execution
1652
+ */
1653
+ let ToolCallStatus = /* @__PURE__ */ function(ToolCallStatus) {
1654
+ ToolCallStatus["InProgress"] = "inProgress";
1655
+ ToolCallStatus["Executing"] = "executing";
1656
+ ToolCallStatus["Complete"] = "complete";
1657
+ return ToolCallStatus;
1658
+ }({});
1659
+
1660
+ //#endregion
1661
+ //#region src/utils/markdown.ts
1662
+ function completePartialMarkdown(input) {
1663
+ let s = input;
1664
+ const fenceMatches = Array.from(s.matchAll(/^(\s*)(`{3,}|~{3,})/gm));
1665
+ if (fenceMatches.length % 2 === 1) {
1666
+ const [, indent, fence] = fenceMatches[0];
1667
+ s += `\n${indent}${fence}`;
1668
+ }
1669
+ if (s.match(/\[([^\]]*)\]\(([^)]*)$/)) s += ")";
1670
+ const openElements = [];
1671
+ const chars = Array.from(s);
1672
+ const codeBlockRanges = [];
1673
+ const inlineCodeRanges = [];
1674
+ let tempCodeFenceCount = 0;
1675
+ let currentCodeBlockStart = -1;
1676
+ for (let i = 0; i < chars.length; i++) if (i === 0 || chars[i - 1] === "\n") {
1677
+ const lineMatch = s.substring(i).match(/^(\s*)(`{3,}|~{3,})/);
1678
+ if (lineMatch) {
1679
+ tempCodeFenceCount++;
1680
+ if (tempCodeFenceCount % 2 === 1) currentCodeBlockStart = i;
1681
+ else if (currentCodeBlockStart !== -1) {
1682
+ codeBlockRanges.push({
1683
+ start: currentCodeBlockStart,
1684
+ end: i + lineMatch[0].length
1685
+ });
1686
+ currentCodeBlockStart = -1;
1687
+ }
1688
+ i += lineMatch[0].length - 1;
1689
+ }
1690
+ }
1691
+ for (let i = 0; i < chars.length; i++) if (chars[i] === "`") {
1692
+ let backslashCount = 0;
1693
+ for (let j = i - 1; j >= 0 && chars[j] === "\\"; j--) backslashCount++;
1694
+ if (backslashCount % 2 === 0) {
1695
+ for (let j = i + 1; j < chars.length; j++) if (chars[j] === "`") {
1696
+ let closingBackslashCount = 0;
1697
+ for (let k = j - 1; k >= 0 && chars[k] === "\\"; k--) closingBackslashCount++;
1698
+ if (closingBackslashCount % 2 === 0) {
1699
+ inlineCodeRanges.push({
1700
+ start: i,
1701
+ end: j + 1
1702
+ });
1703
+ i = j;
1704
+ break;
1705
+ }
1706
+ }
1707
+ }
1708
+ }
1709
+ const isInCode = (pos) => {
1710
+ return codeBlockRanges.some((range) => pos >= range.start && pos < range.end) || inlineCodeRanges.some((range) => pos >= range.start && pos < range.end);
1711
+ };
1712
+ for (let i = 0; i < chars.length; i++) {
1713
+ const char = chars[i];
1714
+ const nextChar = chars[i + 1];
1715
+ const prevChar = chars[i - 1];
1716
+ if (isInCode(i)) continue;
1717
+ if (char === "[") {
1718
+ let isCompleteLink = false;
1719
+ let bracketDepth = 1;
1720
+ let j = i + 1;
1721
+ while (j < chars.length && bracketDepth > 0) {
1722
+ if (chars[j] === "[" && !isInCode(j)) bracketDepth++;
1723
+ if (chars[j] === "]" && !isInCode(j)) bracketDepth--;
1724
+ j++;
1725
+ }
1726
+ if (bracketDepth === 0 && chars[j] === "(") {
1727
+ let parenDepth = 1;
1728
+ j++;
1729
+ while (j < chars.length && parenDepth > 0) {
1730
+ if (chars[j] === "(" && !isInCode(j)) parenDepth++;
1731
+ if (chars[j] === ")" && !isInCode(j)) parenDepth--;
1732
+ j++;
1733
+ }
1734
+ if (parenDepth === 0) {
1735
+ isCompleteLink = true;
1736
+ i = j - 1;
1737
+ continue;
1738
+ }
1739
+ }
1740
+ if (!isCompleteLink) {
1741
+ const existingIndex = openElements.findIndex((el) => el.type === "bracket");
1742
+ if (existingIndex !== -1) openElements.splice(existingIndex, 1);
1743
+ else openElements.push({
1744
+ type: "bracket",
1745
+ marker: "[",
1746
+ position: i
1747
+ });
1748
+ }
1749
+ } else if (char === "*" && nextChar === "*") {
1750
+ const existingIndex = openElements.findIndex((el) => el.type === "bold_star");
1751
+ if (existingIndex !== -1) openElements.splice(existingIndex, 1);
1752
+ else openElements.push({
1753
+ type: "bold_star",
1754
+ marker: "**",
1755
+ position: i
1756
+ });
1757
+ i++;
1758
+ } else if (char === "_" && nextChar === "_") {
1759
+ const existingIndex = openElements.findIndex((el) => el.type === "bold_underscore");
1760
+ if (existingIndex !== -1) openElements.splice(existingIndex, 1);
1761
+ else openElements.push({
1762
+ type: "bold_underscore",
1763
+ marker: "__",
1764
+ position: i
1765
+ });
1766
+ i++;
1767
+ } else if (char === "~" && nextChar === "~") {
1768
+ const existingIndex = openElements.findIndex((el) => el.type === "strike");
1769
+ if (existingIndex !== -1) openElements.splice(existingIndex, 1);
1770
+ else openElements.push({
1771
+ type: "strike",
1772
+ marker: "~~",
1773
+ position: i
1774
+ });
1775
+ i++;
1776
+ } else if (char === "*" && prevChar !== "*" && nextChar !== "*") {
1777
+ const existingIndex = openElements.findIndex((el) => el.type === "italic_star");
1778
+ if (existingIndex !== -1) openElements.splice(existingIndex, 1);
1779
+ else openElements.push({
1780
+ type: "italic_star",
1781
+ marker: "*",
1782
+ position: i
1783
+ });
1784
+ } else if (char === "_" && prevChar !== "_" && nextChar !== "_") {
1785
+ const existingIndex = openElements.findIndex((el) => el.type === "italic_underscore");
1786
+ if (existingIndex !== -1) openElements.splice(existingIndex, 1);
1787
+ else openElements.push({
1788
+ type: "italic_underscore",
1789
+ marker: "_",
1790
+ position: i
1791
+ });
1792
+ }
1793
+ }
1794
+ let backtickCount = 0;
1795
+ for (let i = 0; i < chars.length; i++) if (chars[i] === "`" && !isInCode(i)) backtickCount++;
1796
+ if (backtickCount % 2 === 1) s += "`";
1797
+ openElements.sort((a, b) => b.position - a.position);
1798
+ const closers = openElements.map((el) => {
1799
+ switch (el.type) {
1800
+ case "bracket": return "]";
1801
+ case "bold_star": return "**";
1802
+ case "bold_underscore": return "__";
1803
+ case "strike": return "~~";
1804
+ case "italic_star": return "*";
1805
+ case "italic_underscore": return "_";
1806
+ default: return "";
1807
+ }
1808
+ });
1809
+ let result = s + closers.join("");
1810
+ const finalFenceMatches = Array.from(result.matchAll(/^(\s*)(`{3,}|~{3,})/gm));
1811
+ const hasUnclosedBacktick = (result.match(/`/g) || []).length % 2 === 1;
1812
+ const hasUnclosedCodeFence = finalFenceMatches.length % 2 === 1;
1813
+ let shouldCloseParens = !hasUnclosedBacktick && !hasUnclosedCodeFence;
1814
+ if (shouldCloseParens) {
1815
+ const lastOpenParen = result.lastIndexOf("(");
1816
+ if (lastOpenParen !== -1) {
1817
+ if ((result.substring(0, lastOpenParen).match(/`/g) || []).length % 2 === 1) shouldCloseParens = false;
1818
+ }
1819
+ }
1820
+ if (shouldCloseParens) {
1821
+ const openParens = (result.match(/\(/g) || []).length;
1822
+ const closeParens = (result.match(/\)/g) || []).length;
1823
+ if (openParens > closeParens) result += ")".repeat(openParens - closeParens);
1824
+ }
1825
+ return result;
1826
+ }
1827
+
1828
+ //#endregion
1829
+ exports.AgentRegistry = AgentRegistry;
1830
+ exports.ContextStore = ContextStore;
1831
+ exports.CopilotKitCore = CopilotKitCore;
1832
+ exports.CopilotKitCoreErrorCode = CopilotKitCoreErrorCode;
1833
+ exports.CopilotKitCoreRuntimeConnectionStatus = CopilotKitCoreRuntimeConnectionStatus;
1834
+ exports.ProxiedCopilotRuntimeAgent = ProxiedCopilotRuntimeAgent;
1835
+ exports.RunHandler = RunHandler;
1836
+ exports.StateManager = StateManager;
1837
+ exports.SuggestionEngine = SuggestionEngine;
1838
+ exports.ToolCallStatus = ToolCallStatus;
1839
+ exports.completePartialMarkdown = completePartialMarkdown;
1840
+ });
1841
+ //# sourceMappingURL=index.umd.js.map