@microsoft/agents-copilotstudio-client 1.6.0-beta.4.g8ab0e486bc → 1.6.0-beta.8.g226709c215
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.8.g226709c215",
|
|
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.8.g226709c215",
|
|
31
|
+
"@microsoft/agents-telemetry": "1.6.0-beta.8.g226709c215",
|
|
32
32
|
"eventsource-client": "1.2.0",
|
|
33
33
|
"rxjs": "7.8.2",
|
|
34
34
|
"uuid": "11.1.0"
|
package/dist/src/browser.mjs
CHANGED
|
@@ -2,7 +2,7 @@ var Id=Object.create;var Br=Object.defineProperty;var Ed=Object.getOwnPropertyDe
|
|
|
2
2
|
`;break;case"id":s=S.includes("\0")?void 0:S;break;case"retry":/^\d+$/.test(S)?n(parseInt(S,10)):r(new Hr(`Invalid \`retry\` value: "${S}"`,{type:"invalid-retry",value:S,line:T}));break;default:r(new Hr(`Unknown field "${y.length>20?`${y.slice(0,20)}\u2026`:y}"`,{type:"unknown-field",field:y,value:S,line:T}));break}}function I(){c.length>0&&t({id:s,event:d||void 0,data:c.endsWith(`
|
|
3
3
|
`)?c.slice(0,-1):c}),s=void 0,c="",d=""}function P(y={}){i&&y.consume&&g(i),a=!0,s=void 0,c="",d="",i=""}return{feed:f,reset:P}}function Rd(e){let t=[],r="",n=0;for(;n<e.length;){let o=e.indexOf("\r",n),i=e.indexOf(`
|
|
4
4
|
`,n),a=-1;if(o!==-1&&i!==-1?a=Math.min(o,i):o!==-1?o===e.length-1?a=-1:a=o:i!==-1&&(a=i),a===-1){r=e.slice(n);break}else{let s=e.slice(n,a);t.push(s),n=a+1,e[n-1]==="\r"&&e[n]===`
|
|
5
|
-
`&&n++}}return[t,r]}var Na="connecting",Nd="open",Co="closed",Wr=()=>{};function jd(e,{getStream:t}){let r=typeof e=="string"||e instanceof URL?{url:e}:e,{onMessage:n,onComment:o=Wr,onConnect:i=Wr,onDisconnect:a=Wr,onScheduleReconnect:s=Wr}=r,{fetch:c,url:d,initialLastEventId:f}=kd(r),g={...r.headers},_=[],I=n?[n]:[],P=M=>I.forEach(he=>he(M)),y=Ra({onEvent:Td,onRetry:xd,onComment:o}),S,T=d.toString(),N=new AbortController,O=f,k=2e3,V,L=Co;return Se(),{close:ie,connect:Se,[Symbol.iterator]:()=>{throw new Error("EventSource does not support synchronous iteration. Use `for await` instead.")},[Symbol.asyncIterator]:ur,get lastEventId(){return O},get url(){return T},get readyState(){return L}};function Se(){S||(L=Na,N=new AbortController,S=c(d,Cd()).then(bd).catch(M=>{S=null,!(M.name==="AbortError"||M.type==="aborted"||N.signal.aborted)&&Aa()}))}function ie(){L=Co,N.abort(),y.reset(),clearTimeout(V),_.forEach(M=>M())}function ur(){let M=[],he=[];function dr(){return new Promise(J=>{let ge=he.shift();ge?J({value:ge,done:!1}):M.push(J)})}let It=function(J){let ge=M.shift();ge?ge({value:J,done:!1}):he.push(J)};function Ke(){for(I.splice(I.indexOf(It),1);M.shift(););for(;he.shift(););}function lr(){let J=M.shift();J&&(J({done:!0,value:void 0}),Ke())}return _.push(lr),I.push(It),{next(){return L===Co?this.return():dr()},return(){return Ke(),Promise.resolve({done:!0,value:void 0})},throw(J){return Ke(),Promise.reject(J)},[Symbol.asyncIterator](){return this}}}function Aa(){s({delay:k}),!N.signal.aborted&&(L=Na,V=setTimeout(Se,k))}async function bd(M){i(),y.reset();let{body:he,redirected:dr,status:It}=M;if(It===204){a(),ie();return}if(!he)throw new Error("Missing response body");dr&&(T=M.url);let Ke=t(he),lr=new TextDecoder,J=Ke.getReader(),ge=!0;L=Nd;do{let{done:wa,value:Oa}=await J.read();Oa&&y.feed(lr.decode(Oa,{stream:!wa})),wa&&(ge=!1,S=null,y.reset(),Aa(),a())}while(ge)}function Td(M){typeof M.id=="string"&&(O=M.id),P(M)}function xd(M){k=M}function Cd(){let{mode:M,credentials:he,body:dr,method:It,redirect:Ke,referrer:lr,referrerPolicy:J}=r,ge={Accept:"text/event-stream",...g,...O?{"Last-Event-ID":O}:void 0};return{mode:M,credentials:he,body:dr,method:It,redirect:Ke,referrer:lr,referrerPolicy:J,headers:ge,cache:"no-store",signal:N.signal}}}function kd(e){let t=e.fetch||globalThis.fetch;if(!Ud(t))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}=e;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:t,url:r,initialLastEventId:n}}function Ud(e){return typeof e=="function"}var Dd={getStream:Zd};function Io(e){return jd(e,Dd)}function Zd(e){if(!(e instanceof ReadableStream))throw new Error("Invalid stream, expected a web ReadableStream");return e}var yc=De(Ut());var On=class{constructor(t){this.API_VERSION="2022-03-01-preview";let r="schema"in t?t.schema:t.identifier,n=t.host;this.baseURL=new URL(`/copilotstudio/prebuilt/authenticated/bots/${r}`,n),this.baseURL.searchParams.append("api-version",this.API_VERSION)}getConversationUrl(t){let r=new URL(this.baseURL.href);return r.pathname=`${r.pathname}/conversations`,t&&(r.pathname=`${r.pathname}/${t}`),r.href}};var Pn=class{constructor(t){this.API_VERSION="2022-03-01-preview";let{schema:r,host:n}=t;this.baseURL=new URL(`/copilotstudio/dataverse-backed/authenticated/bots/${r}`,n),this.baseURL.searchParams.append("api-version",this.API_VERSION)}getConversationUrl(t){let r=new URL(this.baseURL.href);return r.pathname=`${r.pathname}/conversations`,t&&(r.pathname=`${r.pathname}/${t}`),r.href}};var Dt=(0,yc.debug)("copilot-studio:power-platform");function Ar(e,t){var c,d,f,g,_,I,P,y;let r=((c=e.schemaName)==null?void 0:c.trim())||((d=e.agentIdentifier)==null?void 0:d.trim());if(!((f=e.directConnectUrl)!=null&&f.trim())&&(!((g=e.environmentId)!=null&&g.trim())||!(r!=null&&r.trim())))throw new Error("Either directConnectUrl OR both environmentId and schemaName/agentIdentifier must be provided");if((_=e.directConnectUrl)!=null&&_.trim()){if(Dt.debug(`Using direct connection: ${e.directConnectUrl}`),!Sr(e.directConnectUrl))throw new Error("directConnectUrl must be a valid URL");return Ef(e.directConnectUrl,t).href}let n=(I=e.cloud)!=null?I:"Prod",o=(P=e.copilotAgentType)!=null?P:"Published";if(Dt.debug(`Using cloud setting: ${n}`),Dt.debug(`Using agent type: ${o}`),n==="Other")if((y=e.customPowerPlatformCloud)!=null&&y.trim())if(Sr(e.customPowerPlatformCloud))Dt.debug(`Using custom Power Platform cloud: ${e.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=Sf(n,e.environmentId,e.customPowerPlatformCloud),s={Published:()=>new Pn({host:i,schema:r}),Prebuilt:()=>new On({host:i,schema:r})}[o]().getConversationUrl(t);return Dt.debug(`Generated Copilot Studio connection URL: ${s}`),s}function vc(e,t){if(!t||!t.trim())throw new Error("conversationId is required for subscribe URL");let r=Ar(e,t),n=new URL(r);n.pathname=n.pathname.endsWith("/")?`${n.pathname}subscribe`:`${n.pathname}/subscribe`;let o=n.href;return Dt.debug(`Generated Copilot Studio subscribe URL: ${o}`),o}function _c(e,t="Unknown",r="",n=""){var o,i;if(!n&&!(e!=null&&e.directConnectUrl)){if(t==="Other"&&!r)throw new Error("cloudBaseAddress must be provided when PowerPlatformCloudCategory is Other");if(!e&&t==="Unknown")throw new Error("Either settings or cloud must be provided");if(e&&e.cloud&&e.cloud!=="Unknown"&&(t=e.cloud),t==="Other")if(r&&Sr(r))t="Other";else if(e!=null&&e.customPowerPlatformCloud&&Sr(e.customPowerPlatformCloud))t="Other",r=e.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://${Rn(t,r)}/.default`}else if(n||(n=(o=e==null?void 0:e.directConnectUrl)!=null?o:""),n&&Sr(n)){if(gc(new URL(n))==="Unknown"){let a=(i=e==null?void 0:e.cloud)!=null?i:t;if(a==="Other"||a==="Unknown")throw new Error("Unable to resolve the PowerPlatform Cloud from DirectConnectUrl. The Token Audience resolver requires a specific PowerPlatformCloudCategory.");if(a!=="Unknown")return`https://${Rn(a,"")}/.default`;throw new Error("Unable to resolve the PowerPlatform Cloud from DirectConnectUrl. The Token Audience resolver requires a specific PowerPlatformCloudCategory.")}return`https://${Rn(gc(new URL(n)),"")}/.default`}else throw new Error("DirectConnectUrl must be provided when DirectConnectUrl is set")}function Sr(e){try{let t=e.startsWith("http")?e:`https://${e}`;return!!new URL(t)}catch{return!1}}function Ef(e,t){let r=new URL(e);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`,t&&(r.pathname=`${r.pathname}/${t}`),r}function Sf(e,t,r){if(e==="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=t.toLowerCase().replaceAll("-",""),o=Af(e),i=n.substring(0,n.length-o),a=n.substring(n.length-o);return new URL(`https://${i}.${a}.environment.${Rn(e,r)}`)}function Rn(e,t){switch(e){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 t;default:throw new Error(`Invalid cluster category value: ${e}`)}}function Af(e){switch(e){case"FirstRelease":case"Prod":return 2;default:return 1}}function gc(e){switch(e.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 xt=De(uo());var zr=class{constructor(t,r){this.activity=t,this.conversationId=r}};var He=De(Ut());var lo="1.6.0-beta.4.g8ab0e486bc";var fo={};var Fr=class{static getProductInfo(){let t=`CopilotStudioClient.agents-sdk-js/${lo}`,r;return typeof window!="undefined"&&window.navigator?r=`${t} ${navigator.userAgent}`:r=`${t} nodejs/${process.version} ${fo.platform()}-${fo.arch()}/${fo.release()}`,r}static getVersionString(){return`CopilotStudioClient.agents-sdk-js/${lo}`}static getVersion(){return lo}};var po=class{static getScopeFromSettings(t){return _c(t)}};function td(e,t){return{activities:e,conversationId:t,isNewConversation:!0}}function rd(e,t){return{activities:e,conversationId:t,activityCount:e.length}}var Z=De(Ut()),X={activitiesReceivedCounter:Z.metric.counter(Z.MetricNames.CSC_ACTIVITIES_RECEIVED,{unit:"activities",description:"Total number of activities received by the Copilot Studio client"}),activitiesSentCounter:Z.metric.counter(Z.MetricNames.CSC_ACTIVITIES_SENT,{unit:"activities",description:"Total number of activities sent to Copilot Studio"}),conversationsStartedCounter:Z.metric.counter(Z.MetricNames.CSC_CONVERSATIONS_STARTED,{unit:"conversations",description:"Total number of conversations started with Copilot Studio"}),webchatConnectionsCounter:Z.metric.counter(Z.MetricNames.CSC_WEBCHAT_CONNECTIONS,{unit:"connections",description:"Total number of webchat connections created with Copilot Studio"}),requestsCounter:Z.metric.counter(Z.MetricNames.CSC_REQUEST_COUNT,{unit:"requests",description:"Total number of HTTP/SSE requests made to Copilot Studio"}),requestsErrorCounter:Z.metric.counter(Z.MetricNames.CSC_REQUEST_ERRORS,{unit:"requests",description:"Total number of failed requests to Copilot Studio"}),executeStreamingCounter:Z.metric.counter(Z.MetricNames.CSC_EXECUTE_STREAMING,{unit:"operations",description:"Total number of execute streaming operations"}),subscribeAsyncCounter:Z.metric.counter(Z.MetricNames.CSC_SUBSCRIBE_ASYNC,{unit:"operations",description:"Total number of subscribeAsync operations"}),subscribeEventCounter:Z.metric.counter(Z.MetricNames.CSC_SUBSCRIBE_EVENT,{unit:"events",description:"Total number of events received via subscribeAsync"}),streamDuration:Z.metric.histogram(Z.MetricNames.CSC_STREAM_DURATION,{unit:"ms",description:"Duration of SSE stream sessions in milliseconds"}),requestDuration:Z.metric.histogram(Z.MetricNames.CSC_REQUEST_DURATION,{unit:"ms",description:"Duration of requests to Copilot Studio in milliseconds"})};var pa=De(uo()),re=De(Ut());var $e={createConnection:re.trace.define({name:re.SpanNames.COPILOT_CREATE_CONNECTION,record:{showTyping:!1},actions:({span:e})=>({receivedFromCopilot(t){var r,n,o;e.addEvent("activity.received.from.copilot.studio",{"copilot.webchat.activity.type":(r=t.type)!=null?r:"unknown","copilot.webchat.activity.conversation_id":(o=(n=t.conversation)==null?void 0:n.id)!=null?o:"unknown"})},sentToWebChat(t){var r,n,o;e.addEvent("activity.sent.to.webchat",{"copilot.webchat.activity.type":(r=t.type)!=null?r:"unknown","copilot.webchat.activity.conversation_id":(o=(n=t.conversation)==null?void 0:n.id)!=null?o:"unknown"})}}),end({span:e,record:t}){var n;let r={"copilot.webchat.show_typing":(n=t.showTyping)!=null?n:"unknown"};e.setAttributes(r),X.webchatConnectionsCounter.add(1,r)}}),postRequest:re.trace.define({name:re.SpanNames.COPILOT_POST_REQUEST,record:{url:"",method:""},actions:({span:e})=>({receivedFromCopilot(t){var n,o,i;let r={"copilot.activity.type":(n=t.type)!=null?n:"unknown","copilot.activity.conversation_id":(i=(o=t.conversation)==null?void 0:o.id)!=null?i:"unknown"};e.addEvent("activity.received",{"copilot.post_request.activity.type":r["copilot.activity.type"],"copilot.post_request.activity.conversation_id":r["copilot.activity.conversation_id"]}),X.activitiesReceivedCounter.add(1,r)}}),end({span:e,record:t,duration:r,error:n}){var a,s;let o={"copilot.post_request.url":(a=t.url)!=null?a:"unknown","copilot.post_request.method":(s=t.method)!=null?s:"unknown"},i={operation:"postRequestAsync","copilot.post_request.url":o["copilot.post_request.url"],"copilot.post_request.method":o["copilot.post_request.method"]};e.setAttributes(o),X.requestsCounter.add(1,i),X.streamDuration.record(r,i),n&&X.requestsErrorCounter.add(1,{...i,"error.type":n instanceof Error?n.name:typeof n})}}),startConversation:re.trace.define({name:re.SpanNames.COPILOT_START_CONVERSATION,record:{shouldEmitStartEvent:!1},end({span:e,record:t,duration:r}){let n=t.shouldEmitStartEvent?{"copilot.emit_start_event":!0}:{"copilot.request":!0},o={operation:"startConversationStreaming",...n};e.setAttributes(n),X.conversationsStartedCounter.add(1,o),X.requestDuration.record(r,o)}}),sendActivity:re.trace.define({name:re.SpanNames.COPILOT_SEND_ACTIVITY,record:{activity:pa.Activity.fromObject({type:"unknown"})},end({span:e,record:t,duration:r}){var i,a,s;let n={"copilot.activity.type":(i=t.activity.type)!=null?i:"unknown","copilot.activity.conversation_id":(s=(a=t.activity.conversation)==null?void 0:a.id)!=null?s:"unknown"},o={operation:"sendActivityStreaming",...n};e.setAttributes(n),X.activitiesSentCounter.add(1,n),X.requestDuration.record(r,o)}}),executeStreaming:re.trace.define({name:re.SpanNames.COPILOT_EXECUTE_STREAMING,record:{activity:pa.Activity.fromObject({type:"unknown"}),conversationId:"unknown"},end({span:e,record:t,duration:r}){var i,a;let n={"copilot.activity.type":(i=t.activity.type)!=null?i:"unknown","copilot.activity.conversation_id":(a=t.conversationId)!=null?a:"unknown"},o={operation:"executeStreaming",...n};e.setAttributes(n),X.executeStreamingCounter.add(1,n),X.requestDuration.record(r,o)}}),subscribeAsync:re.trace.define({name:re.SpanNames.COPILOT_SUBSCRIBE_ASYNC,record:{conversationId:"unknown",lastReceivedEventId:"unknown"},actions:({span:e})=>({eventReceivedFromCopilot(t){var n,o;let r={"copilot.subscribe_async.event.id":(n=t.eventId)!=null?n:"unknown","copilot.subscribe_async.event.activity.type":(o=t.activity.type)!=null?o:"unknown"};e.addEvent("event.received",r),X.subscribeEventCounter.add(1,r)}}),end({span:e,record:t,duration:r}){var i,a;let n={"copilot.subscribe_async.conversation_id":(i=t.conversationId)!=null?i:"unknown","copilot.subscribe_async.last_received_event_id":(a=t.lastReceivedEventId)!=null?a:"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"]};e.setAttributes(n),X.subscribeAsyncCounter.add(1,o),X.streamDuration.record(r,o)}})};var q=(0,He.debug)("copilot-studio:client"),Be=class Be{constructor(t,r){this.conversationId="";this.settings=t,this.token=r}logDiagnostic(t,...r){this.settings.enableDiagnostics&&q.info(`[DIAGNOSTICS] ${t}`,...r)}async*postRequestAsync(t,r,n="POST"){var i,a,s,c,d,f,g,_,I,P;let o=(0,He.trace)($e.postRequest);o.record({url:t,method:n});try{this.logDiagnostic(`Request URL: ${t}`),this.logDiagnostic(`Request Method: ${n}`),this.logDiagnostic("Request Body:",r?JSON.stringify(r,null,2):"none"),q.debug(`>>> SEND TO ${t}`);let y=new Map,S=Io({url:t,headers:{Authorization:`Bearer ${this.token}`,"User-Agent":Fr.getProductInfo(),"Content-Type":"application/json",Accept:"text/event-stream"},body:r?JSON.stringify(r):void 0,method:n,fetch:async(T,N)=>{let O=await fetch(T,N);return this.processResponseHeaders(O.headers),O}});try{for await(let{data:T,event:N}of S){if(T&&N==="activity")try{let O=xt.Activity.fromJson(T);o.actions.receivedFromCopilot(O);let k=(i=O.entities)==null?void 0:i.find(V=>V.type==="streaminfo"&&V.streamType==="streaming");switch(O.type){case xt.ActivityTypes.Message:this.conversationId.trim()||(this.conversationId=(s=(a=O.conversation)==null?void 0:a.id)!=null?s:"",q.debug(`Conversation ID: ${this.conversationId}`)),yield O;break;case xt.ActivityTypes.Typing:if(q.debug(`Activity type: ${O.type}`),k||((c=O.channelData)==null?void 0:c.streamType)==="streaming"){let V=(d=O.text)!=null?d:"",L=(g=k==null?void 0:k.streamId)!=null?g:(f=O.channelData)==null?void 0:f.streamId,Se=(I=k==null?void 0:k.streamSequence)!=null?I:(_=O.channelData)==null?void 0:_.streamSequence;if(L&&Se){if(y.has(L)){let ie=y.get(L);ie.push({text:V,sequence:Se}),y.set(L,ie)}else y.set(L,[{text:V,sequence:Se}]);O.text=((P=y.get(L))==null?void 0:P.sort((ie,ur)=>ie.sequence-ur.sequence).map(ie=>ie.text).join(""))||""}}yield O;break;default:q.debug(`Activity type: ${O.type}`),yield O;break}}catch(O){q.error("Failed to parse activity:",O)}else if(N==="end"){q.debug("Stream complete");break}if(S.readyState==="closed"){q.debug("Connection closed");break}}}finally{S.close()}}catch(y){throw o.fail(y)}finally{o.end()}}processResponseHeaders(t){var n,o;if(this.settings.useExperimentalEndpoint&&!((n=this.settings.directConnectUrl)!=null&&n.trim())){let i=t==null?void 0:t.get(Be.islandExperimentalUrlHeaderKey);i&&(this.settings.directConnectUrl=i,q.debug(`Island Experimental URL: ${i}`))}this.conversationId=(o=t==null?void 0:t.get(Be.conversationIdHeaderKey))!=null?o:"",this.conversationId&&q.debug(`Conversation ID: ${this.conversationId}`);let r=new Headers;t.forEach((i,a)=>{a.toLowerCase()!=="authorization"&&a.toLowerCase()!==Be.conversationIdHeaderKey.toLowerCase()&&r.set(a,i)}),this.logDiagnostic("Response Headers:",r)}async*startConversationStreaming(t){var n,o;let r=(0,He.trace)($e.startConversation);try{let i;typeof t=="boolean"||t===void 0?(r.record({shouldEmitStartEvent:t!=null?t:!0}),i={emitStartConversationEvent:t!=null?t:!0}):(i=t,r.record({shouldEmitStartEvent:(n=i.emitStartConversationEvent)!=null?n:!0}));let a=Ar(this.settings,i.conversationId),s={emitStartConversationEvent:(o=i.emitStartConversationEvent)!=null?o:!0};i.locale&&(s.locale=i.locale),q.info("Starting conversation ...",i),this.logDiagnostic("Start conversation request:",s),yield*this.postRequestAsync(a,s,"POST")}catch(i){throw r.fail(i)}finally{r.end()}}async*sendActivityStreaming(t,r=this.conversationId){var o,i;let n=(0,He.trace)($e.sendActivity);n.record({activity:t});try{let a=(i=(o=t.conversation)==null?void 0:o.id)!=null?i:r,s=Ar(this.settings,a),c=new zr(t);q.info("Sending activity...",t),yield*this.postRequestAsync(s,c,"POST")}catch(a){throw n.fail(a)}finally{n.end()}}async*executeStreaming(t,r){let n=(0,He.trace)($e.executeStreaming);n.record({activity:t,conversationId:r});try{if(!r||!r.trim())throw new Error("conversationId is required for executeStreaming");let o=Ar(this.settings,r),i=new zr(t,r);q.info("Executing turn with conversation ID:",r),this.logDiagnostic("Execute turn request:",{conversationId:r,activityType:t.type,activityText:t.text}),yield*this.postRequestAsync(o,i,"POST")}catch(o){throw n.fail(o)}finally{n.end()}}async execute(t,r){let n=[];for await(let o of this.executeStreaming(t,r))n.push(o);return n}async startConversationAsync(t){let r=[];for await(let n of this.startConversationStreaming(t))r.push(n);return r}async askQuestionAsync(t,r){let o={id:r!=null&&r.trim()?r:this.conversationId},i={type:"message",text:t,conversation:o},a=xt.Activity.fromObject(i),s=[];for await(let c of this.sendActivityStreaming(a,r))s.push(c);return s}async sendActivity(t,r=this.conversationId){let n=[];for await(let o of this.sendActivityStreaming(t,r))n.push(o);return n}async startConversationWithResponse(t){var o;let r=[],n="";for await(let i of this.startConversationStreaming(t))r.push(i),(o=i.conversation)!=null&&o.id&&(n=i.conversation.id);return n=n||this.conversationId,td(r,n)}async executeWithResponse(t,r){let n=[];for await(let o of this.executeStreaming(t,r))n.push(o);return rd(n,r)}async*subscribeAsync(t,r){let n=(0,He.trace)($e.subscribeAsync);n.record({conversationId:t,lastReceivedEventId:r});try{if(!t||!t.trim())throw new Error("conversationId is required for subscribeAsync");let o=vc(this.settings,t);q.info("Subscribing to conversation:",t),this.logDiagnostic("Subscribe request:",{conversationId:t,lastReceivedEventId:r,url:o});let i=Io({url:o,headers:{Authorization:`Bearer ${this.token}`,"User-Agent":Fr.getProductInfo(),Accept:"text/event-stream",...r&&{"Last-Event-ID":r}},method:"GET",fetch:async(a,s)=>{let c=await fetch(a,s);return this.processResponseHeaders(c.headers),c}});try{for await(let{data:a,event:s,id:c}of i){if(a&&s==="activity")try{let d=xt.Activity.fromJson(a),f={activity:d,eventId:c};n.actions.eventReceivedFromCopilot(f),q.debug(`Received activity via subscription, event ID: ${c}`),this.logDiagnostic("Subscribe event received:",{eventId:c,activityType:d.type}),yield f}catch(d){q.error("Failed to parse activity in subscription:",d)}else if(s==="end"){q.debug("Subscription stream complete");break}if(i.readyState==="closed"){q.debug("Subscription connection closed");break}}}finally{i.close()}}catch(o){throw n.fail(o)}finally{n.end()}}};Be.conversationIdHeaderKey="x-ms-conversationid",Be.islandExperimentalUrlHeaderKey="x-ms-d2e-experimental",Be.scopeFromSettings=po.getScopeFromSettings;var nd=Be;var G=[];for(let e=0;e<256;++e)G.push((e+256).toString(16).slice(1));function od(e,t=0){return(G[e[t+0]]+G[e[t+1]]+G[e[t+2]]+G[e[t+3]]+"-"+G[e[t+4]]+G[e[t+5]]+"-"+G[e[t+6]]+G[e[t+7]]+"-"+G[e[t+8]]+G[e[t+9]]+"-"+G[e[t+10]]+G[e[t+11]]+G[e[t+12]]+G[e[t+13]]+G[e[t+14]]+G[e[t+15]]).toLowerCase()}var ma,Qh=new Uint8Array(16);function ha(){if(!ma){if(typeof crypto=="undefined"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");ma=crypto.getRandomValues.bind(crypto)}return ma(Qh)}var eg=typeof crypto!="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),ga={randomUUID:eg};function tg(e,t,r){var o,i,a;if(ga.randomUUID&&!t&&!e)return ga.randomUUID();e=e||{};let n=(a=(i=e.random)!=null?i:(o=e.rng)==null?void 0:o.call(e))!=null?a:ha();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){if(r=r||0,r<0||r+16>t.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let s=0;s<16;++s)t[r+s]=n[s];return t}return od(n)}var ya=tg;var _d=De(uo());var va=function(e,t){return va=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])},va(e,t)};function We(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");va(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}function Gr(e){var t=typeof Symbol=="function"&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function nr(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,i=[],a;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i}function or(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,i;n<o;n++)(i||!(n in t))&&(i||(i=Array.prototype.slice.call(t,0,n)),i[n]=t[n]);return e.concat(i||Array.prototype.slice.call(t))}function le(e){return typeof e=="function"}function mo(e){var t=function(n){Error.call(n),n.stack=new Error().stack},r=e(t);return r.prototype=Object.create(Error.prototype),r.prototype.constructor=r,r}var ho=mo(function(e){return function(r){e(this),this.message=r?r.length+` errors occurred during unsubscription:
|
|
5
|
+
`&&n++}}return[t,r]}var Na="connecting",Nd="open",Co="closed",Wr=()=>{};function jd(e,{getStream:t}){let r=typeof e=="string"||e instanceof URL?{url:e}:e,{onMessage:n,onComment:o=Wr,onConnect:i=Wr,onDisconnect:a=Wr,onScheduleReconnect:s=Wr}=r,{fetch:c,url:d,initialLastEventId:f}=kd(r),g={...r.headers},_=[],I=n?[n]:[],P=M=>I.forEach(he=>he(M)),y=Ra({onEvent:Td,onRetry:xd,onComment:o}),S,T=d.toString(),N=new AbortController,O=f,k=2e3,V,L=Co;return Se(),{close:ie,connect:Se,[Symbol.iterator]:()=>{throw new Error("EventSource does not support synchronous iteration. Use `for await` instead.")},[Symbol.asyncIterator]:ur,get lastEventId(){return O},get url(){return T},get readyState(){return L}};function Se(){S||(L=Na,N=new AbortController,S=c(d,Cd()).then(bd).catch(M=>{S=null,!(M.name==="AbortError"||M.type==="aborted"||N.signal.aborted)&&Aa()}))}function ie(){L=Co,N.abort(),y.reset(),clearTimeout(V),_.forEach(M=>M())}function ur(){let M=[],he=[];function dr(){return new Promise(J=>{let ge=he.shift();ge?J({value:ge,done:!1}):M.push(J)})}let It=function(J){let ge=M.shift();ge?ge({value:J,done:!1}):he.push(J)};function Ke(){for(I.splice(I.indexOf(It),1);M.shift(););for(;he.shift(););}function lr(){let J=M.shift();J&&(J({done:!0,value:void 0}),Ke())}return _.push(lr),I.push(It),{next(){return L===Co?this.return():dr()},return(){return Ke(),Promise.resolve({done:!0,value:void 0})},throw(J){return Ke(),Promise.reject(J)},[Symbol.asyncIterator](){return this}}}function Aa(){s({delay:k}),!N.signal.aborted&&(L=Na,V=setTimeout(Se,k))}async function bd(M){i(),y.reset();let{body:he,redirected:dr,status:It}=M;if(It===204){a(),ie();return}if(!he)throw new Error("Missing response body");dr&&(T=M.url);let Ke=t(he),lr=new TextDecoder,J=Ke.getReader(),ge=!0;L=Nd;do{let{done:wa,value:Oa}=await J.read();Oa&&y.feed(lr.decode(Oa,{stream:!wa})),wa&&(ge=!1,S=null,y.reset(),Aa(),a())}while(ge)}function Td(M){typeof M.id=="string"&&(O=M.id),P(M)}function xd(M){k=M}function Cd(){let{mode:M,credentials:he,body:dr,method:It,redirect:Ke,referrer:lr,referrerPolicy:J}=r,ge={Accept:"text/event-stream",...g,...O?{"Last-Event-ID":O}:void 0};return{mode:M,credentials:he,body:dr,method:It,redirect:Ke,referrer:lr,referrerPolicy:J,headers:ge,cache:"no-store",signal:N.signal}}}function kd(e){let t=e.fetch||globalThis.fetch;if(!Ud(t))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}=e;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:t,url:r,initialLastEventId:n}}function Ud(e){return typeof e=="function"}var Dd={getStream:Zd};function Io(e){return jd(e,Dd)}function Zd(e){if(!(e instanceof ReadableStream))throw new Error("Invalid stream, expected a web ReadableStream");return e}var yc=De(Ut());var On=class{constructor(t){this.API_VERSION="2022-03-01-preview";let r="schema"in t?t.schema:t.identifier,n=t.host;this.baseURL=new URL(`/copilotstudio/prebuilt/authenticated/bots/${r}`,n),this.baseURL.searchParams.append("api-version",this.API_VERSION)}getConversationUrl(t){let r=new URL(this.baseURL.href);return r.pathname=`${r.pathname}/conversations`,t&&(r.pathname=`${r.pathname}/${t}`),r.href}};var Pn=class{constructor(t){this.API_VERSION="2022-03-01-preview";let{schema:r,host:n}=t;this.baseURL=new URL(`/copilotstudio/dataverse-backed/authenticated/bots/${r}`,n),this.baseURL.searchParams.append("api-version",this.API_VERSION)}getConversationUrl(t){let r=new URL(this.baseURL.href);return r.pathname=`${r.pathname}/conversations`,t&&(r.pathname=`${r.pathname}/${t}`),r.href}};var Dt=(0,yc.debug)("copilot-studio:power-platform");function Ar(e,t){var c,d,f,g,_,I,P,y;let r=((c=e.schemaName)==null?void 0:c.trim())||((d=e.agentIdentifier)==null?void 0:d.trim());if(!((f=e.directConnectUrl)!=null&&f.trim())&&(!((g=e.environmentId)!=null&&g.trim())||!(r!=null&&r.trim())))throw new Error("Either directConnectUrl OR both environmentId and schemaName/agentIdentifier must be provided");if((_=e.directConnectUrl)!=null&&_.trim()){if(Dt.debug(`Using direct connection: ${e.directConnectUrl}`),!Sr(e.directConnectUrl))throw new Error("directConnectUrl must be a valid URL");return Ef(e.directConnectUrl,t).href}let n=(I=e.cloud)!=null?I:"Prod",o=(P=e.copilotAgentType)!=null?P:"Published";if(Dt.debug(`Using cloud setting: ${n}`),Dt.debug(`Using agent type: ${o}`),n==="Other")if((y=e.customPowerPlatformCloud)!=null&&y.trim())if(Sr(e.customPowerPlatformCloud))Dt.debug(`Using custom Power Platform cloud: ${e.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=Sf(n,e.environmentId,e.customPowerPlatformCloud),s={Published:()=>new Pn({host:i,schema:r}),Prebuilt:()=>new On({host:i,schema:r})}[o]().getConversationUrl(t);return Dt.debug(`Generated Copilot Studio connection URL: ${s}`),s}function vc(e,t){if(!t||!t.trim())throw new Error("conversationId is required for subscribe URL");let r=Ar(e,t),n=new URL(r);n.pathname=n.pathname.endsWith("/")?`${n.pathname}subscribe`:`${n.pathname}/subscribe`;let o=n.href;return Dt.debug(`Generated Copilot Studio subscribe URL: ${o}`),o}function _c(e,t="Unknown",r="",n=""){var o,i;if(!n&&!(e!=null&&e.directConnectUrl)){if(t==="Other"&&!r)throw new Error("cloudBaseAddress must be provided when PowerPlatformCloudCategory is Other");if(!e&&t==="Unknown")throw new Error("Either settings or cloud must be provided");if(e&&e.cloud&&e.cloud!=="Unknown"&&(t=e.cloud),t==="Other")if(r&&Sr(r))t="Other";else if(e!=null&&e.customPowerPlatformCloud&&Sr(e.customPowerPlatformCloud))t="Other",r=e.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://${Rn(t,r)}/.default`}else if(n||(n=(o=e==null?void 0:e.directConnectUrl)!=null?o:""),n&&Sr(n)){if(gc(new URL(n))==="Unknown"){let a=(i=e==null?void 0:e.cloud)!=null?i:t;if(a==="Other"||a==="Unknown")throw new Error("Unable to resolve the PowerPlatform Cloud from DirectConnectUrl. The Token Audience resolver requires a specific PowerPlatformCloudCategory.");if(a!=="Unknown")return`https://${Rn(a,"")}/.default`;throw new Error("Unable to resolve the PowerPlatform Cloud from DirectConnectUrl. The Token Audience resolver requires a specific PowerPlatformCloudCategory.")}return`https://${Rn(gc(new URL(n)),"")}/.default`}else throw new Error("DirectConnectUrl must be provided when DirectConnectUrl is set")}function Sr(e){try{let t=e.startsWith("http")?e:`https://${e}`;return!!new URL(t)}catch{return!1}}function Ef(e,t){let r=new URL(e);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`,t&&(r.pathname=`${r.pathname}/${t}`),r}function Sf(e,t,r){if(e==="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=t.toLowerCase().replaceAll("-",""),o=Af(e),i=n.substring(0,n.length-o),a=n.substring(n.length-o);return new URL(`https://${i}.${a}.environment.${Rn(e,r)}`)}function Rn(e,t){switch(e){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 t;default:throw new Error(`Invalid cluster category value: ${e}`)}}function Af(e){switch(e){case"FirstRelease":case"Prod":return 2;default:return 1}}function gc(e){switch(e.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 xt=De(uo());var zr=class{constructor(t,r){this.activity=t,this.conversationId=r}};var He=De(Ut());var lo="1.6.0-beta.8.g226709c215";var fo={};var Fr=class{static getProductInfo(){let t=`CopilotStudioClient.agents-sdk-js/${lo}`,r;return typeof window!="undefined"&&window.navigator?r=`${t} ${navigator.userAgent}`:r=`${t} nodejs/${process.version} ${fo.platform()}-${fo.arch()}/${fo.release()}`,r}static getVersionString(){return`CopilotStudioClient.agents-sdk-js/${lo}`}static getVersion(){return lo}};var po=class{static getScopeFromSettings(t){return _c(t)}};function td(e,t){return{activities:e,conversationId:t,isNewConversation:!0}}function rd(e,t){return{activities:e,conversationId:t,activityCount:e.length}}var Z=De(Ut()),X={activitiesReceivedCounter:Z.metric.counter(Z.MetricNames.CSC_ACTIVITIES_RECEIVED,{unit:"activities",description:"Total number of activities received by the Copilot Studio client"}),activitiesSentCounter:Z.metric.counter(Z.MetricNames.CSC_ACTIVITIES_SENT,{unit:"activities",description:"Total number of activities sent to Copilot Studio"}),conversationsStartedCounter:Z.metric.counter(Z.MetricNames.CSC_CONVERSATIONS_STARTED,{unit:"conversations",description:"Total number of conversations started with Copilot Studio"}),webchatConnectionsCounter:Z.metric.counter(Z.MetricNames.CSC_WEBCHAT_CONNECTIONS,{unit:"connections",description:"Total number of webchat connections created with Copilot Studio"}),requestsCounter:Z.metric.counter(Z.MetricNames.CSC_REQUEST_COUNT,{unit:"requests",description:"Total number of HTTP/SSE requests made to Copilot Studio"}),requestsErrorCounter:Z.metric.counter(Z.MetricNames.CSC_REQUEST_ERRORS,{unit:"requests",description:"Total number of failed requests to Copilot Studio"}),executeStreamingCounter:Z.metric.counter(Z.MetricNames.CSC_EXECUTE_STREAMING,{unit:"operations",description:"Total number of execute streaming operations"}),subscribeAsyncCounter:Z.metric.counter(Z.MetricNames.CSC_SUBSCRIBE_ASYNC,{unit:"operations",description:"Total number of subscribeAsync operations"}),subscribeEventCounter:Z.metric.counter(Z.MetricNames.CSC_SUBSCRIBE_EVENT,{unit:"events",description:"Total number of events received via subscribeAsync"}),streamDuration:Z.metric.histogram(Z.MetricNames.CSC_STREAM_DURATION,{unit:"ms",description:"Duration of SSE stream sessions in milliseconds"}),requestDuration:Z.metric.histogram(Z.MetricNames.CSC_REQUEST_DURATION,{unit:"ms",description:"Duration of requests to Copilot Studio in milliseconds"})};var pa=De(uo()),re=De(Ut());var $e={createConnection:re.trace.define({name:re.SpanNames.COPILOT_CREATE_CONNECTION,record:{showTyping:!1},actions:({span:e})=>({receivedFromCopilot(t){var r,n,o;e.addEvent("activity.received.from.copilot.studio",{"copilot.webchat.activity.type":(r=t.type)!=null?r:"unknown","copilot.webchat.activity.conversation_id":(o=(n=t.conversation)==null?void 0:n.id)!=null?o:"unknown"})},sentToWebChat(t){var r,n,o;e.addEvent("activity.sent.to.webchat",{"copilot.webchat.activity.type":(r=t.type)!=null?r:"unknown","copilot.webchat.activity.conversation_id":(o=(n=t.conversation)==null?void 0:n.id)!=null?o:"unknown"})}}),end({span:e,record:t}){var n;let r={"copilot.webchat.show_typing":(n=t.showTyping)!=null?n:"unknown"};e.setAttributes(r),X.webchatConnectionsCounter.add(1,r)}}),postRequest:re.trace.define({name:re.SpanNames.COPILOT_POST_REQUEST,record:{url:"",method:""},actions:({span:e})=>({receivedFromCopilot(t){var n,o,i;let r={"copilot.activity.type":(n=t.type)!=null?n:"unknown","copilot.activity.conversation_id":(i=(o=t.conversation)==null?void 0:o.id)!=null?i:"unknown"};e.addEvent("activity.received",{"copilot.post_request.activity.type":r["copilot.activity.type"],"copilot.post_request.activity.conversation_id":r["copilot.activity.conversation_id"]}),X.activitiesReceivedCounter.add(1,r)}}),end({span:e,record:t,duration:r,error:n}){var a,s;let o={"copilot.post_request.url":(a=t.url)!=null?a:"unknown","copilot.post_request.method":(s=t.method)!=null?s:"unknown"},i={operation:"postRequestAsync","copilot.post_request.url":o["copilot.post_request.url"],"copilot.post_request.method":o["copilot.post_request.method"]};e.setAttributes(o),X.requestsCounter.add(1,i),X.streamDuration.record(r,i),n&&X.requestsErrorCounter.add(1,{...i,"error.type":n instanceof Error?n.name:typeof n})}}),startConversation:re.trace.define({name:re.SpanNames.COPILOT_START_CONVERSATION,record:{shouldEmitStartEvent:!1},end({span:e,record:t,duration:r}){let n=t.shouldEmitStartEvent?{"copilot.emit_start_event":!0}:{"copilot.request":!0},o={operation:"startConversationStreaming",...n};e.setAttributes(n),X.conversationsStartedCounter.add(1,o),X.requestDuration.record(r,o)}}),sendActivity:re.trace.define({name:re.SpanNames.COPILOT_SEND_ACTIVITY,record:{activity:pa.Activity.fromObject({type:"unknown"})},end({span:e,record:t,duration:r}){var i,a,s;let n={"copilot.activity.type":(i=t.activity.type)!=null?i:"unknown","copilot.activity.conversation_id":(s=(a=t.activity.conversation)==null?void 0:a.id)!=null?s:"unknown"},o={operation:"sendActivityStreaming",...n};e.setAttributes(n),X.activitiesSentCounter.add(1,n),X.requestDuration.record(r,o)}}),executeStreaming:re.trace.define({name:re.SpanNames.COPILOT_EXECUTE_STREAMING,record:{activity:pa.Activity.fromObject({type:"unknown"}),conversationId:"unknown"},end({span:e,record:t,duration:r}){var i,a;let n={"copilot.activity.type":(i=t.activity.type)!=null?i:"unknown","copilot.activity.conversation_id":(a=t.conversationId)!=null?a:"unknown"},o={operation:"executeStreaming",...n};e.setAttributes(n),X.executeStreamingCounter.add(1,n),X.requestDuration.record(r,o)}}),subscribeAsync:re.trace.define({name:re.SpanNames.COPILOT_SUBSCRIBE_ASYNC,record:{conversationId:"unknown",lastReceivedEventId:"unknown"},actions:({span:e})=>({eventReceivedFromCopilot(t){var n,o;let r={"copilot.subscribe_async.event.id":(n=t.eventId)!=null?n:"unknown","copilot.subscribe_async.event.activity.type":(o=t.activity.type)!=null?o:"unknown"};e.addEvent("event.received",r),X.subscribeEventCounter.add(1,r)}}),end({span:e,record:t,duration:r}){var i,a;let n={"copilot.subscribe_async.conversation_id":(i=t.conversationId)!=null?i:"unknown","copilot.subscribe_async.last_received_event_id":(a=t.lastReceivedEventId)!=null?a:"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"]};e.setAttributes(n),X.subscribeAsyncCounter.add(1,o),X.streamDuration.record(r,o)}})};var q=(0,He.debug)("copilot-studio:client"),Be=class Be{constructor(t,r){this.conversationId="";this.settings=t,this.token=r}logDiagnostic(t,...r){this.settings.enableDiagnostics&&q.info(`[DIAGNOSTICS] ${t}`,...r)}async*postRequestAsync(t,r,n="POST"){var i,a,s,c,d,f,g,_,I,P;let o=(0,He.trace)($e.postRequest);o.record({url:t,method:n});try{this.logDiagnostic(`Request URL: ${t}`),this.logDiagnostic(`Request Method: ${n}`),this.logDiagnostic("Request Body:",r?JSON.stringify(r,null,2):"none"),q.debug(`>>> SEND TO ${t}`);let y=new Map,S=Io({url:t,headers:{Authorization:`Bearer ${this.token}`,"User-Agent":Fr.getProductInfo(),"Content-Type":"application/json",Accept:"text/event-stream"},body:r?JSON.stringify(r):void 0,method:n,fetch:async(T,N)=>{let O=await fetch(T,N);return this.processResponseHeaders(O.headers),O}});try{for await(let{data:T,event:N}of S){if(T&&N==="activity")try{let O=xt.Activity.fromJson(T);o.actions.receivedFromCopilot(O);let k=(i=O.entities)==null?void 0:i.find(V=>V.type==="streaminfo"&&V.streamType==="streaming");switch(O.type){case xt.ActivityTypes.Message:this.conversationId.trim()||(this.conversationId=(s=(a=O.conversation)==null?void 0:a.id)!=null?s:"",q.debug(`Conversation ID: ${this.conversationId}`)),yield O;break;case xt.ActivityTypes.Typing:if(q.debug(`Activity type: ${O.type}`),k||((c=O.channelData)==null?void 0:c.streamType)==="streaming"){let V=(d=O.text)!=null?d:"",L=(g=k==null?void 0:k.streamId)!=null?g:(f=O.channelData)==null?void 0:f.streamId,Se=(I=k==null?void 0:k.streamSequence)!=null?I:(_=O.channelData)==null?void 0:_.streamSequence;if(L&&Se){if(y.has(L)){let ie=y.get(L);ie.push({text:V,sequence:Se}),y.set(L,ie)}else y.set(L,[{text:V,sequence:Se}]);O.text=((P=y.get(L))==null?void 0:P.sort((ie,ur)=>ie.sequence-ur.sequence).map(ie=>ie.text).join(""))||""}}yield O;break;default:q.debug(`Activity type: ${O.type}`),yield O;break}}catch(O){q.error("Failed to parse activity:",O)}else if(N==="end"){q.debug("Stream complete");break}if(S.readyState==="closed"){q.debug("Connection closed");break}}}finally{S.close()}}catch(y){throw o.fail(y)}finally{o.end()}}processResponseHeaders(t){var n,o;if(this.settings.useExperimentalEndpoint&&!((n=this.settings.directConnectUrl)!=null&&n.trim())){let i=t==null?void 0:t.get(Be.islandExperimentalUrlHeaderKey);i&&(this.settings.directConnectUrl=i,q.debug(`Island Experimental URL: ${i}`))}this.conversationId=(o=t==null?void 0:t.get(Be.conversationIdHeaderKey))!=null?o:"",this.conversationId&&q.debug(`Conversation ID: ${this.conversationId}`);let r=new Headers;t.forEach((i,a)=>{a.toLowerCase()!=="authorization"&&a.toLowerCase()!==Be.conversationIdHeaderKey.toLowerCase()&&r.set(a,i)}),this.logDiagnostic("Response Headers:",r)}async*startConversationStreaming(t){var n,o;let r=(0,He.trace)($e.startConversation);try{let i;typeof t=="boolean"||t===void 0?(r.record({shouldEmitStartEvent:t!=null?t:!0}),i={emitStartConversationEvent:t!=null?t:!0}):(i=t,r.record({shouldEmitStartEvent:(n=i.emitStartConversationEvent)!=null?n:!0}));let a=Ar(this.settings,i.conversationId),s={emitStartConversationEvent:(o=i.emitStartConversationEvent)!=null?o:!0};i.locale&&(s.locale=i.locale),q.info("Starting conversation ...",i),this.logDiagnostic("Start conversation request:",s),yield*this.postRequestAsync(a,s,"POST")}catch(i){throw r.fail(i)}finally{r.end()}}async*sendActivityStreaming(t,r=this.conversationId){var o,i;let n=(0,He.trace)($e.sendActivity);n.record({activity:t});try{let a=(i=(o=t.conversation)==null?void 0:o.id)!=null?i:r,s=Ar(this.settings,a),c=new zr(t);q.info("Sending activity...",t),yield*this.postRequestAsync(s,c,"POST")}catch(a){throw n.fail(a)}finally{n.end()}}async*executeStreaming(t,r){let n=(0,He.trace)($e.executeStreaming);n.record({activity:t,conversationId:r});try{if(!r||!r.trim())throw new Error("conversationId is required for executeStreaming");let o=Ar(this.settings,r),i=new zr(t,r);q.info("Executing turn with conversation ID:",r),this.logDiagnostic("Execute turn request:",{conversationId:r,activityType:t.type,activityText:t.text}),yield*this.postRequestAsync(o,i,"POST")}catch(o){throw n.fail(o)}finally{n.end()}}async execute(t,r){let n=[];for await(let o of this.executeStreaming(t,r))n.push(o);return n}async startConversationAsync(t){let r=[];for await(let n of this.startConversationStreaming(t))r.push(n);return r}async askQuestionAsync(t,r){let o={id:r!=null&&r.trim()?r:this.conversationId},i={type:"message",text:t,conversation:o},a=xt.Activity.fromObject(i),s=[];for await(let c of this.sendActivityStreaming(a,r))s.push(c);return s}async sendActivity(t,r=this.conversationId){let n=[];for await(let o of this.sendActivityStreaming(t,r))n.push(o);return n}async startConversationWithResponse(t){var o;let r=[],n="";for await(let i of this.startConversationStreaming(t))r.push(i),(o=i.conversation)!=null&&o.id&&(n=i.conversation.id);return n=n||this.conversationId,td(r,n)}async executeWithResponse(t,r){let n=[];for await(let o of this.executeStreaming(t,r))n.push(o);return rd(n,r)}async*subscribeAsync(t,r){let n=(0,He.trace)($e.subscribeAsync);n.record({conversationId:t,lastReceivedEventId:r});try{if(!t||!t.trim())throw new Error("conversationId is required for subscribeAsync");let o=vc(this.settings,t);q.info("Subscribing to conversation:",t),this.logDiagnostic("Subscribe request:",{conversationId:t,lastReceivedEventId:r,url:o});let i=Io({url:o,headers:{Authorization:`Bearer ${this.token}`,"User-Agent":Fr.getProductInfo(),Accept:"text/event-stream",...r&&{"Last-Event-ID":r}},method:"GET",fetch:async(a,s)=>{let c=await fetch(a,s);return this.processResponseHeaders(c.headers),c}});try{for await(let{data:a,event:s,id:c}of i){if(a&&s==="activity")try{let d=xt.Activity.fromJson(a),f={activity:d,eventId:c};n.actions.eventReceivedFromCopilot(f),q.debug(`Received activity via subscription, event ID: ${c}`),this.logDiagnostic("Subscribe event received:",{eventId:c,activityType:d.type}),yield f}catch(d){q.error("Failed to parse activity in subscription:",d)}else if(s==="end"){q.debug("Subscription stream complete");break}if(i.readyState==="closed"){q.debug("Subscription connection closed");break}}}finally{i.close()}}catch(o){throw n.fail(o)}finally{n.end()}}};Be.conversationIdHeaderKey="x-ms-conversationid",Be.islandExperimentalUrlHeaderKey="x-ms-d2e-experimental",Be.scopeFromSettings=po.getScopeFromSettings;var nd=Be;var G=[];for(let e=0;e<256;++e)G.push((e+256).toString(16).slice(1));function od(e,t=0){return(G[e[t+0]]+G[e[t+1]]+G[e[t+2]]+G[e[t+3]]+"-"+G[e[t+4]]+G[e[t+5]]+"-"+G[e[t+6]]+G[e[t+7]]+"-"+G[e[t+8]]+G[e[t+9]]+"-"+G[e[t+10]]+G[e[t+11]]+G[e[t+12]]+G[e[t+13]]+G[e[t+14]]+G[e[t+15]]).toLowerCase()}var ma,Qh=new Uint8Array(16);function ha(){if(!ma){if(typeof crypto=="undefined"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");ma=crypto.getRandomValues.bind(crypto)}return ma(Qh)}var eg=typeof crypto!="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),ga={randomUUID:eg};function tg(e,t,r){var o,i,a;if(ga.randomUUID&&!t&&!e)return ga.randomUUID();e=e||{};let n=(a=(i=e.random)!=null?i:(o=e.rng)==null?void 0:o.call(e))!=null?a:ha();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){if(r=r||0,r<0||r+16>t.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let s=0;s<16;++s)t[r+s]=n[s];return t}return od(n)}var ya=tg;var _d=De(uo());var va=function(e,t){return va=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])},va(e,t)};function We(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");va(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}function Gr(e){var t=typeof Symbol=="function"&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function nr(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,i=[],a;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i}function or(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,i;n<o;n++)(i||!(n in t))&&(i||(i=Array.prototype.slice.call(t,0,n)),i[n]=t[n]);return e.concat(i||Array.prototype.slice.call(t))}function le(e){return typeof e=="function"}function mo(e){var t=function(n){Error.call(n),n.stack=new Error().stack},r=e(t);return r.prototype=Object.create(Error.prototype),r.prototype.constructor=r,r}var ho=mo(function(e){return function(r){e(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 $r(e,t){if(e){var r=e.indexOf(t);0<=r&&e.splice(r,1)}}var ir=(function(){function e(t){this.initialTeardown=t,this.closed=!1,this._parentage=null,this._finalizers=null}return e.prototype.unsubscribe=function(){var t,r,n,o,i;if(!this.closed){this.closed=!0;var a=this._parentage;if(a)if(this._parentage=null,Array.isArray(a))try{for(var s=Gr(a),c=s.next();!c.done;c=s.next()){var d=c.value;d.remove(this)}}catch(y){t={error:y}}finally{try{c&&!c.done&&(r=s.return)&&r.call(s)}finally{if(t)throw t.error}}else a.remove(this);var f=this.initialTeardown;if(le(f))try{f()}catch(y){i=y instanceof ho?y.errors:[y]}var g=this._finalizers;if(g){this._finalizers=null;try{for(var _=Gr(g),I=_.next();!I.done;I=_.next()){var P=I.value;try{id(P)}catch(y){i=i!=null?i:[],y instanceof ho?i=or(or([],nr(i)),nr(y.errors)):i.push(y)}}}catch(y){n={error:y}}finally{try{I&&!I.done&&(o=_.return)&&o.call(_)}finally{if(n)throw n.error}}}if(i)throw new ho(i)}},e.prototype.add=function(t){var r;if(t&&t!==this)if(this.closed)id(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=(r=this._finalizers)!==null&&r!==void 0?r:[]).push(t)}},e.prototype._hasParent=function(t){var r=this._parentage;return r===t||Array.isArray(r)&&r.includes(t)},e.prototype._addParent=function(t){var r=this._parentage;this._parentage=Array.isArray(r)?(r.push(t),r):r?[r,t]:t},e.prototype._removeParent=function(t){var r=this._parentage;r===t?this._parentage=null:Array.isArray(r)&&$r(r,t)},e.prototype.remove=function(t){var r=this._finalizers;r&&$r(r,t),t instanceof e&&t._removeParent(this)},e.EMPTY=(function(){var t=new e;return t.closed=!0,t})(),e})();var _a=ir.EMPTY;function go(e){return e instanceof ir||e&&"closed"in e&&le(e.remove)&&le(e.add)&&le(e.unsubscribe)}function id(e){le(e)?e():e.unsubscribe()}var me={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var ar={setTimeout:function(e,t){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];var o=ar.delegate;return o!=null&&o.setTimeout?o.setTimeout.apply(o,or([e,t],nr(r))):setTimeout.apply(void 0,or([e,t],nr(r)))},clearTimeout:function(e){var t=ar.delegate;return((t==null?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function ad(e){ar.setTimeout(function(){var t=me.onUnhandledError;if(t)t(e);else throw e})}function ba(){}var sd=(function(){return Ta("C",void 0,void 0)})();function cd(e){return Ta("E",void 0,e)}function ud(e){return Ta("N",e,void 0)}function Ta(e,t,r){return{kind:e,value:t,error:r}}var Ct=null;function sr(e){if(me.useDeprecatedSynchronousErrorHandling){var t=!Ct;if(t&&(Ct={errorThrown:!1,error:null}),e(),t){var r=Ct,n=r.errorThrown,o=r.error;if(Ct=null,n)throw o}}else e()}function dd(e){me.useDeprecatedSynchronousErrorHandling&&Ct&&(Ct.errorThrown=!0,Ct.error=e)}var Ia=(function(e){We(t,e);function t(r){var n=e.call(this)||this;return n.isStopped=!1,r?(n.destination=r,go(r)&&r.add(n)):n.destination=ig,n}return t.create=function(r,n,o){return new vo(r,n,o)},t.prototype.next=function(r){this.isStopped?Ca(ud(r),this):this._next(r)},t.prototype.error=function(r){this.isStopped?Ca(cd(r),this):(this.isStopped=!0,this._error(r))},t.prototype.complete=function(){this.isStopped?Ca(sd,this):(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(r){this.destination.next(r)},t.prototype._error=function(r){try{this.destination.error(r)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t})(ir);var rg=Function.prototype.bind;function xa(e,t){return rg.call(e,t)}var ng=(function(){function e(t){this.partialObserver=t}return e.prototype.next=function(t){var r=this.partialObserver;if(r.next)try{r.next(t)}catch(n){yo(n)}},e.prototype.error=function(t){var r=this.partialObserver;if(r.error)try{r.error(t)}catch(n){yo(n)}else yo(t)},e.prototype.complete=function(){var t=this.partialObserver;if(t.complete)try{t.complete()}catch(r){yo(r)}},e})(),vo=(function(e){We(t,e);function t(r,n,o){var i=e.call(this)||this,a;if(le(r)||!r)a={next:r!=null?r:void 0,error:n!=null?n:void 0,complete:o!=null?o:void 0};else{var s;i&&me.useDeprecatedNextContext?(s=Object.create(r),s.unsubscribe=function(){return i.unsubscribe()},a={next:r.next&&xa(r.next,s),error:r.error&&xa(r.error,s),complete:r.complete&&xa(r.complete,s)}):a=r}return i.destination=new ng(a),i}return t})(Ia);function yo(e){me.useDeprecatedSynchronousErrorHandling?dd(e):ad(e)}function og(e){throw e}function Ca(e,t){var r=me.onStoppedNotification;r&&ar.setTimeout(function(){return r(e,t)})}var ig={closed:!0,next:ba,error:og,complete:ba};var ld=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function fd(e){return e}function pd(e){return e.length===0?fd:e.length===1?e[0]:function(r){return e.reduce(function(n,o){return o(n)},r)}}var cr=(function(){function e(t){t&&(this._subscribe=t)}return e.prototype.lift=function(t){var r=new e;return r.source=this,r.operator=t,r},e.prototype.subscribe=function(t,r,n){var o=this,i=sg(t)?t:new vo(t,r,n);return sr(function(){var a=o,s=a.operator,c=a.source;i.add(s?s.call(i,c):c?o._subscribe(i):o._trySubscribe(i))}),i},e.prototype._trySubscribe=function(t){try{return this._subscribe(t)}catch(r){t.error(r)}},e.prototype.forEach=function(t,r){var n=this;return r=md(r),new r(function(o,i){var a=new vo({next:function(s){try{t(s)}catch(c){i(c),a.unsubscribe()}},error:i,complete:o});n.subscribe(a)})},e.prototype._subscribe=function(t){var r;return(r=this.source)===null||r===void 0?void 0:r.subscribe(t)},e.prototype[ld]=function(){return this},e.prototype.pipe=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return pd(t)(this)},e.prototype.toPromise=function(t){var r=this;return t=md(t),new t(function(n,o){var i;r.subscribe(function(a){return i=a},function(a){return o(a)},function(){return n(i)})})},e.create=function(t){return new e(t)},e})();function md(e){var t;return(t=e!=null?e:me.Promise)!==null&&t!==void 0?t:Promise}function ag(e){return e&&le(e.next)&&le(e.error)&&le(e.complete)}function sg(e){return e&&e instanceof Ia||ag(e)&&go(e)}var hd=mo(function(e){return function(){e(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}});var Ea=(function(e){We(t,e);function t(){var r=e.call(this)||this;return r.closed=!1,r.currentObservers=null,r.observers=[],r.isStopped=!1,r.hasError=!1,r.thrownError=null,r}return t.prototype.lift=function(r){var n=new gd(this,this);return n.operator=r,n},t.prototype._throwIfClosed=function(){if(this.closed)throw new hd},t.prototype.next=function(r){var n=this;sr(function(){var o,i;if(n._throwIfClosed(),!n.isStopped){n.currentObservers||(n.currentObservers=Array.from(n.observers));try{for(var a=Gr(n.currentObservers),s=a.next();!s.done;s=a.next()){var c=s.value;c.next(r)}}catch(d){o={error:d}}finally{try{s&&!s.done&&(i=a.return)&&i.call(a)}finally{if(o)throw o.error}}}})},t.prototype.error=function(r){var n=this;sr(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)}})},t.prototype.complete=function(){var r=this;sr(function(){if(r._throwIfClosed(),!r.isStopped){r.isStopped=!0;for(var n=r.observers;n.length;)n.shift().complete()}})},t.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(t.prototype,"observed",{get:function(){var r;return((r=this.observers)===null||r===void 0?void 0:r.length)>0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(r){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,r)},t.prototype._subscribe=function(r){return this._throwIfClosed(),this._checkFinalizedStatuses(r),this._innerSubscribe(r)},t.prototype._innerSubscribe=function(r){var n=this,o=this,i=o.hasError,a=o.isStopped,s=o.observers;return i||a?_a:(this.currentObservers=null,s.push(r),new ir(function(){n.currentObservers=null,$r(s,r)}))},t.prototype._checkFinalizedStatuses=function(r){var n=this,o=n.hasError,i=n.thrownError,a=n.isStopped;o?r.error(i):a&&r.complete()},t.prototype.asObservable=function(){var r=new cr;return r.source=this,r},t.create=function(r,n){return new gd(r,n)},t})(cr);var gd=(function(e){We(t,e);function t(r,n){var o=e.call(this)||this;return o.destination=r,o.source=n,o}return t.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)},t.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)},t.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)},t.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:_a},t})(Ea);var Sa=(function(e){We(t,e);function t(r){var n=e.call(this)||this;return n._value=r,n}return Object.defineProperty(t.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),t.prototype._subscribe=function(r){var n=e.prototype._subscribe.call(this,r);return!n.closed&&r.next(this._value),n},t.prototype.getValue=function(){var r=this,n=r.hasError,o=r.thrownError,i=r._value;if(n)throw o;return this._throwIfClosed(),i},t.prototype.next=function(r){e.prototype.next.call(this,this._value=r)},t})(Ea);var _o=De(Ut());var Ue=(0,_o.debug)("copilot-studio:webchat");function cg(e){let t=!1;return r=>{if(!t)return t=!0,e(r)}}var yd=class{static createConnection(t,r){var o;let n=(0,_o.trace)($e.createConnection);n.record({showTyping:r==null?void 0:r.showTyping});try{Ue.info("--> Creating connection between Copilot Studio and WebChat ...");let i=r!=null&&r.conversationId&&r.conversationId.trim()!==""?r.conversationId.trim():void 0,a=(o=r==null?void 0:r.startConversation)!=null?o:!i,s=0,c,d,f=i,g=!1,_=!1,I=new Sa(0),P=vd(async T=>{var N;try{c=T;let O=cg(async()=>{I.next(2),await Promise.resolve()});if(!a||_){await O();return}_=!0,Ue.debug("--> Connection established."),S();for await(let k of t.startConversationStreaming())delete k.replyToId,!d&&k.conversation&&(d=k.conversation),(N=k.conversation)!=null&&N.id&&(f=k.conversation.id),await O(),y(k),n.actions.receivedFromCopilot(k);await O()}catch(O){throw n.fail(O)}finally{n.end()}}),y=T=>{let N={...T,timestamp:new Date().toISOString(),channelData:{...T.channelData,"webchat:sequence-id":s}};s++,Ue.debug(`Notify '${N.type}' activity to WebChat:`,N),c==null||c.next(N)},S=()=>{if(!(r!=null&&r.showTyping))return;let T=d?{id:d.id,name:d.name}:{id:"agent",name:"Agent"};y({type:"typing",from:T})};return{connectionStatus$:I,activity$:P,get conversationId(){return f},postActivity(T){try{if(Ue.info("--> Preparing to send activity to Copilot Studio ..."),!T)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 vd(async O=>{var k;try{Ue.info("--> Sending activity to Copilot Studio ...");let V=_d.Activity.fromObject({...T,id:ya(),attachments:await ug(T)});y(V),n.actions.sentToWebChat(V),S(),O.next(V.id);for await(let L of t.sendActivityStreaming(V,f))!f&&((k=L.conversation)!=null&&k.id)&&(f=L.conversation.id),y(L),n.actions.receivedFromCopilot(L),Ue.info("<-- Activity received correctly from Copilot Studio.");O.complete()}catch(V){Ue.error("Error sending Activity to Copilot Studio:",V),O.error(V),n.fail(V)}finally{n.end()}})}catch(N){throw n.fail(N)}finally{n.end()}},end(){Ue.info("--> Ending connection between Copilot Studio and WebChat ..."),g=!0,I.complete(),c&&(c.complete(),c=void 0),n.end()}}}catch(i){throw n.fail(i)}finally{n.end()}}};async function ug(e){var r;if(e.type!=="message"||!((r=e.attachments)!=null&&r.length))return e.attachments||[];let t=[];for(let n of e.attachments){let o=await dg(n);t.push(o)}return t}async function dg(e){let t=e.contentUrl;if(!(t!=null&&t.startsWith("blob:")))return e;try{let r=await fetch(t);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=lg(o);t=`data:${n.type};base64,${i}`}catch(r){t=e.contentUrl,Ue.error("Error processing blob attachment:",t,r)}return{...e,contentUrl:t}}function lg(e){let t=typeof globalThis.Buffer=="function"?globalThis.Buffer:void 0;if(t&&typeof t.from=="function")return t.from(e).toString("base64");let r="";for(let n of new Uint8Array(e))r+=String.fromCharCode(n);return btoa(r)}function vd(e){return new cr(t=>{Promise.resolve(e(t)).catch(r=>t.error(r))})}function gT(e=!0,t,r){return{emitStartConversationEvent:e,locale:t,conversationId:r}}export{fr as AgentType,To as ConnectionSettings,nd as CopilotStudioClient,yd as CopilotStudioWebChat,zr as ExecuteTurnRequest,pr as PowerPlatformCloud,po as ScopeHelper,Fr as UserAgentHelper,rd as createExecuteTurnResponse,gT as createStartRequest,td as createStartResponse,Ar as getCopilotStudioConnectionUrl,vc as getCopilotStudioSubscribeUrl,_c as getTokenAudience,yg as loadCopilotStudioConnectionSettingsFromEnv};
|
|
8
8
|
//# sourceMappingURL=browser.mjs.map
|