@copilotkitnext/core 1.51.4-next.2 → 1.51.4-next.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +6 -0
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +6 -0
- package/dist/index.mjs.map +1 -1
- package/dist/index.umd.js +1 -1
- package/dist/index.umd.js.map +1 -1
- package/package.json +4 -4
package/dist/index.umd.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
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),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),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}});
|
|
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
2
|
//# sourceMappingURL=index.umd.js.map
|