@microsoft/agents-copilotstudio-client 1.4.1 → 1.5.0-beta.1.g77c44097fe

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@microsoft/agents-copilotstudio-client",
3
- "version": "1.4.1",
3
+ "version": "1.5.0-beta.1.g77c44097fe",
4
4
  "homepage": "https://github.com/microsoft/Agents-for-js",
5
5
  "repository": {
6
6
  "type": "git",
@@ -27,7 +27,7 @@
27
27
  "build:browser": "esbuild --platform=browser --target=es2019 --format=esm --bundle --sourcemap --minify --outfile=dist/src/browser.mjs src/index.ts"
28
28
  },
29
29
  "dependencies": {
30
- "@microsoft/agents-activity": "1.4.1",
30
+ "@microsoft/agents-activity": "1.5.0-beta.1.g77c44097fe",
31
31
  "eventsource-client": "^1.2.0",
32
32
  "rxjs": "7.8.2",
33
33
  "uuid": "^11.1.0"
@@ -2,7 +2,7 @@ var Ds=Object.create;var bo=Object.defineProperty;var Ls=Object.getOwnPropertyDe
2
2
  `;break;case"id":a=b.includes("\0")?void 0:b;break;case"retry":/^\d+$/.test(b)?n(parseInt(b,10)):r(new or(`Invalid \`retry\` value: "${b}"`,{type:"invalid-retry",value:b,line:_}));break;default:r(new or(`Unknown field "${v.length>20?`${v.slice(0,20)}\u2026`:v}"`,{type:"unknown-field",field:v,value:b,line:_}));break}}function T(){d.length>0&&e({id:a,event:l||void 0,data:d.endsWith(`
3
3
  `)?d.slice(0,-1):d}),a=void 0,d="",l=""}function P(v={}){i&&v.consume&&h(i),s=!0,a=void 0,d="",l="",i=""}return{feed:f,reset:P}}function Vs(t){let e=[],r="",n=0;for(;n<t.length;){let o=t.indexOf("\r",n),i=t.indexOf(`
4
4
  `,n),s=-1;if(o!==-1&&i!==-1?s=Math.min(o,i):o!==-1?o===t.length-1?s=-1:s=o:i!==-1&&(s=i),s===-1){r=t.slice(n);break}else{let a=t.slice(n,s);e.push(a),n=s+1,t[n-1]==="\r"&&t[n]===`
5
- `&&n++}}return[e,r]}var xo="connecting",Hs="open",tn="closed",ir=()=>{};function Ws(t,{getStream:e}){let r=typeof t=="string"||t instanceof URL?{url:t}:t,{onMessage:n,onComment:o=ir,onConnect:i=ir,onDisconnect:s=ir,onScheduleReconnect:a=ir}=r,{fetch:d,url:l,initialLastEventId:f}=Bs(r),h={...r.headers},C=[],T=n?[n]:[],P=U=>T.forEach(se=>se(U)),v=_o({onEvent:Us,onRetry:Ns,onComment:o}),b,_=l.toString(),O=new AbortController,E=f,N=2e3,ie,H=tn;return Y(),{close:Pe,connect:Y,[Symbol.iterator]:()=>{throw new Error("EventSource does not support synchronous iteration. Use `for await` instead.")},[Symbol.asyncIterator]:Yr,get lastEventId(){return E},get url(){return _},get readyState(){return H}};function Y(){b||(H=xo,O=new AbortController,b=d(l,Ms()).then(Rs).catch(U=>{b=null,!(U.name==="AbortError"||U.type==="aborted"||O.signal.aborted)&&yo()}))}function Pe(){H=tn,O.abort(),v.reset(),clearTimeout(ie),C.forEach(U=>U())}function Yr(){let U=[],se=[];function Zt(){return new Promise(W=>{let ae=se.shift();ae?W({value:ae,done:!1}):U.push(W)})}let tt=function(W){let ae=U.shift();ae?ae({value:W,done:!1}):se.push(W)};function Oe(){for(T.splice(T.indexOf(tt),1);U.shift(););for(;se.shift(););}function kt(){let W=U.shift();W&&(W({done:!0,value:void 0}),Oe())}return C.push(kt),T.push(tt),{next(){return H===tn?this.return():Zt()},return(){return Oe(),Promise.resolve({done:!0,value:void 0})},throw(W){return Oe(),Promise.reject(W)},[Symbol.asyncIterator](){return this}}}function yo(){a({delay:N}),!O.signal.aborted&&(H=xo,ie=setTimeout(Y,N))}async function Rs(U){i(),v.reset();let{body:se,redirected:Zt,status:tt}=U;if(tt===204){s(),Pe();return}if(!se)throw new Error("Missing response body");Zt&&(_=U.url);let Oe=e(se),kt=new TextDecoder,W=Oe.getReader(),ae=!0;H=Hs;do{let{done:vo,value:go}=await W.read();go&&v.feed(kt.decode(go,{stream:!vo})),vo&&(ae=!1,b=null,v.reset(),yo(),s())}while(ae)}function Us(U){typeof U.id=="string"&&(E=U.id),P(U)}function Ns(U){N=U}function Ms(){let{mode:U,credentials:se,body:Zt,method:tt,redirect:Oe,referrer:kt,referrerPolicy:W}=r,ae={Accept:"text/event-stream",...h,...E?{"Last-Event-ID":E}:void 0};return{mode:U,credentials:se,body:Zt,method:tt,redirect:Oe,referrer:kt,referrerPolicy:W,headers:ae,cache:"no-store",signal:O.signal}}}function Bs(t){let e=t.fetch||globalThis.fetch;if(!Gs(e))throw new Error("No fetch implementation provided, and one was not found on the global object.");if(typeof AbortController!="function")throw new Error("Missing AbortController implementation");let{url:r,initialLastEventId:n}=t;if(typeof r!="string"&&!(r instanceof URL))throw new Error("Invalid URL provided - must be string or URL instance");if(typeof n!="string"&&n!==void 0)throw new Error("Invalid initialLastEventId provided - must be string or undefined");return{fetch:e,url:r,initialLastEventId:n}}function Gs(t){return typeof t=="function"}var Ks={getStream:Js};function rn(t){return Ws(t,Ks)}function Js(t){if(!(t instanceof ReadableStream))throw new Error("Invalid stream, expected a web ReadableStream");return t}var Po=Rt(Mt());var ur=class{constructor(e){this.API_VERSION="2022-03-01-preview";let r="schema"in e?e.schema:e.identifier,n=e.host;this.baseURL=new URL(`/copilotstudio/prebuilt/authenticated/bots/${r}`,n),this.baseURL.searchParams.append("api-version",this.API_VERSION)}getConversationUrl(e){let r=new URL(this.baseURL.href);return r.pathname=`${r.pathname}/conversations`,e&&(r.pathname=`${r.pathname}/${e}`),r.href}};var dr=class{constructor(e){this.API_VERSION="2022-03-01-preview";let{schema:r,host:n}=e;this.baseURL=new URL(`/copilotstudio/dataverse-backed/authenticated/bots/${r}`,n),this.baseURL.searchParams.append("api-version",this.API_VERSION)}getConversationUrl(e){let r=new URL(this.baseURL.href);return r.pathname=`${r.pathname}/conversations`,e&&(r.pathname=`${r.pathname}/${e}`),r.href}};var it=(0,Po.debug)("copilot-studio:power-platform");function Lt(t,e){var d,l,f,h,C,T,P,v;let r=((d=t.schemaName)==null?void 0:d.trim())||((l=t.agentIdentifier)==null?void 0:l.trim());if(!((f=t.directConnectUrl)!=null&&f.trim())&&(!((h=t.environmentId)!=null&&h.trim())||!(r!=null&&r.trim())))throw new Error("Either directConnectUrl OR both environmentId and schemaName/agentIdentifier must be provided");if((C=t.directConnectUrl)!=null&&C.trim()){if(it.debug(`Using direct connection: ${t.directConnectUrl}`),!Dt(t.directConnectUrl))throw new Error("directConnectUrl must be a valid URL");return pa(t.directConnectUrl,e).href}let n=(T=t.cloud)!=null?T:"Prod",o=(P=t.copilotAgentType)!=null?P:"Published";if(it.debug(`Using cloud setting: ${n}`),it.debug(`Using agent type: ${o}`),n==="Other")if((v=t.customPowerPlatformCloud)!=null&&v.trim())if(Dt(t.customPowerPlatformCloud))it.debug(`Using custom Power Platform cloud: ${t.customPowerPlatformCloud}`);else throw new Error("customPowerPlatformCloud must be a valid URL");else throw new Error("customPowerPlatformCloud must be provided when PowerPlatformCloud is Other");let i=ma(n,t.environmentId,t.customPowerPlatformCloud),a={Published:()=>new dr({host:i,schema:r}),Prebuilt:()=>new ur({host:i,schema:r})}[o]().getConversationUrl(e);return it.debug(`Generated Copilot Studio connection URL: ${a}`),a}function Oo(t,e){if(!e||!e.trim())throw new Error("conversationId is required for subscribe URL");let r=Lt(t,e),n=new URL(r);n.pathname=n.pathname.endsWith("/")?`${n.pathname}subscribe`:`${n.pathname}/subscribe`;let o=n.href;return it.debug(`Generated Copilot Studio subscribe URL: ${o}`),o}function Eo(t,e="Unknown",r="",n=""){var o,i;if(!n&&!(t!=null&&t.directConnectUrl)){if(e==="Other"&&!r)throw new Error("cloudBaseAddress must be provided when PowerPlatformCloudCategory is Other");if(!t&&e==="Unknown")throw new Error("Either settings or cloud must be provided");if(t&&t.cloud&&t.cloud!=="Unknown"&&(e=t.cloud),e==="Other")if(r&&Dt(r))e="Other";else if(t!=null&&t.customPowerPlatformCloud&&Dt(t.customPowerPlatformCloud))e="Other",r=t.customPowerPlatformCloud;else throw new Error("Either CustomPowerPlatformCloud or cloudBaseAddress must be provided when PowerPlatformCloudCategory is Other");return r!=null||(r="api.unknown.powerplatform.com"),`https://${lr(e,r)}/.default`}else if(n||(n=(o=t==null?void 0:t.directConnectUrl)!=null?o:""),n&&Dt(n)){if(Ao(new URL(n))==="Unknown"){let s=(i=t==null?void 0:t.cloud)!=null?i:e;if(s==="Other"||s==="Unknown")throw new Error("Unable to resolve the PowerPlatform Cloud from DirectConnectUrl. The Token Audience resolver requires a specific PowerPlatformCloudCategory.");if(s!=="Unknown")return`https://${lr(s,"")}/.default`;throw new Error("Unable to resolve the PowerPlatform Cloud from DirectConnectUrl. The Token Audience resolver requires a specific PowerPlatformCloudCategory.")}return`https://${lr(Ao(new URL(n)),"")}/.default`}else throw new Error("DirectConnectUrl must be provided when DirectConnectUrl is set")}function Dt(t){try{let e=t.startsWith("http")?t:`https://${t}`;return!!new URL(e)}catch{return!1}}function pa(t,e){let r=new URL(t);return r.searchParams.has("api-version")||r.searchParams.append("api-version","2022-03-01-preview"),r.pathname.endsWith("/")&&(r.pathname=r.pathname.slice(0,-1)),r.pathname.includes("/conversations")&&(r.pathname=r.pathname.substring(0,r.pathname.indexOf("/conversations"))),r.pathname=`${r.pathname}/conversations`,e&&(r.pathname=`${r.pathname}/${e}`),r}function ma(t,e,r){if(t==="Other"&&(!r||!r.trim()))throw new Error("cloudBaseAddress must be provided when PowerPlatformCloud is Other");r=r!=null?r:"api.unknown.powerplatform.com";let n=e.toLowerCase().replaceAll("-",""),o=ha(t),i=n.substring(0,n.length-o),s=n.substring(n.length-o);return new URL(`https://${i}.${s}.environment.${lr(t,r)}`)}function lr(t,e){switch(t){case"Local":return"api.powerplatform.localhost";case"Exp":return"api.exp.powerplatform.com";case"Dev":return"api.dev.powerplatform.com";case"Prv":return"api.prv.powerplatform.com";case"Test":return"api.test.powerplatform.com";case"Preprod":return"api.preprod.powerplatform.com";case"FirstRelease":case"Prod":return"api.powerplatform.com";case"GovFR":return"api.gov.powerplatform.microsoft.us";case"Gov":return"api.gov.powerplatform.microsoft.us";case"High":return"api.high.powerplatform.microsoft.us";case"DoD":return"api.appsplatform.us";case"Mooncake":return"api.powerplatform.partner.microsoftonline.cn";case"Ex":return"api.powerplatform.eaglex.ic.gov";case"Rx":return"api.powerplatform.microsoft.scloud";case"Other":return e;default:throw new Error(`Invalid cluster category value: ${t}`)}}function ha(t){switch(t){case"FirstRelease":case"Prod":return 2;default:return 1}}function Ao(t){switch(t.host.toLowerCase()){case"api.powerplatform.localhost":return"Local";case"api.exp.powerplatform.com":return"Exp";case"api.dev.powerplatform.com":return"Dev";case"api.prv.powerplatform.com":return"Prv";case"api.test.powerplatform.com":return"Test";case"api.preprod.powerplatform.com":return"Preprod";case"api.powerplatform.com":return"Prod";case"api.gov.powerplatform.microsoft.us":return"GovFR";case"api.high.powerplatform.microsoft.us":return"High";case"api.appsplatform.us":return"DoD";case"api.powerplatform.partner.microsoftonline.cn":return"Mooncake";default:return"Unknown"}}var Qe=Rt(to());var er=class{constructor(e,r){this.activity=e,this.conversationId=r}};var ys=Rt(Mt());var $r="1.4.1";var Vr={};var tr=class{static getProductInfo(){let e=`CopilotStudioClient.agents-sdk-js/${$r}`,r;return typeof window!="undefined"&&window.navigator?r=`${e} ${navigator.userAgent}`:r=`${e} nodejs/${process.version} ${Vr.platform()}-${Vr.arch()}/${Vr.release()}`,r}static getVersionString(){return`CopilotStudioClient.agents-sdk-js/${$r}`}static getVersion(){return $r}};var Hr=class{static getScopeFromSettings(e){return Eo(e)}};function ps(t,e){return{activities:t,conversationId:e,isNewConversation:!0}}function ms(t,e){return{activities:t,conversationId:e,activityCount:t.length}}var M=(0,ys.debug)("copilot-studio:client"),Se=class Se{constructor(e,r){this.conversationId="";this.settings=e,this.token=r}logDiagnostic(e,...r){this.settings.enableDiagnostics&&M.info(`[DIAGNOSTICS] ${e}`,...r)}async*postRequestAsync(e,r,n="POST"){var s,a,d,l,f,h,C,T,P,v;this.logDiagnostic(`Request URL: ${e}`),this.logDiagnostic(`Request Method: ${n}`),this.logDiagnostic("Request Body:",r?JSON.stringify(r,null,2):"none"),M.debug(`>>> SEND TO ${e}`);let o=new Map,i=rn({url:e,headers:{Authorization:`Bearer ${this.token}`,"User-Agent":tr.getProductInfo(),"Content-Type":"application/json",Accept:"text/event-stream"},body:r?JSON.stringify(r):void 0,method:n,fetch:async(b,_)=>{let O=await fetch(b,_);return this.processResponseHeaders(O.headers),O}});try{for await(let{data:b,event:_}of i){if(b&&_==="activity")try{let O=Qe.Activity.fromJson(b),E=(s=O.entities)==null?void 0:s.find(N=>N.type==="streaminfo"&&N.streamType==="streaming");switch(O.type){case Qe.ActivityTypes.Message:this.conversationId.trim()||(this.conversationId=(d=(a=O.conversation)==null?void 0:a.id)!=null?d:"",M.debug(`Conversation ID: ${this.conversationId}`)),yield O;break;case Qe.ActivityTypes.Typing:if(M.debug(`Activity type: ${O.type}`),E||((l=O.channelData)==null?void 0:l.streamType)==="streaming"){let N=(f=O.text)!=null?f:"",ie=(C=E==null?void 0:E.streamId)!=null?C:(h=O.channelData)==null?void 0:h.streamId,H=(P=E==null?void 0:E.streamSequence)!=null?P:(T=O.channelData)==null?void 0:T.streamSequence;if(ie&&H){if(o.has(ie)){let Y=o.get(ie);Y.push({text:N,sequence:H}),o.set(ie,Y)}else o.set(ie,[{text:N,sequence:H}]);O.text=((v=o.get(ie))==null?void 0:v.sort((Y,Pe)=>Y.sequence-Pe.sequence).map(Y=>Y.text).join(""))||""}}yield O;break;default:M.debug(`Activity type: ${O.type}`),yield O;break}}catch(O){M.error("Failed to parse activity:",O)}else if(_==="end"){M.debug("Stream complete");break}if(i.readyState==="closed"){M.debug("Connection closed");break}}}finally{i.close()}}processResponseHeaders(e){var n,o;if(this.settings.useExperimentalEndpoint&&!((n=this.settings.directConnectUrl)!=null&&n.trim())){let i=e==null?void 0:e.get(Se.islandExperimentalUrlHeaderKey);i&&(this.settings.directConnectUrl=i,M.debug(`Island Experimental URL: ${i}`))}this.conversationId=(o=e==null?void 0:e.get(Se.conversationIdHeaderKey))!=null?o:"",this.conversationId&&M.debug(`Conversation ID: ${this.conversationId}`);let r=new Headers;e.forEach((i,s)=>{s.toLowerCase()!=="authorization"&&s.toLowerCase()!==Se.conversationIdHeaderKey.toLowerCase()&&r.set(s,i)}),this.logDiagnostic("Response Headers:",r)}async*startConversationStreaming(e){var i;let r;typeof e=="boolean"||e===void 0?r={emitStartConversationEvent:e!=null?e:!0}:r=e;let n=Lt(this.settings,r.conversationId),o={emitStartConversationEvent:(i=r.emitStartConversationEvent)!=null?i:!0};r.locale&&(o.locale=r.locale),M.info("Starting conversation ...",r),this.logDiagnostic("Start conversation request:",o),yield*this.postRequestAsync(n,o,"POST")}async*sendActivityStreaming(e,r=this.conversationId){var s,a;let n=(a=(s=e.conversation)==null?void 0:s.id)!=null?a:r,o=Lt(this.settings,n),i=new er(e);M.info("Sending activity...",e),yield*this.postRequestAsync(o,i,"POST")}async*executeStreaming(e,r){if(!r||!r.trim())throw new Error("conversationId is required for executeStreaming");let n=Lt(this.settings,r),o=new er(e,r);M.info("Executing turn with conversation ID:",r),this.logDiagnostic("Execute turn request:",{conversationId:r,activityType:e.type,activityText:e.text}),yield*this.postRequestAsync(n,o,"POST")}async execute(e,r){let n=[];for await(let o of this.executeStreaming(e,r))n.push(o);return n}async startConversationAsync(e){let r=[];for await(let n of this.startConversationStreaming(e))r.push(n);return r}async askQuestionAsync(e,r){let o={id:r!=null&&r.trim()?r:this.conversationId},i={type:"message",text:e,conversation:o},s=Qe.Activity.fromObject(i),a=[];for await(let d of this.sendActivityStreaming(s,r))a.push(d);return a}async sendActivity(e,r=this.conversationId){let n=[];for await(let o of this.sendActivityStreaming(e,r))n.push(o);return n}async startConversationWithResponse(e){var o;let r=[],n="";for await(let i of this.startConversationStreaming(e))r.push(i),(o=i.conversation)!=null&&o.id&&(n=i.conversation.id);return n=n||this.conversationId,ps(r,n)}async executeWithResponse(e,r){let n=[];for await(let o of this.executeStreaming(e,r))n.push(o);return ms(n,r)}async*subscribeAsync(e,r){if(!e||!e.trim())throw new Error("conversationId is required for subscribeAsync");let n=Oo(this.settings,e);M.info("Subscribing to conversation:",e),this.logDiagnostic("Subscribe request:",{conversationId:e,lastReceivedEventId:r,url:n});let o=rn({url:n,headers:{Authorization:`Bearer ${this.token}`,"User-Agent":tr.getProductInfo(),Accept:"text/event-stream",...r&&{"Last-Event-ID":r}},method:"GET",fetch:async(i,s)=>{let a=await fetch(i,s);return this.processResponseHeaders(a.headers),a}});try{for await(let{data:i,event:s,id:a}of o){if(i&&s==="activity")try{let d=Qe.Activity.fromJson(i),l={activity:d,eventId:a};M.debug(`Received activity via subscription, event ID: ${a}`),this.logDiagnostic("Subscribe event received:",{eventId:a,activityType:d.type}),yield l}catch(d){M.error("Failed to parse activity in subscription:",d)}else if(s==="end"){M.debug("Subscription stream complete");break}if(o.readyState==="closed"){M.debug("Subscription connection closed");break}}}finally{o.close()}}};Se.conversationIdHeaderKey="x-ms-conversationid",Se.islandExperimentalUrlHeaderKey="x-ms-d2e-experimental",Se.scopeFromSettings=Hr.getScopeFromSettings;var hs=Se;var L=[];for(let t=0;t<256;++t)L.push((t+256).toString(16).slice(1));function vs(t,e=0){return(L[t[e+0]]+L[t[e+1]]+L[t[e+2]]+L[t[e+3]]+"-"+L[t[e+4]]+L[t[e+5]]+"-"+L[t[e+6]]+L[t[e+7]]+"-"+L[t[e+8]]+L[t[e+9]]+"-"+L[t[e+10]]+L[t[e+11]]+L[t[e+12]]+L[t[e+13]]+L[t[e+14]]+L[t[e+15]]).toLowerCase()}var ro,qd=new Uint8Array(16);function no(){if(!ro){if(typeof crypto=="undefined"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");ro=crypto.getRandomValues.bind(crypto)}return ro(qd)}var Fd=typeof crypto!="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),oo={randomUUID:Fd};function $d(t,e,r){var o,i,s;if(oo.randomUUID&&!e&&!t)return oo.randomUUID();t=t||{};let n=(s=(i=t.random)!=null?i:(o=t.rng)==null?void 0:o.call(t))!=null?s:no();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){if(r=r||0,r<0||r+16>e.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let a=0;a<16;++a)e[r+a]=n[a];return e}return vs(n)}var io=$d;var Zs=Rt(to());var so=function(t,e){return so=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[o]=n[o])},so(t,e)};function Ae(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");so(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function rr(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function St(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],s;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(a){s={error:a}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(s)throw s.error}}return i}function At(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))}function te(t){return typeof t=="function"}function Wr(t){var e=function(n){Error.call(n),n.stack=new Error().stack},r=t(e);return r.prototype=Object.create(Error.prototype),r.prototype.constructor=r,r}var Br=Wr(function(t){return function(r){t(this),this.message=r?r.length+` errors occurred during unsubscription:
5
+ `&&n++}}return[e,r]}var xo="connecting",Hs="open",tn="closed",ir=()=>{};function Ws(t,{getStream:e}){let r=typeof t=="string"||t instanceof URL?{url:t}:t,{onMessage:n,onComment:o=ir,onConnect:i=ir,onDisconnect:s=ir,onScheduleReconnect:a=ir}=r,{fetch:d,url:l,initialLastEventId:f}=Bs(r),h={...r.headers},C=[],T=n?[n]:[],P=U=>T.forEach(se=>se(U)),v=_o({onEvent:Us,onRetry:Ns,onComment:o}),b,_=l.toString(),O=new AbortController,E=f,N=2e3,ie,H=tn;return Y(),{close:Pe,connect:Y,[Symbol.iterator]:()=>{throw new Error("EventSource does not support synchronous iteration. Use `for await` instead.")},[Symbol.asyncIterator]:Yr,get lastEventId(){return E},get url(){return _},get readyState(){return H}};function Y(){b||(H=xo,O=new AbortController,b=d(l,Ms()).then(Rs).catch(U=>{b=null,!(U.name==="AbortError"||U.type==="aborted"||O.signal.aborted)&&yo()}))}function Pe(){H=tn,O.abort(),v.reset(),clearTimeout(ie),C.forEach(U=>U())}function Yr(){let U=[],se=[];function Zt(){return new Promise(W=>{let ae=se.shift();ae?W({value:ae,done:!1}):U.push(W)})}let tt=function(W){let ae=U.shift();ae?ae({value:W,done:!1}):se.push(W)};function Oe(){for(T.splice(T.indexOf(tt),1);U.shift(););for(;se.shift(););}function kt(){let W=U.shift();W&&(W({done:!0,value:void 0}),Oe())}return C.push(kt),T.push(tt),{next(){return H===tn?this.return():Zt()},return(){return Oe(),Promise.resolve({done:!0,value:void 0})},throw(W){return Oe(),Promise.reject(W)},[Symbol.asyncIterator](){return this}}}function yo(){a({delay:N}),!O.signal.aborted&&(H=xo,ie=setTimeout(Y,N))}async function Rs(U){i(),v.reset();let{body:se,redirected:Zt,status:tt}=U;if(tt===204){s(),Pe();return}if(!se)throw new Error("Missing response body");Zt&&(_=U.url);let Oe=e(se),kt=new TextDecoder,W=Oe.getReader(),ae=!0;H=Hs;do{let{done:vo,value:go}=await W.read();go&&v.feed(kt.decode(go,{stream:!vo})),vo&&(ae=!1,b=null,v.reset(),yo(),s())}while(ae)}function Us(U){typeof U.id=="string"&&(E=U.id),P(U)}function Ns(U){N=U}function Ms(){let{mode:U,credentials:se,body:Zt,method:tt,redirect:Oe,referrer:kt,referrerPolicy:W}=r,ae={Accept:"text/event-stream",...h,...E?{"Last-Event-ID":E}:void 0};return{mode:U,credentials:se,body:Zt,method:tt,redirect:Oe,referrer:kt,referrerPolicy:W,headers:ae,cache:"no-store",signal:O.signal}}}function Bs(t){let e=t.fetch||globalThis.fetch;if(!Gs(e))throw new Error("No fetch implementation provided, and one was not found on the global object.");if(typeof AbortController!="function")throw new Error("Missing AbortController implementation");let{url:r,initialLastEventId:n}=t;if(typeof r!="string"&&!(r instanceof URL))throw new Error("Invalid URL provided - must be string or URL instance");if(typeof n!="string"&&n!==void 0)throw new Error("Invalid initialLastEventId provided - must be string or undefined");return{fetch:e,url:r,initialLastEventId:n}}function Gs(t){return typeof t=="function"}var Ks={getStream:Js};function rn(t){return Ws(t,Ks)}function Js(t){if(!(t instanceof ReadableStream))throw new Error("Invalid stream, expected a web ReadableStream");return t}var Po=Rt(Mt());var ur=class{constructor(e){this.API_VERSION="2022-03-01-preview";let r="schema"in e?e.schema:e.identifier,n=e.host;this.baseURL=new URL(`/copilotstudio/prebuilt/authenticated/bots/${r}`,n),this.baseURL.searchParams.append("api-version",this.API_VERSION)}getConversationUrl(e){let r=new URL(this.baseURL.href);return r.pathname=`${r.pathname}/conversations`,e&&(r.pathname=`${r.pathname}/${e}`),r.href}};var dr=class{constructor(e){this.API_VERSION="2022-03-01-preview";let{schema:r,host:n}=e;this.baseURL=new URL(`/copilotstudio/dataverse-backed/authenticated/bots/${r}`,n),this.baseURL.searchParams.append("api-version",this.API_VERSION)}getConversationUrl(e){let r=new URL(this.baseURL.href);return r.pathname=`${r.pathname}/conversations`,e&&(r.pathname=`${r.pathname}/${e}`),r.href}};var it=(0,Po.debug)("copilot-studio:power-platform");function Lt(t,e){var d,l,f,h,C,T,P,v;let r=((d=t.schemaName)==null?void 0:d.trim())||((l=t.agentIdentifier)==null?void 0:l.trim());if(!((f=t.directConnectUrl)!=null&&f.trim())&&(!((h=t.environmentId)!=null&&h.trim())||!(r!=null&&r.trim())))throw new Error("Either directConnectUrl OR both environmentId and schemaName/agentIdentifier must be provided");if((C=t.directConnectUrl)!=null&&C.trim()){if(it.debug(`Using direct connection: ${t.directConnectUrl}`),!Dt(t.directConnectUrl))throw new Error("directConnectUrl must be a valid URL");return pa(t.directConnectUrl,e).href}let n=(T=t.cloud)!=null?T:"Prod",o=(P=t.copilotAgentType)!=null?P:"Published";if(it.debug(`Using cloud setting: ${n}`),it.debug(`Using agent type: ${o}`),n==="Other")if((v=t.customPowerPlatformCloud)!=null&&v.trim())if(Dt(t.customPowerPlatformCloud))it.debug(`Using custom Power Platform cloud: ${t.customPowerPlatformCloud}`);else throw new Error("customPowerPlatformCloud must be a valid URL");else throw new Error("customPowerPlatformCloud must be provided when PowerPlatformCloud is Other");let i=ma(n,t.environmentId,t.customPowerPlatformCloud),a={Published:()=>new dr({host:i,schema:r}),Prebuilt:()=>new ur({host:i,schema:r})}[o]().getConversationUrl(e);return it.debug(`Generated Copilot Studio connection URL: ${a}`),a}function Oo(t,e){if(!e||!e.trim())throw new Error("conversationId is required for subscribe URL");let r=Lt(t,e),n=new URL(r);n.pathname=n.pathname.endsWith("/")?`${n.pathname}subscribe`:`${n.pathname}/subscribe`;let o=n.href;return it.debug(`Generated Copilot Studio subscribe URL: ${o}`),o}function Eo(t,e="Unknown",r="",n=""){var o,i;if(!n&&!(t!=null&&t.directConnectUrl)){if(e==="Other"&&!r)throw new Error("cloudBaseAddress must be provided when PowerPlatformCloudCategory is Other");if(!t&&e==="Unknown")throw new Error("Either settings or cloud must be provided");if(t&&t.cloud&&t.cloud!=="Unknown"&&(e=t.cloud),e==="Other")if(r&&Dt(r))e="Other";else if(t!=null&&t.customPowerPlatformCloud&&Dt(t.customPowerPlatformCloud))e="Other",r=t.customPowerPlatformCloud;else throw new Error("Either CustomPowerPlatformCloud or cloudBaseAddress must be provided when PowerPlatformCloudCategory is Other");return r!=null||(r="api.unknown.powerplatform.com"),`https://${lr(e,r)}/.default`}else if(n||(n=(o=t==null?void 0:t.directConnectUrl)!=null?o:""),n&&Dt(n)){if(Ao(new URL(n))==="Unknown"){let s=(i=t==null?void 0:t.cloud)!=null?i:e;if(s==="Other"||s==="Unknown")throw new Error("Unable to resolve the PowerPlatform Cloud from DirectConnectUrl. The Token Audience resolver requires a specific PowerPlatformCloudCategory.");if(s!=="Unknown")return`https://${lr(s,"")}/.default`;throw new Error("Unable to resolve the PowerPlatform Cloud from DirectConnectUrl. The Token Audience resolver requires a specific PowerPlatformCloudCategory.")}return`https://${lr(Ao(new URL(n)),"")}/.default`}else throw new Error("DirectConnectUrl must be provided when DirectConnectUrl is set")}function Dt(t){try{let e=t.startsWith("http")?t:`https://${t}`;return!!new URL(e)}catch{return!1}}function pa(t,e){let r=new URL(t);return r.searchParams.has("api-version")||r.searchParams.append("api-version","2022-03-01-preview"),r.pathname.endsWith("/")&&(r.pathname=r.pathname.slice(0,-1)),r.pathname.includes("/conversations")&&(r.pathname=r.pathname.substring(0,r.pathname.indexOf("/conversations"))),r.pathname=`${r.pathname}/conversations`,e&&(r.pathname=`${r.pathname}/${e}`),r}function ma(t,e,r){if(t==="Other"&&(!r||!r.trim()))throw new Error("cloudBaseAddress must be provided when PowerPlatformCloud is Other");r=r!=null?r:"api.unknown.powerplatform.com";let n=e.toLowerCase().replaceAll("-",""),o=ha(t),i=n.substring(0,n.length-o),s=n.substring(n.length-o);return new URL(`https://${i}.${s}.environment.${lr(t,r)}`)}function lr(t,e){switch(t){case"Local":return"api.powerplatform.localhost";case"Exp":return"api.exp.powerplatform.com";case"Dev":return"api.dev.powerplatform.com";case"Prv":return"api.prv.powerplatform.com";case"Test":return"api.test.powerplatform.com";case"Preprod":return"api.preprod.powerplatform.com";case"FirstRelease":case"Prod":return"api.powerplatform.com";case"GovFR":return"api.gov.powerplatform.microsoft.us";case"Gov":return"api.gov.powerplatform.microsoft.us";case"High":return"api.high.powerplatform.microsoft.us";case"DoD":return"api.appsplatform.us";case"Mooncake":return"api.powerplatform.partner.microsoftonline.cn";case"Ex":return"api.powerplatform.eaglex.ic.gov";case"Rx":return"api.powerplatform.microsoft.scloud";case"Other":return e;default:throw new Error(`Invalid cluster category value: ${t}`)}}function ha(t){switch(t){case"FirstRelease":case"Prod":return 2;default:return 1}}function Ao(t){switch(t.host.toLowerCase()){case"api.powerplatform.localhost":return"Local";case"api.exp.powerplatform.com":return"Exp";case"api.dev.powerplatform.com":return"Dev";case"api.prv.powerplatform.com":return"Prv";case"api.test.powerplatform.com":return"Test";case"api.preprod.powerplatform.com":return"Preprod";case"api.powerplatform.com":return"Prod";case"api.gov.powerplatform.microsoft.us":return"GovFR";case"api.high.powerplatform.microsoft.us":return"High";case"api.appsplatform.us":return"DoD";case"api.powerplatform.partner.microsoftonline.cn":return"Mooncake";default:return"Unknown"}}var Qe=Rt(to());var er=class{constructor(e,r){this.activity=e,this.conversationId=r}};var ys=Rt(Mt());var $r="1.5.0-beta.1.g77c44097fe";var Vr={};var tr=class{static getProductInfo(){let e=`CopilotStudioClient.agents-sdk-js/${$r}`,r;return typeof window!="undefined"&&window.navigator?r=`${e} ${navigator.userAgent}`:r=`${e} nodejs/${process.version} ${Vr.platform()}-${Vr.arch()}/${Vr.release()}`,r}static getVersionString(){return`CopilotStudioClient.agents-sdk-js/${$r}`}static getVersion(){return $r}};var Hr=class{static getScopeFromSettings(e){return Eo(e)}};function ps(t,e){return{activities:t,conversationId:e,isNewConversation:!0}}function ms(t,e){return{activities:t,conversationId:e,activityCount:t.length}}var M=(0,ys.debug)("copilot-studio:client"),Se=class Se{constructor(e,r){this.conversationId="";this.settings=e,this.token=r}logDiagnostic(e,...r){this.settings.enableDiagnostics&&M.info(`[DIAGNOSTICS] ${e}`,...r)}async*postRequestAsync(e,r,n="POST"){var s,a,d,l,f,h,C,T,P,v;this.logDiagnostic(`Request URL: ${e}`),this.logDiagnostic(`Request Method: ${n}`),this.logDiagnostic("Request Body:",r?JSON.stringify(r,null,2):"none"),M.debug(`>>> SEND TO ${e}`);let o=new Map,i=rn({url:e,headers:{Authorization:`Bearer ${this.token}`,"User-Agent":tr.getProductInfo(),"Content-Type":"application/json",Accept:"text/event-stream"},body:r?JSON.stringify(r):void 0,method:n,fetch:async(b,_)=>{let O=await fetch(b,_);return this.processResponseHeaders(O.headers),O}});try{for await(let{data:b,event:_}of i){if(b&&_==="activity")try{let O=Qe.Activity.fromJson(b),E=(s=O.entities)==null?void 0:s.find(N=>N.type==="streaminfo"&&N.streamType==="streaming");switch(O.type){case Qe.ActivityTypes.Message:this.conversationId.trim()||(this.conversationId=(d=(a=O.conversation)==null?void 0:a.id)!=null?d:"",M.debug(`Conversation ID: ${this.conversationId}`)),yield O;break;case Qe.ActivityTypes.Typing:if(M.debug(`Activity type: ${O.type}`),E||((l=O.channelData)==null?void 0:l.streamType)==="streaming"){let N=(f=O.text)!=null?f:"",ie=(C=E==null?void 0:E.streamId)!=null?C:(h=O.channelData)==null?void 0:h.streamId,H=(P=E==null?void 0:E.streamSequence)!=null?P:(T=O.channelData)==null?void 0:T.streamSequence;if(ie&&H){if(o.has(ie)){let Y=o.get(ie);Y.push({text:N,sequence:H}),o.set(ie,Y)}else o.set(ie,[{text:N,sequence:H}]);O.text=((v=o.get(ie))==null?void 0:v.sort((Y,Pe)=>Y.sequence-Pe.sequence).map(Y=>Y.text).join(""))||""}}yield O;break;default:M.debug(`Activity type: ${O.type}`),yield O;break}}catch(O){M.error("Failed to parse activity:",O)}else if(_==="end"){M.debug("Stream complete");break}if(i.readyState==="closed"){M.debug("Connection closed");break}}}finally{i.close()}}processResponseHeaders(e){var n,o;if(this.settings.useExperimentalEndpoint&&!((n=this.settings.directConnectUrl)!=null&&n.trim())){let i=e==null?void 0:e.get(Se.islandExperimentalUrlHeaderKey);i&&(this.settings.directConnectUrl=i,M.debug(`Island Experimental URL: ${i}`))}this.conversationId=(o=e==null?void 0:e.get(Se.conversationIdHeaderKey))!=null?o:"",this.conversationId&&M.debug(`Conversation ID: ${this.conversationId}`);let r=new Headers;e.forEach((i,s)=>{s.toLowerCase()!=="authorization"&&s.toLowerCase()!==Se.conversationIdHeaderKey.toLowerCase()&&r.set(s,i)}),this.logDiagnostic("Response Headers:",r)}async*startConversationStreaming(e){var i;let r;typeof e=="boolean"||e===void 0?r={emitStartConversationEvent:e!=null?e:!0}:r=e;let n=Lt(this.settings,r.conversationId),o={emitStartConversationEvent:(i=r.emitStartConversationEvent)!=null?i:!0};r.locale&&(o.locale=r.locale),M.info("Starting conversation ...",r),this.logDiagnostic("Start conversation request:",o),yield*this.postRequestAsync(n,o,"POST")}async*sendActivityStreaming(e,r=this.conversationId){var s,a;let n=(a=(s=e.conversation)==null?void 0:s.id)!=null?a:r,o=Lt(this.settings,n),i=new er(e);M.info("Sending activity...",e),yield*this.postRequestAsync(o,i,"POST")}async*executeStreaming(e,r){if(!r||!r.trim())throw new Error("conversationId is required for executeStreaming");let n=Lt(this.settings,r),o=new er(e,r);M.info("Executing turn with conversation ID:",r),this.logDiagnostic("Execute turn request:",{conversationId:r,activityType:e.type,activityText:e.text}),yield*this.postRequestAsync(n,o,"POST")}async execute(e,r){let n=[];for await(let o of this.executeStreaming(e,r))n.push(o);return n}async startConversationAsync(e){let r=[];for await(let n of this.startConversationStreaming(e))r.push(n);return r}async askQuestionAsync(e,r){let o={id:r!=null&&r.trim()?r:this.conversationId},i={type:"message",text:e,conversation:o},s=Qe.Activity.fromObject(i),a=[];for await(let d of this.sendActivityStreaming(s,r))a.push(d);return a}async sendActivity(e,r=this.conversationId){let n=[];for await(let o of this.sendActivityStreaming(e,r))n.push(o);return n}async startConversationWithResponse(e){var o;let r=[],n="";for await(let i of this.startConversationStreaming(e))r.push(i),(o=i.conversation)!=null&&o.id&&(n=i.conversation.id);return n=n||this.conversationId,ps(r,n)}async executeWithResponse(e,r){let n=[];for await(let o of this.executeStreaming(e,r))n.push(o);return ms(n,r)}async*subscribeAsync(e,r){if(!e||!e.trim())throw new Error("conversationId is required for subscribeAsync");let n=Oo(this.settings,e);M.info("Subscribing to conversation:",e),this.logDiagnostic("Subscribe request:",{conversationId:e,lastReceivedEventId:r,url:n});let o=rn({url:n,headers:{Authorization:`Bearer ${this.token}`,"User-Agent":tr.getProductInfo(),Accept:"text/event-stream",...r&&{"Last-Event-ID":r}},method:"GET",fetch:async(i,s)=>{let a=await fetch(i,s);return this.processResponseHeaders(a.headers),a}});try{for await(let{data:i,event:s,id:a}of o){if(i&&s==="activity")try{let d=Qe.Activity.fromJson(i),l={activity:d,eventId:a};M.debug(`Received activity via subscription, event ID: ${a}`),this.logDiagnostic("Subscribe event received:",{eventId:a,activityType:d.type}),yield l}catch(d){M.error("Failed to parse activity in subscription:",d)}else if(s==="end"){M.debug("Subscription stream complete");break}if(o.readyState==="closed"){M.debug("Subscription connection closed");break}}}finally{o.close()}}};Se.conversationIdHeaderKey="x-ms-conversationid",Se.islandExperimentalUrlHeaderKey="x-ms-d2e-experimental",Se.scopeFromSettings=Hr.getScopeFromSettings;var hs=Se;var L=[];for(let t=0;t<256;++t)L.push((t+256).toString(16).slice(1));function vs(t,e=0){return(L[t[e+0]]+L[t[e+1]]+L[t[e+2]]+L[t[e+3]]+"-"+L[t[e+4]]+L[t[e+5]]+"-"+L[t[e+6]]+L[t[e+7]]+"-"+L[t[e+8]]+L[t[e+9]]+"-"+L[t[e+10]]+L[t[e+11]]+L[t[e+12]]+L[t[e+13]]+L[t[e+14]]+L[t[e+15]]).toLowerCase()}var ro,qd=new Uint8Array(16);function no(){if(!ro){if(typeof crypto=="undefined"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");ro=crypto.getRandomValues.bind(crypto)}return ro(qd)}var Fd=typeof crypto!="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),oo={randomUUID:Fd};function $d(t,e,r){var o,i,s;if(oo.randomUUID&&!e&&!t)return oo.randomUUID();t=t||{};let n=(s=(i=t.random)!=null?i:(o=t.rng)==null?void 0:o.call(t))!=null?s:no();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){if(r=r||0,r<0||r+16>e.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let a=0;a<16;++a)e[r+a]=n[a];return e}return vs(n)}var io=$d;var Zs=Rt(to());var so=function(t,e){return so=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[o]=n[o])},so(t,e)};function Ae(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");so(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function rr(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function St(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],s;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(a){s={error:a}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(s)throw s.error}}return i}function At(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))}function te(t){return typeof t=="function"}function Wr(t){var e=function(n){Error.call(n),n.stack=new Error().stack},r=t(e);return r.prototype=Object.create(Error.prototype),r.prototype.constructor=r,r}var Br=Wr(function(t){return function(r){t(this),this.message=r?r.length+` errors occurred during unsubscription:
6
6
  `+r.map(function(n,o){return o+1+") "+n.toString()}).join(`
7
7
  `):"",this.name="UnsubscriptionError",this.errors=r}});function nr(t,e){if(t){var r=t.indexOf(e);0<=r&&t.splice(r,1)}}var Pt=(function(){function t(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return t.prototype.unsubscribe=function(){var e,r,n,o,i;if(!this.closed){this.closed=!0;var s=this._parentage;if(s)if(this._parentage=null,Array.isArray(s))try{for(var a=rr(s),d=a.next();!d.done;d=a.next()){var l=d.value;l.remove(this)}}catch(v){e={error:v}}finally{try{d&&!d.done&&(r=a.return)&&r.call(a)}finally{if(e)throw e.error}}else s.remove(this);var f=this.initialTeardown;if(te(f))try{f()}catch(v){i=v instanceof Br?v.errors:[v]}var h=this._finalizers;if(h){this._finalizers=null;try{for(var C=rr(h),T=C.next();!T.done;T=C.next()){var P=T.value;try{gs(P)}catch(v){i=i!=null?i:[],v instanceof Br?i=At(At([],St(i)),St(v.errors)):i.push(v)}}}catch(v){n={error:v}}finally{try{T&&!T.done&&(o=C.return)&&o.call(C)}finally{if(n)throw n.error}}}if(i)throw new Br(i)}},t.prototype.add=function(e){var r;if(e&&e!==this)if(this.closed)gs(e);else{if(e instanceof t){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(r=this._finalizers)!==null&&r!==void 0?r:[]).push(e)}},t.prototype._hasParent=function(e){var r=this._parentage;return r===e||Array.isArray(r)&&r.includes(e)},t.prototype._addParent=function(e){var r=this._parentage;this._parentage=Array.isArray(r)?(r.push(e),r):r?[r,e]:e},t.prototype._removeParent=function(e){var r=this._parentage;r===e?this._parentage=null:Array.isArray(r)&&nr(r,e)},t.prototype.remove=function(e){var r=this._finalizers;r&&nr(r,e),e instanceof t&&e._removeParent(this)},t.EMPTY=(function(){var e=new t;return e.closed=!0,e})(),t})();var ao=Pt.EMPTY;function Gr(t){return t instanceof Pt||t&&"closed"in t&&te(t.remove)&&te(t.add)&&te(t.unsubscribe)}function gs(t){te(t)?t():t.unsubscribe()}var oe={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var Ot={setTimeout:function(t,e){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];var o=Ot.delegate;return o!=null&&o.setTimeout?o.setTimeout.apply(o,At([t,e],St(r))):setTimeout.apply(void 0,At([t,e],St(r)))},clearTimeout:function(t){var e=Ot.delegate;return((e==null?void 0:e.clearTimeout)||clearTimeout)(t)},delegate:void 0};function bs(t){Ot.setTimeout(function(){var e=oe.onUnhandledError;if(e)e(t);else throw t})}function co(){}var _s=(function(){return uo("C",void 0,void 0)})();function xs(t){return uo("E",void 0,t)}function ws(t){return uo("N",t,void 0)}function uo(t,e,r){return{kind:t,value:e,error:r}}var et=null;function Et(t){if(oe.useDeprecatedSynchronousErrorHandling){var e=!et;if(e&&(et={errorThrown:!1,error:null}),t(),e){var r=et,n=r.errorThrown,o=r.error;if(et=null,n)throw o}}else t()}function Cs(t){oe.useDeprecatedSynchronousErrorHandling&&et&&(et.errorThrown=!0,et.error=t)}var po=(function(t){Ae(e,t);function e(r){var n=t.call(this)||this;return n.isStopped=!1,r?(n.destination=r,Gr(r)&&r.add(n)):n.destination=Bd,n}return e.create=function(r,n,o){return new Jr(r,n,o)},e.prototype.next=function(r){this.isStopped?fo(ws(r),this):this._next(r)},e.prototype.error=function(r){this.isStopped?fo(xs(r),this):(this.isStopped=!0,this._error(r))},e.prototype.complete=function(){this.isStopped?fo(_s,this):(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,t.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(r){this.destination.next(r)},e.prototype._error=function(r){try{this.destination.error(r)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e})(Pt);var Vd=Function.prototype.bind;function lo(t,e){return Vd.call(t,e)}var Hd=(function(){function t(e){this.partialObserver=e}return t.prototype.next=function(e){var r=this.partialObserver;if(r.next)try{r.next(e)}catch(n){Kr(n)}},t.prototype.error=function(e){var r=this.partialObserver;if(r.error)try{r.error(e)}catch(n){Kr(n)}else Kr(e)},t.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(r){Kr(r)}},t})(),Jr=(function(t){Ae(e,t);function e(r,n,o){var i=t.call(this)||this,s;if(te(r)||!r)s={next:r!=null?r:void 0,error:n!=null?n:void 0,complete:o!=null?o:void 0};else{var a;i&&oe.useDeprecatedNextContext?(a=Object.create(r),a.unsubscribe=function(){return i.unsubscribe()},s={next:r.next&&lo(r.next,a),error:r.error&&lo(r.error,a),complete:r.complete&&lo(r.complete,a)}):s=r}return i.destination=new Hd(s),i}return e})(po);function Kr(t){oe.useDeprecatedSynchronousErrorHandling?Cs(t):bs(t)}function Wd(t){throw t}function fo(t,e){var r=oe.onStoppedNotification;r&&Ot.setTimeout(function(){return r(t,e)})}var Bd={closed:!0,next:co,error:Wd,complete:co};var Is=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function Ts(t){return t}function Ss(t){return t.length===0?Ts:t.length===1?t[0]:function(r){return t.reduce(function(n,o){return o(n)},r)}}var jt=(function(){function t(e){e&&(this._subscribe=e)}return t.prototype.lift=function(e){var r=new t;return r.source=this,r.operator=e,r},t.prototype.subscribe=function(e,r,n){var o=this,i=Kd(e)?e:new Jr(e,r,n);return Et(function(){var s=o,a=s.operator,d=s.source;i.add(a?a.call(i,d):d?o._subscribe(i):o._trySubscribe(i))}),i},t.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(r){e.error(r)}},t.prototype.forEach=function(e,r){var n=this;return r=As(r),new r(function(o,i){var s=new Jr({next:function(a){try{e(a)}catch(d){i(d),s.unsubscribe()}},error:i,complete:o});n.subscribe(s)})},t.prototype._subscribe=function(e){var r;return(r=this.source)===null||r===void 0?void 0:r.subscribe(e)},t.prototype[Is]=function(){return this},t.prototype.pipe=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return Ss(e)(this)},t.prototype.toPromise=function(e){var r=this;return e=As(e),new e(function(n,o){var i;r.subscribe(function(s){return i=s},function(s){return o(s)},function(){return n(i)})})},t.create=function(e){return new t(e)},t})();function As(t){var e;return(e=t!=null?t:oe.Promise)!==null&&e!==void 0?e:Promise}function Gd(t){return t&&te(t.next)&&te(t.error)&&te(t.complete)}function Kd(t){return t&&t instanceof po||Gd(t)&&Gr(t)}var Ps=Wr(function(t){return function(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}});var mo=(function(t){Ae(e,t);function e(){var r=t.call(this)||this;return r.closed=!1,r.currentObservers=null,r.observers=[],r.isStopped=!1,r.hasError=!1,r.thrownError=null,r}return e.prototype.lift=function(r){var n=new Os(this,this);return n.operator=r,n},e.prototype._throwIfClosed=function(){if(this.closed)throw new Ps},e.prototype.next=function(r){var n=this;Et(function(){var o,i;if(n._throwIfClosed(),!n.isStopped){n.currentObservers||(n.currentObservers=Array.from(n.observers));try{for(var s=rr(n.currentObservers),a=s.next();!a.done;a=s.next()){var d=a.value;d.next(r)}}catch(l){o={error:l}}finally{try{a&&!a.done&&(i=s.return)&&i.call(s)}finally{if(o)throw o.error}}}})},e.prototype.error=function(r){var n=this;Et(function(){if(n._throwIfClosed(),!n.isStopped){n.hasError=n.isStopped=!0,n.thrownError=r;for(var o=n.observers;o.length;)o.shift().error(r)}})},e.prototype.complete=function(){var r=this;Et(function(){if(r._throwIfClosed(),!r.isStopped){r.isStopped=!0;for(var n=r.observers;n.length;)n.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var r;return((r=this.observers)===null||r===void 0?void 0:r.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(r){return this._throwIfClosed(),t.prototype._trySubscribe.call(this,r)},e.prototype._subscribe=function(r){return this._throwIfClosed(),this._checkFinalizedStatuses(r),this._innerSubscribe(r)},e.prototype._innerSubscribe=function(r){var n=this,o=this,i=o.hasError,s=o.isStopped,a=o.observers;return i||s?ao:(this.currentObservers=null,a.push(r),new Pt(function(){n.currentObservers=null,nr(a,r)}))},e.prototype._checkFinalizedStatuses=function(r){var n=this,o=n.hasError,i=n.thrownError,s=n.isStopped;o?r.error(i):s&&r.complete()},e.prototype.asObservable=function(){var r=new jt;return r.source=this,r},e.create=function(r,n){return new Os(r,n)},e})(jt);var Os=(function(t){Ae(e,t);function e(r,n){var o=t.call(this)||this;return o.destination=r,o.source=n,o}return e.prototype.next=function(r){var n,o;(o=(n=this.destination)===null||n===void 0?void 0:n.next)===null||o===void 0||o.call(n,r)},e.prototype.error=function(r){var n,o;(o=(n=this.destination)===null||n===void 0?void 0:n.error)===null||o===void 0||o.call(n,r)},e.prototype.complete=function(){var r,n;(n=(r=this.destination)===null||r===void 0?void 0:r.complete)===null||n===void 0||n.call(r)},e.prototype._subscribe=function(r){var n,o;return(o=(n=this.source)===null||n===void 0?void 0:n.subscribe(r))!==null&&o!==void 0?o:ao},e})(mo);var ho=(function(t){Ae(e,t);function e(r){var n=t.call(this)||this;return n._value=r,n}return Object.defineProperty(e.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),e.prototype._subscribe=function(r){var n=t.prototype._subscribe.call(this,r);return!n.closed&&r.next(this._value),n},e.prototype.getValue=function(){var r=this,n=r.hasError,o=r.thrownError,i=r._value;if(n)throw o;return this._throwIfClosed(),i},e.prototype.next=function(r){t.prototype.next.call(this,this._value=r)},e})(mo);var ks=Rt(Mt()),ve=(0,ks.debug)("copilot-studio:webchat");function Jd(t){let e=!1;return r=>{if(!e)return e=!0,t(r)}}var Es=class{static createConnection(e,r){var v;ve.info("--> Creating connection between Copilot Studio and WebChat ...");let n=r!=null&&r.conversationId&&r.conversationId.trim()!==""?r.conversationId.trim():void 0,o=(v=r==null?void 0:r.startConversation)!=null?v:!n,i=0,s,a,d=n,l=!1,f=!1,h=new ho(0),C=js(async b=>{var O;s=b;let _=Jd(async()=>{h.next(2),await Promise.resolve()});if(!o||f){await _();return}f=!0,ve.debug("--> Connection established."),P();for await(let E of e.startConversationStreaming())delete E.replyToId,!a&&E.conversation&&(a=E.conversation),(O=E.conversation)!=null&&O.id&&(d=E.conversation.id),await _(),T(E);await _()}),T=b=>{let _={...b,timestamp:new Date().toISOString(),channelData:{...b.channelData,"webchat:sequence-id":i}};i++,ve.debug(`Notify '${_.type}' activity to WebChat:`,_),s==null||s.next(_)},P=()=>{if(!(r!=null&&r.showTyping))return;let b=a?{id:a.id,name:a.name}:{id:"agent",name:"Agent"};T({type:"typing",from:b})};return{connectionStatus$:h,activity$:C,get conversationId(){return d},postActivity(b){if(ve.info("--> Preparing to send activity to Copilot Studio ..."),!b)throw new Error("Activity cannot be null.");if(l)throw new Error("Connection has been ended.");if(!s)throw new Error("Activity subscriber is not initialized.");return js(async _=>{var O;try{ve.info("--> Sending activity to Copilot Studio ...");let E=Zs.Activity.fromObject({...b,id:io(),attachments:await Yd(b)});T(E),P(),_.next(E.id);for await(let N of e.sendActivityStreaming(E,d))!d&&((O=N.conversation)!=null&&O.id)&&(d=N.conversation.id),T(N),ve.info("<-- Activity received correctly from Copilot Studio.");_.complete()}catch(E){ve.error("Error sending Activity to Copilot Studio:",E),_.error(E)}})},end(){ve.info("--> Ending connection between Copilot Studio and WebChat ..."),l=!0,h.complete(),s&&(s.complete(),s=void 0)}}}};async function Yd(t){var r;if(t.type!=="message"||!((r=t.attachments)!=null&&r.length))return t.attachments||[];let e=[];for(let n of t.attachments){let o=await Xd(n);e.push(o)}return e}async function Xd(t){let e=t.contentUrl;if(!(e!=null&&e.startsWith("blob:")))return t;try{let r=await fetch(e);if(!r.ok)throw new Error(`Failed to fetch blob URL: ${r.status} ${r.statusText}`);let n=await r.blob(),o=await n.arrayBuffer(),i=Qd(o);e=`data:${n.type};base64,${i}`}catch(r){e=t.contentUrl,ve.error("Error processing blob attachment:",e,r)}return{...t,contentUrl:e}}function Qd(t){let e=typeof globalThis.Buffer=="function"?globalThis.Buffer:void 0;if(e&&typeof e.from=="function")return e.from(t).toString("base64");let r="";for(let n of new Uint8Array(t))r+=String.fromCharCode(n);return btoa(r)}function js(t){return new jt(e=>{Promise.resolve(t(e)).catch(r=>e.error(r))})}function ym(t=!0,e,r){return{emitStartConversationEvent:t,locale:e,conversationId:r}}export{Ut as AgentType,Qr as ConnectionSettings,hs as CopilotStudioClient,Es as CopilotStudioWebChat,er as ExecuteTurnRequest,Nt as PowerPlatformCloud,Hr as ScopeHelper,tr as UserAgentHelper,ms as createExecuteTurnResponse,ym as createStartRequest,ps as createStartResponse,Lt as getCopilotStudioConnectionUrl,Oo as getCopilotStudioSubscribeUrl,Eo as getTokenAudience,il as loadCopilotStudioConnectionSettingsFromEnv};
8
8
  //# sourceMappingURL=browser.mjs.map