@microsoft/agents-copilotstudio-client 1.5.1 → 1.6.0-beta.2.ga8529bd583
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 +2 -2
- 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.
|
|
3
|
+
"version": "1.6.0-beta.2.ga8529bd583",
|
|
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.
|
|
31
|
-
"@microsoft/agents-telemetry": "1.
|
|
30
|
+
"@microsoft/agents-activity": "1.6.0-beta.2.ga8529bd583",
|
|
31
|
+
"@microsoft/agents-telemetry": "1.6.0-beta.2.ga8529bd583",
|
|
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 Cd=Object.create;var Br=Object.defineProperty;var Id=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:x}));break;default:r(new Hr(`Unknown field "${y.length>20?`${y.slice(0,20)}\u2026`:y}"`,{type:"unknown-field",field:y,value:S,line:x}));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 Pd(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 Ra="connecting",Rd="open",Co="closed",Wr=()=>{};function Nd(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}=jd(r),g={...r.headers},_=[],I=n?[n]:[],P=M=>I.forEach(he=>he(M)),y=Pa({onEvent:bd,onRetry:xd,onComment:o}),S,x=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 x},get readyState(){return L}};function Se(){S||(L=Ra,N=new AbortController,S=c(d,Td()).then(_d).catch(M=>{S=null,!(M.name==="AbortError"||M.type==="aborted"||N.signal.aborted)&&Sa()}))}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 Sa(){s({delay:k}),!N.signal.aborted&&(L=Ra,V=setTimeout(Se,k))}async function _d(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&&(x=M.url);let Ke=t(he),lr=new TextDecoder,J=Ke.getReader(),ge=!0;L=Rd;do{let{done:Aa,value:wa}=await J.read();wa&&y.feed(lr.decode(wa,{stream:!Aa})),Aa&&(ge=!1,S=null,y.reset(),Sa(),a())}while(ge)}function bd(M){typeof M.id=="string"&&(O=M.id),P(M)}function xd(M){k=M}function Td(){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 jd(e){let t=e.fetch||globalThis.fetch;if(!kd(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 kd(e){return typeof e=="function"}var Ud={getStream:Dd};function Io(e){return Nd(e,Ud)}function Dd(e){if(!(e instanceof ReadableStream))throw new Error("Invalid stream, expected a web ReadableStream");return e}var gc=ke(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,gc.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 If(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=Ef(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 yc(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 vc(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(hc(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(hc(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 If(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 Ef(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=Sf(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 Sf(e){switch(e){case"FirstRelease":case"Prod":return 2;default:return 1}}function hc(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 Tt=ke(uo());var zr=class{constructor(t,r){this.activity=t,this.conversationId=r}};var He=ke(Ut());var lo="1.5.1";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 vc(t)}};function ed(e,t){return{activities:e,conversationId:t,isNewConversation:!0}}function td(e,t){return{activities:e,conversationId:t,activityCount:e.length}}var Z=ke(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 fa=ke(uo()),re=ke(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:fa.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:fa.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(x,N)=>{let O=await fetch(x,N);return this.processResponseHeaders(O.headers),O}});try{for await(let{data:x,event:N}of S){if(x&&N==="activity")try{let O=Tt.Activity.fromJson(x);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 Tt.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 Tt.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=Tt.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,ed(r,n)}async executeWithResponse(t,r){let n=[];for await(let o of this.executeStreaming(t,r))n.push(o);return td(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=yc(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=Tt.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 rd=Be;var G=[];for(let e=0;e<256;++e)G.push((e+256).toString(16).slice(1));function nd(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 pa,Jh=new Uint8Array(16);function ma(){if(!pa){if(typeof crypto=="undefined"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");pa=crypto.getRandomValues.bind(crypto)}return pa(Jh)}var Qh=typeof crypto!="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),ha={randomUUID:Qh};function eg(e,t,r){var o,i,a;if(ha.randomUUID&&!t&&!e)return ha.randomUUID();e=e||{};let n=(a=(i=e.random)!=null?i:(o=e.rng)==null?void 0:o.call(e))!=null?a:ma();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 nd(n)}var ga=eg;var vd=ke(uo());var ya=function(e,t){return ya=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])},ya(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");ya(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 Ra="connecting",Rd="open",Co="closed",Wr=()=>{};function Nd(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}=jd(r),g={...r.headers},_=[],I=n?[n]:[],P=M=>I.forEach(he=>he(M)),y=Pa({onEvent:bd,onRetry:xd,onComment:o}),S,x=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 x},get readyState(){return L}};function Se(){S||(L=Ra,N=new AbortController,S=c(d,Td()).then(_d).catch(M=>{S=null,!(M.name==="AbortError"||M.type==="aborted"||N.signal.aborted)&&Sa()}))}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 Sa(){s({delay:k}),!N.signal.aborted&&(L=Ra,V=setTimeout(Se,k))}async function _d(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&&(x=M.url);let Ke=t(he),lr=new TextDecoder,J=Ke.getReader(),ge=!0;L=Rd;do{let{done:Aa,value:wa}=await J.read();wa&&y.feed(lr.decode(wa,{stream:!Aa})),Aa&&(ge=!1,S=null,y.reset(),Sa(),a())}while(ge)}function bd(M){typeof M.id=="string"&&(O=M.id),P(M)}function xd(M){k=M}function Td(){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 jd(e){let t=e.fetch||globalThis.fetch;if(!kd(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 kd(e){return typeof e=="function"}var Ud={getStream:Dd};function Io(e){return Nd(e,Ud)}function Dd(e){if(!(e instanceof ReadableStream))throw new Error("Invalid stream, expected a web ReadableStream");return e}var gc=ke(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,gc.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 If(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=Ef(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 yc(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 vc(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(hc(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(hc(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 If(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 Ef(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=Sf(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 Sf(e){switch(e){case"FirstRelease":case"Prod":return 2;default:return 1}}function hc(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 Tt=ke(uo());var zr=class{constructor(t,r){this.activity=t,this.conversationId=r}};var He=ke(Ut());var lo="1.6.0-beta.2.ga8529bd583";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 vc(t)}};function ed(e,t){return{activities:e,conversationId:t,isNewConversation:!0}}function td(e,t){return{activities:e,conversationId:t,activityCount:e.length}}var Z=ke(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 fa=ke(uo()),re=ke(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:fa.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:fa.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(x,N)=>{let O=await fetch(x,N);return this.processResponseHeaders(O.headers),O}});try{for await(let{data:x,event:N}of S){if(x&&N==="activity")try{let O=Tt.Activity.fromJson(x);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 Tt.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 Tt.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=Tt.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,ed(r,n)}async executeWithResponse(t,r){let n=[];for await(let o of this.executeStreaming(t,r))n.push(o);return td(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=yc(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=Tt.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 rd=Be;var G=[];for(let e=0;e<256;++e)G.push((e+256).toString(16).slice(1));function nd(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 pa,Jh=new Uint8Array(16);function ma(){if(!pa){if(typeof crypto=="undefined"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");pa=crypto.getRandomValues.bind(crypto)}return pa(Jh)}var Qh=typeof crypto!="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),ha={randomUUID:Qh};function eg(e,t,r){var o,i,a;if(ha.randomUUID&&!t&&!e)return ha.randomUUID();e=e||{};let n=(a=(i=e.random)!=null?i:(o=e.rng)==null?void 0:o.call(e))!=null?a:ma();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 nd(n)}var ga=eg;var vd=ke(uo());var ya=function(e,t){return ya=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])},ya(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");ya(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{od(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)od(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 va=ir.EMPTY;function go(e){return e instanceof ir||e&&"closed"in e&&le(e.remove)&&le(e.add)&&le(e.unsubscribe)}function od(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 id(e){ar.setTimeout(function(){var t=me.onUnhandledError;if(t)t(e);else throw e})}function _a(){}var ad=(function(){return ba("C",void 0,void 0)})();function sd(e){return ba("E",void 0,e)}function cd(e){return ba("N",e,void 0)}function ba(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 ud(e){me.useDeprecatedSynchronousErrorHandling&&Ct&&(Ct.errorThrown=!0,Ct.error=e)}var Ca=(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=og,n}return t.create=function(r,n,o){return new vo(r,n,o)},t.prototype.next=function(r){this.isStopped?Ta(cd(r),this):this._next(r)},t.prototype.error=function(r){this.isStopped?Ta(sd(r),this):(this.isStopped=!0,this._error(r))},t.prototype.complete=function(){this.isStopped?Ta(ad,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 tg=Function.prototype.bind;function xa(e,t){return tg.call(e,t)}var rg=(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 rg(a),i}return t})(Ca);function yo(e){me.useDeprecatedSynchronousErrorHandling?ud(e):id(e)}function ng(e){throw e}function Ta(e,t){var r=me.onStoppedNotification;r&&ar.setTimeout(function(){return r(e,t)})}var og={closed:!0,next:_a,error:ng,complete:_a};var dd=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function ld(e){return e}function fd(e){return e.length===0?ld: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=ag(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=pd(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[dd]=function(){return this},e.prototype.pipe=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return fd(t)(this)},e.prototype.toPromise=function(t){var r=this;return t=pd(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 pd(e){var t;return(t=e!=null?e:me.Promise)!==null&&t!==void 0?t:Promise}function ig(e){return e&&le(e.next)&&le(e.error)&&le(e.complete)}function ag(e){return e&&e instanceof Ca||ig(e)&&go(e)}var md=mo(function(e){return function(){e(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}});var Ia=(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 hd(this,this);return n.operator=r,n},t.prototype._throwIfClosed=function(){if(this.closed)throw new md},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?va:(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 hd(r,n)},t})(cr);var hd=(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:va},t})(Ia);var Ea=(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})(Ia);var _o=ke(Ut());var je=(0,_o.debug)("copilot-studio:webchat");function sg(e){let t=!1;return r=>{if(!t)return t=!0,e(r)}}var gd=class{static createConnection(t,r){var o;let n=(0,_o.trace)($e.createConnection);n.record({showTyping:r==null?void 0:r.showTyping});try{je.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 Ea(0),P=yd(async x=>{var N;try{c=x;let O=sg(async()=>{I.next(2),await Promise.resolve()});if(!a||_){await O();return}_=!0,je.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=x=>{let N={...x,timestamp:new Date().toISOString(),channelData:{...x.channelData,"webchat:sequence-id":s}};s++,je.debug(`Notify '${N.type}' activity to WebChat:`,N),c==null||c.next(N)},S=()=>{if(!(r!=null&&r.showTyping))return;let x=d?{id:d.id,name:d.name}:{id:"agent",name:"Agent"};y({type:"typing",from:x})};return{connectionStatus$:I,activity$:P,get conversationId(){return f},postActivity(x){try{if(je.info("--> Preparing to send activity to Copilot Studio ..."),!x)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 yd(async O=>{var k;try{je.info("--> Sending activity to Copilot Studio ...");let V=vd.Activity.fromObject({...x,id:ga(),attachments:await cg(x)});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),je.info("<-- Activity received correctly from Copilot Studio.");O.complete()}catch(V){je.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(){je.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 cg(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 ug(n);t.push(o)}return t}async function ug(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=dg(o);t=`data:${n.type};base64,${i}`}catch(r){t=e.contentUrl,je.error("Error processing blob attachment:",t,r)}return{...e,contentUrl:t}}function dg(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 yd(e){return new cr(t=>{Promise.resolve(e(t)).catch(r=>t.error(r))})}function hx(e=!0,t,r){return{emitStartConversationEvent:e,locale:t,conversationId:r}}export{fr as AgentType,xo as ConnectionSettings,rd as CopilotStudioClient,gd as CopilotStudioWebChat,zr as ExecuteTurnRequest,pr as PowerPlatformCloud,po as ScopeHelper,Fr as UserAgentHelper,td as createExecuteTurnResponse,hx as createStartRequest,ed as createStartResponse,Ar as getCopilotStudioConnectionUrl,yc as getCopilotStudioSubscribeUrl,vc as getTokenAudience,gg as loadCopilotStudioConnectionSettingsFromEnv};
|
|
8
8
|
//# sourceMappingURL=browser.mjs.map
|