@microsoft/agents-copilotstudio-client 1.6.0-beta.23.g73ada8e5f2 → 1.6.0-beta.24.g285b02c21b
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 +3 -3
- package/dist/src/browser.mjs +1 -1
- package/dist/src/browser.mjs.map +1 -1
- package/package.json +3 -3
package/dist/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@microsoft/agents-copilotstudio-client",
|
|
3
|
-
"version": "1.6.0-beta.
|
|
3
|
+
"version": "1.6.0-beta.24.g285b02c21b",
|
|
4
4
|
"homepage": "https://github.com/microsoft/Agents-for-js",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -27,8 +27,8 @@
|
|
|
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.6.0-beta.
|
|
31
|
-
"@microsoft/agents-telemetry": "1.6.0-beta.
|
|
30
|
+
"@microsoft/agents-activity": "1.6.0-beta.24.g285b02c21b",
|
|
31
|
+
"@microsoft/agents-telemetry": "1.6.0-beta.24.g285b02c21b",
|
|
32
32
|
"eventsource-client": "1.2.0",
|
|
33
33
|
"rxjs": "7.8.2"
|
|
34
34
|
},
|
package/dist/src/browser.mjs
CHANGED
|
@@ -2,7 +2,7 @@ var au=Object.create;var wr=Object.defineProperty;var cu=Object.getOwnPropertyDe
|
|
|
2
2
|
`;break;case"id":a=w.includes("\0")?void 0:w;break;case"retry":/^\d+$/.test(w)?n(parseInt(w,10)):r(new Or(`Invalid \`retry\` value: "${w}"`,{type:"invalid-retry",value:w,line:b}));break;default:r(new Or(`Unknown field "${h.length>20?`${h.slice(0,20)}\u2026`:h}"`,{type:"unknown-field",field:h,value:w,line:b}));break}}function E(){c.length>0&&e({id:a,event:l||void 0,data:c.endsWith(`
|
|
3
3
|
`)?c.slice(0,-1):c}),a=void 0,c="",l=""}function M(h={}){i&&h.consume&&g(i),s=!0,a=void 0,c="",l="",i=""}return{feed:p,reset:M}}function pu(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 Vi="connecting",fu="open",to="closed",Pr=()=>{};function mu(t,{getStream:e}){let r=typeof t=="string"||t instanceof URL?{url:t}:t,{onMessage:n,onComment:o=Pr,onConnect:i=Pr,onDisconnect:s=Pr,onScheduleReconnect:a=Pr}=r,{fetch:c,url:l,initialLastEventId:p}=hu(r),g={...r.headers},T=[],E=n?[n]:[],M=D=>E.forEach(ce=>ce(D)),h=Li({onEvent:ou,onRetry:iu,onComment:o}),w,b=l.toString(),P=new AbortController,O=p,N=2e3,L,j=to;return _e(),{close:J,connect:_e,[Symbol.iterator]:()=>{throw new Error("EventSource does not support synchronous iteration. Use `for await` instead.")},[Symbol.asyncIterator]:Jt,get lastEventId(){return O},get url(){return b},get readyState(){return j}};function _e(){w||(j=Vi,P=new AbortController,w=c(l,su()).then(nu).catch(D=>{w=null,!(D.name==="AbortError"||D.type==="aborted"||P.signal.aborted)&&ki()}))}function J(){j=to,P.abort(),h.reset(),clearTimeout(L),T.forEach(D=>D())}function Jt(){let D=[],ce=[];function Qt(){return new Promise($=>{let ue=ce.shift();ue?$({value:ue,done:!1}):D.push($)})}let pt=function($){let ue=D.shift();ue?ue({value:$,done:!1}):ce.push($)};function Le(){for(E.splice(E.indexOf(pt),1);D.shift(););for(;ce.shift(););}function er(){let $=D.shift();$&&($({done:!0,value:void 0}),Le())}return T.push(er),E.push(pt),{next(){return j===to?this.return():Qt()},return(){return Le(),Promise.resolve({done:!0,value:void 0})},throw($){return Le(),Promise.reject($)},[Symbol.asyncIterator](){return this}}}function ki(){a({delay:N}),!P.signal.aborted&&(j=Vi,L=setTimeout(_e,N))}async function nu(D){i(),h.reset();let{body:ce,redirected:Qt,status:pt}=D;if(pt===204){s(),J();return}if(!ce)throw new Error("Missing response body");Qt&&(b=D.url);let Le=e(ce),er=new TextDecoder,$=Le.getReader(),ue=!0;j=fu;do{let{done:Zi,value:Ui}=await $.read();Ui&&h.feed(er.decode(Ui,{stream:!Zi})),Zi&&(ue=!1,w=null,h.reset(),ki(),s())}while(ue)}function ou(D){typeof D.id=="string"&&(O=D.id),M(D)}function iu(D){N=D}function su(){let{mode:D,credentials:ce,body:Qt,method:pt,redirect:Le,referrer:er,referrerPolicy:$}=r,ue={Accept:"text/event-stream",...g,...O?{"Last-Event-ID":O}:void 0};return{mode:D,credentials:ce,body:Qt,method:pt,redirect:Le,referrer:er,referrerPolicy:$,headers:ue,cache:"no-store",signal:P.signal}}}function hu(t){let e=t.fetch||globalThis.fetch;if(!gu(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 gu(t){return typeof t=="function"}var yu={getStream:vu};function ro(t){return mu(t,yu)}function vu(t){if(!(t instanceof ReadableStream))throw new Error("Invalid stream, expected a web ReadableStream");return t}var Ea=Se(xt());var ln=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 pn=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,Ea.debug)("copilot-studio:power-platform");function gr(t,e){var c,l,p,g,T,E,M,h;let r=((c=t.schemaName)==null?void 0:c.trim())||((l=t.agentIdentifier)==null?void 0:l.trim());if(!((p=t.directConnectUrl)!=null&&p.trim())&&(!((g=t.environmentId)!=null&&g.trim())||!(r!=null&&r.trim())))throw new Error("Either directConnectUrl OR both environmentId and schemaName/agentIdentifier must be provided");if((T=t.directConnectUrl)!=null&&T.trim()){if(It.debug(`Using direct connection: ${t.directConnectUrl}`),!hr(t.directConnectUrl))throw new Error("directConnectUrl must be a valid URL");return il(t.directConnectUrl,e).href}let n=(E=t.cloud)!=null?E:"Prod",o=(M=t.copilotAgentType)!=null?M:"Published";if(It.debug(`Using cloud setting: ${n}`),It.debug(`Using agent type: ${o}`),n==="Other")if((h=t.customPowerPlatformCloud)!=null&&h.trim())if(hr(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=sl(n,t.environmentId,t.customPowerPlatformCloud),a={Published:()=>new pn({host:i,schema:r}),Prebuilt:()=>new ln({host:i,schema:r})}[o]().getConversationUrl(e);return It.debug(`Generated Copilot Studio connection URL: ${a}`),a}function Aa(t,e){if(!e||!e.trim())throw new Error("conversationId is required for subscribe URL");let r=gr(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 Sa(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&&hr(r))e="Other";else if(t!=null&&t.customPowerPlatformCloud&&hr(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://${fn(e,r)}/.default`}else if(n||(n=(o=t==null?void 0:t.directConnectUrl)!=null?o:""),n&&hr(n)){if(Ia(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://${fn(s,"")}/.default`;throw new Error("Unable to resolve the PowerPlatform Cloud from DirectConnectUrl. The Token Audience resolver requires a specific PowerPlatformCloudCategory.")}return`https://${fn(Ia(new URL(n)),"")}/.default`}else throw new Error("DirectConnectUrl must be provided when DirectConnectUrl is set")}function hr(t){try{let e=t.startsWith("http")?t:`https://${t}`;return!!new URL(e)}catch{return!1}}function il(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 sl(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=al(t),i=n.substring(0,n.length-o),s=n.substring(n.length-o);return new URL(`https://${i}.${s}.environment.${fn(t,r)}`)}function fn(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 al(t){switch(t){case"FirstRelease":case"Prod":return 2;default:return 1}}function Ia(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 dt=Se(qn());var Ir=class{constructor(e,r){this.activity=e,this.conversationId=r}};var De=Se(xt());var Fn="1.6.0-beta.23.g73ada8e5f2";var Gn={};var Er=class{static getProductInfo(){let e=`CopilotStudioClient.agents-sdk-js/${Fn}`,r;return typeof window!="undefined"&&window.navigator?r=`${e} ${navigator.userAgent}`:r=`${e} nodejs/${process.version} ${Gn.platform()}-${Gn.arch()}/${Gn.release()}`,r}static getVersionString(){return`CopilotStudioClient.agents-sdk-js/${Fn}`}static getVersion(){return Fn}};var $n=class{static getScopeFromSettings(e){return Sa(e)}};function Mc(t,e){return{activities:t,conversationId:e,isNewConversation:!0}}function Lc(t,e){return{activities:t,conversationId:e,activityCount:t.length}}var U=Se(xt()),G={activitiesReceivedCounter:U.metric.counter(U.MetricNames.CSC_ACTIVITIES_RECEIVED,{unit:"activities",description:"Total number of activities received by the Copilot Studio client"}),activitiesSentCounter:U.metric.counter(U.MetricNames.CSC_ACTIVITIES_SENT,{unit:"activities",description:"Total number of activities sent to Copilot Studio"}),conversationsStartedCounter:U.metric.counter(U.MetricNames.CSC_CONVERSATIONS_STARTED,{unit:"conversations",description:"Total number of conversations started with Copilot Studio"}),webchatConnectionsCounter:U.metric.counter(U.MetricNames.CSC_WEBCHAT_CONNECTIONS,{unit:"connections",description:"Total number of webchat connections created with Copilot Studio"}),requestsCounter:U.metric.counter(U.MetricNames.CSC_REQUEST_COUNT,{unit:"requests",description:"Total number of HTTP/SSE requests made to Copilot Studio"}),requestsErrorCounter:U.metric.counter(U.MetricNames.CSC_REQUEST_ERRORS,{unit:"requests",description:"Total number of failed requests to Copilot Studio"}),executeStreamingCounter:U.metric.counter(U.MetricNames.CSC_EXECUTE_STREAMING,{unit:"operations",description:"Total number of execute streaming operations"}),subscribeAsyncCounter:U.metric.counter(U.MetricNames.CSC_SUBSCRIBE_ASYNC,{unit:"operations",description:"Total number of subscribeAsync operations"}),subscribeEventCounter:U.metric.counter(U.MetricNames.CSC_SUBSCRIBE_EVENT,{unit:"events",description:"Total number of events received via subscribeAsync"}),streamDuration:U.metric.histogram(U.MetricNames.CSC_STREAM_DURATION,{unit:"ms",description:"Duration of SSE stream sessions in milliseconds"}),requestDuration:U.metric.histogram(U.MetricNames.CSC_REQUEST_DURATION,{unit:"ms",description:"Duration of requests to Copilot Studio in milliseconds"})};var xi=Se(qn()),K=Se(xt());var Ue={createConnection:K.trace.define({name:K.SpanNames.COPILOT_CREATE_CONNECTION,record:{showTyping:!1},actions:({span:t})=>({receivedFromCopilot(e){var r,n,o;t.addEvent("activity.received.from.copilot.studio",{"copilot.webchat.activity.type":(r=e.type)!=null?r:"unknown","copilot.webchat.activity.conversation_id":(o=(n=e.conversation)==null?void 0:n.id)!=null?o:"unknown"})},sentToWebChat(e){var r,n,o;t.addEvent("activity.sent.to.webchat",{"copilot.webchat.activity.type":(r=e.type)!=null?r:"unknown","copilot.webchat.activity.conversation_id":(o=(n=e.conversation)==null?void 0:n.id)!=null?o:"unknown"})}}),end({span:t,record:e}){var n;let r={"copilot.webchat.show_typing":(n=e.showTyping)!=null?n:"unknown"};t.setAttributes(r),G.webchatConnectionsCounter.add(1,r)}}),postRequest:K.trace.define({name:K.SpanNames.COPILOT_POST_REQUEST,record:{url:"",method:""},actions:({span:t})=>({receivedFromCopilot(e){var n,o,i;let r={"copilot.activity.type":(n=e.type)!=null?n:"unknown","copilot.activity.conversation_id":(i=(o=e.conversation)==null?void 0:o.id)!=null?i:"unknown"};t.addEvent("activity.received",{"copilot.post_request.activity.type":r["copilot.activity.type"],"copilot.post_request.activity.conversation_id":r["copilot.activity.conversation_id"]}),G.activitiesReceivedCounter.add(1,r)}}),end({span:t,record:e,duration:r,error:n}){var s,a;let o={"copilot.post_request.url":(s=e.url)!=null?s:"unknown","copilot.post_request.method":(a=e.method)!=null?a:"unknown"},i={operation:"postRequestAsync","copilot.post_request.url":o["copilot.post_request.url"],"copilot.post_request.method":o["copilot.post_request.method"]};t.setAttributes(o),G.requestsCounter.add(1,i),G.streamDuration.record(r,i),n&&G.requestsErrorCounter.add(1,{...i,"error.type":n instanceof Error?n.name:typeof n})}}),startConversation:K.trace.define({name:K.SpanNames.COPILOT_START_CONVERSATION,record:{shouldEmitStartEvent:!1},end({span:t,record:e,duration:r}){let n=e.shouldEmitStartEvent?{"copilot.emit_start_event":!0}:{"copilot.request":!0},o={operation:"startConversationStreaming",...n};t.setAttributes(n),G.conversationsStartedCounter.add(1,o),G.requestDuration.record(r,o)}}),sendActivity:K.trace.define({name:K.SpanNames.COPILOT_SEND_ACTIVITY,record:{activity:xi.Activity.fromObject({type:"unknown"})},end({span:t,record:e,duration:r}){var i,s,a;let n={"copilot.activity.type":(i=e.activity.type)!=null?i:"unknown","copilot.activity.conversation_id":(a=(s=e.activity.conversation)==null?void 0:s.id)!=null?a:"unknown"},o={operation:"sendActivityStreaming",...n};t.setAttributes(n),G.activitiesSentCounter.add(1,n),G.requestDuration.record(r,o)}}),executeStreaming:K.trace.define({name:K.SpanNames.COPILOT_EXECUTE_STREAMING,record:{activity:xi.Activity.fromObject({type:"unknown"}),conversationId:"unknown"},end({span:t,record:e,duration:r}){var i,s;let n={"copilot.activity.type":(i=e.activity.type)!=null?i:"unknown","copilot.activity.conversation_id":(s=e.conversationId)!=null?s:"unknown"},o={operation:"executeStreaming",...n};t.setAttributes(n),G.executeStreamingCounter.add(1,n),G.requestDuration.record(r,o)}}),subscribeAsync:K.trace.define({name:K.SpanNames.COPILOT_SUBSCRIBE_ASYNC,record:{conversationId:"unknown",lastReceivedEventId:"unknown"},actions:({span:t})=>({eventReceivedFromCopilot(e){var n,o;let r={"copilot.subscribe_async.event.id":(n=e.eventId)!=null?n:"unknown","copilot.subscribe_async.event.activity.type":(o=e.activity.type)!=null?o:"unknown"};t.addEvent("event.received",r),G.subscribeEventCounter.add(1,r)}}),end({span:t,record:e,duration:r}){var i,s;let n={"copilot.subscribe_async.conversation_id":(i=e.conversationId)!=null?i:"unknown","copilot.subscribe_async.last_received_event_id":(s=e.lastReceivedEventId)!=null?s:"unknown"},o={operation:"subscribeAsync","copilot.conversation_id":n["copilot.subscribe_async.conversation_id"],"copilot.last_received_event_id":n["copilot.subscribe_async.last_received_event_id"]};t.setAttributes(n),G.subscribeAsyncCounter.add(1,o),G.streamDuration.record(r,o)}})};var V=(0,De.debug)("copilot-studio:client"),je=class je{constructor(e,r){this.conversationId="";this.settings=e,this.token=r}logDiagnostic(e,...r){this.settings.enableDiagnostics&&V.info(`[DIAGNOSTICS] ${e}`,...r)}async*postRequestAsync(e,r,n="POST"){var i,s,a,c,l,p,g,T,E,M;let o=(0,De.trace)(Ue.postRequest);o.record({url:e,method:n});try{this.logDiagnostic(`Request URL: ${e}`),this.logDiagnostic(`Request Method: ${n}`),this.logDiagnostic("Request Body:",r?JSON.stringify(r,null,2):"none"),V.debug(`>>> SEND TO ${e}`);let h=new Map,w=ro({url:e,headers:{Authorization:`Bearer ${this.token}`,"User-Agent":Er.getProductInfo(),"Content-Type":"application/json",Accept:"text/event-stream"},body:r?JSON.stringify(r):void 0,method:n,fetch:async(b,P)=>{let O=await fetch(b,P);return this.processResponseHeaders(O.headers),O}});try{for await(let{data:b,event:P}of w){if(b&&P==="activity")try{let O=dt.Activity.fromJson(b);o.actions.receivedFromCopilot(O);let N=(i=O.entities)==null?void 0:i.find(L=>L.type==="streaminfo"&&L.streamType==="streaming");switch(O.type){case dt.ActivityTypes.Message:this.conversationId.trim()||(this.conversationId=(a=(s=O.conversation)==null?void 0:s.id)!=null?a:"",V.debug(`Conversation ID: ${this.conversationId}`)),yield O;break;case dt.ActivityTypes.Typing:if(V.debug(`Activity type: ${O.type}`),N||((c=O.channelData)==null?void 0:c.streamType)==="streaming"){let L=(l=O.text)!=null?l:"",j=(g=N==null?void 0:N.streamId)!=null?g:(p=O.channelData)==null?void 0:p.streamId,_e=(E=N==null?void 0:N.streamSequence)!=null?E:(T=O.channelData)==null?void 0:T.streamSequence;if(j&&_e){if(h.has(j)){let J=h.get(j);J.push({text:L,sequence:_e}),h.set(j,J)}else h.set(j,[{text:L,sequence:_e}]);O.text=((M=h.get(j))==null?void 0:M.sort((J,Jt)=>J.sequence-Jt.sequence).map(J=>J.text).join(""))||""}}yield O;break;default:V.debug(`Activity type: ${O.type}`),yield O;break}}catch(O){V.error("Failed to parse activity:",O)}else if(P==="end"){V.debug("Stream complete");break}if(w.readyState==="closed"){V.debug("Connection closed");break}}}finally{w.close()}}catch(h){throw o.fail(h)}finally{o.end()}}processResponseHeaders(e){var n,o;if(this.settings.useExperimentalEndpoint&&!((n=this.settings.directConnectUrl)!=null&&n.trim())){let i=e==null?void 0:e.get(je.islandExperimentalUrlHeaderKey);i&&(this.settings.directConnectUrl=i,V.debug(`Island Experimental URL: ${i}`))}this.conversationId=(o=e==null?void 0:e.get(je.conversationIdHeaderKey))!=null?o:"",this.conversationId&&V.debug(`Conversation ID: ${this.conversationId}`);let r=new Headers;e.forEach((i,s)=>{s.toLowerCase()!=="authorization"&&s.toLowerCase()!==je.conversationIdHeaderKey.toLowerCase()&&r.set(s,i)}),this.logDiagnostic("Response Headers:",r)}async*startConversationStreaming(e){var n,o;let r=(0,De.trace)(Ue.startConversation);try{let i;typeof e=="boolean"||e===void 0?(r.record({shouldEmitStartEvent:e!=null?e:!0}),i={emitStartConversationEvent:e!=null?e:!0}):(i=e,r.record({shouldEmitStartEvent:(n=i.emitStartConversationEvent)!=null?n:!0}));let s=gr(this.settings,i.conversationId),a={emitStartConversationEvent:(o=i.emitStartConversationEvent)!=null?o:!0};i.locale&&(a.locale=i.locale),V.info("Starting conversation ...",i),this.logDiagnostic("Start conversation request:",a),yield*this.postRequestAsync(s,a,"POST")}catch(i){throw r.fail(i)}finally{r.end()}}async*sendActivityStreaming(e,r=this.conversationId){var o,i;let n=(0,De.trace)(Ue.sendActivity);n.record({activity:e});try{let s=(i=(o=e.conversation)==null?void 0:o.id)!=null?i:r,a=gr(this.settings,s),c=new Ir(e);V.info("Sending activity...",e),yield*this.postRequestAsync(a,c,"POST")}catch(s){throw n.fail(s)}finally{n.end()}}async*executeStreaming(e,r){let n=(0,De.trace)(Ue.executeStreaming);n.record({activity:e,conversationId:r});try{if(!r||!r.trim())throw new Error("conversationId is required for executeStreaming");let o=gr(this.settings,r),i=new Ir(e,r);V.info("Executing turn with conversation ID:",r),this.logDiagnostic("Execute turn request:",{conversationId:r,activityType:e.type,activityText:e.text}),yield*this.postRequestAsync(o,i,"POST")}catch(o){throw n.fail(o)}finally{n.end()}}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=dt.Activity.fromObject(i),a=[];for await(let c of this.sendActivityStreaming(s,r))a.push(c);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,Mc(r,n)}async executeWithResponse(e,r){let n=[];for await(let o of this.executeStreaming(e,r))n.push(o);return Lc(n,r)}async*subscribeAsync(e,r){let n=(0,De.trace)(Ue.subscribeAsync);n.record({conversationId:e,lastReceivedEventId:r});try{if(!e||!e.trim())throw new Error("conversationId is required for subscribeAsync");let o=Aa(this.settings,e);V.info("Subscribing to conversation:",e),this.logDiagnostic("Subscribe request:",{conversationId:e,lastReceivedEventId:r,url:o});let i=ro({url:o,headers:{Authorization:`Bearer ${this.token}`,"User-Agent":Er.getProductInfo(),Accept:"text/event-stream",...r&&{"Last-Event-ID":r}},method:"GET",fetch:async(s,a)=>{let c=await fetch(s,a);return this.processResponseHeaders(c.headers),c}});try{for await(let{data:s,event:a,id:c}of i){if(s&&a==="activity")try{let l=dt.Activity.fromJson(s),p={activity:l,eventId:c};n.actions.eventReceivedFromCopilot(p),V.debug(`Received activity via subscription, event ID: ${c}`),this.logDiagnostic("Subscribe event received:",{eventId:c,activityType:l.type}),yield p}catch(l){V.error("Failed to parse activity in subscription:",l)}else if(a==="end"){V.debug("Subscription stream complete");break}if(i.readyState==="closed"){V.debug("Subscription connection closed");break}}}finally{i.close()}}catch(o){throw n.fail(o)}finally{n.end()}}};je.conversationIdHeaderKey="x-ms-conversationid",je.islandExperimentalUrlHeaderKey="x-ms-d2e-experimental",je.scopeFromSettings=$n.getScopeFromSettings;var Vc=je;function zc(){return globalThis.crypto.randomUUID()}var ru=Se(qn());var Ii=function(t,e){return Ii=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])},Ii(t,e)};function Me(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Ii(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function Ar(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 Bt(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 Wt(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 oe(t){return typeof t=="function"}function Bn(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 Wn=Bn(function(t){return function(r){t(this),this.message=r?r.length+` errors occurred during unsubscription:
|
|
5
|
+
`&&n++}}return[e,r]}var Vi="connecting",fu="open",to="closed",Pr=()=>{};function mu(t,{getStream:e}){let r=typeof t=="string"||t instanceof URL?{url:t}:t,{onMessage:n,onComment:o=Pr,onConnect:i=Pr,onDisconnect:s=Pr,onScheduleReconnect:a=Pr}=r,{fetch:c,url:l,initialLastEventId:p}=hu(r),g={...r.headers},T=[],E=n?[n]:[],M=D=>E.forEach(ce=>ce(D)),h=Li({onEvent:ou,onRetry:iu,onComment:o}),w,b=l.toString(),P=new AbortController,O=p,N=2e3,L,j=to;return _e(),{close:J,connect:_e,[Symbol.iterator]:()=>{throw new Error("EventSource does not support synchronous iteration. Use `for await` instead.")},[Symbol.asyncIterator]:Jt,get lastEventId(){return O},get url(){return b},get readyState(){return j}};function _e(){w||(j=Vi,P=new AbortController,w=c(l,su()).then(nu).catch(D=>{w=null,!(D.name==="AbortError"||D.type==="aborted"||P.signal.aborted)&&ki()}))}function J(){j=to,P.abort(),h.reset(),clearTimeout(L),T.forEach(D=>D())}function Jt(){let D=[],ce=[];function Qt(){return new Promise($=>{let ue=ce.shift();ue?$({value:ue,done:!1}):D.push($)})}let pt=function($){let ue=D.shift();ue?ue({value:$,done:!1}):ce.push($)};function Le(){for(E.splice(E.indexOf(pt),1);D.shift(););for(;ce.shift(););}function er(){let $=D.shift();$&&($({done:!0,value:void 0}),Le())}return T.push(er),E.push(pt),{next(){return j===to?this.return():Qt()},return(){return Le(),Promise.resolve({done:!0,value:void 0})},throw($){return Le(),Promise.reject($)},[Symbol.asyncIterator](){return this}}}function ki(){a({delay:N}),!P.signal.aborted&&(j=Vi,L=setTimeout(_e,N))}async function nu(D){i(),h.reset();let{body:ce,redirected:Qt,status:pt}=D;if(pt===204){s(),J();return}if(!ce)throw new Error("Missing response body");Qt&&(b=D.url);let Le=e(ce),er=new TextDecoder,$=Le.getReader(),ue=!0;j=fu;do{let{done:Zi,value:Ui}=await $.read();Ui&&h.feed(er.decode(Ui,{stream:!Zi})),Zi&&(ue=!1,w=null,h.reset(),ki(),s())}while(ue)}function ou(D){typeof D.id=="string"&&(O=D.id),M(D)}function iu(D){N=D}function su(){let{mode:D,credentials:ce,body:Qt,method:pt,redirect:Le,referrer:er,referrerPolicy:$}=r,ue={Accept:"text/event-stream",...g,...O?{"Last-Event-ID":O}:void 0};return{mode:D,credentials:ce,body:Qt,method:pt,redirect:Le,referrer:er,referrerPolicy:$,headers:ue,cache:"no-store",signal:P.signal}}}function hu(t){let e=t.fetch||globalThis.fetch;if(!gu(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 gu(t){return typeof t=="function"}var yu={getStream:vu};function ro(t){return mu(t,yu)}function vu(t){if(!(t instanceof ReadableStream))throw new Error("Invalid stream, expected a web ReadableStream");return t}var Ea=Se(xt());var ln=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 pn=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,Ea.debug)("copilot-studio:power-platform");function gr(t,e){var c,l,p,g,T,E,M,h;let r=((c=t.schemaName)==null?void 0:c.trim())||((l=t.agentIdentifier)==null?void 0:l.trim());if(!((p=t.directConnectUrl)!=null&&p.trim())&&(!((g=t.environmentId)!=null&&g.trim())||!(r!=null&&r.trim())))throw new Error("Either directConnectUrl OR both environmentId and schemaName/agentIdentifier must be provided");if((T=t.directConnectUrl)!=null&&T.trim()){if(It.debug(`Using direct connection: ${t.directConnectUrl}`),!hr(t.directConnectUrl))throw new Error("directConnectUrl must be a valid URL");return il(t.directConnectUrl,e).href}let n=(E=t.cloud)!=null?E:"Prod",o=(M=t.copilotAgentType)!=null?M:"Published";if(It.debug(`Using cloud setting: ${n}`),It.debug(`Using agent type: ${o}`),n==="Other")if((h=t.customPowerPlatformCloud)!=null&&h.trim())if(hr(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=sl(n,t.environmentId,t.customPowerPlatformCloud),a={Published:()=>new pn({host:i,schema:r}),Prebuilt:()=>new ln({host:i,schema:r})}[o]().getConversationUrl(e);return It.debug(`Generated Copilot Studio connection URL: ${a}`),a}function Aa(t,e){if(!e||!e.trim())throw new Error("conversationId is required for subscribe URL");let r=gr(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 Sa(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&&hr(r))e="Other";else if(t!=null&&t.customPowerPlatformCloud&&hr(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://${fn(e,r)}/.default`}else if(n||(n=(o=t==null?void 0:t.directConnectUrl)!=null?o:""),n&&hr(n)){if(Ia(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://${fn(s,"")}/.default`;throw new Error("Unable to resolve the PowerPlatform Cloud from DirectConnectUrl. The Token Audience resolver requires a specific PowerPlatformCloudCategory.")}return`https://${fn(Ia(new URL(n)),"")}/.default`}else throw new Error("DirectConnectUrl must be provided when DirectConnectUrl is set")}function hr(t){try{let e=t.startsWith("http")?t:`https://${t}`;return!!new URL(e)}catch{return!1}}function il(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 sl(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=al(t),i=n.substring(0,n.length-o),s=n.substring(n.length-o);return new URL(`https://${i}.${s}.environment.${fn(t,r)}`)}function fn(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 al(t){switch(t){case"FirstRelease":case"Prod":return 2;default:return 1}}function Ia(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 dt=Se(qn());var Ir=class{constructor(e,r){this.activity=e,this.conversationId=r}};var De=Se(xt());var Fn="1.6.0-beta.24.g285b02c21b";var Gn={};var Er=class{static getProductInfo(){let e=`CopilotStudioClient.agents-sdk-js/${Fn}`,r;return typeof window!="undefined"&&window.navigator?r=`${e} ${navigator.userAgent}`:r=`${e} nodejs/${process.version} ${Gn.platform()}-${Gn.arch()}/${Gn.release()}`,r}static getVersionString(){return`CopilotStudioClient.agents-sdk-js/${Fn}`}static getVersion(){return Fn}};var $n=class{static getScopeFromSettings(e){return Sa(e)}};function Mc(t,e){return{activities:t,conversationId:e,isNewConversation:!0}}function Lc(t,e){return{activities:t,conversationId:e,activityCount:t.length}}var U=Se(xt()),G={activitiesReceivedCounter:U.metric.counter(U.MetricNames.CSC_ACTIVITIES_RECEIVED,{unit:"activities",description:"Total number of activities received by the Copilot Studio client"}),activitiesSentCounter:U.metric.counter(U.MetricNames.CSC_ACTIVITIES_SENT,{unit:"activities",description:"Total number of activities sent to Copilot Studio"}),conversationsStartedCounter:U.metric.counter(U.MetricNames.CSC_CONVERSATIONS_STARTED,{unit:"conversations",description:"Total number of conversations started with Copilot Studio"}),webchatConnectionsCounter:U.metric.counter(U.MetricNames.CSC_WEBCHAT_CONNECTIONS,{unit:"connections",description:"Total number of webchat connections created with Copilot Studio"}),requestsCounter:U.metric.counter(U.MetricNames.CSC_REQUEST_COUNT,{unit:"requests",description:"Total number of HTTP/SSE requests made to Copilot Studio"}),requestsErrorCounter:U.metric.counter(U.MetricNames.CSC_REQUEST_ERRORS,{unit:"requests",description:"Total number of failed requests to Copilot Studio"}),executeStreamingCounter:U.metric.counter(U.MetricNames.CSC_EXECUTE_STREAMING,{unit:"operations",description:"Total number of execute streaming operations"}),subscribeAsyncCounter:U.metric.counter(U.MetricNames.CSC_SUBSCRIBE_ASYNC,{unit:"operations",description:"Total number of subscribeAsync operations"}),subscribeEventCounter:U.metric.counter(U.MetricNames.CSC_SUBSCRIBE_EVENT,{unit:"events",description:"Total number of events received via subscribeAsync"}),streamDuration:U.metric.histogram(U.MetricNames.CSC_STREAM_DURATION,{unit:"ms",description:"Duration of SSE stream sessions in milliseconds"}),requestDuration:U.metric.histogram(U.MetricNames.CSC_REQUEST_DURATION,{unit:"ms",description:"Duration of requests to Copilot Studio in milliseconds"})};var xi=Se(qn()),K=Se(xt());var Ue={createConnection:K.trace.define({name:K.SpanNames.COPILOT_CREATE_CONNECTION,record:{showTyping:!1},actions:({span:t})=>({receivedFromCopilot(e){var r,n,o;t.addEvent("activity.received.from.copilot.studio",{"copilot.webchat.activity.type":(r=e.type)!=null?r:"unknown","copilot.webchat.activity.conversation_id":(o=(n=e.conversation)==null?void 0:n.id)!=null?o:"unknown"})},sentToWebChat(e){var r,n,o;t.addEvent("activity.sent.to.webchat",{"copilot.webchat.activity.type":(r=e.type)!=null?r:"unknown","copilot.webchat.activity.conversation_id":(o=(n=e.conversation)==null?void 0:n.id)!=null?o:"unknown"})}}),end({span:t,record:e}){var n;let r={"copilot.webchat.show_typing":(n=e.showTyping)!=null?n:"unknown"};t.setAttributes(r),G.webchatConnectionsCounter.add(1,r)}}),postRequest:K.trace.define({name:K.SpanNames.COPILOT_POST_REQUEST,record:{url:"",method:""},actions:({span:t})=>({receivedFromCopilot(e){var n,o,i;let r={"copilot.activity.type":(n=e.type)!=null?n:"unknown","copilot.activity.conversation_id":(i=(o=e.conversation)==null?void 0:o.id)!=null?i:"unknown"};t.addEvent("activity.received",{"copilot.post_request.activity.type":r["copilot.activity.type"],"copilot.post_request.activity.conversation_id":r["copilot.activity.conversation_id"]}),G.activitiesReceivedCounter.add(1,r)}}),end({span:t,record:e,duration:r,error:n}){var s,a;let o={"copilot.post_request.url":(s=e.url)!=null?s:"unknown","copilot.post_request.method":(a=e.method)!=null?a:"unknown"},i={operation:"postRequestAsync","copilot.post_request.url":o["copilot.post_request.url"],"copilot.post_request.method":o["copilot.post_request.method"]};t.setAttributes(o),G.requestsCounter.add(1,i),G.streamDuration.record(r,i),n&&G.requestsErrorCounter.add(1,{...i,"error.type":n instanceof Error?n.name:typeof n})}}),startConversation:K.trace.define({name:K.SpanNames.COPILOT_START_CONVERSATION,record:{shouldEmitStartEvent:!1},end({span:t,record:e,duration:r}){let n=e.shouldEmitStartEvent?{"copilot.emit_start_event":!0}:{"copilot.request":!0},o={operation:"startConversationStreaming",...n};t.setAttributes(n),G.conversationsStartedCounter.add(1,o),G.requestDuration.record(r,o)}}),sendActivity:K.trace.define({name:K.SpanNames.COPILOT_SEND_ACTIVITY,record:{activity:xi.Activity.fromObject({type:"unknown"})},end({span:t,record:e,duration:r}){var i,s,a;let n={"copilot.activity.type":(i=e.activity.type)!=null?i:"unknown","copilot.activity.conversation_id":(a=(s=e.activity.conversation)==null?void 0:s.id)!=null?a:"unknown"},o={operation:"sendActivityStreaming",...n};t.setAttributes(n),G.activitiesSentCounter.add(1,n),G.requestDuration.record(r,o)}}),executeStreaming:K.trace.define({name:K.SpanNames.COPILOT_EXECUTE_STREAMING,record:{activity:xi.Activity.fromObject({type:"unknown"}),conversationId:"unknown"},end({span:t,record:e,duration:r}){var i,s;let n={"copilot.activity.type":(i=e.activity.type)!=null?i:"unknown","copilot.activity.conversation_id":(s=e.conversationId)!=null?s:"unknown"},o={operation:"executeStreaming",...n};t.setAttributes(n),G.executeStreamingCounter.add(1,n),G.requestDuration.record(r,o)}}),subscribeAsync:K.trace.define({name:K.SpanNames.COPILOT_SUBSCRIBE_ASYNC,record:{conversationId:"unknown",lastReceivedEventId:"unknown"},actions:({span:t})=>({eventReceivedFromCopilot(e){var n,o;let r={"copilot.subscribe_async.event.id":(n=e.eventId)!=null?n:"unknown","copilot.subscribe_async.event.activity.type":(o=e.activity.type)!=null?o:"unknown"};t.addEvent("event.received",r),G.subscribeEventCounter.add(1,r)}}),end({span:t,record:e,duration:r}){var i,s;let n={"copilot.subscribe_async.conversation_id":(i=e.conversationId)!=null?i:"unknown","copilot.subscribe_async.last_received_event_id":(s=e.lastReceivedEventId)!=null?s:"unknown"},o={operation:"subscribeAsync","copilot.conversation_id":n["copilot.subscribe_async.conversation_id"],"copilot.last_received_event_id":n["copilot.subscribe_async.last_received_event_id"]};t.setAttributes(n),G.subscribeAsyncCounter.add(1,o),G.streamDuration.record(r,o)}})};var V=(0,De.debug)("copilot-studio:client"),je=class je{constructor(e,r){this.conversationId="";this.settings=e,this.token=r}logDiagnostic(e,...r){this.settings.enableDiagnostics&&V.info(`[DIAGNOSTICS] ${e}`,...r)}async*postRequestAsync(e,r,n="POST"){var i,s,a,c,l,p,g,T,E,M;let o=(0,De.trace)(Ue.postRequest);o.record({url:e,method:n});try{this.logDiagnostic(`Request URL: ${e}`),this.logDiagnostic(`Request Method: ${n}`),this.logDiagnostic("Request Body:",r?JSON.stringify(r,null,2):"none"),V.debug(`>>> SEND TO ${e}`);let h=new Map,w=ro({url:e,headers:{Authorization:`Bearer ${this.token}`,"User-Agent":Er.getProductInfo(),"Content-Type":"application/json",Accept:"text/event-stream"},body:r?JSON.stringify(r):void 0,method:n,fetch:async(b,P)=>{let O=await fetch(b,P);return this.processResponseHeaders(O.headers),O}});try{for await(let{data:b,event:P}of w){if(b&&P==="activity")try{let O=dt.Activity.fromJson(b);o.actions.receivedFromCopilot(O);let N=(i=O.entities)==null?void 0:i.find(L=>L.type==="streaminfo"&&L.streamType==="streaming");switch(O.type){case dt.ActivityTypes.Message:this.conversationId.trim()||(this.conversationId=(a=(s=O.conversation)==null?void 0:s.id)!=null?a:"",V.debug(`Conversation ID: ${this.conversationId}`)),yield O;break;case dt.ActivityTypes.Typing:if(V.debug(`Activity type: ${O.type}`),N||((c=O.channelData)==null?void 0:c.streamType)==="streaming"){let L=(l=O.text)!=null?l:"",j=(g=N==null?void 0:N.streamId)!=null?g:(p=O.channelData)==null?void 0:p.streamId,_e=(E=N==null?void 0:N.streamSequence)!=null?E:(T=O.channelData)==null?void 0:T.streamSequence;if(j&&_e){if(h.has(j)){let J=h.get(j);J.push({text:L,sequence:_e}),h.set(j,J)}else h.set(j,[{text:L,sequence:_e}]);O.text=((M=h.get(j))==null?void 0:M.sort((J,Jt)=>J.sequence-Jt.sequence).map(J=>J.text).join(""))||""}}yield O;break;default:V.debug(`Activity type: ${O.type}`),yield O;break}}catch(O){V.error("Failed to parse activity:",O)}else if(P==="end"){V.debug("Stream complete");break}if(w.readyState==="closed"){V.debug("Connection closed");break}}}finally{w.close()}}catch(h){throw o.fail(h)}finally{o.end()}}processResponseHeaders(e){var n,o;if(this.settings.useExperimentalEndpoint&&!((n=this.settings.directConnectUrl)!=null&&n.trim())){let i=e==null?void 0:e.get(je.islandExperimentalUrlHeaderKey);i&&(this.settings.directConnectUrl=i,V.debug(`Island Experimental URL: ${i}`))}this.conversationId=(o=e==null?void 0:e.get(je.conversationIdHeaderKey))!=null?o:"",this.conversationId&&V.debug(`Conversation ID: ${this.conversationId}`);let r=new Headers;e.forEach((i,s)=>{s.toLowerCase()!=="authorization"&&s.toLowerCase()!==je.conversationIdHeaderKey.toLowerCase()&&r.set(s,i)}),this.logDiagnostic("Response Headers:",r)}async*startConversationStreaming(e){var n,o;let r=(0,De.trace)(Ue.startConversation);try{let i;typeof e=="boolean"||e===void 0?(r.record({shouldEmitStartEvent:e!=null?e:!0}),i={emitStartConversationEvent:e!=null?e:!0}):(i=e,r.record({shouldEmitStartEvent:(n=i.emitStartConversationEvent)!=null?n:!0}));let s=gr(this.settings,i.conversationId),a={emitStartConversationEvent:(o=i.emitStartConversationEvent)!=null?o:!0};i.locale&&(a.locale=i.locale),V.info("Starting conversation ...",i),this.logDiagnostic("Start conversation request:",a),yield*this.postRequestAsync(s,a,"POST")}catch(i){throw r.fail(i)}finally{r.end()}}async*sendActivityStreaming(e,r=this.conversationId){var o,i;let n=(0,De.trace)(Ue.sendActivity);n.record({activity:e});try{let s=(i=(o=e.conversation)==null?void 0:o.id)!=null?i:r,a=gr(this.settings,s),c=new Ir(e);V.info("Sending activity...",e),yield*this.postRequestAsync(a,c,"POST")}catch(s){throw n.fail(s)}finally{n.end()}}async*executeStreaming(e,r){let n=(0,De.trace)(Ue.executeStreaming);n.record({activity:e,conversationId:r});try{if(!r||!r.trim())throw new Error("conversationId is required for executeStreaming");let o=gr(this.settings,r),i=new Ir(e,r);V.info("Executing turn with conversation ID:",r),this.logDiagnostic("Execute turn request:",{conversationId:r,activityType:e.type,activityText:e.text}),yield*this.postRequestAsync(o,i,"POST")}catch(o){throw n.fail(o)}finally{n.end()}}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=dt.Activity.fromObject(i),a=[];for await(let c of this.sendActivityStreaming(s,r))a.push(c);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,Mc(r,n)}async executeWithResponse(e,r){let n=[];for await(let o of this.executeStreaming(e,r))n.push(o);return Lc(n,r)}async*subscribeAsync(e,r){let n=(0,De.trace)(Ue.subscribeAsync);n.record({conversationId:e,lastReceivedEventId:r});try{if(!e||!e.trim())throw new Error("conversationId is required for subscribeAsync");let o=Aa(this.settings,e);V.info("Subscribing to conversation:",e),this.logDiagnostic("Subscribe request:",{conversationId:e,lastReceivedEventId:r,url:o});let i=ro({url:o,headers:{Authorization:`Bearer ${this.token}`,"User-Agent":Er.getProductInfo(),Accept:"text/event-stream",...r&&{"Last-Event-ID":r}},method:"GET",fetch:async(s,a)=>{let c=await fetch(s,a);return this.processResponseHeaders(c.headers),c}});try{for await(let{data:s,event:a,id:c}of i){if(s&&a==="activity")try{let l=dt.Activity.fromJson(s),p={activity:l,eventId:c};n.actions.eventReceivedFromCopilot(p),V.debug(`Received activity via subscription, event ID: ${c}`),this.logDiagnostic("Subscribe event received:",{eventId:c,activityType:l.type}),yield p}catch(l){V.error("Failed to parse activity in subscription:",l)}else if(a==="end"){V.debug("Subscription stream complete");break}if(i.readyState==="closed"){V.debug("Subscription connection closed");break}}}finally{i.close()}}catch(o){throw n.fail(o)}finally{n.end()}}};je.conversationIdHeaderKey="x-ms-conversationid",je.islandExperimentalUrlHeaderKey="x-ms-d2e-experimental",je.scopeFromSettings=$n.getScopeFromSettings;var Vc=je;function zc(){return globalThis.crypto.randomUUID()}var ru=Se(qn());var Ii=function(t,e){return Ii=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])},Ii(t,e)};function Me(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Ii(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function Ar(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 Bt(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 Wt(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 oe(t){return typeof t=="function"}function Bn(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 Wn=Bn(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 Sr(t,e){if(t){var r=t.indexOf(e);0<=r&&t.splice(r,1)}}var Ht=(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=Ar(s),c=a.next();!c.done;c=a.next()){var l=c.value;l.remove(this)}}catch(h){e={error:h}}finally{try{c&&!c.done&&(r=a.return)&&r.call(a)}finally{if(e)throw e.error}}else s.remove(this);var p=this.initialTeardown;if(oe(p))try{p()}catch(h){i=h instanceof Wn?h.errors:[h]}var g=this._finalizers;if(g){this._finalizers=null;try{for(var T=Ar(g),E=T.next();!E.done;E=T.next()){var M=E.value;try{qc(M)}catch(h){i=i!=null?i:[],h instanceof Wn?i=Wt(Wt([],Bt(i)),Bt(h.errors)):i.push(h)}}}catch(h){n={error:h}}finally{try{E&&!E.done&&(o=T.return)&&o.call(T)}finally{if(n)throw n.error}}}if(i)throw new Wn(i)}},t.prototype.add=function(e){var r;if(e&&e!==this)if(this.closed)qc(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)&&Sr(r,e)},t.prototype.remove=function(e){var r=this._finalizers;r&&Sr(r,e),e instanceof t&&e._removeParent(this)},t.EMPTY=(function(){var e=new t;return e.closed=!0,e})(),t})();var Ei=Ht.EMPTY;function Hn(t){return t instanceof Ht||t&&"closed"in t&&oe(t.remove)&&oe(t.add)&&oe(t.unsubscribe)}function qc(t){oe(t)?t():t.unsubscribe()}var ae={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var Kt={setTimeout:function(t,e){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];var o=Kt.delegate;return o!=null&&o.setTimeout?o.setTimeout.apply(o,Wt([t,e],Bt(r))):setTimeout.apply(void 0,Wt([t,e],Bt(r)))},clearTimeout:function(t){var e=Kt.delegate;return((e==null?void 0:e.clearTimeout)||clearTimeout)(t)},delegate:void 0};function Fc(t){Kt.setTimeout(function(){var e=ae.onUnhandledError;if(e)e(t);else throw t})}function Ai(){}var Gc=(function(){return Si("C",void 0,void 0)})();function $c(t){return Si("E",void 0,t)}function Bc(t){return Si("N",t,void 0)}function Si(t,e,r){return{kind:t,value:e,error:r}}var lt=null;function Yt(t){if(ae.useDeprecatedSynchronousErrorHandling){var e=!lt;if(e&&(lt={errorThrown:!1,error:null}),t(),e){var r=lt,n=r.errorThrown,o=r.error;if(lt=null,n)throw o}}else t()}function Wc(t){ae.useDeprecatedSynchronousErrorHandling&<&&(lt.errorThrown=!0,lt.error=t)}var Pi=(function(t){Me(e,t);function e(r){var n=t.call(this)||this;return n.isStopped=!1,r?(n.destination=r,Hn(r)&&r.add(n)):n.destination=Df,n}return e.create=function(r,n,o){return new Yn(r,n,o)},e.prototype.next=function(r){this.isStopped?Oi(Bc(r),this):this._next(r)},e.prototype.error=function(r){this.isStopped?Oi($c(r),this):(this.isStopped=!0,this._error(r))},e.prototype.complete=function(){this.isStopped?Oi(Gc,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})(Ht);var Zf=Function.prototype.bind;function wi(t,e){return Zf.call(t,e)}var Uf=(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){Kn(n)}},t.prototype.error=function(e){var r=this.partialObserver;if(r.error)try{r.error(e)}catch(n){Kn(n)}else Kn(e)},t.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(r){Kn(r)}},t})(),Yn=(function(t){Me(e,t);function e(r,n,o){var i=t.call(this)||this,s;if(oe(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&&ae.useDeprecatedNextContext?(a=Object.create(r),a.unsubscribe=function(){return i.unsubscribe()},s={next:r.next&&wi(r.next,a),error:r.error&&wi(r.error,a),complete:r.complete&&wi(r.complete,a)}):s=r}return i.destination=new Uf(s),i}return e})(Pi);function Kn(t){ae.useDeprecatedSynchronousErrorHandling?Wc(t):Fc(t)}function jf(t){throw t}function Oi(t,e){var r=ae.onStoppedNotification;r&&Kt.setTimeout(function(){return r(t,e)})}var Df={closed:!0,next:Ai,error:jf,complete:Ai};var Hc=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function Kc(t){return t}function Yc(t){return t.length===0?Kc:t.length===1?t[0]:function(r){return t.reduce(function(n,o){return o(n)},r)}}var Xt=(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=Lf(e)?e:new Yn(e,r,n);return Yt(function(){var s=o,a=s.operator,c=s.source;i.add(a?a.call(i,c):c?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=Xc(r),new r(function(o,i){var s=new Yn({next:function(a){try{e(a)}catch(c){i(c),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[Hc]=function(){return this},t.prototype.pipe=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return Yc(e)(this)},t.prototype.toPromise=function(e){var r=this;return e=Xc(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 Xc(t){var e;return(e=t!=null?t:ae.Promise)!==null&&e!==void 0?e:Promise}function Mf(t){return t&&oe(t.next)&&oe(t.error)&&oe(t.complete)}function Lf(t){return t&&t instanceof Pi||Mf(t)&&Hn(t)}var Jc=Bn(function(t){return function(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}});var Ri=(function(t){Me(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 Qc(this,this);return n.operator=r,n},e.prototype._throwIfClosed=function(){if(this.closed)throw new Jc},e.prototype.next=function(r){var n=this;Yt(function(){var o,i;if(n._throwIfClosed(),!n.isStopped){n.currentObservers||(n.currentObservers=Array.from(n.observers));try{for(var s=Ar(n.currentObservers),a=s.next();!a.done;a=s.next()){var c=a.value;c.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;Yt(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;Yt(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?Ei:(this.currentObservers=null,a.push(r),new Ht(function(){n.currentObservers=null,Sr(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 Xt;return r.source=this,r},e.create=function(r,n){return new Qc(r,n)},e})(Xt);var Qc=(function(t){Me(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:Ei},e})(Ri);var Ni=(function(t){Me(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})(Ri);var Xn=Se(xt());var Ae=(0,Xn.debug)("copilot-studio:webchat");function Vf(t){let e=!1;return r=>{if(!e)return e=!0,t(r)}}var eu=class{static createConnection(e,r){var o;let n=(0,Xn.trace)(Ue.createConnection);n.record({showTyping:r==null?void 0:r.showTyping});try{Ae.info("--> Creating connection between Copilot Studio and WebChat ...");let i=r!=null&&r.conversationId&&r.conversationId.trim()!==""?r.conversationId.trim():void 0,s=(o=r==null?void 0:r.startConversation)!=null?o:!i,a=0,c,l,p=i,g=!1,T=!1,E=new Ni(0),M=tu(async b=>{var P;try{c=b;let O=Vf(async()=>{E.next(2),await Promise.resolve()});if(!s||T){await O();return}T=!0,Ae.debug("--> Connection established."),w();for await(let N of e.startConversationStreaming())delete N.replyToId,!l&&N.conversation&&(l=N.conversation),(P=N.conversation)!=null&&P.id&&(p=N.conversation.id),await O(),h(N),n.actions.receivedFromCopilot(N);await O()}catch(O){throw n.fail(O)}finally{n.end()}}),h=b=>{let P={...b,timestamp:new Date().toISOString(),channelData:{...b.channelData,"webchat:sequence-id":a}};a++,Ae.debug(`Notify '${P.type}' activity to WebChat:`,P),c==null||c.next(P)},w=()=>{if(!(r!=null&&r.showTyping))return;let b=l?{id:l.id,name:l.name}:{id:"agent",name:"Agent"};h({type:"typing",from:b})};return{connectionStatus$:E,activity$:M,get conversationId(){return p},postActivity(b){try{if(Ae.info("--> Preparing to send activity to Copilot Studio ..."),!b)throw new Error("Activity cannot be null.");if(g)throw new Error("Connection has been ended.");if(!c)throw new Error("Activity subscriber is not initialized.");return tu(async O=>{var N;try{Ae.info("--> Sending activity to Copilot Studio ...");let L=ru.Activity.fromObject({...b,id:zc(),attachments:await zf(b)});h(L),n.actions.sentToWebChat(L),w(),O.next(L.id);for await(let j of e.sendActivityStreaming(L,p))!p&&((N=j.conversation)!=null&&N.id)&&(p=j.conversation.id),h(j),n.actions.receivedFromCopilot(j),Ae.info("<-- Activity received correctly from Copilot Studio.");O.complete()}catch(L){Ae.error("Error sending Activity to Copilot Studio:",L),O.error(L),n.fail(L)}finally{n.end()}})}catch(P){throw n.fail(P)}finally{n.end()}},end(){Ae.info("--> Ending connection between Copilot Studio and WebChat ..."),g=!0,E.complete(),c&&(c.complete(),c=void 0),n.end()}}}catch(i){throw n.fail(i)}finally{n.end()}}};async function zf(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 qf(n);e.push(o)}return e}async function qf(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=Ff(o);e=`data:${n.type};base64,${i}`}catch(r){e=t.contentUrl,Ae.error("Error processing blob attachment:",e,r)}return{...t,contentUrl:e}}function Ff(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 tu(t){return new Xt(e=>{Promise.resolve(t(e)).catch(r=>e.error(r))})}function __(t=!0,e,r){return{emitStartConversationEvent:t,locale:e,conversationId:r}}export{tr as AgentType,Qn as ConnectionSettings,Vc as CopilotStudioClient,eu as CopilotStudioWebChat,Ir as ExecuteTurnRequest,rr as PowerPlatformCloud,$n as ScopeHelper,Er as UserAgentHelper,Lc as createExecuteTurnResponse,__ as createStartRequest,Mc as createStartResponse,gr as getCopilotStudioConnectionUrl,Aa as getCopilotStudioSubscribeUrl,Sa as getTokenAudience,Kf as loadCopilotStudioConnectionSettingsFromEnv};
|
|
8
8
|
//# sourceMappingURL=browser.mjs.map
|