UNPKG

@squidcloud/client

Version:

A typescript implementation of the Squid client

1 lines 187 kB
(()=>{"use strict";var e={273(e,t){Object.defineProperty(t,"__esModule",{value:!0})},150(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,s)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),s=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(t,"__esModule",{value:!0});const r=i(642);t.default=r.PromisePool,s(i(273),t),s(i(642),t),s(i(837),t),s(i(426),t),s(i(858),t),s(i(172),t)},837(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePoolError=void 0;class i extends Error{constructor(e,t){super(),this.raw=e,this.item=t,this.name=this.constructor.name,this.message=this.messageFrom(e),Error.captureStackTrace&&"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}static createFrom(e,t){return new this(e,t)}messageFrom(e){return e instanceof Error||"object"==typeof e?e.message:"string"==typeof e||"number"==typeof e?e.toString():""}}t.PromisePoolError=i},234(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePoolExecutor=void 0;const n=i(642),s=i(172),r=i(837),o=i(858);t.PromisePoolExecutor=class{constructor(){this.meta={tasks:[],items:[],errors:[],results:[],stopped:!1,concurrency:10,shouldResultsCorrespond:!1,processedItems:[],processedItemsCounter:0,taskTimeout:0,shouldStoreProcessedItems:!0},this.handler=e=>e,this.errorHandler=void 0,this.onTaskStartedHandlers=[],this.onTaskFinishedHandlers=[]}useConcurrency(e){if(!this.isValidConcurrency(e))throw s.ValidationError.createFrom(`"concurrency" must be a number, 1 or up. Received "${e}" (${typeof e})`);return this.meta.concurrency=e,this}storeProcessedItems(e=!0){return this.meta.shouldStoreProcessedItems=e,this}shouldStoreProcessedItems(){return this.meta.shouldStoreProcessedItems}isValidConcurrency(e){return"number"==typeof e&&e>=1}withTaskTimeout(e){return this.meta.taskTimeout=e,this}concurrency(){return this.meta.concurrency}useCorrespondingResults(e){return this.meta.shouldResultsCorrespond=e,this}shouldUseCorrespondingResults(){return this.meta.shouldResultsCorrespond}taskTimeout(){return this.meta.taskTimeout}for(e){return this.meta.items=e,this}items(){return this.meta.items}itemsCount(){const e=this.items();return Array.isArray(e)?e.length:NaN}tasks(){return this.meta.tasks}activeTaskCount(){return this.activeTasksCount()}activeTasksCount(){return this.tasks().length}processedItems(){return this.meta.processedItems}flushProcessedItems(){this.meta.processedItems=[]}incrementProcessedItemsCounter(){this.meta.processedItemsCounter+=1}processedCount(){return this.meta.processedItemsCounter}processedPercentage(){return this.processedCount()/this.itemsCount()*100}results(){return this.meta.results}errors(){return this.meta.errors}withHandler(e){return this.handler=e,this}hasErrorHandler(){return!!this.errorHandler}handleError(e){return this.errorHandler=e,this}onTaskStarted(e){return this.onTaskStartedHandlers=e,this}onTaskFinished(e){return this.onTaskFinishedHandlers=e,this}hasReachedConcurrencyLimit(){return this.activeTasksCount()>=this.concurrency()}stop(){throw this.markAsStopped(),new o.StopThePromisePoolError}markAsStopped(){return this.meta.stopped=!0,this}isStopped(){return this.meta.stopped}async start(){return await this.validateInputs().prepareResultsArray().process()}validateInputs(){if("function"!=typeof this.handler)throw s.ValidationError.createFrom("The first parameter for the .process(fn) method must be a function");const e=this.taskTimeout();if(!(null==e||"number"==typeof e&&e>=0))throw s.ValidationError.createFrom(`"timeout" must be undefined or a number. A number must be 0 or up. Received "${String(e)}" (${typeof e})`);if(!this.areItemsValid())throw s.ValidationError.createFrom(`"items" must be an array, an iterable or an async iterable. Received "${typeof this.items()}"`);if(this.errorHandler&&"function"!=typeof this.errorHandler)throw s.ValidationError.createFrom(`The error handler must be a function. Received "${typeof this.errorHandler}"`);return this.onTaskStartedHandlers.forEach(e=>{if(e&&"function"!=typeof e)throw s.ValidationError.createFrom(`The onTaskStarted handler must be a function. Received "${typeof e}"`)}),this.onTaskFinishedHandlers.forEach(e=>{if(e&&"function"!=typeof e)throw s.ValidationError.createFrom(`The error handler must be a function. Received "${typeof e}"`)}),this}areItemsValid(){const e=this.items();return Array.isArray(e)||"function"==typeof e[Symbol.iterator]||"function"==typeof e[Symbol.asyncIterator]}prepareResultsArray(){const e=this.items();return Array.isArray(e)&&this.shouldUseCorrespondingResults()&&(this.meta.results=Array(e.length).fill(n.PromisePool.notRun)),this}async process(){let e=0;for await(const t of this.items()){if(this.isStopped())break;this.shouldUseCorrespondingResults()&&(this.results()[e]=n.PromisePool.notRun),this.startProcessing(t,e),e+=1,await this.waitForProcessingSlot()}return await this.drained()}async waitForProcessingSlot(){for(;this.hasReachedConcurrencyLimit();)await this.waitForActiveTaskToFinish()}async waitForActiveTaskToFinish(){await Promise.race(this.tasks())}startProcessing(e,t){const i=this.createTaskFor(e,t).then(e=>{this.save(e,t).removeActive(i)}).catch(async n=>{await this.handleErrorFor(n,e,t),this.removeActive(i)}).finally(()=>{this.shouldStoreProcessedItems()&&this.processedItems().push(e),this.incrementProcessedItemsCounter(),this.runOnTaskFinishedHandlers(e)});this.tasks().push(i),this.runOnTaskStartedHandlers(e)}async createTaskFor(e,t){if(void 0===this.taskTimeout())return this.handler(e,t,this);const[i,n]=this.createTaskTimeout(e);return Promise.race([this.handler(e,t,this),i()]).finally(n)}createTaskTimeout(e){let t;return[async()=>new Promise((i,n)=>{t=setTimeout(()=>{n(new r.PromisePoolError(`Task in promise pool timed out after ${this.taskTimeout()}ms`,e))},this.taskTimeout())}),()=>clearTimeout(t)]}save(e,t){return this.shouldUseCorrespondingResults()?this.results()[t]=e:this.results().push(e),this}removeActive(e){return this.tasks().splice(this.tasks().indexOf(e),1),this}async handleErrorFor(e,t,i){if(this.shouldUseCorrespondingResults()&&(this.results()[i]=n.PromisePool.failed),!this.isStoppingThePoolError(e)){if(this.isValidationError(e))throw this.markAsStopped(),e;this.hasErrorHandler()?await this.runErrorHandlerFor(e,t):this.saveErrorFor(e,t)}}isStoppingThePoolError(e){return e instanceof o.StopThePromisePoolError}isValidationError(e){return e instanceof s.ValidationError}async runErrorHandlerFor(e,t){try{await(this.errorHandler?.(e,t,this))}catch(e){this.rethrowIfNotStoppingThePool(e)}}runOnTaskStartedHandlers(e){this.onTaskStartedHandlers.forEach(t=>{t(e,this)})}runOnTaskFinishedHandlers(e){this.onTaskFinishedHandlers.forEach(t=>{t(e,this)})}rethrowIfNotStoppingThePool(e){if(!this.isStoppingThePoolError(e))throw e}saveErrorFor(e,t){this.errors().push(r.PromisePoolError.createFrom(e,t))}async drained(){return await this.drainActiveTasks(),{errors:this.errors(),results:this.results()}}async drainActiveTasks(){await Promise.all(this.tasks())}}},642(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePool=void 0;const n=i(234);class s{constructor(e){this.shouldStoreProcessedItems=!0,this.timeout=void 0,this.concurrency=10,this.items=e??[],this.errorHandler=void 0,this.onTaskStartedHandlers=[],this.onTaskFinishedHandlers=[],this.shouldResultsCorrespond=!1}withConcurrency(e){return this.concurrency=e,this}static withConcurrency(e){return(new this).withConcurrency(e)}withTaskTimeout(e){return this.timeout=e,this}static withTaskTimeout(e){return(new this).withTaskTimeout(e)}for(e){const t=new s(e).withConcurrency(this.concurrency);return"function"==typeof this.errorHandler&&t.handleError(this.errorHandler),"number"==typeof this.timeout?t.withTaskTimeout(this.timeout):t}static for(e){return(new this).for(e)}handleError(e){return this.errorHandler=e,this}onTaskStarted(e){return this.onTaskStartedHandlers.push(e),this}dontStoreProcessedItems(){return this.shouldStoreProcessedItems=!1,this}onTaskFinished(e){return this.onTaskFinishedHandlers.push(e),this}useCorrespondingResults(){return this.shouldResultsCorrespond=!0,this}async process(e){return(new n.PromisePoolExecutor).useConcurrency(this.concurrency).useCorrespondingResults(this.shouldResultsCorrespond).storeProcessedItems(this.shouldStoreProcessedItems).withTaskTimeout(this.timeout).withHandler(e).handleError(this.errorHandler).onTaskStarted(this.onTaskStartedHandlers).onTaskFinished(this.onTaskFinishedHandlers).for(this.items).start()}}t.PromisePool=s,s.notRun=Symbol("notRun"),s.failed=Symbol("failed")},426(e,t){Object.defineProperty(t,"__esModule",{value:!0})},858(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.StopThePromisePoolError=void 0;class i extends Error{}t.StopThePromisePoolError=i},172(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.ValidationError=void 0;class i extends Error{constructor(e){super(e),Error.captureStackTrace&&"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}static createFrom(e){return new this(e)}}t.ValidationError=i},86(e){e.exports=require("ws")}},t={};function i(n){var s=t[n];if(void 0!==s)return s.exports;var r=t[n]={exports:{}};return e[n].call(r.exports,r,r.exports,i),r.exports}i.d=(e,t)=>{for(var n in t)i.o(t,n)&&!i.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n={};i.r(n),i.d(n,{AGENT_STATUS_TITLE_ACCESSING_KB:()=>ge,AGENT_STATUS_TITLE_AGENT_RESPONSE:()=>pe,AGENT_STATUS_TITLE_CALLING_AI_FUNCTION:()=>fe,AGENT_STATUS_TITLE_INSPECTING_KB_METADATA:()=>ye,AGENT_STATUS_TITLE_QUERYING_SPREADSHEET:()=>me,AI_AGENTS_INTEGRATION_ID:()=>Ze,AI_AUDIO_CREATE_SPEECH_MODEL_NAMES:()=>Qe,AI_AUDIO_TRANSCRIPTION_MODEL_NAMES:()=>Le,AI_CHAT_MESSAGE_SOURCE:()=>Ie,AI_EMBEDDINGS_MODEL_NAMES:()=>Ae,AI_IMAGE_MODEL_NAMES:()=>Be,AI_MODEL_SOURCES:()=>$e,AI_PROVIDER_TYPES:()=>ve,ALL_OPERATORS:()=>It,ANTHROPIC_CHAT_MODEL_NAMES:()=>_e,API_INJECTION_FIELD_TYPES:()=>Ke,ARRAY_OPERATORS:()=>mt,AUTH_INTEGRATION_TYPES:()=>it,AdminClient:()=>d,AiAgentClient:()=>ne,AiAgentReference:()=>te,AiAudioClient:()=>re,AiClient:()=>St,AiFilesClient:()=>oe,AiImageClient:()=>ae,AiKnowledgeBaseClient:()=>le,AiKnowledgeBaseReference:()=>ue,AiMatchMakingClient:()=>de,ApiClient:()=>Mt,ApiKeysSecretClient:()=>l,AuthManager:()=>_t,BEDROCK_EMBEDDING_MODEL_NAMES:()=>De,BUILT_IN_AGENT_ID:()=>Je,BUILT_IN_DB_INTEGRATION_ID:()=>ot,BUILT_IN_QUEUE_INTEGRATION_ID:()=>at,BUILT_IN_STORAGE_INTEGRATION_ID:()=>ct,BackendFunctionManager:()=>Wt,BaseQueryBuilder:()=>gi,CLIENT_CONNECTION_STATES:()=>vt,CLIENT_ID_GENERATOR_KEY:()=>Zt,CLIENT_REQUEST_ID_GENERATOR_KEY:()=>ei,CONNECTOR_IDS:()=>Ye,Changes:()=>mi,ClientIdService:()=>Xt,CollectionReference:()=>wi,CollectionReferenceFactory:()=>_i,ConnectionDetails:()=>Ti,ConnectorClient:()=>a,DATA_INTEGRATION_TYPES:()=>tt,DEFAULT_SHORT_ID_LENGTH:()=>K,DOC_ID_FIELD:()=>yt,DataManager:()=>Vi,DereferencedJoin:()=>bi,DestructManager:()=>Wi,DistributedLockImpl:()=>Ji,DistributedLockManager:()=>zi,DocumentReference:()=>di,DocumentReferenceFactory:()=>Xi,DocumentStore:()=>Zi,EMPTY_CHAT_ID:()=>se,ENVIRONMENT_IDS:()=>ze,EventsClient:()=>en,ExternalAuthClient:()=>tn,ExtractionClient:()=>nn,FETCH_BEYOND_LIMIT:()=>ts,FLUX_MODEL_NAMES:()=>Pe,GEMINI_CHAT_MODEL_NAMES:()=>we,GRAPHQL_INTEGRATION_TYPES:()=>nt,GROK_CHAT_MODEL_NAMES:()=>Me,GroupedJoin:()=>Si,HTTP_INTEGRATION_TYPES:()=>st,HttpStatus:()=>Xe,INTEGRATION_SCHEMA_TYPES:()=>rt,INTEGRATION_TYPES:()=>et,IntegrationClient:()=>c,JobClient:()=>sn,JoinQueryBuilder:()=>Ii,LastUsedValueExecuteFunctionCache:()=>Ht,LimitUnderflowState:()=>Hi,LocalQueryManager:()=>On,METRIC_DOMAIN:()=>pt,METRIC_FUNCTIONS:()=>ht,METRIC_INTERVAL_ALIGNMENT:()=>gt,METRIC_NO_DATA_BEHAVIOR:()=>ft,ManagementClient:()=>In,MatchMaker:()=>he,MutationSender:()=>bn,NOOP_FN:()=>cn,NativeQueryManager:()=>vn,NotificationClient:()=>Sn,OPENAI_AUDIO_CREATE_SPEECH_MODEL_NAMES:()=>je,OPENAI_AUDIO_MODEL_NAMES:()=>Fe,OPENAI_AUDIO_TRANSCRIPTION_MODEL_NAMES:()=>Re,OPENAI_CHAT_MODEL_NAMES:()=>Se,OPENAI_EMBEDDINGS_MODEL_NAMES:()=>Ee,OPENAI_IMAGE_MODEL_NAMES:()=>Ne,OPEN_AI_CREATE_SPEECH_FORMATS:()=>Ue,ObservabilityClient:()=>Mn,Pagination:()=>hi,QueryBuilder:()=>yi,QueryBuilderFactory:()=>pi,QuerySender:()=>Nn,QuerySubscriptionManager:()=>is,QueueManagerFactory:()=>os,QueueManagerImpl:()=>cs,RAG_TYPES:()=>Ve,RERANK_PROVIDERS:()=>be,RUN_IN_TRANSACTION_MUTEX:()=>Gi,RateLimiter:()=>us,RpcManager:()=>ls,SQUID_BUILT_IN_INTEGRATION_IDS:()=>ut,SQUID_METRIC_NAMES:()=>dt,SQUID_REGIONS:()=>bt,STABLE_DIFFUSION_MODEL_NAMES:()=>xe,SchedulerClient:()=>ps,SecretClient:()=>u,SocketManager:()=>ys,Squid:()=>_s,SquidClientError:()=>un,StorageClient:()=>Ss,VECTOR_DB_TYPES:()=>He,VENDOR_AI_CHAT_MODEL_NAMES:()=>Te,VOYAGE_EMBEDDING_MODEL_NAMES:()=>Ce,WebClient:()=>ws,WebhookManager:()=>Ms,assertNotPassiveMode:()=>hs,compareArgsByReference:()=>$t,compareArgsBySerializedValue:()=>Gt,deserializeQuery:()=>Cn,generateId:()=>V,generateShortId:()=>J,generateShortIds:()=>Y,generateUUID:()=>G,generateUUIDPolyfill:()=>H,getConsoleUrl:()=>o,getCustomizationFlag:()=>zt,isAiEmbeddingsModelName:()=>Oe,isBuiltInIntegrationId:()=>lt,isIntegrationEmbeddingModelSpec:()=>qe,isIntegrationModelSpec:()=>Ge,isPlaceholderParam:()=>We,isVendorAiChatModelName:()=>ke,loadQueryResultDocIds:()=>En,rawSquidHttpDelete:()=>fn,rawSquidHttpGet:()=>hn,rawSquidHttpPatch:()=>gn,rawSquidHttpPost:()=>dn,rawSquidHttpPut:()=>pn,transformFileArgs:()=>Vt,tryDeserializing:()=>mn,visitQueryResults:()=>kn});const s=["api","application","auth","mutation","native-query","query","queue","notification"];function r(e,t,i,n,r,o){let a="https",c=`${n||t}.${r||e}.${new URL("https://squid.cloud").host}`,u="";if(/^local/.test(e)){if(a="http",u=o||function(e){const t=e.replace(/^\/+/,"").split("/"),i=t[0]||"";return"ws"===i?"squidlet"===t[1]:s.includes(i)}(i)?"8001":"8000","undefined"!=typeof process){const e=o?void 0:process.env.SQUID_LOCAL_WS_FORCE_PORT;e&&i.replace(/^\/+/,"").startsWith("ws/general")&&(u=e)}/android$/.test(e)?c="10.0.2.2":function(e){return/ios$/.test(e)}(e)&&(c="localhost")}const l=a+"://"+c+(u?`:${u}`:""),d=i.replace(/^\/+/,"");return d?`${l}/${d}`:l}function o(e,t,i=""){return r(function(e,t){return t||(e.includes("sandbox")?"squidai.westus3.azure.sandbox":e.includes("local")?"local":e.includes("staging")?"squidai.westus3.azure.staging":"us-east-1.aws")}(e,t),"console",i)}class a{constructor(e,t,i,n){this.rpcManager=e,this.iacBaseUrl=o(t,n,`openapi/iac/applications/${i}/connectors`)}async list(){return await this.rpcManager.get(this.iacBaseUrl)??[]}async connect(e){await this.rpcManager.put(`${this.iacBaseUrl}/${e}`,{})}async disconnect(e){await this.rpcManager.delete(`${this.iacBaseUrl}/${e}`)}}class c{constructor(e,t,i,n){this.rpcManager=e,this.iacBaseUrl=o(t,n,`openapi/iac/applications/${i}/integrations`)}async list(e){const t=await this.rpcManager.get(this.iacBaseUrl);return e?t.filter(t=>t.type===e):t}async get(e){return await this.rpcManager.get(`${this.iacBaseUrl}/${e}`)}async getIntegrationSchema(e){return await this.rpcManager.get(`${this.iacBaseUrl}/${e}/schema`)}async setIntegrationSchema(e,t){await this.rpcManager.put(`${this.iacBaseUrl}/${e}/schema`,t)}async delete(e){await this.rpcManager.delete(`${this.iacBaseUrl}/${e}`)}async deleteMany(e){await Promise.all(e.map(e=>this.delete(e)))}async upsertIntegration(e){await this.rpcManager.put(`${this.iacBaseUrl}/${e.id}`,e)}async generateAiDescriptionsForDataSchema(e,t){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/schema/generate-ai-descriptions`,t)}async generateAiDescriptionsForAssociations(e,t){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/schema/generate-ai-descriptions-for-associations`,t)}async generateAiDescriptionsForStoredProcedures(e,t){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/schema/generate-ai-descriptions-for-stored-procedures`,t)}async generateAiDescriptionsForEndpoints(e,t){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/schema/generate-ai-descriptions-for-endpoints`,t)}async discoverDataConnectionSchema(e){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/discover-schema`,{})}async testDataConnection(e){return await this.rpcManager.post(`${this.iacBaseUrl}/test-connection`,e)}async discoverGraphQLConnectionSchema(e,t){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/discover-graphql-schema`,t)}async discoverOpenApiSchema(e,t){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/discover-openapi-schema`,t)}async discoverOpenApiSchemaFromFile(e){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/discover-openapi-schema-from-file`,{})}}class u{constructor(e){this.rpcManager=e}get apiKeys(){return new l(this.rpcManager)}async get(e){const t={key:e};return await this.rpcManager.post("secret/get",t)||void 0}getAll(){return this.rpcManager.post("secret/getAll",{})}async upsert(e,t){return this.upsertMany([{key:e,value:t}]).then(e=>e[0])}async upsertMany(e){if(0===e.length)return[];const t={entries:e};return this.rpcManager.post("secret/upsert",t)}delete(e,t=!1){const i={keys:[e],force:t};return this.rpcManager.post("secret/delete",i)}async deleteMany(e,t=!1){if(0===e.length)return;const i={keys:e,force:t};return this.rpcManager.post("secret/delete",i)}}class l{constructor(e){this.rpcManager=e}get(e){const t={key:e};return this.rpcManager.post("secret/api-key/get",t)}getAll(){return this.rpcManager.post("secret/api-key/getAll",{})}upsert(e){const t={key:e};return this.rpcManager.post("secret/api-key/upsert",t)}delete(e){const t={key:e};return this.rpcManager.post("secret/api-key/delete",t)}}class d{constructor(e,t,i,n){this.rpcManager=e,this.region=t,this.appId=i,this.consoleRegion=n,this.integrationClient=new c(this.rpcManager,this.region,this.appId,this.consoleRegion),this.connectorClient=new a(this.rpcManager,this.region,this.appId,this.consoleRegion),this.secretClient=new u(this.rpcManager)}integrations(){return this.integrationClient}connectors(){return this.connectorClient}secrets(){return this.secretClient}}const h=require("rxjs");function p(e){return"function"==typeof e}function g(e){return function(t){if(function(e){return p(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 f=function(e,t){return f=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},f(e,t)};function y(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function i(){this.constructor=e}f(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}function m(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],n=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function I(e,t){var i="function"==typeof Symbol&&e[Symbol.iterator];if(!i)return e;var n,s,r=i.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(n=r.next()).done;)o.push(n.value)}catch(e){s={error:e}}finally{try{n&&!n.done&&(i=r.return)&&i.call(r)}finally{if(s)throw s.error}}return o}function b(e,t,i){if(i||2===arguments.length)for(var n,s=0,r=t.length;s<r;s++)!n&&s in t||(n||(n=Array.prototype.slice.call(t,0,s)),n[s]=t[s]);return e.concat(n||Array.prototype.slice.call(t))}Object.create,Object.create;var v,S=((v=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),v.prototype.constructor=v,v);function w(e,t){if(e){var i=e.indexOf(t);0<=i&&e.splice(i,1)}}var M=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,i,n,s;if(!this.closed){this.closed=!0;var r=this._parentage;if(r)if(this._parentage=null,Array.isArray(r))try{for(var o=m(r),a=o.next();!a.done;a=o.next())a.value.remove(this)}catch(t){e={error:t}}finally{try{a&&!a.done&&(t=o.return)&&t.call(o)}finally{if(e)throw e.error}}else r.remove(this);var c=this.initialTeardown;if(p(c))try{c()}catch(e){s=e instanceof S?e.errors:[e]}var u=this._finalizers;if(u){this._finalizers=null;try{for(var l=m(u),d=l.next();!d.done;d=l.next()){var h=d.value;try{_(h)}catch(e){s=null!=s?s:[],e instanceof S?s=b(b([],I(s)),I(e.errors)):s.push(e)}}}catch(e){i={error:e}}finally{try{d&&!d.done&&(n=l.return)&&n.call(l)}finally{if(i)throw i.error}}}if(s)throw new S(s)}},e.prototype.add=function(t){var i;if(t&&t!==this)if(this.closed)_(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(i=this._finalizers)&&void 0!==i?i:[]).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)&&w(t,e)},e.prototype.remove=function(t){var i=this._finalizers;i&&w(i,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}();function _(e){p(e)?e():e.unsubscribe()}M.EMPTY;var T={setTimeout:function(e,t){for(var i=[],n=2;n<arguments.length;n++)i[n-2]=arguments[n];var s=T.delegate;return(null==s?void 0:s.setTimeout)?s.setTimeout.apply(s,b([e,t],I(i))):setTimeout.apply(void 0,b([e,t],I(i)))},clearTimeout:function(e){var t=T.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function k(){}var E=C("C",void 0,void 0);function C(e,t,i){return{kind:e,value:t,error:i}}var D=function(e){function t(t){var i,n=e.call(this)||this;return n.isStopped=!1,t?(n.destination=t,((i=t)instanceof M||i&&"closed"in i&&p(i.remove)&&p(i.add)&&p(i.unsubscribe))&&t.add(n)):n.destination=R,n}return y(t,e),t.create=function(e,t,i){return new O(e,t,i)},t.prototype.next=function(e){this.isStopped?N(function(e){return C("N",e,void 0)}(e),this):this._next(e)},t.prototype.error=function(e){this.isStopped?N(C("E",void 0,e),this):(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped?N(E,this):(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}(M);Function.prototype.bind;var A=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){q(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){q(e)}else q(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){q(e)}},e}(),O=function(e){function t(t,i,n){var s,r=e.call(this)||this;return s=p(t)||!t?{next:null!=t?t:void 0,error:null!=i?i:void 0,complete:null!=n?n:void 0}:t,r.destination=new A(s),r}return y(t,e),t}(D);function q(e){!function(e){T.setTimeout(function(){throw e})}(e)}function N(e,t){var i=null;i&&T.setTimeout(function(){return i(e,t)})}var R={closed:!0,next:k,error:function(e){throw e},complete:k};function j(e,t,i,n,s){return new F(e,t,i,n,s)}var F=function(e){function t(t,i,n,s,r,o){var a=e.call(this,t)||this;return a.onFinalize=r,a.shouldUnsubscribe=o,a._next=i?function(e){try{i(e)}catch(e){t.error(e)}}:e.prototype._next,a._error=s?function(e){try{s(e)}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._error,a._complete=n?function(){try{n()}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._complete,a}return y(t,e),t.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var i=this.closed;e.prototype.unsubscribe.call(this),!i&&(null===(t=this.onFinalize)||void 0===t||t.call(this))}},t}(D);function x(e,t){return g(function(i,n){var s=0;i.subscribe(j(n,function(i){n.next(e.call(t,i,s++))}))})}function P(e){return null!=e}let B=e=>new Error(e);function L(e,t,...i){e||function(e,...t){const i=U(e);if("object"==typeof i)throw i;throw B(i||"Assertion error",...t)}(t,...i)}function Q(e,t,...i){return L(e,t,...i),e}function U(e){return void 0===e?"":"string"==typeof e?e:e()}function $(e,t,i){const n=U(e);if("object"==typeof n)throw n;return`${n?`${n}: `:""}${t} ${function(e){return void 0===e?"<undefined>":"symbol"==typeof e?e.toString():null===e?"<null>":`<${typeof e}:${e}>`}(i)}`}function G(){return"function"==typeof globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():H()}function H(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}function V(){return G()}const K=18,W="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function z(){return W.charAt(Math.floor(Math.random()*W.length))}function J(e=K,t="",i=""){L(t.length<e,"ID prefix is too long"),L(!t||!i||i.length>t.length,"Invalid 'prefix'/'prefixToAvoid' config");let n="";for(let t=0;t<e;t++)n+=z();if(t.length>0&&(n=t+n.substring(t.length)),i)for(;n.charAt(t.length)===i[t.length];)n=n.substring(0,t.length)+z()+n.substring(t.length+1);return n}function Y({count:e,length:t,prefix:i}){L(e>=0,`Invalid IDs count: ${e}`);const n=new Set;for(;n.size<e;)n.add(J(t||K,i||""));return[...n]}const X=["groupId","appId","integrationId","profileId","index","text","filePathInBucket"];function Z(e){if(function(e){return"$and"in e}(e))for(const t of e.$and)Z(t);else if(function(e){return"$or"in e}(e))for(const t of e.$or)Z(t);else for(const t in e){if(!/^[a-zA-Z0-9_]+$/.test(t))throw new Error(`Invalid metadata filter key ${t} - can only contain letters, numbers, and underscores`);if(X.includes(t))throw new Error(`Invalid metadata filter key ${t} - cannot be an internal key. Internal keys: ${X.join(", ")}`);const i=e[t];if("object"!=typeof i&&"string"!=typeof i&&"number"!=typeof i&&"boolean"!=typeof i)throw new Error(`Invalid metadata filter value for key ${t} - cannot be of type ${typeof i}`)}}function ee(e,t,i){const n=atob(e),s=new Uint8Array(n.length);for(let e=0;e<n.length;e++)s[e]=n.charCodeAt(e);return new File([s],t,{type:i||"application/octet-stream"})}class te{constructor(e,t,i,n,s,r,o,a=()=>{}){this.agentId=e,this.agentApiKey=t,this.ongoingChatSequences=i,this.rpcManager=n,this.socketManager=s,this.jobClient=r,this.backendFunctionManager=o,this.getMetricAnnotations=a}async get(){const e=await this.post("ai/agent/getAgent",{agentId:this.agentId});return e?.agent}async upsert(e){await this.post("ai/agent/upsertAgent",{...e,id:this.agentId})}async delete(){await this.post("ai/agent/deleteAgent",{agentId:this.agentId})}async updateInstructions(e){await this.setAgentOptionInPath("instructions",e)}async updateModel(e){await this.setAgentOptionInPath("model",e)}async updateConnectedAgents(e){await this.setAgentOptionInPath("connectedAgents",e)}async updateGuardrails(e){const t=await this.get();L(t,"Agent not found");const i={...t.options?.guardrails,...e};await this.setAgentOptionInPath("guardrails",i)}async updateCustomGuardrails(e){await this.post("ai/agent/upsertCustomGuardrails",{agentId:this.agentId,customGuardrail:e})}async deleteCustomGuardrail(){await this.post("ai/agent/deleteCustomGuardrails",{agentId:this.agentId})}async regenerateApiKey(){return await this.post("ai/agent/regenerateApiKey",{agentId:this.agentId})}async getApiKey(){return await this.post("ai/agent/getApiKey",{agentId:this.agentId})}async listRevisions(){return await this.post("ai/agent/listRevisions",{agentId:this.agentId})}async restoreRevision(e){await this.post("ai/agent/restoreRevision",{agentId:this.agentId,revisionNumber:e})}async deleteRevision(e){await this.post("ai/agent/deleteRevision",{agentId:this.agentId,revisionNumber:e})}chat(e,t,i){return this.chatInternal(e,t,i).responseStream}async transcribeAndChat(e,t,i){const n=this.chatInternal(e,t,i),s=await Q(n.serverResponse,"TRANSCRIPTION_RESPONSE_NOT_FOUND");return{responseStream:n.responseStream,transcribedPrompt:s.transcribedPrompt}}async ask(e,t,i){const n=await this.askInternal(e,!1,t,i);return this.replaceFileTags(n.responseString,n.annotations)}async askWithAnnotations(e,t,i){const n=await this.askInternal(e,!1,t,i);return{responseString:n.responseString,annotations:n.annotations}}async askAsync(e,t,i){const n={agentId:this.agentId,prompt:e,options:this.withMetricAnnotations(i),jobId:t};await this.post("ai/chatbot/askAsync",n)}observeStatusUpdates(e){return this.socketManager.notifyWebSocketIsNeeded(),this.socketManager.observeNotifications().pipe((0,h.filter)(e=>"aiStatus"===e.type&&e.agentId===this.agentId),(0,h.filter)(t=>!e||t.jobId===e),x(e=>({agentId:this.agentId,jobId:e.jobId,chatId:e.chatId,tags:e.payload.tags,title:e.payload.title,body:e.payload.body,parentStatusUpdateId:e.payload.parentStatusUpdateId,messageId:e.messageId})))}async getChatHistory(e){const t={agentId:this.agentId,memoryId:e};return(await this.post("ai/chatbot/history",t)).messages}async transcribeAndAsk(e,t,i){return await this.askInternal(e,!1,t,i)}async transcribeAndAskWithVoiceResponse(e,t,i){const n=await this.askInternal(e,!0,t,i),s=n.voiceResponse;return{responseString:n.responseString,transcribedPrompt:n.transcribedPrompt,voiceResponseFile:ee(s.base64File,`voice.${s.extension}`,s.mimeType)}}async askWithVoiceResponse(e,t,i){const n=await this.askInternal(e,!0,t,i),s=n.voiceResponse;return{responseString:n.responseString,voiceResponseFile:ee(s.base64File,`voice.${s.extension}`,s.mimeType)}}async setAgentOptionInPath(e,t){await this.post("ai/agent/setAgentOptionInPath",{agentId:this.agentId,path:e,value:t})}async addConnectedIntegration(e){await this.post("ai/agent/addConnectedIntegration",{agentId:this.agentId,integrationId:e.integrationId,integrationType:e.integrationType,description:e.description??""})}async addConnectedAgent(e){await this.post("ai/agent/addConnectedAgent",{agentId:this.agentId,connectedAgentId:e.agentId,description:e.description})}async addConnectedKnowledgeBase(e){await this.post("ai/agent/addConnectedKnowledgeBase",{agentId:this.agentId,knowledgeBaseId:e.knowledgeBaseId,description:e.description,includeMetadata:e.includeMetadata})}async addFunction(e){await this.post("ai/agent/addFunction",{agentId:this.agentId,functionId:e})}async removeConnectedAgent(e){await this.post("ai/agent/removeConnectedAgent",{agentId:this.agentId,connectedAgentId:e})}async removeConnectedIntegration(e){await this.post("ai/agent/removeConnectedIntegration",{agentId:this.agentId,integrationId:e})}async removeConnectedKnowledgeBase(e){await this.post("ai/agent/removeConnectedKnowledgeBase",{agentId:this.agentId,knowledgeBaseId:e})}async removeFunction(e){await this.post("ai/agent/removeFunction",{agentId:this.agentId,functionId:e})}async setAgentDescription(e){await this.post("ai/agent/setAgentDescription",{agentId:this.agentId,description:e})}async provideFeedback(e){const t={agentId:this.agentId,feedback:e};return await this.backendFunctionManager.executeFunction("provideAgentFeedback",t)}async build(e,t,i){const n={agentId:this.agentId,request:e,memoryId:t,options:i};return await this.backendFunctionManager.executeFunction("buildAgent",n)}replaceFileTags(e,t={}){let i=e;for(const[e,n]of Object.entries(t)){let t="";const s=n.aiFileUrl.fileName?n.aiFileUrl.fileName:n.aiFileUrl.url;switch(n.aiFileUrl.type){case"image":t=`![${s}](${n.aiFileUrl.url})`;break;case"document":t=`[${s}](${n.aiFileUrl.url})`}const r=`\${id:${e}}`;i=i.replaceAll("`"+r+"`",t).replaceAll(r,t)}return i}async askInternal(e,t,i,n){if(i?.contextMetadataFilter&&Z(i.contextMetadataFilter),i?.contextMetadataFilterForKnowledgeBase)for(const e in i.contextMetadataFilterForKnowledgeBase)Z(i.contextMetadataFilterForKnowledgeBase[e]);n=n||G(),i=this.withMetricAnnotations({...ie,...i||{}});const s="string"==typeof e;let r="ai/chatbot/";r+=s||t?!s&&t?"transcribeAndAskWithVoiceResponse":s&&t?"askWithVoiceResponse":"ask":"transcribeAndAsk";const o={agentId:this.agentId,prompt:s?e:void 0,options:i,jobId:n},a=s?void 0:[e];return await this.post(r,o,a,"file"),await this.jobClient.awaitJob(n)}chatInternal(e,t,i){if(this.socketManager.notifyWebSocketIsNeeded(),t?.contextMetadataFilter&&Z(t.contextMetadataFilter),t?.contextMetadataFilterForKnowledgeBase)for(const e in t.contextMetadataFilterForKnowledgeBase)Z(t.contextMetadataFilterForKnowledgeBase[e]);const n=G(),s=void 0===(t=this.withMetricAnnotations({...ie,...t||{}})).smoothTyping||t.smoothTyping;let r="";const o=new h.Subject,a=new h.Subject;this.ongoingChatSequences[n]=a;let c=-1;a.pipe((0,h.tap)(({tokenIndex:e})=>{void 0!==e&&e<c&&console.warn("Received token index out of order",e,c),void 0!==e&&(c=e)}),(0,h.concatMap)(({value:e,complete:t,annotations:i})=>t?(0,h.of)({value:e,complete:t,annotations:i}):(0,h.of)(e).pipe(s?(0,h.delay)(0):(0,h.tap)(),x(e=>({value:e,complete:!1,annotations:void 0})))),(0,h.takeWhile)(({complete:e})=>!e,!0)).subscribe({next:({value:e,complete:t,annotations:i})=>{r+=e,t&&i&&(r=this.replaceFileTags(r,i)),o.next(r)},error:e=>{console.error(e)},complete:()=>{o.complete()}});const u="string"==typeof e;i=i||G();const l={agentId:this.agentId,jobId:i,prompt:u?e:void 0,options:t,clientRequestId:n},d={responseStream:o.pipe((0,h.finalize)(()=>{delete this.ongoingChatSequences[n]}),(0,h.share)())};let p;return p=u?this.post("ai/chatbot/chat",l).catch(e=>{o.error(e),o.complete()}):this.post("ai/chatbot/transcribeAndChat",l,[e],"file").catch(e=>{throw o.error(e),o.complete(),e}),d.serverResponse=p.then(()=>this.jobClient.awaitJob(i)).catch(e=>{o.error(e),o.complete()}),d}withMetricAnnotations(e){const t=this.getMetricAnnotations();return t?{...e||{},metricAnnotations:{...t,...e?.metricAnnotations}}:e}async post(e,t,i=[],n="files"){const s={};return this.agentApiKey&&(s["x-squid-agent-api-key"]=`Bearer ${this.agentApiKey}`),this.rpcManager.post(e,t,i,n,s)}}const ie={smoothTyping:!0,responseFormat:"text"};class ne{constructor(e,t,i,n,s=()=>{}){this.rpcManager=e,this.socketManager=t,this.jobClient=i,this.backendFunctionManager=n,this.getMetricAnnotations=s,this.ongoingChatSequences={},this.socketManager.observeNotifications().pipe((0,h.filter)(e=>"aiChatbot"===e.type),x(e=>e)).subscribe(e=>{this.handleChatResponse(e)})}agent(e,t=void 0){return new te(e,t?.apiKey,this.ongoingChatSequences,this.rpcManager,this.socketManager,this.jobClient,this.backendFunctionManager,this.getMetricAnnotations)}async listAgents(){return(await this.rpcManager.post("ai/agent/listAgents",{})).agents}async handleChatResponse(e){const t=this.ongoingChatSequences[e.clientRequestId];if(!t)return;const{token:i,complete:n,tokenIndex:s,annotations:r}=e.payload;if(n&&!i.length)t.next({value:"",complete:!0,tokenIndex:void 0,annotations:r});else if(i.match(/\[.*?]\((.*?)\)/g))t.next({value:i,complete:n,tokenIndex:void 0===s?void 0:s,annotations:r});else for(let e=0;e<i.length;e++)t.next({value:i[e],complete:n&&e===i.length-1,tokenIndex:void 0===s?void 0:s,annotations:r})}}const se="__squid_empty_chat_id";class re{constructor(e){this.rpcManager=e}async transcribe(e,t={modelName:"whisper-1"}){return this.rpcManager.post("ai/audio/transcribe",t,[e])}async createSpeech(e,t){const i={input:e,options:t},n=await this.rpcManager.post("ai/audio/createSpeech",i);return ee(n.base64File,`audio.${n.extension}`,n.mimeType)}}class oe{constructor(e,t){this.provider=e,this.rpcManager=t}async uploadFile(e){const t={provider:this.provider,expirationInSeconds:e.expirationInSeconds};return(await this.rpcManager.post("ai/files/uploadFile",t,[e.file],"file")).fileId}async deleteFile(e){const t={fileId:e,provider:this.provider};return(await this.rpcManager.post("ai/files/deleteFile",t)).deleted}}class ae{constructor(e){this.rpcManager=e}async generate(e,t){const i={prompt:e,options:t};return await this.rpcManager.post("ai/image/generate",i)}async removeBackground(e){return await this.rpcManager.post("ai/image/removeBackground",{},[e])}}function ce(e){for(const t in e){const i=e[t];L("string"==typeof i||"number"==typeof i||"boolean"==typeof i||void 0===i,`Invalid metadata value for key ${t} - cannot be of type ${typeof i}`),L(/^[a-zA-Z0-9_]+$/.test(t),`Invalid metadata key ${t} - can only contain letters, numbers, and underscores`)}}class ue{constructor(e,t,i){this.knowledgeBaseId=e,this.rpcManager=t,this.jobClient=i}async getKnowledgeBase(){return(await this.rpcManager.post("ai/knowledge-base/getKnowledgeBase",{knowledgeBaseId:this.knowledgeBaseId})).knowledgeBase}async listKnowledgeBases(){return(await this.rpcManager.post("ai/knowledge-base/listKnowledgeBases",void 0)).knowledgeBases}async upsertKnowledgeBase(e){await this.rpcManager.post("ai/knowledge-base/upsertKnowledgeBase",{knowledgeBase:{id:this.knowledgeBaseId,...e}})}async generateMetadataFieldDescriptions(e){return this.rpcManager.post("ai/knowledge-base/generateMetadataFieldDescriptions",{knowledgeBaseId:this.knowledgeBaseId,fieldNames:e?.fieldNames,overwriteExisting:e?.overwriteExisting})}async delete(){await this.rpcManager.post("ai/knowledge-base/deleteKnowledgeBase",{id:this.knowledgeBaseId})}async listContexts(e){return(await this.rpcManager.post("ai/knowledge-base/listContexts",{id:this.knowledgeBaseId,truncateTextAfter:e})).contexts||[]}async listContextIds(){return(await this.rpcManager.post("ai/knowledge-base/listContextIds",{id:this.knowledgeBaseId})).contextIds||[]}async getContext(e){return(await this.rpcManager.post("ai/knowledge-base/getContext",{knowledgeBaseId:this.knowledgeBaseId,contextId:e})).context}async deleteContext(e){await this.deleteContexts([e])}async deleteContexts(e){await this.rpcManager.post("ai/knowledge-base/deleteContexts",{knowledgeBaseId:this.knowledgeBaseId,contextIds:e})}async upsertContext(e,t){const{failures:i}=await this.upsertContexts([e],t?[t]:void 0);return i.length>0?{failure:i[0]}:{}}async upsertContexts(e,t){for(const t of e)t.metadata&&ce(t.metadata);const i=G();return await this.rpcManager.post("ai/knowledge-base/upsertContexts",{knowledgeBaseId:this.knowledgeBaseId,contextRequests:e,jobId:i},t),await this.jobClient.awaitJob(i)}async search(e){const t={options:e,prompt:e.prompt,knowledgeBaseId:this.knowledgeBaseId};return(await this.rpcManager.post("ai/knowledge-base/search",t)).chunks}async searchContextsWithPrompt(e){return(await this.rpcManager.post("ai/knowledge-base/searchContextsWithPrompt",{...e,knowledgeBaseId:this.knowledgeBaseId})).results}async searchContextsWithContextId(e){return(await this.rpcManager.post("ai/knowledge-base/searchContextsWithContextId",{...e,knowledgeBaseId:this.knowledgeBaseId})).results}async downloadContext(e){const t={knowledgeBaseId:this.knowledgeBaseId,contextId:e};return await this.rpcManager.post("ai/knowledge-base/downloadContext",t)}}class le{constructor(e,t){this.rpcManager=e,this.jobClient=t}knowledgeBase(e){return new ue(e,this.rpcManager,this.jobClient)}async listKnowledgeBases(){return(await this.rpcManager.post("ai/knowledge-base/listKnowledgeBases",void 0)).knowledgeBases}async delete(e){await this.rpcManager.post("ai/knowledge-base/deleteKnowledgeBase",{id:e})}}class de{constructor(e){this.rpcManager=e}async createMatchMaker(e){const t=await this.rpcManager.post("matchMaking/createMatchMaker",{matchMaker:e});return new he(t,this.rpcManager)}async getMatchMaker(e){const t=(await this.rpcManager.post("matchMaking/getMatchMaker",{matchMakerId:e})).matchMaker;if(t)return new he(t,this.rpcManager)}async listMatchMakers(){return await this.rpcManager.post("matchMaking/listMatchMakers",{})}}class he{constructor(e,t){this.matchMaker=e,this.rpcManager=t,this.id=e.id}async insertEntity(e){await this.rpcManager.post("matchMaking/insertEntity",{matchMakerId:this.id,entity:e})}async insertManyEntities(e){await this.rpcManager.post("matchMaking/insertEntities",{matchMakerId:this.id,entities:e})}async delete(){await this.rpcManager.post("matchMaking/deleteMatchMaker",{matchMakerId:this.id})}async deleteEntity(e){await this.rpcManager.post("matchMaking/deleteEntity",{entityId:e,matchMakerId:this.id})}async findMatches(e,t={}){return(await this.rpcManager.post("matchMaking/findMatches",{matchMakerId:this.id,entityId:e,options:t})).matches}async findMatchesForEntity(e,t={}){return(await this.rpcManager.post("matchMaking/findMatchesForEntity",{matchMakerId:this.id,entity:e,options:t})).matches}async listEntities(e,t={}){return await this.rpcManager.post("matchMaking/listEntities",{categoryId:e,options:t,matchMakerId:this.id})}async getEntity(e){return(await this.rpcManager.post("matchMaking/getEntity",{matchMakerId:this.id,entityId:e})).entity}getMatchMakerDetails(){return this.matchMaker}}const pe="Agent Response",ge="Accessing Knowledge Base",fe="Calling AI Function",ye="Inspecting Knowledge Base Metadata",me="Querying Spreadsheet",Ie=["user","ai"],be=["cohere","none"],ve=["anthropic","bedrock","claude-code","codex","cohere","flux","gemini","openai","grok","stability","voyage","mistral","textract","vertex","external"],Se=["gpt-5.4-mini","gpt-5.4-nano","gpt-5.5","gpt-5.5-pro"],we=["gemini-3.1-pro","gemini-3.5-flash","gemini-3.1-flash-lite"],Me=["grok-4.3","grok-4-1-fast-reasoning","grok-4-1-fast-non-reasoning"],_e=["claude-haiku-4-5-20251001","claude-opus-4-8","claude-sonnet-5"],Te=[...Se,..._e,...we,...Me];function ke(e){return Te.includes(e)}const Ee=["text-embedding-3-small"],Ce=["voyage-3-large"],De=["titan-embed-text-v2"],Ae=[...Ee,...Ce,...De];function Oe(e){return Ae.includes(e)}function qe(e){return"object"==typeof e&&null!==e&&"integrationId"in e&&"model"in e&&"dimensions"in e}const Ne=["gpt-image-1","gpt-image-1-mini","gpt-image-1.5","gpt-image-2","gpt-image-2-2026-04-21","chatgpt-image-latest"],Re=["whisper-1","gpt-4o-transcribe","gpt-4o-mini-transcribe"],je=["tts-1","tts-1-hd","gpt-4o-mini-tts"],Fe=[...Re,...je],xe=["stable-diffusion-core"],Pe=["flux-pro-1.1","flux-kontext-pro"],Be=[...Ne,...xe,...Pe],Le=[...Re],Qe=[...je],Ue=["mp3","opus","aac","flac","wav","pcm"],$e=["vendor","connector","custom"];function Ge(e){return"object"==typeof e&&null!==e&&"integrationId"in e&&"model"in e}const He=["postgres","mongoAtlas"],Ve=["contextual","basic"],Ke=["secret","regular"];function We(e){return!!e&&"object"==typeof e&&"__squid_placeholder__"in e}const ze=["dev","prod"],Je="built_in_agent",Ye=["confluence","cotomi","essentials","freshdesk","github","google_calendar","google_drive","hubspot","sharepoint","jira","jira_jsm","linear","mail","onedrive","salesforce","servicenow_csm","slack","teams","ticketmind_companion","zendesk"],Xe={CONTINUE:100,SWITCHING_PROTOCOLS:101,PROCESSING:102,EARLY_HINTS:103,OK:200,CREATED:201,ACCEPTED:202,NON_AUTHORITATIVE_INFORMATION:203,NO_CONTENT:204,RESET_CONTENT:205,PARTIAL_CONTENT:206,MULTI_STATUS:207,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,MOVED_TEMPORARILY:302,SEE_OTHER:303,NOT_MODIFIED:304,USE_PROXY:305,TEMPORARY_REDIRECT:307,PERMANENT_REDIRECT:308,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,REQUEST_TOO_LONG:413,REQUEST_URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,REQUESTED_RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,IM_A_TEAPOT:418,INSUFFICIENT_SPACE_ON_RESOURCE:419,METHOD_FAILURE:420,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,INSUFFICIENT_STORAGE:507,NETWORK_AUTHENTICATION_REQUIRED:511},Ze="ai_agents",et=["active_directory","ai_agents","ai_chatbot","algolia","alloydb","api","auth0","bedrock","azure_blob","azure_cosmosdb","azure_postgresql","azure_sql","bigquery","built_in_azure_blob","built_in_db","built_in_gcs","built_in_queue","built_in_s3","cassandra","clickhouse","cloudsql","cockroach","cognito","connected_knowledgebases","confluence","confluent","datadog","db2","descope","documentdb","azure-entra-external-id","dynamodb","elasticsearch","firebase_auth","firestore","gcs","github","google_calendar","google_docs","google_drive","graphql","hubspot","jira","jira_jsm","jwt_hmac","jwt_rsa","kafka","keycloak","linear","mariadb","monday","mongo","mssql","databricks","mysql","newrelic","okta","onedrive","oracledb","pinecone","postgres","redis","s3","salesforce","sap_hana","sentry","snowflake","spanner","xata","zendesk","servicenow_csm","freshdesk","mail","slack","mcp","a2a","legend","teams","openai_compatible","openai_compatible_embedding","sharepoint","vertex"],tt=["bigquery","built_in_db","clickhouse","cockroach","dynamodb","mongo","mssql","databricks","mysql","oracledb","postgres","sap_hana","snowflake","elasticsearch","legend"],it=["auth0","jwt_rsa","jwt_hmac","cognito","okta","keycloak","descope","firebase_auth","azure-entra-external-id"],nt=["graphql"],st=["api"],rt=["data","api","graphql"],ot="built_in_db",at="built_in_queue",ct="built_in_storage",ut=[ot,at,ct];function lt(e){return ut.includes(e)}const dt=["squid_functionExecution_count","squid_functionExecution_time"],ht=["sum","max","min","average","median","p95","p99","count"],pt=["user","squid"],gt=["align-by-start-time","align-by-end-time"],ft=["return-no-result-groups","return-result-group-with-default-values"],yt="__docId__",mt=["in","not in","array_includes_some","array_includes_all","array_not_includes"],It=[...mt,"==","!=",">=","<=",">","<","like","not like","like_cs","not like_cs"],bt=["us-east-1.aws","ap-south-1.aws","us-central1.gcp"],vt=["CONNECTED","DISCONNECTED","REMOVED"];class St{constructor(e,t,i,n,s=()=>{}){this.socketManager=e,this.rpcManager=t,this.jobClient=i,this.backendFunctionManager=n,this.getMetricAnnotations=s}agent(e=Je,t=void 0){return this.getAiAgentClient().agent(e,t)}knowledgeBase(e){return this.getAiKnowledgeBaseClient().knowledgeBase(e)}async listAgents(){return this.getAiAgentClient().listAgents()}async listKnowledgeBases(){return this.getAiKnowledgeBaseClient().listKnowledgeBases()}async listFunctions(){const e=await this.rpcManager.post("/application/getBundleMetadata",{});return Object.values(e.aiFunctions||{})}async listChatModels(e){return(await this.rpcManager.post("ai/settings/listChatModels",e??{})).models}image(){return new ae(this.rpcManager)}audio(){return new re(this.rpcManager)}matchMaking(){return new de(this.rpcManager)}files(e){return new oe(e,this.rpcManager)}executeAiQuery(e,t,i,n){const s={integrationId:e,prompt:t,options:i};return this.rpcManager.post("ai/query/executeDataQuery",s,[],"files",{},n)}executeAiApiCall(e,t,i,n){const s={integrationId:e,prompt:t,options:i,sessionContext:n};return this.rpcManager.post("ai/query/executeApiQuery",s)}async getApplicationAiSettings(){return(await this.rpcManager.post("ai/settings/getApplicationAiSettings",{})).settings}async setApplicationAiSettings(e){const t={settings:e};await this.rpcManager.post("ai/settings/setApplicationAiSettings",t)}async setAiProviderApiKeySecret(e,t){const i={providerType:e,secretKey:t};return(await this.rpcManager.post("ai/settings/setAiProviderApiKeySecret",i)).settings}observeStatusUpdates(e){return this.socketManager.notifyWebSocketIsNeeded(),this.socketManager.observeNotifications().pipe((0,h.filter)(e=>"aiStatus"===e.type),(0,h.filter)(t=>!e||t.jobId===e),(0,h.map)(e=>({agentId:e.agentId,jobId:e.jobId,chatId:e.chatId,tags:e.payload.tags,title:e.payload.title,body:e.payload.body,parentStatusUpdateId:e.payload.parentStatusUpdateId,messageId:e.messageId})))}getAiAgentClient(){return this.aiAgentClient||(this.aiAgentClient=new ne(this.rpcManager,this.socketManager,this.jobClient,this.backendFunctionManager,this.getMetricAnnotations)),this.aiAgentClient}getAiKnowledgeBaseClient(){return this.aiKnowledgeBaseClient||(this.aiKnowledgeBaseClient=new le(this.rpcManager,this.jobClient)),this.aiKnowledgeBaseClient}}const wt={headers:{},queryParams:{},pathParams:{}};class Mt{constructor(e){this.rpcManager=e}async get(e,t,i){return this.request(e,t,void 0,i,"get")}async post(e,t,i,n){return this.request(e,t,i,n,"post")}async delete(e,t,i,n){return this.request(e,t,i,n,"delete")}async patch(e,t,i,n){return this.request(e,t,i,n,"patch")}async put(e,t,i,n){return this.request(e,t,i,n,"put")}async request(e,t,i,n,s){const r={integrationId:e,endpointId:t,body:i,options:{...wt,...this.convertOptionsToStrings(n||{})},overrideMethod:s};return await this.rpcManager.rawPost("api/callApi",r,void 0,void 0,!1)}convertOptionsToStrings(e){return{headers:this.convertToStrings(e.headers),queryParams:this.convertToStrings(e.queryParams),pathParams:this.convertToStrings(e.pathParams)}}convertToStrings(e){if(!e)return{};const t=Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>[e,String(t)]);return