@microsoft/agents-copilotstudio-client 1.6.0-beta.41.g36be9b7b46 → 1.6.0-beta.43.g9cc9760779
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.43.g9cc9760779",
|
|
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.43.g9cc9760779",
|
|
31
|
+
"@microsoft/agents-telemetry": "1.6.0-beta.43.g9cc9760779",
|
|
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 fu=Object.create;var Nr=Object.defineProperty;var mu=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 fn(`Invalid \`retry\` value: "${w}"`,{type:"invalid-retry",value:w,line:b}));break;default:r(new fn(`Unknown field "${h.length>20?`${h.slice(0,20)}\u2026`:h}"`,{type:"unknown-field",field:h,value:w,line:b}));break}}function I(){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&&y(i),s=!0,a=void 0,c="",l="",i=""}return{feed:p,reset:M}}function cl(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 Oa="connecting",ul="open",Xo="closed",mn=()=>{};function dl(t,{getStream:e}){let r=typeof t=="string"||t instanceof URL?{url:t}:t,{onMessage:n,onComment:o=mn,onConnect:i=mn,onDisconnect:s=mn,onScheduleReconnect:a=mn}=r,{fetch:c,url:l,initialLastEventId:p}=ll(r),y={...r.headers},T=[],I=n?[n]:[],M=j=>I.forEach(ce=>ce(j)),h=wa({onEvent:du,onRetry:lu,onComment:o}),w,b=l.toString(),P=new AbortController,O=p,N=2e3,L,Z=Xo;return be(),{close:Q,connect:be,[Symbol.iterator]:()=>{throw new Error("EventSource does not support synchronous iteration. Use `for await` instead.")},[Symbol.asyncIterator]:Qt,get lastEventId(){return O},get url(){return b},get readyState(){return Z}};function be(){w||(Z=Oa,P=new AbortController,w=c(l,pu()).then(uu).catch(j=>{w=null,!(j.name==="AbortError"||j.type==="aborted"||P.signal.aborted)&&Mi()}))}function Q(){Z=Xo,P.abort(),h.reset(),clearTimeout(L),T.forEach(j=>j())}function Qt(){let j=[],ce=[];function er(){return new Promise(B=>{let ue=ce.shift();ue?B({value:ue,done:!1}):j.push(B)})}let ft=function(B){let ue=j.shift();ue?ue({value:B,done:!1}):ce.push(B)};function Le(){for(I.splice(I.indexOf(ft),1);j.shift(););for(;ce.shift(););}function tr(){let B=j.shift();B&&(B({done:!0,value:void 0}),Le())}return T.push(tr),I.push(ft),{next(){return Z===Xo?this.return():er()},return(){return Le(),Promise.resolve({done:!0,value:void 0})},throw(B){return Le(),Promise.reject(B)},[Symbol.asyncIterator](){return this}}}function Mi(){a({delay:N}),!P.signal.aborted&&(Z=Oa,L=setTimeout(be,N))}async function uu(j){i(),h.reset();let{body:ce,redirected:er,status:ft}=j;if(ft===204){s(),Q();return}if(!ce)throw new Error("Missing response body");er&&(b=j.url);let Le=e(ce),tr=new TextDecoder,B=Le.getReader(),ue=!0;Z=ul;do{let{done:Li,value:Vi}=await B.read();Vi&&h.feed(tr.decode(Vi,{stream:!Li})),Li&&(ue=!1,w=null,h.reset(),Mi(),s())}while(ue)}function du(j){typeof j.id=="string"&&(O=j.id),M(j)}function lu(j){N=j}function pu(){let{mode:j,credentials:ce,body:er,method:ft,redirect:Le,referrer:tr,referrerPolicy:B}=r,ue={Accept:"text/event-stream",...y,...O?{"Last-Event-ID":O}:void 0};return{mode:j,credentials:ce,body:er,method:ft,redirect:Le,referrer:tr,referrerPolicy:B,headers:ue,cache:"no-store",signal:P.signal}}}function ll(t){let e=t.fetch||globalThis.fetch;if(!pl(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 pl(t){return typeof t=="function"}var fl={getStream:ml};function Jo(t){return dl(t,fl)}function ml(t){if(!(t instanceof ReadableStream))throw new Error("Invalid stream, expected a web ReadableStream");return t}var Ra=Te($e());var hn=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 gn=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 Et=(0,Ra.debug)("copilot-studio:power-platform");function br(t,e){var c,l,p,y,T,I,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())&&(!((y=t.environmentId)!=null&&y.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(Et.debug(`Using direct connection: ${t.directConnectUrl}`),!_r(t.directConnectUrl))throw new Error("directConnectUrl must be a valid URL");return hl(t.directConnectUrl,e).href}let n=(I=t.cloud)!=null?I:"Prod",o=(M=t.copilotAgentType)!=null?M:"Published";if(Et.debug(`Using cloud setting: ${n}`),Et.debug(`Using agent type: ${o}`),n==="Other")if((h=t.customPowerPlatformCloud)!=null&&h.trim())if(_r(t.customPowerPlatformCloud))Et.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=gl(n,t.environmentId,t.customPowerPlatformCloud),a={Published:()=>new gn({host:i,schema:r}),Prebuilt:()=>new hn({host:i,schema:r})}[o]().getConversationUrl(e);return Et.debug(`Generated Copilot Studio connection URL: ${a}`),a}function Na(t,e){if(!e||!e.trim())throw new Error("conversationId is required for subscribe URL");let r=br(t,e),n=new URL(r);n.pathname=n.pathname.endsWith("/")?`${n.pathname}subscribe`:`${n.pathname}/subscribe`;let o=n.href;return Et.debug(`Generated Copilot Studio subscribe URL: ${o}`),o}function ka(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&&_r(r))e="Other";else if(t!=null&&t.customPowerPlatformCloud&&_r(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://${yn(e,r)}/.default`}else if(n||(n=(o=t==null?void 0:t.directConnectUrl)!=null?o:""),n&&_r(n)){if(Pa(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://${yn(s,"")}/.default`;throw new Error("Unable to resolve the PowerPlatform Cloud from DirectConnectUrl. The Token Audience resolver requires a specific PowerPlatformCloudCategory.")}return`https://${yn(Pa(new URL(n)),"")}/.default`}else throw new Error("DirectConnectUrl must be provided when DirectConnectUrl is set")}function _r(t){try{let e=t.startsWith("http")?t:`https://${t}`;return!!new URL(e)}catch{return!1}}function hl(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 gl(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=yl(t),i=n.substring(0,n.length-o),s=n.substring(n.length-o);return new URL(`https://${i}.${s}.environment.${yn(t,r)}`)}function yn(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 yl(t){switch(t){case"FirstRelease":case"Prod":return 2;default:return 1}}function Pa(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 lt=Te(Bn());var wr=class{constructor(e,r){this.activity=e,this.conversationId=r}};var je=Te($e());var Hn="1.6.0-beta.41.g36be9b7b46";var Wn={};var Or=class{static getProductInfo(){var n;let e=`CopilotStudioClient.agents-sdk-js/${Hn}`,r=globalThis;return typeof r.document!="undefined"&&typeof((n=r.navigator)==null?void 0:n.userAgent)=="string"?`${e} ${r.navigator.userAgent}`:`${e} nodejs/${process.version} ${Wn.platform()}-${Wn.arch()}/${Wn.release()}`}static getVersionString(){return`CopilotStudioClient.agents-sdk-js/${Hn}`}static getVersion(){return Hn}};var Kn=class{static getScopeFromSettings(e){return ka(e)}};function Gc(t,e){return{activities:t,conversationId:e,isNewConversation:!0}}function $c(t,e){return{activities:t,conversationId:e,activityCount:t.length}}var U=Te($e()),$={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 wi=Te(Bn()),Y=Te($e());var Ue={createConnection:Y.trace.define({name:Y.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),$.webchatConnectionsCounter.add(1,r)}}),postRequest:Y.trace.define({name:Y.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"]}),$.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),$.requestsCounter.add(1,i),$.streamDuration.record(r,i),n&&$.requestsErrorCounter.add(1,{...i,"error.type":n instanceof Error?n.name:typeof n})}}),startConversation:Y.trace.define({name:Y.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),$.conversationsStartedCounter.add(1,o),$.requestDuration.record(r,o)}}),sendActivity:Y.trace.define({name:Y.SpanNames.COPILOT_SEND_ACTIVITY,record:{activity:wi.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),$.activitiesSentCounter.add(1,n),$.requestDuration.record(r,o)}}),executeStreaming:Y.trace.define({name:Y.SpanNames.COPILOT_EXECUTE_STREAMING,record:{activity:wi.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),$.executeStreamingCounter.add(1,n),$.requestDuration.record(r,o)}}),subscribeAsync:Y.trace.define({name:Y.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),$.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),$.subscribeAsyncCounter.add(1,o),$.streamDuration.record(r,o)}})};var z=(0,je.debug)("copilot-studio:client"),Ze=class Ze{constructor(e,r){this.conversationId="";this.settings=e,this.token=r}logDiagnostic(e,...r){this.settings.enableDiagnostics&&z.info(`[DIAGNOSTICS] ${e}`,...r)}async*postRequestAsync(e,r,n="POST"){var i,s,a,c,l,p,y,T,I,M;let o=(0,je.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"),z.debug(`>>> SEND TO ${e}`);let h=new Map,w=Jo({url:e,headers:{Authorization:`Bearer ${this.token}`,"User-Agent":Or.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=lt.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 lt.ActivityTypes.Message:this.conversationId.trim()||(this.conversationId=(a=(s=O.conversation)==null?void 0:s.id)!=null?a:"",z.debug(`Conversation ID: ${this.conversationId}`)),yield O;break;case lt.ActivityTypes.Typing:if(z.debug(`Activity type: ${O.type}`),N||((c=O.channelData)==null?void 0:c.streamType)==="streaming"){let L=(l=O.text)!=null?l:"",Z=(y=N==null?void 0:N.streamId)!=null?y:(p=O.channelData)==null?void 0:p.streamId,be=(I=N==null?void 0:N.streamSequence)!=null?I:(T=O.channelData)==null?void 0:T.streamSequence;if(Z&&be){if(h.has(Z)){let Q=h.get(Z);Q.push({text:L,sequence:be}),h.set(Z,Q)}else h.set(Z,[{text:L,sequence:be}]);O.text=((M=h.get(Z))==null?void 0:M.sort((Q,Qt)=>Q.sequence-Qt.sequence).map(Q=>Q.text).join(""))||""}}yield O;break;default:z.debug(`Activity type: ${O.type}`),yield O;break}}catch(O){z.error("Failed to parse activity:",O)}else if(P==="end"){z.debug("Stream complete");break}if(w.readyState==="closed"){z.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(Ze.islandExperimentalUrlHeaderKey);i&&(this.settings.directConnectUrl=i,z.debug(`Island Experimental URL: ${i}`))}this.conversationId=(o=e==null?void 0:e.get(Ze.conversationIdHeaderKey))!=null?o:"",this.conversationId&&z.debug(`Conversation ID: ${this.conversationId}`);let r=new Headers;e.forEach((i,s)=>{s.toLowerCase()!=="authorization"&&s.toLowerCase()!==Ze.conversationIdHeaderKey.toLowerCase()&&r.set(s,i)}),this.logDiagnostic("Response Headers:",r)}async*startConversationStreaming(e){var n,o;let r=(0,je.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=br(this.settings,i.conversationId),a={emitStartConversationEvent:(o=i.emitStartConversationEvent)!=null?o:!0};i.locale&&(a.locale=i.locale),z.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,je.trace)(Ue.sendActivity);n.record({activity:e});try{let s=(i=(o=e.conversation)==null?void 0:o.id)!=null?i:r,a=br(this.settings,s),c=new wr(e);z.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,je.trace)(Ue.executeStreaming);n.record({activity:e,conversationId:r});try{if(!r||!r.trim())throw new Error("conversationId is required for executeStreaming");let o=br(this.settings,r),i=new wr(e,r);z.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=lt.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,Gc(r,n)}async executeWithResponse(e,r){let n=[];for await(let o of this.executeStreaming(e,r))n.push(o);return $c(n,r)}async*subscribeAsync(e,r){let n=(0,je.trace)(Ue.subscribeAsync);n.record({conversationId:e,lastReceivedEventId:r});try{if(!e||!e.trim())throw new Error("conversationId is required for subscribeAsync");let o=Na(this.settings,e);z.info("Subscribing to conversation:",e),this.logDiagnostic("Subscribe request:",{conversationId:e,lastReceivedEventId:r,url:o});let i=Jo({url:o,headers:{Authorization:`Bearer ${this.token}`,"User-Agent":Or.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=lt.Activity.fromJson(s),p={activity:l,eventId:c};n.actions.eventReceivedFromCopilot(p),z.debug(`Received activity via subscription, event ID: ${c}`),this.logDiagnostic("Subscribe event received:",{eventId:c,activityType:l.type}),yield p}catch(l){z.error("Failed to parse activity in subscription:",l)}else if(a==="end"){z.debug("Subscription stream complete");break}if(i.readyState==="closed"){z.debug("Subscription connection closed");break}}}finally{i.close()}}catch(o){throw n.fail(o)}finally{n.end()}}};Ze.conversationIdHeaderKey="x-ms-conversationid",Ze.islandExperimentalUrlHeaderKey="x-ms-d2e-experimental",Ze.scopeFromSettings=Kn.getScopeFromSettings;var Bc=Ze;function Hc(){return globalThis.crypto.randomUUID()}var cu=Te(Bn());var Oi=function(t,e){return Oi=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])},Oi(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");Oi(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function Pr(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 Ht(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 Yn(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 Xn=Yn(function(t){return function(r){t(this),this.message=r?r.length+` errors occurred during unsubscription:
|
|
5
|
+
`&&n++}}return[e,r]}var Oa="connecting",ul="open",Xo="closed",mn=()=>{};function dl(t,{getStream:e}){let r=typeof t=="string"||t instanceof URL?{url:t}:t,{onMessage:n,onComment:o=mn,onConnect:i=mn,onDisconnect:s=mn,onScheduleReconnect:a=mn}=r,{fetch:c,url:l,initialLastEventId:p}=ll(r),y={...r.headers},T=[],I=n?[n]:[],M=j=>I.forEach(ce=>ce(j)),h=wa({onEvent:du,onRetry:lu,onComment:o}),w,b=l.toString(),P=new AbortController,O=p,N=2e3,L,Z=Xo;return be(),{close:Q,connect:be,[Symbol.iterator]:()=>{throw new Error("EventSource does not support synchronous iteration. Use `for await` instead.")},[Symbol.asyncIterator]:Qt,get lastEventId(){return O},get url(){return b},get readyState(){return Z}};function be(){w||(Z=Oa,P=new AbortController,w=c(l,pu()).then(uu).catch(j=>{w=null,!(j.name==="AbortError"||j.type==="aborted"||P.signal.aborted)&&Mi()}))}function Q(){Z=Xo,P.abort(),h.reset(),clearTimeout(L),T.forEach(j=>j())}function Qt(){let j=[],ce=[];function er(){return new Promise(B=>{let ue=ce.shift();ue?B({value:ue,done:!1}):j.push(B)})}let ft=function(B){let ue=j.shift();ue?ue({value:B,done:!1}):ce.push(B)};function Le(){for(I.splice(I.indexOf(ft),1);j.shift(););for(;ce.shift(););}function tr(){let B=j.shift();B&&(B({done:!0,value:void 0}),Le())}return T.push(tr),I.push(ft),{next(){return Z===Xo?this.return():er()},return(){return Le(),Promise.resolve({done:!0,value:void 0})},throw(B){return Le(),Promise.reject(B)},[Symbol.asyncIterator](){return this}}}function Mi(){a({delay:N}),!P.signal.aborted&&(Z=Oa,L=setTimeout(be,N))}async function uu(j){i(),h.reset();let{body:ce,redirected:er,status:ft}=j;if(ft===204){s(),Q();return}if(!ce)throw new Error("Missing response body");er&&(b=j.url);let Le=e(ce),tr=new TextDecoder,B=Le.getReader(),ue=!0;Z=ul;do{let{done:Li,value:Vi}=await B.read();Vi&&h.feed(tr.decode(Vi,{stream:!Li})),Li&&(ue=!1,w=null,h.reset(),Mi(),s())}while(ue)}function du(j){typeof j.id=="string"&&(O=j.id),M(j)}function lu(j){N=j}function pu(){let{mode:j,credentials:ce,body:er,method:ft,redirect:Le,referrer:tr,referrerPolicy:B}=r,ue={Accept:"text/event-stream",...y,...O?{"Last-Event-ID":O}:void 0};return{mode:j,credentials:ce,body:er,method:ft,redirect:Le,referrer:tr,referrerPolicy:B,headers:ue,cache:"no-store",signal:P.signal}}}function ll(t){let e=t.fetch||globalThis.fetch;if(!pl(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 pl(t){return typeof t=="function"}var fl={getStream:ml};function Jo(t){return dl(t,fl)}function ml(t){if(!(t instanceof ReadableStream))throw new Error("Invalid stream, expected a web ReadableStream");return t}var Ra=Te($e());var hn=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 gn=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 Et=(0,Ra.debug)("copilot-studio:power-platform");function br(t,e){var c,l,p,y,T,I,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())&&(!((y=t.environmentId)!=null&&y.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(Et.debug(`Using direct connection: ${t.directConnectUrl}`),!_r(t.directConnectUrl))throw new Error("directConnectUrl must be a valid URL");return hl(t.directConnectUrl,e).href}let n=(I=t.cloud)!=null?I:"Prod",o=(M=t.copilotAgentType)!=null?M:"Published";if(Et.debug(`Using cloud setting: ${n}`),Et.debug(`Using agent type: ${o}`),n==="Other")if((h=t.customPowerPlatformCloud)!=null&&h.trim())if(_r(t.customPowerPlatformCloud))Et.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=gl(n,t.environmentId,t.customPowerPlatformCloud),a={Published:()=>new gn({host:i,schema:r}),Prebuilt:()=>new hn({host:i,schema:r})}[o]().getConversationUrl(e);return Et.debug(`Generated Copilot Studio connection URL: ${a}`),a}function Na(t,e){if(!e||!e.trim())throw new Error("conversationId is required for subscribe URL");let r=br(t,e),n=new URL(r);n.pathname=n.pathname.endsWith("/")?`${n.pathname}subscribe`:`${n.pathname}/subscribe`;let o=n.href;return Et.debug(`Generated Copilot Studio subscribe URL: ${o}`),o}function ka(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&&_r(r))e="Other";else if(t!=null&&t.customPowerPlatformCloud&&_r(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://${yn(e,r)}/.default`}else if(n||(n=(o=t==null?void 0:t.directConnectUrl)!=null?o:""),n&&_r(n)){if(Pa(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://${yn(s,"")}/.default`;throw new Error("Unable to resolve the PowerPlatform Cloud from DirectConnectUrl. The Token Audience resolver requires a specific PowerPlatformCloudCategory.")}return`https://${yn(Pa(new URL(n)),"")}/.default`}else throw new Error("DirectConnectUrl must be provided when DirectConnectUrl is set")}function _r(t){try{let e=t.startsWith("http")?t:`https://${t}`;return!!new URL(e)}catch{return!1}}function hl(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 gl(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=yl(t),i=n.substring(0,n.length-o),s=n.substring(n.length-o);return new URL(`https://${i}.${s}.environment.${yn(t,r)}`)}function yn(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 yl(t){switch(t){case"FirstRelease":case"Prod":return 2;default:return 1}}function Pa(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 lt=Te(Bn());var wr=class{constructor(e,r){this.activity=e,this.conversationId=r}};var je=Te($e());var Hn="1.6.0-beta.43.g9cc9760779";var Wn={};var Or=class{static getProductInfo(){var n;let e=`CopilotStudioClient.agents-sdk-js/${Hn}`,r=globalThis;return typeof r.document!="undefined"&&typeof((n=r.navigator)==null?void 0:n.userAgent)=="string"?`${e} ${r.navigator.userAgent}`:`${e} nodejs/${process.version} ${Wn.platform()}-${Wn.arch()}/${Wn.release()}`}static getVersionString(){return`CopilotStudioClient.agents-sdk-js/${Hn}`}static getVersion(){return Hn}};var Kn=class{static getScopeFromSettings(e){return ka(e)}};function Gc(t,e){return{activities:t,conversationId:e,isNewConversation:!0}}function $c(t,e){return{activities:t,conversationId:e,activityCount:t.length}}var U=Te($e()),$={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 wi=Te(Bn()),Y=Te($e());var Ue={createConnection:Y.trace.define({name:Y.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),$.webchatConnectionsCounter.add(1,r)}}),postRequest:Y.trace.define({name:Y.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"]}),$.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),$.requestsCounter.add(1,i),$.streamDuration.record(r,i),n&&$.requestsErrorCounter.add(1,{...i,"error.type":n instanceof Error?n.name:typeof n})}}),startConversation:Y.trace.define({name:Y.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),$.conversationsStartedCounter.add(1,o),$.requestDuration.record(r,o)}}),sendActivity:Y.trace.define({name:Y.SpanNames.COPILOT_SEND_ACTIVITY,record:{activity:wi.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),$.activitiesSentCounter.add(1,n),$.requestDuration.record(r,o)}}),executeStreaming:Y.trace.define({name:Y.SpanNames.COPILOT_EXECUTE_STREAMING,record:{activity:wi.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),$.executeStreamingCounter.add(1,n),$.requestDuration.record(r,o)}}),subscribeAsync:Y.trace.define({name:Y.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),$.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),$.subscribeAsyncCounter.add(1,o),$.streamDuration.record(r,o)}})};var z=(0,je.debug)("copilot-studio:client"),Ze=class Ze{constructor(e,r){this.conversationId="";this.settings=e,this.token=r}logDiagnostic(e,...r){this.settings.enableDiagnostics&&z.info(`[DIAGNOSTICS] ${e}`,...r)}async*postRequestAsync(e,r,n="POST"){var i,s,a,c,l,p,y,T,I,M;let o=(0,je.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"),z.debug(`>>> SEND TO ${e}`);let h=new Map,w=Jo({url:e,headers:{Authorization:`Bearer ${this.token}`,"User-Agent":Or.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=lt.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 lt.ActivityTypes.Message:this.conversationId.trim()||(this.conversationId=(a=(s=O.conversation)==null?void 0:s.id)!=null?a:"",z.debug(`Conversation ID: ${this.conversationId}`)),yield O;break;case lt.ActivityTypes.Typing:if(z.debug(`Activity type: ${O.type}`),N||((c=O.channelData)==null?void 0:c.streamType)==="streaming"){let L=(l=O.text)!=null?l:"",Z=(y=N==null?void 0:N.streamId)!=null?y:(p=O.channelData)==null?void 0:p.streamId,be=(I=N==null?void 0:N.streamSequence)!=null?I:(T=O.channelData)==null?void 0:T.streamSequence;if(Z&&be){if(h.has(Z)){let Q=h.get(Z);Q.push({text:L,sequence:be}),h.set(Z,Q)}else h.set(Z,[{text:L,sequence:be}]);O.text=((M=h.get(Z))==null?void 0:M.sort((Q,Qt)=>Q.sequence-Qt.sequence).map(Q=>Q.text).join(""))||""}}yield O;break;default:z.debug(`Activity type: ${O.type}`),yield O;break}}catch(O){z.error("Failed to parse activity:",O)}else if(P==="end"){z.debug("Stream complete");break}if(w.readyState==="closed"){z.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(Ze.islandExperimentalUrlHeaderKey);i&&(this.settings.directConnectUrl=i,z.debug(`Island Experimental URL: ${i}`))}this.conversationId=(o=e==null?void 0:e.get(Ze.conversationIdHeaderKey))!=null?o:"",this.conversationId&&z.debug(`Conversation ID: ${this.conversationId}`);let r=new Headers;e.forEach((i,s)=>{s.toLowerCase()!=="authorization"&&s.toLowerCase()!==Ze.conversationIdHeaderKey.toLowerCase()&&r.set(s,i)}),this.logDiagnostic("Response Headers:",r)}async*startConversationStreaming(e){var n,o;let r=(0,je.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=br(this.settings,i.conversationId),a={emitStartConversationEvent:(o=i.emitStartConversationEvent)!=null?o:!0};i.locale&&(a.locale=i.locale),z.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,je.trace)(Ue.sendActivity);n.record({activity:e});try{let s=(i=(o=e.conversation)==null?void 0:o.id)!=null?i:r,a=br(this.settings,s),c=new wr(e);z.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,je.trace)(Ue.executeStreaming);n.record({activity:e,conversationId:r});try{if(!r||!r.trim())throw new Error("conversationId is required for executeStreaming");let o=br(this.settings,r),i=new wr(e,r);z.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=lt.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,Gc(r,n)}async executeWithResponse(e,r){let n=[];for await(let o of this.executeStreaming(e,r))n.push(o);return $c(n,r)}async*subscribeAsync(e,r){let n=(0,je.trace)(Ue.subscribeAsync);n.record({conversationId:e,lastReceivedEventId:r});try{if(!e||!e.trim())throw new Error("conversationId is required for subscribeAsync");let o=Na(this.settings,e);z.info("Subscribing to conversation:",e),this.logDiagnostic("Subscribe request:",{conversationId:e,lastReceivedEventId:r,url:o});let i=Jo({url:o,headers:{Authorization:`Bearer ${this.token}`,"User-Agent":Or.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=lt.Activity.fromJson(s),p={activity:l,eventId:c};n.actions.eventReceivedFromCopilot(p),z.debug(`Received activity via subscription, event ID: ${c}`),this.logDiagnostic("Subscribe event received:",{eventId:c,activityType:l.type}),yield p}catch(l){z.error("Failed to parse activity in subscription:",l)}else if(a==="end"){z.debug("Subscription stream complete");break}if(i.readyState==="closed"){z.debug("Subscription connection closed");break}}}finally{i.close()}}catch(o){throw n.fail(o)}finally{n.end()}}};Ze.conversationIdHeaderKey="x-ms-conversationid",Ze.islandExperimentalUrlHeaderKey="x-ms-d2e-experimental",Ze.scopeFromSettings=Kn.getScopeFromSettings;var Bc=Ze;function Hc(){return globalThis.crypto.randomUUID()}var cu=Te(Bn());var Oi=function(t,e){return Oi=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])},Oi(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");Oi(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function Pr(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 Ht(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 Yn(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 Xn=Yn(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 Rr(t,e){if(t){var r=t.indexOf(e);0<=r&&t.splice(r,1)}}var Wt=(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=Pr(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 Xn?h.errors:[h]}var y=this._finalizers;if(y){this._finalizers=null;try{for(var T=Pr(y),I=T.next();!I.done;I=T.next()){var M=I.value;try{Wc(M)}catch(h){i=i!=null?i:[],h instanceof Xn?i=Ht(Ht([],Bt(i)),Bt(h.errors)):i.push(h)}}}catch(h){n={error:h}}finally{try{I&&!I.done&&(o=T.return)&&o.call(T)}finally{if(n)throw n.error}}}if(i)throw new Xn(i)}},t.prototype.add=function(e){var r;if(e&&e!==this)if(this.closed)Wc(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)&&Rr(r,e)},t.prototype.remove=function(e){var r=this._finalizers;r&&Rr(r,e),e instanceof t&&e._removeParent(this)},t.EMPTY=(function(){var e=new t;return e.closed=!0,e})(),t})();var Pi=Wt.EMPTY;function Jn(t){return t instanceof Wt||t&&"closed"in t&&oe(t.remove)&&oe(t.add)&&oe(t.unsubscribe)}function Wc(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,Ht([t,e],Bt(r))):setTimeout.apply(void 0,Ht([t,e],Bt(r)))},clearTimeout:function(t){var e=Kt.delegate;return((e==null?void 0:e.clearTimeout)||clearTimeout)(t)},delegate:void 0};function Kc(t){Kt.setTimeout(function(){var e=ae.onUnhandledError;if(e)e(t);else throw t})}function Ri(){}var Yc=(function(){return Ni("C",void 0,void 0)})();function Xc(t){return Ni("E",void 0,t)}function Jc(t){return Ni("N",t,void 0)}function Ni(t,e,r){return{kind:t,value:e,error:r}}var pt=null;function Yt(t){if(ae.useDeprecatedSynchronousErrorHandling){var e=!pt;if(e&&(pt={errorThrown:!1,error:null}),t(),e){var r=pt,n=r.errorThrown,o=r.error;if(pt=null,n)throw o}}else t()}function Qc(t){ae.useDeprecatedSynchronousErrorHandling&&pt&&(pt.errorThrown=!0,pt.error=t)}var Ui=(function(t){Me(e,t);function e(r){var n=t.call(this)||this;return n.isStopped=!1,r?(n.destination=r,Jn(r)&&r.add(n)):n.destination=Hf,n}return e.create=function(r,n,o){return new eo(r,n,o)},e.prototype.next=function(r){this.isStopped?Di(Jc(r),this):this._next(r)},e.prototype.error=function(r){this.isStopped?Di(Xc(r),this):(this.isStopped=!0,this._error(r))},e.prototype.complete=function(){this.isStopped?Di(Yc,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})(Wt);var Gf=Function.prototype.bind;function ki(t,e){return Gf.call(t,e)}var $f=(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){Qn(n)}},t.prototype.error=function(e){var r=this.partialObserver;if(r.error)try{r.error(e)}catch(n){Qn(n)}else Qn(e)},t.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(r){Qn(r)}},t})(),eo=(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&&ki(r.next,a),error:r.error&&ki(r.error,a),complete:r.complete&&ki(r.complete,a)}):s=r}return i.destination=new $f(s),i}return e})(Ui);function Qn(t){ae.useDeprecatedSynchronousErrorHandling?Qc(t):Kc(t)}function Bf(t){throw t}function Di(t,e){var r=ae.onStoppedNotification;r&&Kt.setTimeout(function(){return r(t,e)})}var Hf={closed:!0,next:Ri,error:Bf,complete:Ri};var eu=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function tu(t){return t}function ru(t){return t.length===0?tu: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=Kf(e)?e:new eo(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=nu(r),new r(function(o,i){var s=new eo({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[eu]=function(){return this},t.prototype.pipe=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return ru(e)(this)},t.prototype.toPromise=function(e){var r=this;return e=nu(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 nu(t){var e;return(e=t!=null?t:ae.Promise)!==null&&e!==void 0?e:Promise}function Wf(t){return t&&oe(t.next)&&oe(t.error)&&oe(t.complete)}function Kf(t){return t&&t instanceof Ui||Wf(t)&&Jn(t)}var ou=Yn(function(t){return function(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}});var Zi=(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 iu(this,this);return n.operator=r,n},e.prototype._throwIfClosed=function(){if(this.closed)throw new ou},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=Pr(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?Pi:(this.currentObservers=null,a.push(r),new Wt(function(){n.currentObservers=null,Rr(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 iu(r,n)},e})(Xt);var iu=(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:Pi},e})(Zi);var ji=(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})(Zi);var Jt=Te($e());var _e=(0,Jt.debug)("copilot-studio:webchat");function Yf(t){let e=!1;return r=>{if(!e)return e=!0,t(r)}}var su=class{static createConnection(e,r){var o;let n=(0,Jt.trace)(Ue.createConnection);n.record({showTyping:r==null?void 0:r.showTyping});try{_e.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;_e.info("Copilot Studio WebChat settings loaded",{showTyping:r==null?void 0:r.showTyping,conversationId:(0,Jt.redactString)(i,!0),startConversation:r==null?void 0:r.startConversation,connectionMode:i?"resume":"new",acknowledgementMode:s?"startConversationStreaming":"resumeWithoutStart"});let a=0,c,l,p=i,y=!1,T=!1,I=new ji(0),M=au(async b=>{var P;try{c=b;let O=Yf(async()=>{I.next(2),await Promise.resolve()});if(!s||T){await O();return}T=!0,_e.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++,_e.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$:I,activity$:M,get conversationId(){return p},postActivity(b){try{if(_e.info("--> Preparing to send activity to Copilot Studio ..."),!b)throw new Error("Activity cannot be null.");if(y)throw new Error("Connection has been ended.");if(!c)throw new Error("Activity subscriber is not initialized.");return au(async O=>{var N;try{_e.info("--> Sending activity to Copilot Studio ...");let L=cu.Activity.fromObject({...b,id:Hc(),attachments:await Xf(b)});h(L),n.actions.sentToWebChat(L),w(),O.next(L.id);for await(let Z of e.sendActivityStreaming(L,p))!p&&((N=Z.conversation)!=null&&N.id)&&(p=Z.conversation.id),h(Z),n.actions.receivedFromCopilot(Z),_e.info("<-- Activity received correctly from Copilot Studio.");O.complete()}catch(L){_e.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(){_e.info("--> Ending connection between Copilot Studio and WebChat ..."),y=!0,I.complete(),c&&(c.complete(),c=void 0),n.end()}}}catch(i){throw n.fail(i)}finally{n.end()}}};async function Xf(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 Jf(n);e.push(o)}return e}async function Jf(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=Qf(o);e=`data:${n.type};base64,${i}`}catch(r){e=t.contentUrl,_e.error("Error processing blob attachment:",e,r)}return{...t,contentUrl:e}}function Qf(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 au(t){return new Xt(e=>{Promise.resolve(t(e)).catch(r=>e.error(r))})}function P_(t=!0,e,r){return{emitStartConversationEvent:t,locale:e,conversationId:r}}export{rr as AgentType,Ko as ConnectionSettings,Bc as CopilotStudioClient,su as CopilotStudioWebChat,wr as ExecuteTurnRequest,nr as PowerPlatformCloud,Kn as ScopeHelper,Or as UserAgentHelper,$c as createExecuteTurnResponse,P_ as createStartRequest,Gc as createStartResponse,br as getCopilotStudioConnectionUrl,Na as getCopilotStudioSubscribeUrl,ka as getTokenAudience,Gg as loadCopilotStudioConnectionSettingsFromEnv};
|
|
8
8
|
//# sourceMappingURL=browser.mjs.map
|