forked from github/docs
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathui_packages_copilot-chat_utils_CopilotChatContext_tsx-9409beae5202.js.download
More file actions
16 lines (13 loc) · 109 KB
/
Copy pathui_packages_copilot-chat_utils_CopilotChatContext_tsx-9409beae5202.js.download
File metadata and controls
16 lines (13 loc) · 109 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
"use strict";(globalThis.webpackChunk=globalThis.webpackChunk||[]).push([["ui_packages_copilot-chat_utils_CopilotChatContext_tsx"],{57712:(e,t,s)=>{s.d(t,{Z:()=>a});function a(e){let t;let s=null;return{load:()=>(s||(s=e().then(e=>t=e)),s),read(){if(t)return t;throw this.load()}}}},54807:(e,t,s)=>{s.d(t,{BV:()=>r,My:()=>n,QM:()=>i});var a=s(57572);async function r(e,t,s){let r=await (0,a.DI)(t,{method:"POST",body:o(e),signal:s}),i=await r.json();if(!r.ok)throw new GenericServerError("Error creating policy",i.errors);if(!i.asset_upload_url)throw Error("Unexpected error, missing asset upload URL");return i}async function i(e,t,s){let a=await fetch(t.upload_url,{method:"POST",body:o({...t.form,file:e}),signal:s});if(!a.ok)throw Error(await a.text())}async function n(e,t){let s=await (0,a.DI)(e.asset_upload_url,{method:"PUT",signal:t}),r=await s.json();if(!s.ok)throw new GenericServerError("Error completing the upload",r.errors);return r}let GenericServerError=class GenericServerError extends Error{constructor(e,t){super(e),function(e,t,s){t in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s}(this,"errors",void 0),this.name="GenericServerError",this.errors=t}};function o(e){let t=new FormData;for(let[s,a]of Object.entries(e))t.append(s,a);return t}},22756:(e,t,s)=>{s.d(t,{L:()=>BlackbirdPermissionCaches});var a=s(56176),r=s(57572),i=s(55156);function n(e,t,s){return t in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}let BlackbirdPermissionCaches=class BlackbirdPermissionCaches{async setupWarmCachesLoop(){(0,a.M3)()&&(BlackbirdPermissionCaches.warmCachesLoopSetup?await BlackbirdPermissionCaches.warm:(BlackbirdPermissionCaches.warmCachesLoopSetup=!0,await this.warmCaches()))}async warmCaches(){let e=54e4;try{let t=await (0,r.lS)("/search/warm_blackbird_caches",{headers:{Accept:"application/json",...(0,i.kt)()}}),s=await t.json();e=new Date(s.userCacheExpiresAt).getTime()-Date.now()-3e4,(isNaN(e)||e<=5)&&(e=3e4)}catch{}BlackbirdPermissionCaches.warmResolve(),setTimeout(()=>{this.warmCaches()},e)}};n(BlackbirdPermissionCaches,"warmCachesLoopSetup",!1),n(BlackbirdPermissionCaches,"warmResolve",void 0),n(BlackbirdPermissionCaches,"warm",new Promise(e=>{BlackbirdPermissionCaches.warmResolve=e}))},56244:(e,t,s)=>{function a(e,t,s){return t in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}s.d(t,{d:()=>ApiCache});let ApiCache=class ApiCache{async get(...e){let t=e.join(this.separator),s=this.cache.get(t);if(s)return s;{let s=this.fetchFn(...e);return this.cache.set(t,s),(await s).ok||this.cache.delete(t),s}}constructor(e){a(this,"separator","-!-"),a(this,"cache",new Map),this.fetchFn=e}}},96558:(e,t,s)=>{s.d(t,{Bc:()=>i,Qs:()=>c,fv:()=>n,uN:()=>r,wJ:()=>l,wX:()=>o,wg:()=>a});let a="copilot-chat-textarea",r="copilot-chat-topic-search",i="Review",n="copilot-chat-header-button",o="copilot-diff-header-button",l="copilot-chat-panel",c="copilot-chat-panel"},29664:(e,t,s)=>{s.d(t,{Z:()=>d});var a=s(97665),r=s(97286),i=s(57572),n=s(96540),o=s(77342),l=s(2622);function c(e,t,s){return t in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}function d(e,t,s){let c=(0,a.jE)(),d=(0,n.useCallback)(()=>c.invalidateQueries({queryKey:["copilot-chat","entitlement"]}),[c]),{data:h}=(0,r.I)({queryKey:["copilot-chat","entitlement"],queryFn:async()=>{let e=await (0,i.lS)("/github-copilot/chat/entitlement");if(!e.ok)throw Error(`Failed to retrieve Copilot chat entitlement (${e.status} on ${e.url})`);return await e.json()},enabled:e===o.mF.LicensedLimited||l.W.premiumRequestQuotasEnabled,placeholderData:{licenseType:e,plan:t,quotas:s},staleTime:3e5}),u=h?.licenseType??e,p=h?.plan??t,g=(0,n.useCallback)(()=>{(u===o.mF.LicensedLimited||l.W.premiumRequestQuotasEnabled)&&d()},[d,u]);return[new CopilotChatEntitlement(u,p,h?.quotas),g]}let CopilotChatEntitlement=class CopilotChatEntitlement{isLicensed(){return this.licenseType&&this.licenseType!==o.mF.Unlicensed}canPurchaseAdditionalQuota(){return this.licenseType!==o.mF.LicensedLimited&&l.W.premiumRequestQuotasEnabled&&(this.plan===o.UH.IndividualPro||this.plan===o.UH.IndividualProPlus||this.plan===o.UH.Business||this.plan===o.UH.Enterprise)}canUpgradePlan(){return this.licenseType===o.mF.LicensedLimited||l.W.premiumRequestQuotasEnabled&&(this.plan===o.UH.IndividualPro||this.plan===o.UH.Business)}chatQuotaRemaining(){return l.W.premiumRequestQuotasEnabled?this.quotas?.remaining.chatPercentage??0:this.quotas?.remaining.chat??0}premiumInteractionsQuotaRemaining(){return this.quotas?.remaining.premiumInteractionsPercentage??0}constructor(e,t,s){c(this,"licenseType",void 0),c(this,"plan",void 0),c(this,"quotas",void 0),this.licenseType=e,this.plan=t,this.quotas=s}}},55854:(e,t,s)=>{function a(e,t,s){return t in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}s.d(t,{X:()=>CopilotChatMessageStreamer});let r=/^data:\s+/;let CopilotStreamingError=class CopilotStreamingError extends Error{constructor(e){super(e.description),a(this,"error",void 0),this.error=e,this.name="CopilotStreamingError"}};let CopilotChatMessageStreamer=class CopilotChatMessageStreamer{async *stream(){let e=new TextDecoder("utf-8"),t="";for(;;){let s,a;try{({value:s,done:a}=await this.reader.read())}catch{throw new CopilotStreamingError({type:"error",errorType:"networkError",description:"NETWORK_CONNECTION_INTERRUPTED"})}if(a)break;for(t+=e.decode(s);;){let e=t.indexOf("\n\n");if(-1===e)break;let s=t.slice(0,e).replace(r,"");if("[DONE]"===s)return;let a=JSON.parse(s);if(yield a,a?.type==="complete")return;t=t.slice(e+2)}}}async stop(){return this.reader.cancel()}constructor(e){a(this,"reader",void 0),this.reader=e}}},37404:(e,t,s)=>{s.d(t,{k:()=>CopilotChatService});var a=s(22756),r=s(49339),i=s(5796),n=s(57572),o=s(56244),l=s(82610),c=s(2622),d=s(37937),h=s(76303),u=s(48247),p=s(27297);function g(e,t,s){return t in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}let m=new Set(["snippet","file","symbol","docset","repository"]);let CopilotChatService=class CopilotChatService{async fetchThreads(e={}){let t=new URLSearchParams;"string"==typeof e.name&&t.set("name",e.name);let s=`/threads?${t.toString()}`,a=await this.makeCAPIRequest(s,"GET");if(!a.ok)return a;let r=(await a.json()).threads||[];return{status:a.status,ok:!0,payload:r}}async fetchSharedThreads(){let e=await this.makeCAPIRequest("/threads?shared","GET");if(!e.ok)return e;let t=(await e.json()).threads||[];return{status:e.status,ok:!0,payload:t}}async fetchLatestThread(e){let t=new URLSearchParams;"string"==typeof e&&t.set("thread_id",e);let s=await this.makeCAPIRequest(`/threads/latest?${t.toString()}`,"GET");if(!s.ok)return s;let a=(await s.json()).thread;return{status:s.status,ok:!0,payload:a}}async createThread(e){let t={custom_copilot_id:e?.id,custom_copilot_owner:e?.owner},s=await this.makeCAPIRequest("/threads","POST",t);if(!s.ok)return s;let a=(await s.json()).thread;return{status:s.status,ok:!0,payload:a}}async deleteThread(e){let t=await this.makeCAPIRequest(`/threads/${e}`,"DELETE");return t.ok?{status:t.status,ok:!0,payload:null}:t}async deleteAllThreads(e){let t=await this.makeCAPIRequest("/threads","DELETE",e);return t.ok?{status:t.status,ok:!0,payload:null}:t}async renameThread(e,t){let s=await this.makeCAPIRequest(`/threads/${e}/name`,"PATCH",{generate:!1,name:t});if(!s.ok)return s;let a=(await s.json()).name||"";return{status:s.status,ok:!0,payload:a}}async clearThread(e){let t=await this.makeCAPIRequest(`/threads/${e}/clear`,"PATCH");return t.ok?{status:t.status,ok:!0,payload:null}:t}async shareThread(e,t){let s=await this.makeCAPIRequest(`/threads/${e}/share`,"PATCH",{shared_message_id:t});if(!s.ok)return s;let a=(await s.json()).thread;return{status:s.status,ok:!0,payload:a}}async unshareThread(e){let t=await this.makeCAPIRequest(`/threads/${e}/unshare`,"PATCH");if(!t.ok)return t;let s=(await t.json()).thread;return{status:t.status,ok:!0,payload:s}}async unshareAllThreads(){let e=await this.makeCAPIRequest("/threads/unshare","POST");return e.ok?{status:e.status,ok:!0,payload:null}:e}async continueSharedThread(e){let t=await this.makeCAPIRequest(`/shared/${e}/duplicate`,"POST");return t.ok?{status:200,ok:!0,payload:await t.json()}:t}async generateThreadName(e){let t=await this.makeCAPIRequest(`/threads/${e}/name`,"PATCH",{generate:!0,name:""});if(!t.ok)return t;let s=(await t.json()).name||"";return{status:t.status,ok:!0,payload:s}}async getSystemPrompt(e){let t=await this.makeCAPIRequest(`/system_prompt/${e}`,"GET");if(!t.ok)return t;let s=await t.json();return{status:t.status,ok:!0,payload:s}}async listMessages(e){if(this.listMessagesCache?.thread.id===e)return{status:200,ok:!0,payload:this.listMessagesCache};let t=await this.makeCAPIRequest(`/threads/${e}/messages`,"GET");if(!t.ok){if(!(404===t.status&&t.response?.headers.has("Content-Type"))||"application/json"!==t.response.headers.get("Content-Type"))return t;{let e=await t.response.json();return{...t,payload:e}}}let s=await t.json();return c.W.customCopilots&&Array.isArray(s.messages)&&(s.messages=s.messages.map(e=>(e.references=(0,h.q)(e.references),e))),this.listMessagesCache=s,{status:t.status,ok:!0,payload:s}}async listSharedThreadMessages(e){let t=await this.makeCAPIRequest(`/shared/${e}/messages`,"GET");if(!t.ok)return t;let s=await t.json();return{status:t.status,ok:!0,payload:s}}async createMessage(e,t,s,a,r,i,n){this.listMessagesCache=void 0;let o=await this.makeCAPIRequest(`/threads/${e}/messages`,"POST",{content:t,mediaContent:s,intent:a,references:r,currentURL:window.location.href,customInstructions:i,model:n,settings:d.J.settings??void 0});if(!o.ok)return o;let l=(await o.json()).message;return{status:o.status,ok:!0,payload:l}}async createMessageStreaming({threadID:e,messageID:t,content:s,mediaContent:a,intent:r,mode:i,references:n,context:o,confirmations:l,customInstructions:h,model:u,customCopilotID:p,parentMessageID:g,tools:m,clientToolResults:f,signal:_,skillOptions:S}){this.listMessagesCache=void 0;let T=c.W.domPageContext&&"immersive"!==i?function(){let e=(document.querySelector("main")||document.body).cloneNode(!0);for(let t of["script","style","svg","iframe","textarea",".js-header-wrapper",".footer",".sr-only",".react-code-file-contents"])for(let s of e.querySelectorAll(t))s.remove();for(let t of e.querySelectorAll("*")){if(!t.textContent?.trim()){t.remove();continue}let e=window.getComputedStyle(t);("none"===e.display||"hidden"===e.visibility)&&t.remove()}let t=e.querySelectorAll("p, h1, h2, h3, h4, li, td, th, blockquote, pre, code:not(pre code)"),s=[];for(let e of t){let t=E(e);t&&s.push(t)}let a=s.join("\n");return(a.length<=16e3?a:`${a.substring(0,16e3)}
Content was truncated. Use the API to get full content.`).replace(/\s{2,}/g," ").trim()}():void 0,I={responseMessageID:t,content:s,intent:r,references:n,context:o,currentURL:window.location.href,streaming:!0,confirmations:l,customInstructions:h,model:u,mode:i,settings:d.J.settings??void 0,customCopilotID:p?.id,customCopilotOwner:p?.owner,parentMessageID:g,tools:m,clientToolResults:f,mediaContent:a,skillOptions:S,pageContext:T},C=this.processQueryParams(new URLSearchParams(window.location.search)),y=await this.makeCAPIRequest(`/threads/${e}/messages?${C.toString()}`,"POST",I,!0,void 0,_);return y.ok?{status:y.status,ok:!0,response:y}:y}processQueryParams(e){let t=["instruction_prompt"],s=new URLSearchParams;for(let[a,r]of e)t.includes(a)&&s.append(a,r);return s}async listModels(){let e=await this.makeCAPIRequest("/models","GET",void 0,!1,"");if(!e.ok)return e;let t=await e.json();return{status:e.status,ok:!0,payload:t.data}}async setModelPolicyState(e,t){let s=await this.makeCAPIRequest(`/models/${e}/policy`,"POST",{state:t},!1,"");if(!s.ok)return Promise.reject(Error(`Failed to update model policy state: ${s.status}`))}async getSimpleCompletion(e,t){let s=(0,p.wv)(),a=t??s.id,r=await this.makeCAPIRequest("/chat/completions","POST",{messages:[{role:"user",content:e}],selectedModel:a,stream:!1},!1,"");if(!r.ok)return r;let i=(await r.json()).choices[0]?.message?.content||"";return{status:r.status,ok:!0,payload:i}}async sendFeedback({feedback:e,feedbackChoice:t,messageId:s,threadId:a,textResponse:r}){let i=await this.makeDotcomRequest(`${this.urlPathPrefix}/feedback`,"POST",{feedback:e,feedback_choice:t,message_id:s,thread_id:a,text_response:r});return i.ok?{status:i.status,ok:!0,payload:null}:i}async listDocsets(){let e=await this.fetchDocsetsResponse();return e.ok?{status:200,ok:!0,payload:e.payload.knowledgeBases}:e}async listAdministratedCopilotEnterpriseOrganizations(){let e=await this.fetchDocsetsResponse();return e.ok?{status:200,ok:!0,payload:e.payload.administratedCopilotEnterpriseOrganizations}:e}fetchDocsetsResponse(){return this.docsetsPromise||(this.docsetsPromise=this.docsetRequestPromise()),this.docsetsPromise}async docsetRequestPromise(){let e=await this.makeDotcomRequest("/github-copilot/docs/docsets","GET");return e.ok?{status:200,ok:!0,payload:await e.json()}:e}async deleteDocset(e){let t=await this.makeDotcomRequest(`/copilot/docsets/${e.id}`,"DELETE");return t.ok?{status:t.status,ok:!0,payload:null}:t}async listRepoFiles(e,t=!1){let s=(0,i.ClY)({repo:e,commitOid:e.commitOID,includeDirectories:t});return this.repoFilesCache.get(s)}async querySymbols(e,t){return await this.blackbirdCaches.setupWarmCachesLoop(),this.querySymbolsCache.get(e.ownerLogin,e.name,t)}async fetchImplicitContext(e,t,s){let a=await this.makeDotcomRequest(`${this.urlPathPrefix}/implicit-context/${t}/${s}/${encodeURIComponent(e)}`,"GET");return a.ok?{status:a.status,ok:a.ok,payload:await a.json()}:a}async fetchRepo(e){let t;if(this.repoDetailsCache.has(e))t=this.repoDetailsCache.get(e);else{let s=await this.makeDotcomRequest(`${this.urlPathPrefix}/repositories/${e}`,"GET");if(!s.ok)return s;t=await s.json(),this.repoDetailsCache.set(e,t)}return{status:200,ok:!0,payload:t}}async listAgents(e){let t=await (0,n.lS)(e);if(!t.ok)return{status:t.status,ok:!1,error:l.nN[t.status]||l.DW};let s=await t.json();return{status:t.status,ok:t.ok,payload:s}}async listCustomCopilots(){let e=await (0,n.lS)(`${this.urlPathPrefix}/custom_copilots`);if(!e.ok)return{status:e.status,ok:!1,error:l.nN[e.status]||l.DW};let t=await e.json();return{status:e.status,ok:!0,payload:t}}async fetchCustomCopilot(e){let t;let{owner:s,id:a}=e;t=s?`${this.urlPathPrefix}/custom_copilots/${s}/${a}`:`${this.urlPathPrefix}/custom_copilots/${a}`;let r=await (0,n.lS)(t);if(!r.ok)return{status:r.status,ok:!1,error:l.nN[r.status]||l.DW};let i=await r.json();return{status:r.status,ok:!0,payload:i}}async hydrateReference(e){if(!m.has(e.type))return{status:204,ok:!0,payload:e};let t=await this.makeDotcomRequest(`${this.urlPathPrefix}/reference_details`,"POST",{reference:e});return t.ok?{status:t.status,ok:t.ok,payload:await t.json()}:t}async fetchLanguageForFileReference(e){let{repoOwner:t,repoName:s}=e,a=window.btoa(e.path),r=(0,i.RT3)({ownerLogin:t,name:s},a,!0),n=await this.makeDotcomRequest(r,"GET");return n.ok?{status:n.status,ok:n.ok,payload:await n.json()}:n}async fetchAutocompleteIssues(e,t){let s=await this.makeDotcomRequest(`/copilot/chat/autocomplete/issues?repo=${e}&q=${t}`,"GET");return s.ok?await s.json():[]}async fetchAutocompletePullRequests(e,t){let s=await this.makeDotcomRequest(`/copilot/chat/autocomplete/pulls?repo=${e}&q=${t}`,"GET");return s.ok?await s.json():[]}async fetchAutocompleteDiscussions(e,t){let s=await this.makeDotcomRequest(`/copilot/chat/autocomplete/discussions?repo=${e}&q=${t}`,"GET");return s.ok?await s.json():[]}async makeDotcomRequest(e,t,s){let a={};for(let e of(0,u.f)()){let t=e.split("="),s=t[0]?.replaceAll("_","-"),r="1";t.length>1&&(r=t[1]),a[`X-Experiment-${s}`]=r}let r=await this.copilotAuthTokenProvider.getAuthToken();a["X-Copilot-Api-Token"]=r.value;try{let r=await (0,n.lS)(e,{method:t,body:s,headers:a});if(r.ok)return r;return{status:r.status,ok:!1,error:l.nN[r.status]||l.DW}}catch{return{status:500,ok:!1,error:l.DW}}}get directConnectConfiguration(){return{integrationID:"copilot-chat"}}async makeCAPIRequest(e,t,s,a=!1,r="/github/chat",i){let n=this.apiURL,o=await this.copilotAuthTokenProvider.getAuthToken();return await (0,l.p)({basePath:n+r,path:e,method:t,body:s,streamingResponse:a,authToken:o,integrationId:this.directConnectConfiguration.integrationID,realIp:this.realIp,signal:i,apiVersion:this.apiVersion})}constructor(e,t,s,i){g(this,"apiURL",void 0),g(this,"urlPathPrefix","/github-copilot/chat"),g(this,"docsetsPromise",void 0),g(this,"repoDetailsCache",new Map),g(this,"listMessagesCache",void 0),g(this,"copilotAuthTokenProvider",void 0),g(this,"blackbirdCaches",new a.L),g(this,"realIp",void 0),g(this,"apiVersion",void 0),g(this,"listRepoFilesImpl",async e=>{let t=await this.makeDotcomRequest(e,"GET");return t.ok?{status:200,ok:!0,payload:await t.json()}:t}),g(this,"repoFilesCache",new o.d(this.listRepoFilesImpl)),g(this,"querySymbolsImpl",async(e,t,s)=>{let a=await this.makeDotcomRequest(`/search/suggestions?query=repo:${e}/${t} ${s}`,"GET");return a.ok?{status:200,ok:!0,payload:(await a.json()).suggestions.filter(e=>"SUGGESTION_KIND_SYMBOL"===e.kind)}:a}),g(this,"querySymbolsCache",new o.d(this.querySymbolsImpl)),this.apiURL=e,this.copilotAuthTokenProvider=new r.J(t.map(e=>e.id)),this.realIp=s||"",this.apiVersion=i}};let E=e=>{let t=e.tagName.toLowerCase(),s=e.textContent;if(!s||!s.trim())return null;let a=s.trim();switch(t){case"h1":return`# ${a}`;case"h2":return`## ${a}`;case"h3":return`### ${a}`;case"h4":return`#### ${a}`;case"p":default:return a;case"li":return`\u{2022} ${a}`;case"code":return`\`${a}\``;case"pre":return`\`\`\`
${a}
\`\`\``;case"blockquote":return`> ${a}`}}},93589:(e,t,s)=>{s.d(t,{B:()=>i,CX:()=>c,HR:()=>l,TC:()=>o,ws:()=>n,zh:()=>r});var a=s(46988);function r(e,t=!0){let s=performance.now(),i=0,n=e.map(e=>({...e})),o={id:"root",role:"user",createdAt:"",threadID:"",references:null,childMessageIndexes:[],messageIndex:0,clientSide:!1};if(0===n.length)return n.push(o),i=performance.now()-s,(0,a.BI)("copilot.timings",{function:"constructMessagesHierarchy",timeElapsed:i,messagesLength:n.length,selectMostRecentMessages:t}),n;"root"!==n[0].id&&(n.unshift(o),(0,a.BI)("copilot.legacy_thread_updated",{threadID:n[1].threadID,messagesLength:n.length,selectMostRecentMessages:t}));let l=n[1];if(!l)return n;l.parentMessageID="root";let d=new Map;for(let[e,t]of n.entries()){if(t.messageIndex=e,t.childMessageIndexes=[],d.set(t.id,e),"root"===t.id)continue;t.parentMessageID||(t.parentMessageID=l.id,l=t);let s=d.get(t.parentMessageID);if(void 0!==s){t.parentMessageIndex=s;let e=n[s];e&&(e.childMessageIndexes.push(t.messageIndex),void 0===e.selectedChildIndex&&(e.selectedChildIndex=t.messageIndex))}}if(t){let e=n.at(-1);for(;e;){let t=c(n,e);t&&(t.selectedChildIndex=e.messageIndex),e=t}}return i=performance.now()-s,(0,a.BI)("copilot.timings",{function:"constructMessagesHierarchy",timeElapsed:i,messagesLength:n.length,selectMostRecentMessages:t}),n}function i(e){let t=e[0],s=[];for(;t;)"root"!==t.id&&s.push(t),t=void 0!==t.selectedChildIndex?e[t.selectedChildIndex]:void 0;return s}function n(e,t){let s=e.map(e=>({...e})),a=s[t.parentMessageIndex];return a&&(a.selectedChildIndex=t.messageIndex),s}function o(e,t){let s=e.map(e=>({...e})),a=s[t.messageIndex];return a&&void 0!==a.selectedChildIndex&&(a.selectedChildIndex=void 0),s}function l(e,t){let s=e.map(e=>({...e})),a={...t},r=s.find(e=>e.id===a?.parentMessageID);return r&&(s.push(a),a.messageIndex=e.length,a.childMessageIndexes=[],a.parentMessageIndex=r.messageIndex,r.childMessageIndexes||(r.childMessageIndexes=[]),r.childMessageIndexes.includes(a.messageIndex)||r.childMessageIndexes.push(a.messageIndex),r.selectedChildIndex=a.messageIndex),s}function c(e,t){return void 0!==t.parentMessageIndex?e[t.parentMessageIndex]:void 0}},5271:(e,t,s)=>{s.d(t,{d:()=>r});var a=s(46988);function r(e,t){(0,a.BI)("dotcom_chat.vision.error",{type:e,...t})}},37937:(e,t,s)=>{s.d(t,{J:()=>o});var a=s(45062),r=s(80688),i=s(82610);function n(e,t,s){return t in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}let CopilotLocalStorage=class CopilotLocalStorage{get selectedThreadID(){return this.localStorage.getItem(this.COPILOT_SELECTED_THREAD_ID_STORAGE_KEY)}set selectedThreadID(e){let t=this.COPILOT_SELECTED_THREAD_ID_STORAGE_KEY;if(null==e){this.localStorage.removeItem(t);return}this.localStorage.setItem(t,e)}getModel(e){let t=this.localStorage.getItem(this.COPILOT_SELECTED_MODEL_STORAGE_KEY(e));return null===t?t:JSON.parse(t)}setModel(e,t){this.localStorage.setItem(this.COPILOT_SELECTED_MODEL_STORAGE_KEY(e),JSON.stringify(t)),e&&this.localStorage.setItem(this.COPILOT_SELECTED_MODEL_STORAGE_KEY(null),JSON.stringify(t))}get settings(){let e=this.localStorage.getItem(this.COPILOT_SETTINGS_STORAGE_KEY(this.selectedThreadID));return null===e?e:JSON.parse(e)}set settings(e){this.localStorage.setItem(this.COPILOT_SETTINGS_STORAGE_KEY(this.selectedThreadID),JSON.stringify(e))}getPanelHeight(){let e=this.localStorage.getItem(this.COPILOT_PANEL_HEIGHT);return e?parseInt(e):this.DEFAULT_PANEL_HEIGHT}setPanelHeight(e){let t=this.COPILOT_PANEL_HEIGHT;this.localStorage.setItem(t,e.toString())}getPanelWidth(){let e=this.localStorage.getItem(this.COPILOT_PANEL_WIDTH);return e?parseInt(e):this.DEFAULT_PANEL_WIDTH}setPanelWidth(e){let t=this.COPILOT_PANEL_WIDTH;this.localStorage.setItem(t,e.toString())}getRepoCustomInstructionsState(){return"false"!==this.localStorage.getItem(this.COPILOT_REPO_CUSTOM_INSTRUCTIONS_STATE_KEY)}setRepoCustomInstructionsState(e){let t=this.COPILOT_REPO_CUSTOM_INSTRUCTIONS_STATE_KEY;this.localStorage.setItem(t,e.toString())}getCollapsedState(){return"false"!==this.sessionStorage.getItem(this.COPILOT_COLLAPSED_STATE_KEY)}setCollapsedState(e){let t=this.COPILOT_COLLAPSED_STATE_KEY;this.sessionStorage.setItem(t,e.toString())}getSelectedTopic(e){return this.localStorage.getItem(this.COPILOT_SELECTED_TOPIC_STORAGE_KEY(e))}setSelectedTopic(e,t){if(null==t){this.localStorage.removeItem(this.COPILOT_SELECTED_TOPIC_STORAGE_KEY(e));return}let s=this.COPILOT_SELECTED_TOPIC_STORAGE_KEY(e);this.localStorage.setItem(s,t)}getSavedMessage(e){return this.localStorage.getItem(this.COPILOT_SAVED_USER_MESSAGE_KEY(e))}setSavedMessage(e,t){this.setSavedMessageFast(e,t)}setSavedMessageFast(e,t){let s=this.COPILOT_SAVED_USER_MESSAGE_KEY(e);if(null==t){this.localStorage.removeItem(s);return}this.localStorage.setItem(s,t)}clearSavedUserMessage(e){this.localStorage.removeItem(this.COPILOT_SAVED_USER_MESSAGE_KEY(e))}getSavedUserMessageOnError(e){return this.localStorage.getItem(this.COPILOT_SAVED_USER_MESSAGE_ON_ERROR_KEY(e))}setSavedUserMessageOnError(e,t){let s=this.COPILOT_SAVED_USER_MESSAGE_ON_ERROR_KEY(e);if(null==t){this.localStorage.removeItem(s);return}this.localStorage.setItem(s,t)}clearSavedUserMessageOnError(e){this.localStorage.removeItem(this.COPILOT_SAVED_USER_MESSAGE_ON_ERROR_KEY(e))}getEntrypointMessage(){return this.localStorage.getItem(this.COPILOT_ENTRYPOINT_MESSAGE_KEY)}setEntrypointMessage(e){if(null==e){this.localStorage.removeItem(this.COPILOT_ENTRYPOINT_MESSAGE_KEY);return}this.localStorage.setItem(this.COPILOT_ENTRYPOINT_MESSAGE_KEY,e)}getCurrentReferences(e){let t=this.COPILOT_CURRENT_REFERENCES_KEY(e),s=this.localStorage.getItem(t);return s?JSON.parse(s):null}setCurrentReferences(e,t){let s=this.COPILOT_CURRENT_REFERENCES_KEY(e),a=t.filter((e,s)=>s===t.findIndex(t=>(0,i.Vb)(e)===(0,i.Vb)(t)));this.localStorage.setItem(s,JSON.stringify(a))}clearCurrentReferences(e){let t=this.COPILOT_CURRENT_REFERENCES_KEY(e);this.localStorage.removeItem(t)}migrateNullThreadToNewThread(e){let t=this.getSavedMessage(null);this.setSavedMessageFast(null,null),t&&this.setSavedMessageFast(e,t);let s=this.getCurrentReferences(null);this.clearCurrentReferences(null),s&&this.setCurrentReferences(e,s)}getImmersiveSidebarCollapsedState(){return"true"===localStorage.getItem(this.COPILOT_IMMERSIVE_SIDEBAR_COLLAPSED_STATE_KEY)}setImmersiveSidebarCollapsedState(e){localStorage.setItem(this.COPILOT_IMMERSIVE_SIDEBAR_COLLAPSED_STATE_KEY,String(e))}getMeterBannerFlag(){let e=this.localStorage.getItem(this.COPILOT_METER_BANNER_FLAG);return null===e?null:"true"===e}setMeterBannerFlag(e){this.localStorage.setItem(this.COPILOT_METER_BANNER_FLAG,String(e))}removeMeterBannerFlag(){this.localStorage.removeItem(this.COPILOT_METER_BANNER_FLAG)}getTrialSuccessBannerFlag(){return this.getBooleanFlag(this.COPILOT_TRIAL_SUCCESS_BANNER_FLAG)}setTrialSuccessBannerFlag(e){this.tempStorage.setItem(this.COPILOT_TRIAL_SUCCESS_BANNER_FLAG,String(e))}removeTrialSuccessBannerFlag(){this.tempStorage.removeItem(this.COPILOT_TRIAL_SUCCESS_BANNER_FLAG)}getProPlusSuccessBannerFlag(){return this.getBooleanFlag(this.COPILOT_PRO_PLUS_SUCCESS_BANNER_FLAG)}setProPlusSuccessBannerFlag(e){this.tempStorage.setItem(this.COPILOT_PRO_PLUS_SUCCESS_BANNER_FLAG,String(e))}removeProPlusSuccessBannerFlag(){this.tempStorage.removeItem(this.COPILOT_PRO_PLUS_SUCCESS_BANNER_FLAG)}getProPlusAnimationFlag(){return this.getBooleanFlag(this.COPILOT_PRO_PLUS_ANIMATION_FLAG)}setProPlusAnimationFlag(e){this.tempStorage.setItem(this.COPILOT_PRO_PLUS_ANIMATION_FLAG,String(e))}removeProPlusAnimationFlag(){this.tempStorage.removeItem(this.COPILOT_PRO_PLUS_ANIMATION_FLAG)}getWrapCodeLines(){return"true"===localStorage.getItem(this.COPILOT_WRAP_CODE_LINES_KEY)}setWrapCodeLines(e){this.localStorage.setItem(this.COPILOT_WRAP_CODE_LINES_KEY,String(e))}getBooleanFlag(e){let t=this.tempStorage.getItem(e);return null===t?null:"true"===t}retrieveAndValidateRequestIDs(){let e=this.localStorage.getItem(this.COPILOT_MESSAGE_REQUEST_ID_KEY);try{let t=JSON.parse(e||"[]");if(!Array.isArray(t)||0===t.length)return[];return t.filter(e=>"string"==typeof e.messageID&&"string"==typeof e.requestID)}catch{return[]}}addRequestID(e,t){let s=this.retrieveAndValidateRequestIDs(),a=s.findIndex(t=>t.messageID===e);-1!==a&&s.splice(a,1),s.push({messageID:e,requestID:t}),s.length>this.MAX_MESSAGE_REQUEST_ID_STORAGE_COUNT&&s.shift(),this.localStorage.setItem(this.COPILOT_MESSAGE_REQUEST_ID_KEY,JSON.stringify(s))}getRequestID(e){let t=this.retrieveAndValidateRequestIDs().find(t=>t.messageID===e);return t?t.requestID:void 0}constructor(){n(this,"COPILOT_REPO_CUSTOM_INSTRUCTIONS_STATE_KEY","COPILOT_REPO_CUSTOM_INSTRUCTIONS_STATE_KEY"),n(this,"COPILOT_SELECTED_THREAD_ID_STORAGE_KEY","COPILOT_SELECTED_THREAD_ID_STORAGE_KEY"),n(this,"COPILOT_COLLAPSED_STATE_KEY","COPILOT_COLLAPSED_STATE_KEY"),n(this,"COPILOT_IMMERSIVE_SIDEBAR_COLLAPSED_STATE_KEY","COPILOT_IMMERSIVE_SIDEBAR_COLLAPSED_STATE_KEY"),n(this,"COPILOT_PANEL_HEIGHT","COPILOT_PANEL_HEIGHT"),n(this,"DEFAULT_PANEL_HEIGHT",600),n(this,"COPILOT_PANEL_WIDTH","COPILOT_PANEL_WIDTH"),n(this,"COPILOT_ENTRYPOINT_MESSAGE_KEY","COPILOT_ENTRYPOINT_MESSAGE_KEY"),n(this,"COPILOT_MESSAGE_REQUEST_ID_KEY","COPILOT_MESSAGE_REQUEST_ID_KEY"),n(this,"COPILOT_METER_BANNER_FLAG","COPILOT_METER_BANNER_FLAG"),n(this,"COPILOT_TRIAL_SUCCESS_BANNER_FLAG","COPILOT_TRIAL_SUCCESS_BANNER_FLAG"),n(this,"COPILOT_PRO_PLUS_SUCCESS_BANNER_FLAG","COPILOT_PRO_PLUS_SUCCESS_BANNER_FLAG"),n(this,"COPILOT_PRO_PLUS_ANIMATION_FLAG","COPILOT_PRO_PLUS_ANIMATION_FLAG"),n(this,"COPILOT_WRAP_CODE_LINES_KEY","COPILOT_WRAP_CODE_LINES_KEY"),n(this,"MAX_MESSAGE_REQUEST_ID_STORAGE_COUNT",100),n(this,"DEFAULT_PANEL_WIDTH",480),n(this,"COPILOT_SELECTED_MODEL_STORAGE_KEY",e=>`COPILOT_SELECTED_MODEL_${e}`),n(this,"COPILOT_SETTINGS_STORAGE_KEY",e=>`COPILOT_SETTINGS_${e}`),n(this,"COPILOT_SAVED_USER_MESSAGE_KEY",e=>`COPILOT_SAVED_USER_MESSAGE_${e}`),n(this,"COPILOT_SAVED_USER_MESSAGE_ON_ERROR_KEY",e=>`COPILOT_SAVED_USER_MESSAGE_ON_ERROR_${e}`),n(this,"COPILOT_CURRENT_REFERENCES_KEY",e=>`COPILOT_CURRENT_REFERENCES_${e}`),n(this,"COPILOT_SELECTED_TOPIC_STORAGE_KEY",e=>`COPILOT_SELECTED_TOPIC_${e}`),n(this,"localStorage",(0,r.A)("localStorage",{throwQuotaErrorsOnSet:!1,ttl:864e5})),n(this,"tempStorage",(0,r.A)("localStorage",{throwQuotaErrorsOnSet:!1,ttl:18e5})),n(this,"sessionStorage",(0,r.A)("sessionStorage",{throwQuotaErrorsOnSet:!1,ttl:864e5}))}};!function(e,t,s,a){var r,i=arguments.length,n=i<3?t:null===a?a=Object.getOwnPropertyDescriptor(t,s):a;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,s,a);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(n=(i<3?r(n):i>3?r(t,s,n):r(t,s))||n);i>3&&n&&Object.defineProperty(t,s,n)}([(0,a.s)(100)],CopilotLocalStorage.prototype,"setSavedMessage",null);let o=new CopilotLocalStorage},68956:(e,t,s)=>{s.d(t,{Cb:()=>l,E1:()=>d,GL:()=>h,Hh:()=>I,JB:()=>_,UG:()=>f,VR:()=>u,Xw:()=>E,fn:()=>S,hH:()=>g,iI:()=>m,j0:()=>o,k1:()=>p,q5:()=>y,rl:()=>T,xh:()=>C,zY:()=>c});var a=s(5796),r=s(47584),i=s(96540),n=s(82610);s(2622);let o="The name of this space is too close to another existing space. Please modify the name and try again.";function l(e){let{id:t,owner:s}=e;return s?`${n.VR}/${s}/${t}`:`${n.VR}/${t}`}function c(){return r.fV?.pathname===`${n.VR}/new`}function d(){let e=RegExp(`^${n.VR}/[0-9]+/edit$`),t=RegExp(`^${n.VR}/[a-zA-Z0-9-]+/[0-9]+/edit$`);return!!(r.fV?.pathname?.match(e)||r.fV?.pathname?.match(t))}function h(e){return`${l(e)}/edit`}function u(){let e=r.fV?.pathname;return e===n.VR||e===`${n.VR}/`}function p(){let e=RegExp(`^${n.VR}/[0-9]+$`),t=RegExp(`^${n.VR}/[a-zA-Z0-9-]+/[0-9]+$`);return!!(r.fV?.pathname?.match(e)||r.fV?.pathname?.match(t))}function g(){return u()||p()}function m(){let e=r.fV.pathname;return(0,i.useMemo)(()=>{let t=e.match(/\/copilot\/spaces\/([^/]+)\/([^/]+)/);if(t){let[,e,s]=t;if(e&&s){let t=parseInt(s,10);if(!isNaN(t))return{id:t,owner:e}}return null}let s=e.match(/\/copilot\/spaces\/([^/]+)/);if(s){let[,e]=s;if(e){let t=parseInt(e,10);if(!isNaN(t))return{id:t}}}return null},[e])}function E(e){return e&&e.customCopilotID?{id:e.customCopilotID,...e.customCopilotOwner&&{owner:e.customCopilotOwner}}:null}function f(e,t){return t.owner?e.id===t.id&&e.owner===t.owner:e.oldId===t.id}function _(e,t){if(t)return e?.find(e=>f(e,t))}function S(e){return e&&e.id?e.owner?`${n.VR}/${e.owner}/${e.id}`:`/custom_copilots/${e.id}`:n.VR}function T(e,t){let s=t.indexOf("/");if(-1===s||0===s)return`org:${e} ${t} in:name archived:false`;let a=t.slice(s+1);return 0===a.length?`org:${e} in:name archived:false`:`org:${e} ${a} in:name archived:false`}function I(e){return(e?.sizePercentage??0)>100}let C=e=>t=>{t.stopPropagation(),e(t)};function y(e){let t=e.filePath.split("/"),s=t.pop(),r=[e.nwo,...t].join("/"),i=e.nwo.split("/");return{filePath:r,fileName:s,fileUrl:e.fileExists&&e.commitish?(0,a.IO9)({repo:{ownerLogin:i[0],name:i[1]},commitish:e.commitish,action:"blob",path:e.filePath}):void 0}}},76303:(e,t,s)=>{s.d(t,{q:()=>r});let a=e=>"refOrigin"in e&&"custom_copilot"===e.refOrigin;function r(e){return Array.isArray(e)?e.filter(e=>!a(e)):e}},27297:(e,t,s)=>{s.d(t,{QA:()=>n,eW:()=>d,fZ:()=>c,wv:()=>l});var a=s(2622);let r="/images/modules/marketplace/models/families/openai.svg",i=new Map([["Azure OpenAI",r],["Anthropic","/images/modules/marketplace/models/families/anthropic.svg"],["Google","/images/modules/marketplace/models/families/gemini.svg"]]),n="copilot-base";function o(){return{capabilities:{family:"gpt-4o",limits:{max_prompt_tokens:2e4,vision:{supported_media_types:["image/jpeg","image/png","image/webp","image/gif"]}},supports:{parallel_tool_calls:!0,tool_calls:!0},tokenizer:"o200k_base",type:"chat"},id:"gpt-4o",name:"GPT 4o",version:"gpt-4o-2024-05-13",displayName:"GPT 4o",vendor:"Azure OpenAI",logoURL:r,hasLimitedCapabilities:!1,preview:!1,isThirdParty:!1,model_picker_enabled:!0}}function l(){let e=a.W.default41PolicyEnabled,t=a.W.default41Preview;return{capabilities:{family:"gpt-4.1",limits:{max_prompt_tokens:128e3,vision:{supported_media_types:["image/jpeg","image/png","image/webp","image/gif"]}},supports:{parallel_tool_calls:!0,tool_calls:!0},tokenizer:"o200k_base",type:"chat"},id:"gpt-4.1",name:"GPT-4.1",displayName:"GPT-4.1",model_picker_enabled:!0,...e&&{policy:{state:"enabled",terms:"Enable access to the latest GPT-4.1 model from OpenAI. [Learn more about how GitHub Copilot serves GPT-4.1](https://docs.github.com/en/copilot/using-github-copilot/ai-models/choosing-the-right-ai-model-for-your-task#gpt-41)."}},preview:t,vendor:"OpenAI",logoURL:r,isThirdParty:!1,hasLimitedCapabilities:!1,version:"gpt-4.1-2025-04-14"}}function c(e){var t;return a.W.forceLegacyChatDefaultModel?o():a.W.useCAPIDefaultModel?(t=e,t?.find(e=>!0===e.is_chat_default)||l()):a.W.default41BaseModel?l():o()}function d(e){return(e??[l()]).map(h).filter(e=>!!e).filter(e=>e.model_picker_enabled)}function h(e){var t;return"chat"===e.capabilities.type&&e.model_picker_enabled&&(!e.policy||"enabled"===e.policy.state||e.policy.terms)?{...e,displayName:function(e){for(let t of u)if(e.name.endsWith(t))return e.name.replace(t,"").trim();return e.name}(e),hasLimitedCapabilities:(t=a.W.copilotChatO1Tools,"o1-ga"===e.capabilities.family?!t:"o3"===e.capabilities.family||!e.capabilities.supports.tool_calls),isThirdParty:"Azure OpenAI"!==e.vendor,logoURL:i.get(e.vendor)}:null}let u=["(Beta)","(Preview)"]},84310:(e,t,s)=>{s.d(t,{K:()=>ReadLocalWorkspaceFileSkill});var a=s(80688),r=s(59937),i=s(90254);function n(e,t,s){return t in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}let ReadLocalWorkspaceFileSkill=class ReadLocalWorkspaceFileSkill{requiresConfirmation(){return!1}confirmationMessage(){return"Read the local workspace file"}static schema(){return{type:"function",function:{name:"read-local-workspace-file",description:"Read a local file. This can be used to read files on the user's local machine. It is the equivalent of running `cat` in the terminal. The file path is relative to the current directory.",parameters:{type:"object",required:["path","repository","pullRequest"],properties:{path:{type:"string",description:"The path to the file to read."},repository:{required:["ownerLogin","name"],type:"object",description:"the repository containing the file to read.",properties:{ownerLogin:{type:"string",description:"the owner of the repository."},name:{type:"string",description:"the name of the repository."}}},pullRequest:{type:"object",description:"the pull request containing the file to read.",required:["number","headSHA"],properties:{number:{type:"string",description:"the number of the pull request."},headSHA:{type:"string",description:"the head SHA of the pull request."}}}}}}}}assertDefined(e,t){if(null==e)throw Error(t)}validateArgs(){let e=JSON.parse(this.rawArguments);return this.assertDefined(e,"No parsed arguments found in raw arguments"),this.assertDefined(e.path,"No path found on parsed arguments"),this.assertDefined(e.repository,"No repository found on parsed arguments"),this.assertDefined(e.pullRequest,"No pullRequest found on parsed arguments"),this.assertDefined(e.repository.ownerLogin,"No ownerLogin found on repository"),this.assertDefined(e.repository.name,"No name found on repository"),this.assertDefined(e.pullRequest.number,"No number found on pullRequest"),this.assertDefined(e.pullRequest.headSHA,"No headSHA found on pullRequest"),e}getArguments(){let e=this.validateArgs(),{repository:t,pullRequest:s}=e;return{path:e.path.startsWith("./")?e.path.slice(2):e.path,repository:t,pullRequest:s}}async fetchBlob(e,t,s){try{let a=await this.blobService.getBlob(e,t.ownerLogin,s.number,t.name,s.headSHA);return a.ok&&a.payload.blobContents||""}catch{return""}}toResult(e,t){return{ok:t,result:e}}async execute(){try{let e=(0,a.A)("localStorage"),{path:t,repository:s,pullRequest:r}=this.getArguments(),n=await this.fetchBlob(t,s,r),o=`hadron-editor-file-deltas-v2/${s.ownerLogin}/${s.name}/${r.number}`,l=JSON.parse(e.getItem(o)||"{}"),c=(l||{diffs:[],sessionId:"",latestTimestamp:0}).diffs?.find(e=>e.path===t);if(!c)return this.toResult(n,!0);let d=n?(0,i.X6)(n,c.diff):(0,i.Gu)(c.diff),h=!1===d?n:d;return this.toResult(h,!0)}catch(t){let e=`Error: ${t instanceof Error?t.message:`Error executing ${this.name} skill`}`;return this.toResult(e,!1)}}constructor(e,t,s){n(this,"id",void 0),n(this,"name",void 0),n(this,"rawArguments",void 0),n(this,"blobService",void 0),this.id=e,this.name=t,this.rawArguments=s,this.blobService=new r.T}}},31747:(e,t,s)=>{s.d(t,{J:()=>Base64FileAttachment,N:()=>UploadableFileAttachment});var a=s(54807),r=s(57712),i=s(5271);function n(e,t,s){if(!t.has(e))throw TypeError("attempted to "+s+" private field on non-instance");return t.get(e)}function o(e,t){var s=n(e,t,"get");return s.get?s.get.call(e):s.value}function l(e,t,s){!function(e,t){if(t.has(e))throw TypeError("Cannot initialize the same private elements twice on an object")}(e,t),t.set(e,s)}function c(e,t,s){var a=n(e,t,"set");return!function(e,t,s){if(t.set)t.set.call(e,s);else{if(!t.writable)throw TypeError("attempted to set read only private field");t.value=s}}(e,a,s),s}function d(e,t,s){return t in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}var h=new WeakMap,u=new WeakMap,p=new WeakMap;let UploadableFileAttachment=class UploadableFileAttachment{prefetch(){return o(this,p).load()}get previewUrl(){return o(this,p).read().href}async url(){return(await o(this,p).load()).href}getDimensions(){return new Promise(e=>{let t=new FileReader;t.onload=t=>{if(!t.target||!t.target.result)return;let s=t.target.result;if("string"!=typeof s)return;let a=new Image;a.onload=()=>{e({width:a.width,height:a.height})},a.src=s},t.readAsDataURL(this.file)})}constructor(e,t,s){d(this,"file",void 0),d(this,"width",void 0),d(this,"height",void 0),l(this,h,{writable:!0,value:void 0}),l(this,u,{writable:!0,value:void 0}),d(this,"abortController",void 0),d(this,"key",void 0),d(this,"threadID",void 0),d(this,"isLoaded",!1),d(this,"hasError",!1),l(this,p,{writable:!0,value:(0,r.Z)(async()=>{let e=await (0,a.BV)({name:this.file.name,size:String(this.file.size),content_type:this.file.type,thread_id:this.threadID},"/upload/policies/copilot-chat-attachments",o(this,u));await (0,a.QM)(this.file,e,o(this,u));let t=await (0,a.My)(e,o(this,u)),s=await o(this,h);return this.width=s.width,this.height=s.height,this.isLoaded=!0,t})}),this.file=t,this.abortController=new AbortController,c(this,u,this.abortController.signal),this.key=e,c(this,h,this.getDimensions()),this.threadID=s}};var g=new WeakMap;let Base64FileAttachment=class Base64FileAttachment{prefetch(){return o(this,g).load()}get previewUrl(){return o(this,g).read()}url(){return o(this,g).load()}constructor(e,t){d(this,"key",void 0),d(this,"file",void 0),d(this,"width",void 0),d(this,"height",void 0),d(this,"isLoaded",!1),d(this,"hasError",!1),l(this,g,{writable:!0,value:(0,r.Z)(async()=>new Promise((e,t)=>{let s=new FileReader;s.onload=a=>{if(!a.target||!a.target.result)return;let r=a.target.result;if("string"!=typeof r)return;let n=r.split(",")[1];if(n){if(n.length>5e5){(0,i.d)("size_limit_exceeded",{size:n.length});let e=Error("Only images below 500KB are supported during this preview period");e.name="FileSizeError",t(e),this.hasError=!0;return}let a=new Image;a.onload=()=>{this.width=a.width,this.height=a.height},a.src=r,e(s.result),this.isLoaded=!0}},s.onerror=e=>{if(e.target){let s=e.target.error;if(s){(0,i.d)(s.name,{message:s.message}),t(s),this.hasError=!0;return}}t(Error("Couldn't read the file due to an unknown error")),this.hasError=!0},s.readAsDataURL(this.file)}))}),this.file=t,this.key=e}}},37304:(e,t,s)=>{function a(e,t,s){if(!t.has(e))throw TypeError("attempted to "+s+" private field on non-instance");return t.get(e)}function r(e,t){var s=a(e,t,"get");return s.get?s.get.call(e):s.value}function i(e,t,s){!function(e,t){if(t.has(e))throw TypeError("Cannot initialize the same private elements twice on an object")}(e,t),t.set(e,s)}function n(e,t,s){var r=a(e,t,"set");return!function(e,t,s){if(t.set)t.set.call(e,s);else{if(!t.writable)throw TypeError("attempted to set read only private field");t.value=s}}(e,r,s),s}s.d(t,{Es:()=>ObservableMap,Lj:()=>ObservableValue,yy:()=>ObservableSet});var o=new WeakMap;let l=class ObservableBase{subscribe(e){return r(this,o).add(e),()=>{r(this,o).delete(e)}}notify(e){for(let t of r(this,o))t(e)}constructor(){i(this,o,{writable:!0,value:new Set})}};var c=new WeakMap;let ObservableValue=class ObservableValue extends l{get value(){return r(this,c)}set value(e){var t;t=r(this,c),("object"==typeof e&&e&&"object"==typeof t&&t?function(e,t){for(let s of new Set(Object.keys(e).concat(Object.keys(t))))if(!Object.is(e[s],t[s]))return!0;return!1}(t,e):!Object.is(t,e))&&(n(this,c,e),this.notify(e))}constructor(e){super(),i(this,c,{writable:!0,value:void 0}),n(this,c,e)}};var d=new WeakMap,h=new WeakMap;let ObservableSet=class ObservableSet extends l{get value(){return r(this,d)}has(e){if(!r(this,h).has(e)){let t=new ObservableValue(r(this,d).has(e));r(this,h).set(e,t)}return r(this,h).get(e)}add(e){r(this,d).has(e)||(r(this,d).add(e),r(this,h).has(e)&&(r(this,h).get(e).value=!0),this.notify(r(this,d)))}delete(e){r(this,d).has(e)&&(r(this,d).delete(e),r(this,h).has(e)&&(r(this,h).get(e).value=!1),this.notify(r(this,d)))}clear(){if(0!==r(this,d).size){for(let e of(r(this,d).clear(),r(this,h).values()))e.value=!1;this.notify(r(this,d))}}constructor(...e){super(),i(this,d,{writable:!0,value:void 0}),i(this,h,{writable:!0,value:new Map}),n(this,d,new Set(...e))}};var u=new WeakMap,p=new WeakMap,g=new WeakMap;let ObservableMap=class ObservableMap extends l{get value(){return r(this,u)}has(e){if(!r(this,p).has(e)){let t=new ObservableValue(r(this,u).has(e));r(this,p).set(e,t)}return r(this,p).get(e)}get(e){if(!r(this,g).has(e)){let t=new ObservableValue(r(this,u).get(e));r(this,g).set(e,t)}return r(this,g).get(e)}set(e,t){r(this,u).get(e)!==t&&(r(this,u).set(e,t),r(this,p).has(e)&&(r(this,p).get(e).value=!0),r(this,g).has(e)&&(r(this,g).get(e).value=t),this.notify(r(this,u)))}delete(e){r(this,u).has(e)&&(r(this,u).delete(e),r(this,p).has(e)&&(r(this,p).get(e).value=!1),r(this,g).has(e)&&(r(this,g).get(e).value=void 0),this.notify(r(this,u)))}clear(){if(0!==r(this,u).size){for(let e of(r(this,u).clear(),r(this,p).values()))e.value=!1;for(let e of r(this,g).values())e.value=void 0;this.notify(r(this,u))}}constructor(...e){super(),i(this,u,{writable:!0,value:void 0}),i(this,p,{writable:!0,value:new Map}),i(this,g,{writable:!0,value:new Map}),n(this,u,new Map(...e))}}},10124:(e,t,s)=>{s.d(t,{AI:()=>i,HN:()=>l,R:()=>n,Rs:()=>o,Sk:()=>d,tQ:()=>c});var a=s(96540),r=s(37304);function i(e){let[t]=(0,a.useState)(()=>new r.Lj(e));return t}function n(...e){let[t]=(0,a.useState)(()=>new r.Es(...e));return t}function o(e,t){let s=(0,a.useRef)(t);(0,a.useEffect)(()=>{s.current=t}),(0,a.useEffect)(()=>e.subscribe(e=>s.current(e)),[e])}function l(e){let[t,s]=(0,a.useState)(e.value);return o(e,e=>s(e)),t}function c(e){let[t,s]=(0,a.useState)(e.value),[r,i]=(0,a.useState)({});return o(e,e=>{s(e),i({})}),t}function d(e,t){let s=i(t(e.value));return o(e,e=>{s.value=t(e)}),s}},2914:(e,t,s)=>{s.d(t,{$d:()=>c,xR:()=>d});var a=s(74848),r=s(96540),i=s(29664),n=s(77342),o=s(2622);let l=(0,r.createContext)(void 0);function c({children:e,initialLicenseType:t,initialPlan:s,initialQuotas:c}){let[d,h]=(0,i.Z)(t,s,c),u=d.licenseType,p=d.plan??null,g=d.chatQuotaRemaining()??1/0,m=d.premiumInteractionsQuotaRemaining()??1/0,E=d.quotas?.resetDate?new Date(d.quotas.resetDate).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"}):"",f=u===n.mF.LicensedLimited,_=d.canPurchaseAdditionalQuota(),S=d.canUpgradePlan(),T=f&&g<=0,I=o.W.premiumRequestQuotasEnabled&&m<=0,C=d.quotas?.overagesEnabled??!1,y=(0,r.useMemo)(()=>({licenseType:u,chatQuotaRemaining:g,premiumChatQuotaRemaining:m,resetDate:E,isLicensedLimited:f,chatQuotaExceeded:T,premiumInteractionsQuotaExceeded:I,reloadQuota:h,plan:p,canPurchaseAdditionalQuota:_,canUpgradePlan:S,overagesEnabled:C}),[u,g,m,E,f,T,I,h,p,_,S,C]);return(0,a.jsx)(l.Provider,{value:y,children:e})}let d=()=>{let e=(0,r.useContext)(l);if(!e)throw Error("useEntitlement must be used within EntitlementProvider");return e};try{l.displayName||(l.displayName="EntitlementContext")}catch{}try{c.displayName||(c.displayName="EntitlementProvider")}catch{}},44848:(e,t,s)=>{s.d(t,{Hb:()=>n,nu:()=>l,qw:()=>o});var a=s(74848),r=s(96540);let i=(0,r.createContext)([]);function n({plugins:e,children:t}){return(0,a.jsx)(i.Provider,{value:e,children:t})}function o(){return(0,r.useContext)(i)}function l(e){return o().find(t=>t.id===e)??null}try{i.displayName||(i.displayName="PluginsContext")}catch{}try{n.displayName||(n.displayName="ImmersivePluginsProvider")}catch{}},65615:(e,t,s)=>{s.d(t,{Mj:()=>v,IJ:()=>G,Pk:()=>b,pn:()=>M,A3:()=>k,bP:()=>N});var a=s(74848),r=s(10124),i=s(38568),n=s(96540),o=s(2914);let l=(0,s(80688).A)("sessionStorage");function c(e,t){return!!e&&"assistive"===t}let d="restored-chat-messages";var h=s(82610),u=s(13080),p=s(46988),g=s(93589),m=s(2622),E=s(37937),f=s(68956);let _=(e,t)=>{let s=t=>{t&&(E.J.selectedThreadID=t);let s=t!==e.selectedThreadID,a=E.J.getModel(t)?.id,r=e.availableModels?.find(e=>e.id===a)??e.model;return{...e,model:r,selectedThreadID:t,currentView:"thread",showTopicPicker:!t&&e.showTopicPicker,currentReferences:s?[]:e.currentReferences,threadHasNewMessages:!s&&e.threadHasNewMessages,editingMessage:s?void 0:e.editingMessage}};switch(t.type){case"SLASH_COMMANDS_ERROR":return(0,p.BI)("copilot.slash_commands_error"),{...e,slashCommandLoading:{...e.slashCommandLoading,state:"error"}};case"SLASH_COMMANDS_LOADED":return(0,p.BI)("copilot.slash_commands_loaded"),{...e,slashCommandLoading:{...e.slashCommandLoading,state:"loaded"}};case"SLASH_COMMANDS_LOADING":return{...e,slashCommandLoading:{...e.slashCommandLoading,state:"loading"}};case"OPEN_COPILOT_CHAT":return(0,p.BI)("copilot.open_copilot_chat",{source:t.source}),{...e,chatIsOpen:!0,chatIsVisible:!0,entryPointId:t.id};case"CLOSE_COPILOT_CHAT":return(0,p.BI)("copilot.close_copilot_chat"),{...e,chatIsOpen:!1};case"HIDE_COPILOT_CHAT":return(0,p.BI)("copilot.hide_copilot_chat"),{...e,chatIsVisible:!1};case"THREAD_CREATED":{let a=new Map(e.threads);return(0,p.BI)("copilot.thread_created",{...I(t.thread),mode:e.mode,count:a.size+1}),a.set(t.thread.id,t.thread),{...s(t.thread.id),threads:a}}case"THREAD_CONTINUED":{let a=new Map(e.threads);return(0,p.BI)("copilot.thread_continued",{...I(t.thread),mode:e.mode,count:a.size+1}),a.set(t.thread.id,t.thread),{...s(t.thread.id),threads:a}}case"THREAD_CONTINUED_FAILED":return(0,p.BI)("copilot.thread_continued_failed",{stateSelectedThreadID:e.selectedThreadID,sharedIdOnFetch:e.fetchSharedThreads?.shareId,mode:e.mode}),{...e};case"SUGGESTIONS_GENERATED":return{...e,suggestions:t.suggestions};case"CLEAR_SUGGESTIONS":return{...e,suggestions:null};case"CLEAR_THREAD":return(0,p.BI)("copilot.clear_thread"),{...e,messages:[],currentReferences:[]};case"CLEAR_CURRENT_REFERENCES":{(0,p.BI)("copilot.clear_current_references");let s=t.keepTypes&&new Set(t.keepTypes),a=s?e.currentReferences.filter(e=>s.has("image")&&"image"===e.type?m.W.attachImagesImmersive:s.has(e.type)):[];return{...e,currentReferences:a}}case"MESSAGES_UPDATED":{let s=t.messages?[...t.messages]:[];if("error"===t.state&&(0,p.BI)("copilot.messages_updated",{count:t.messages?.length,loading:t.state}),!s)return{...e,messagesLoading:{...e.messagesLoading,state:t.state,missingOrgIds:t.missingOrgIds,notFound:t.notFound}};{let a=e.defaultRecipient,r=e.allClientConfirmations;for(let i of("loaded"===t.state&&s.length>0&&(a=R(s[s.length-1],e),r=s.map(e=>e.clientConfirmations?.map(e=>JSON.stringify(Object.values(e.confirmation).sort()))).flat().filter(Boolean)),s))i.clientSide=!1;return s=(0,g.zh)(s),{...e,defaultRecipient:a,allClientConfirmations:r,messages:s,messagesLoading:{...e.messagesLoading,state:t.state,missingOrgIds:t.missingOrgIds,notFound:t.notFound},messagesRestored:!1}}}case"WAITING_ON_COPILOT":return{...e,isWaitingOnCopilot:t.loading,threadHasNewMessages:!0};case"SELECT_THREAD":{(0,p.BI)("copilot.select_thread",{threadID:t.thread?.id,mode:e.mode});let a={...s(t.thread?.id||null),currentTopic:t.clearTopic?void 0:e.currentTopic,topicLoading:t.clearTopic?{error:null,state:"loaded"}:e.topicLoading};return null===t.thread&&e.currentRepository&&m.W.topicsAsReferences&&(a.currentReferences=[(0,h.qS)(e.currentRepository)]),a}case"HANDLE_EVENT_START":return(0,p.BI)("copilot.handle_event_start"),{...e,chatIsOpen:!0,chatIsVisible:!0,entryPointId:t.id,currentReferences:t.references??e.currentReferences};case"THREADS_LOADING":return{...e,threadsLoading:{...e.threadsLoading,state:"loading"}};case"DISMISS_ATTACH_KNOWLEDGE_BASE_HERE_POPOVER":return(0,p.BI)("copilot.dismiss_attach_knowledge_base_here_popover"),{...e,renderAttachKnowledgeBaseHerePopover:!1};case"DISMISS_KNOWLEDGE_BASE_ATTACHED_TO_CHAT_POPOVER":return(0,p.BI)("copilot.dismiss_knowledge_base_attached_to_chat_popover"),{...e,renderKnowledgeBaseAttachedToChatPopover:!1};case"KNOWLEDGE_BASES_LOADING":return{...e,knowledgeBasesLoading:{...e.knowledgeBasesLoading,state:"loading"}};case"KNOWLEDGE_BASES_LOADED":return(0,p.BI)("copilot.knowledge_bases_loaded",{count:t.knowledgeBases.length}),{...e,knowledgeBases:t.knowledgeBases,knowledgeBasesLoading:{...e.knowledgeBasesLoading,state:"loaded",error:null}};case"KNOWLEDGE_BASES_LOADING_ERROR":return(0,p.BI)("copilot.knowledge_bases_loading_error",{error:t.message}),{...e,knowledgeBasesLoading:{...e.knowledgeBasesLoading,state:"error",error:t.message}};case"LATEST_THREAD_LOADED":{let s=new Map(e.threads);return s.set(t.latestThread.id,t.latestThread),{...e,threads:s}}case"THREADS_LOADED":return(0,p.BI)("copilot.threads_loaded",{count:t.threads.length,mode:e.mode}),{...e,threadsLoading:{...e.threadsLoading,state:"loaded"},threads:new Map(t.threads.map(e=>[e.id,e]))};case"THREADS_LOADING_ERROR":return(0,p.BI)("copilot.threads_loading_error",{error:t.message}),{...e,threadsLoading:{error:t.message,state:"error",status:t.status}};case"DELETE_THREAD_KEEP_SELECTION":{let a=new Map(e.threads);return(0,p.BI)("copilot.thread_deleted",{...I(t.thread),count:a.size-1}),a.delete(t.thread.id),{...s(null),threads:a,threadsLoading:{...e.threadsLoading,state:"loaded"},messages:[],messagesLoading:{state:"loaded",error:null},currentReferences:[],currentView:"list"}}case"DELETE_ALL_THREADS_KEEP_SELECTION":{let a=new Map(e.threads);for(let e of t.threads)(0,p.BI)("copilot.thread_deleted",{...I(e),count:a.size-1}),a.delete(e.id);return{...s(null),threads:a,threadsLoading:{...e.threadsLoading,state:"loaded"},messages:[],messagesLoading:{state:"loaded",error:null},currentReferences:[],currentView:"list"}}case"DELETE_THREAD":{let a=new Map(e.threads);if((0,p.BI)("copilot.thread_deleted",{...I(t.thread),count:a.size-1,mode:e.mode}),a.delete(t.thread.id),e.selectedThreadID===t.thread.id)return{...s(null),threads:a,threadsLoading:{...e.threadsLoading,state:"loaded"},messages:[],messagesLoading:{state:"loaded",error:null},currentReferences:[]};return{...e,threads:a}}case"DELETE_THREAD_ERROR":{(0,p.BI)("copilot.delete_thread_error",{...I(t.thread),error:t.error});let s=new Map(e.threads);return s.set(t.thread.id,t.thread),{...e,threadsLoading:{...e.threadsLoading,error:t.error},threads:s}}case"DELETE_ALL_THREADS_ERROR":{for(let e of t.threads)(0,p.BI)("copilot.delete_thread_error",{...I(e),error:t.error});let s=new Map(e.threads);for(let e of t.threads)s.set(e.id,e);return{...e,threadsLoading:{...e.threadsLoading,error:t.error},threads:s}}case"MESSAGE_ADDED":{(0,p.BI)("copilot.message_added",{...T(t.message),count:e.messages.length+1,repoHasCustomInstructions:!!t.repoHasCustomInstructions,usedRepoCustomInstructions:!!t.usedRepoCustomInstructions});let s=(0,g.HR)(e.messages,t.message);return{...e,messages:s,messagesLoading:{state:"loaded",error:null},threadHasNewMessages:!0,editingMessage:void 0}}case"MESSAGE_FEEDBACK":{let s=e.messages.map(e=>({...e})),a=s.find(e=>e.id===t.message.id);if(null==a)return(0,p.BI)("copilot.message_feedback_no_message_found",{...T(t.message)}),e;return a.feedback=t.feedback,{...e,messages:s}}case"MESSAGES_SET_SELECTED_MESSAGE":{let s=(0,g.ws)(e.messages,t.message);return{...e,messages:s,threadHasNewMessages:!1}}case"MESSAGES_UNSELECT_PREVIOUS_MESSAGE":{let s=(0,g.TC)(e.messages,t.message);return{...e,messages:s,threadHasNewMessages:!1}}case"THREAD_UPDATED":return{...e,threads:S(e,t.thread)};case"REFERENCES_LOADED":return(0,p.BI)("copilot.references_loaded",{count:t.references.length}),{...e,currentReferences:e.currentReferences.filter(e=>t.references.every(t=>(0,h.Vb)(t)!==(0,h.Vb)(e))).concat(t.references)};case"ADD_REFERENCE":{let s=[...e.currentReferences.filter(e=>!(0,h.x_)(e,t.reference)),t.reference];return s.length>e.currentReferences.length&&(0,p.BI)("copilot.add_reference",{...C(t.reference),source:t.source,count:e.currentReferences.length+1}),(t.reference&&"issue"===t.reference.type||"pull-request"===t.reference.type||"discussion"===t.reference.type)&&(0,u.i)(`Adding ${t.reference.type} ${t.reference.number} as a reference.`),{...e,currentReferences:s}}case"REMOVE_REFERENCES":{let s=t.references;return s.length>0&&(0,p.BI)("copilot.remove_reference",{count:e.currentReferences.length-s.length}),s[0]&&("issue"===s[0].type||"pull-request"===s[0].type||"discussion"===s[0].type)&&(0,u.i)(`Removing ${s[0].type} ${s[0].number} as a reference.`),{...e,currentReferences:e.currentReferences.filter(e=>!s.includes(e))}}case"REPLACE_REFERENCE":{let s=[];for(let a of e.currentReferences)(0,h.x_)(a,t.referenceToDelete)?s.push(t.referenceToInsert):(0,h.x_)(a,t.referenceToInsert)||s.push(a);return(0,p.BI)("copilot.replace_reference",{removedReference:(0,h.Vb)(t.referenceToDelete),addedReference:(0,h.Vb)(t.referenceToInsert),count:s.length}),{...e,currentReferences:s}}case"SHOW_TOPIC_PICKER":return{...e,showTopicPicker:t.show};case"CURRENT_TOPIC_UPDATED":return t.topic&&(0,p.BI)("copilot.current_topic_updated",{type:t.topic?(0,h.P)(t.topic)?"docset":"repository":"none",mode:e.mode}),{...e,currentTopic:t.topic,topicLoading:{...e.topicLoading,state:t.state}};case"MESSAGE_STREAMING_STARTED":return(0,p.BI)("copilot.message_streaming_started",{...T(t.message),model:e.model?.id,mode:e.mode}),{...e,isWaitingOnCopilot:!0,streamingMessage:t.message,messages:[...e.messages]};case"MESSAGE_STREAMING_TOKEN_ADDED":return{...e,streamingMessage:e.streamingMessage?{...e.streamingMessage,content:e.streamingMessage.content+t.token}:null};case"MESSAGE_STREAMING_FUNCTION_CALLED":if(e.streamingMessage){let s=e.streamingMessage.skillExecutions||[],a=s.findIndex(e=>"started"===e.status||"progress"===e.status),r=a>=0?s[a]:null,i=s,n=e.streamingMessage.references||[];switch(t.status){case"started":i=[...s,{slug:t.name,status:t.status,arguments:t.arguments,errorMessage:t.errorMessage,references:[]}];break;case"progress":if(r){let e={...r,status:t.status,statusMessage:t.statusMessage};i=[...s.slice(0,a),e,...s.slice(a+1)]}break;case"completed":r&&(i[a]={...r,status:t.status,references:t.references}),n=Array.from(new Set([...n,...t.references]));break;case"error":r&&(i[a]={...r,status:t.status,errorMessage:t.errorMessage})}return{...e,streamingMessage:{...e.streamingMessage,skillExecutions:i,references:n}}}return e;case"CLIENT_SKILL_CONFIRMATION_REQUEST":return{...e,clientSkillConfirmation:t.confirmation};case"CLIENT_SKILLS_REQUEST":return{...e,streamingMessage:e.streamingMessage?{...e.streamingMessage,clientSkillsRequests:t.toolCalls}:null};case"READ_DOM_SKILL_INVOKED":return{...e,elementMap:t.elementMap};case"MESSAGE_STREAMING_COMPLETED":{let s,a=e.defaultRecipient,r=e.messages;if(e.streamingMessage){a=R(s={...e.streamingMessage,id:t.messageResponse.id,references:t.messageResponse.references,createdAt:t.messageResponse.createdAt,intent:t.messageResponse.intent,copilotAnnotations:t.messageResponse.copilotAnnotations,parentMessageID:t.messageResponse.parentMessageID,model:t.messageResponse.model,clientSide:!1},e),(0,p.BI)("copilot.message_streaming_completed",{...T(s),...y(t.timings),model:e.model?.id,mode:e.mode,count:e.messages.length+1}),e.streamingMessage.requestID&&E.J.addRequestID(s.id,e.streamingMessage?.requestID);let i=r.map(e=>({...e}));if(null==i.find(e=>e.id===s?.parentMessageID)){let e=(0,g.B)(i),t=e[e.length-1];void 0!==t&&(t.clientSide&&"user"===t.role?(t.id=s.parentMessageID,t.clientSide=!1):s.parentMessageID=t.id)}r=(0,g.HR)(i,s)}return{...e,defaultRecipient:a,isWaitingOnCopilot:!1,streamingMessage:null,messages:r}}case"MESSAGE_STREAMING_FAILED":return(0,p.BI)("copilot.message_streaming_failed",{...e.streamingMessage?T(e.streamingMessage):{},...y(t.timings),model:e.model?.id,mode:e.mode}),{...e,isWaitingOnCopilot:!1,streamingMessage:null};case"MESSAGE_STREAMING_STOPPED":{let s;let a=g.B(e.messages).findLast(e=>"user"===e.role)?.id;e.streamingMessage?(s={...e.streamingMessage,interrupted:!0,parentMessageID:a},(0,p.BI)("copilot.message_streaming_stopped",{...T(s),...y(t.timings),model:e.model?.id,mode:e.mode,count:e.messages.length+1})):e.isWaitingOnCopilot&&(s={id:crypto.randomUUID(),role:"assistant",threadID:e.selectedThreadID??"",references:[],createdAt:new Date().toISOString(),interrupted:!0,clientSide:!0,parentMessageID:a});let r=e.messages;if(null!=s){let e=r.findLast(e=>"user"===e.role);void 0!==e&&(s.parentMessageID=e.id),r=(0,g.HR)(r,s)}return{...e,isWaitingOnCopilot:!1,streamingMessage:null,messages:r}}case"MESSAGES_CLEAR_LAST_ERROR":{let t=(0,g.B)(e.messages),s=e.messages,a=t[t.length-1],r=a?.error||a?.interrupted,i=s;return r&&(i=s.filter(e=>e.id!==a?.id)),{...e,streamingMessage:null,messages:[...i]}}case"SELECT_REFERENCE":return t.reference&&(0,p.BI)("copilot.select_reference",C(t.reference)),{...e,selectedReference:t.reference};case"MODELS_LOADING":return{...e,modelsLoading:{state:"loaded",error:null}};case"MODELS_LOADING_ERROR":return{...e,modelsLoading:{state:"error",error:t.error}};case"MODELS_LOADED":{let s=t.models;return m.W.visionAllowedInClaude||(s=t.models.map(e=>{if(e.id.startsWith("claude")){let t={...e};return t.capabilities.supports.vision=!1,t}return e})),{...e,model:(s||[]).find(t=>t.id===e.model.id)||e.model,availableModels:s||[]}}case"SELECT_MODEL":{if("immersive"!==e.mode)return e;let s=t.model?.capabilities?.supports?.vision?e.currentReferences:e.currentReferences.filter(e=>"image"!==e.type);return(0,p.BI)("copilot.select_model",{model:t.model?.name,mode:e.mode}),{...e,model:t.model,currentReferences:s}}case"VIEW_ALL_THREADS":return{...e,currentView:"list"};case"VIEW_CURRENT_THREAD":return{...e,currentView:"thread"};case"IMPLICIT_CONTEXT_UPDATED":if(!(0,h.yR)(t.context,e.context))return{...e,context:t.context};return e;case"SET_TOP_REPOSITORIES":return{...e,topRepositoriesCache:t.topics};case"SET_AGENTS":return{...e,agents:t.agents};case"SET_CUSTOM_COPILOT":{let s=e.customCopilots?.find(e=>f.UG(e,t.customCopilot)),a=s?e.customCopilots?.map(e=>f.UG(e,s)?t.customCopilot:e):[...e.customCopilots??[],t.customCopilot];return{...e,customCopilots:a}}case"SET_CUSTOM_COPILOTS":return{...e,customCopilots:t.customCopilots};case"SET_DEEP_CODESEARCH":return{...e,skillOptions:{...e.skillOptions,deepCodeSearch:t.deepCodeSearch}};case"MESSAGE_STREAMING_CONFIRMATION":{let s={title:t.title,message:t.message,confirmation:t.confirmation};return{...e,streamingMessage:e.streamingMessage?{...e.streamingMessage,confirmations:e.streamingMessage.confirmations?[...e.streamingMessage.confirmations,s]:[s]}:null}}case"AGENT_ERROR":{let s=e.streamingMessage,a=t.error;return{...e,streamingMessage:s&&{...s,agentErrors:[...s.agentErrors??[],{type:a.type,code:a.code,message:a.message,identifier:a.identifier}]}}}case"ENTITLEMENT_UPDATED":return{...e,entitlement:t.entitlement??e.entitlement};case"TOGGLE_REPO_CUSTOM_INSTRUCTIONS":return(0,p.BI)("copilot.repo_custom_instructions_toggled",{isEnabling:!!t.value}),{...e,repoCustomInstructionsEnabled:t.value};case"DISMISS_EDITOR_UPSELL_BANNER":return{...e,isEditorUpsellBannerDismissed:!0};case"DISMISS_AMBIENT_ERROR":return{...e,ambientError:null};case"ADD_AMBIENT_ERROR":return{...e,ambientError:{message:t.message}};case"SET_PERSONAL_INSTRUCTIONS":return{...e,personalInstructions:t.personalInstructions};case"SELECT_PLUGIN":return{...e,activePlugin:t.plugin??void 0};case"SHARED_THREAD_UPDATED":{let s=S(e,t.thread),a=s.get(t.thread.id);return a&&(0,p.BI)("copilot.shared_thread_update",I(a)),{...e,threads:s}}case"SHARED_THREADS_LOADING":return{...e,sharedThreadsLoading:{...e.sharedThreadsLoading,state:"loading"}};case"SHARED_THREADS_LOADED":return(0,p.BI)("copilot.shared_threads_loaded"),{...e,sharedThreadsLoading:{...e.sharedThreadsLoading,state:"loaded"}};case"SHARED_THREADS_LOADING_ERROR":return(0,p.BI)("copilot.shared_threads_loading_error",{error:t.message}),{...e,sharedThreadsLoading:{...e.sharedThreadsLoading,state:"error",error:t.message}};case"IMAGE_UPLOADED":return{...e,currentReferences:e.currentReferences.map(e=>"image"===e.type&&e.id===t.referenceId?{...e,imageUrl:t.dotcomAttachment.previewUrl}:e)};case"START_EDITING_MESSAGE":return(0,p.BI)("dotcom_chat.activate",{target:"USER_MESSAGE_ACTION_EDIT",mode:"immersive"}),{...e,editingMessage:t.messageId};case"CANCEL_EDITING_MESSAGE":return{...e,editingMessage:void 0};case"FETCH_SHARED_THREAD_MESSAGES":return{...e,fetchSharedThreads:{ok:t.ok,status:t.status,shareId:t.shareId}};case"SET_WRAP_CODE_LINES":return{...e,wrapCodeLines:t.value};case"CLEAR_SHARED_THREAD_CHANNEL":return{...e,sharedThreadChannel:null}}};function S(e,t){let s=new Map(e.threads),a=e.threads.get(t.id);if(!a)return s;let r={...a,...t};return s.set(t.id,r),s}function T(e){var t;if(!e)return(0,p.Ti)({});let s={id:e.id,role:e.role,createdAt:e.createdAt,threadID:e.threadID,referenceCount:e.references?.length??0};return e.intent&&(s.intent=e.intent),e.error&&(s.error=e.error),e.copilotAnnotations&&(s.copilotAnnotations=function(e){if(e)return{CodeVulnerability:e.CodeVulnerability?.map(e=>({details:{type:e?.details?.type}})),PublicCodeReference:e.PublicCodeReference?.map(e=>({details:{license:e?.details?.license,language:e?.details?.language}}))}}(e.copilotAnnotations)),e.skillExecutions&&(s.skillExecutions=(t=e.skillExecutions)?t.map(e=>({slug:e?.slug,status:e?.status,argumentCount:e?.arguments?.length??0,errorMessage:e?.errorMessage,references:e?.references?.length??0})):[]),e.interrupted&&(s.interrupted=!0),(0,p.Ti)(s)}function I(e){return e?(0,p.Ti)({id:e.id,createdAt:e.createdAt,updatedAt:e.updatedAt,currentReferenceCount:e.currentReferences?.length??0}):(0,p.Ti)({})}function C(e){return e?(0,p.Ti)({type:e.type}):(0,p.Ti)({})}function y(e){let t={totalTime:e.endTime-e.startTime};return void 0!==e.firstByte&&(t.ttfb=e.firstByte-e.startTime),void 0!==e.firstToken&&(t.ttft=e.firstToken-e.startTime),t}function R(e,t){let s=(0,h.Th)(e,t.currentUserLogin);if("agent"===s.type)return s.name}var w=s(7426),A=s(27297),O=s(22232);let D=(0,n.createContext)(null);function v({children:e,topic:t,workerPath:s,threadId:r,pluginId:i,refs:u,selectedReference:p,mode:f,ssoOrganizations:S,chatIsOpen:T,chatIsVisible:I,chatVisibleSettingPath:C,agents:y,customCopilots:R,messages:O,testReducerState:v,realIp:L,currentView:b,copilotUpsellBannerDismissed:M,copilotChatPayload:k}){let N=function(e,t){let s=c(e,t),a=l.getItem(d),r=a?JSON.parse(a):void 0;return((0,n.useEffect)(()=>{l.removeItem(d)},[]),s&&r?.expiry&&r.expiry>Date.now()&&r.threadId===e)?{restoredMessages:r.restoredMessages,restoredThreadTitle:r.threadTitle}:{}}(r,f),G=N.restoredMessages,U=N.restoredThreadTitle;G&&(G=(0,g.zh)(G));let x=t?(0,h.qS)(t):void 0,B=(0,A.fZ)(null),H=v||{threadsLoading:{state:"pending",error:null},messagesLoading:{state:"pending",error:null},messagesRestored:!!G,slashCommandLoading:{state:"pending",error:null},showTopicPicker:"immersive"!==f&&(!r||"assistive"===f)&&!t,topicLoading:{state:"pending",error:null},threads:new Map,restoredThreadTitle:U,knowledgeBasesLoading:{state:"pending",error:null},knowledgeBases:[],model:B,availableModels:[B],modelsLoading:{state:"pending",error:null},messages:O??G??[],streamingMessage:null,selectedThreadID:r,currentTopic:m.W.topicsAsReferences?void 0:t,chatIsOpen:!!T,isWaitingOnCopilot:!1,currentUserLogin:k.currentUserLogin,apiUrl:k.apiURL,currentReferences:m.W.topicsAsReferences&&x?[x,...u]:u,findFileWorkerPath:s,currentView:b||"thread",selectedReference:p??null,mode:f,currentRepository:t,ssoOrganizations:S,context:void 0,renderKnowledgeBases:k.renderKnowledgeBases??!0,renderAttachKnowledgeBaseHerePopover:k.renderAttachKnowledgeBaseHerePopover,renderKnowledgeBaseAttachedToChatPopover:k.renderKnowledgeBaseAttachedToChatPopover,customInstructions:k.customInstructions,chatIsVisible:I,chatVisibleSettingPath:C,renderBetaLabel:k.renderBetaLabel,topRepositoriesCache:void 0,agentsPath:k.agentsPath,optedInToPreviewFeatures:k.optedInToPreviewFeatures,optedInToUserFeedback:k.optedInToUserFeedback,agents:y,customCopilots:R,activePlugin:i??void 0,reviewLab:k.reviewLab,repoCustomInstructionsEnabled:E.J.getRepoCustomInstructionsState(),isEditorUpsellBannerDismissed:M,ambientError:void 0,personalInstructions:k.personalInstructions??null,threadHasNewMessages:!1,sharedThreadsLoading:{state:"pending",error:null},skillOptions:{deepCodeSearch:!1},wrapCodeLines:E.J.getWrapCodeLines(),sharedThreadChannel:k.sharedThreadChannel,autoSubmit:k.autoSubmit??!1},[F,$]=(0,n.useReducer)(_,H);return!function(e,t,s,a){let r=c(t,a);(0,n.useEffect)(()=>{if(!r)return;let a=(e,t)=>{if("childMessages"!==e&&"parentMessage"!==e)return t},i=()=>{if(!e?.length||!t)return;let r=s.get(t),i=r?.name,n={expiry:Date.now()+8e3,restoredMessages:e,threadId:t,threadTitle:i};l.setItem(d,JSON.stringify(n,a))};return window.addEventListener("turbo:before-fetch-response",i),window.addEventListener("beforeunload",i),window.addEventListener("popstate",i),()=>{window.removeEventListener("turbo:before-fetch-response",i),window.removeEventListener("beforeunload",i),window.removeEventListener("popstate",i)}},[e,r,t,s])}(F.messages,F.selectedThreadID,F.threads,F.mode),(0,n.useEffect)(function(){if(!F.chatIsOpen)return;let e=F.currentReferences.filter(e=>"repository"!==e.type||e.id!==F.currentRepository?.id);E.J.setCurrentReferences(F.selectedThreadID,e)},[F.selectedThreadID,F.currentReferences,F.currentRepository,F.chatIsOpen]),(0,a.jsx)(o.$d,{initialLicenseType:k.licenseType,initialPlan:k.plan,initialQuotas:k.quotas,children:(0,a.jsx)(P,{state:F,children:(0,a.jsx)(D.Provider,{value:$,children:(0,a.jsx)(w.v,{apiURL:k.apiURL,apiVersion:k.apiVersion,state:F,dispatch:$,ssoOrganizations:S,realIp:L,hasCEorCBAccess:k.hasCEorCBAccess,children:e})})})})}let L=(0,n.createContext)(null);function P({state:e,children:t}){let s=(0,r.AI)(e);return(0,i.N)(()=>{s.value=e},[e,s]),(0,a.jsx)(O.sw,{value:s,children:(0,a.jsx)(L.Provider,{value:e,children:t})})}function b(){let e=(0,n.useContext)(L);if(!e)throw Error("useChatState can only be used inside a CopilotChatProvider");return e}function M(e){let t=(0,O.rE)();if(!t)throw Error("useChatStateLens can only be used inside a CopilotChatProvider");let s=(0,r.Sk)(t,e);return(0,r.HN)(s)}function k(e){return M(t=>t[e])}function N(...e){return M(t=>(function(e,t){let s={};for(let a of t)s[a]=e[a];return s})(t,e))}function G(){let e=(0,n.useContext)(D);if(!e)throw Error("useChatDispatch can only be used inside a CopilotChatProvider");return e}try{D.displayName||(D.displayName="CopilotChatDispatchContext")}catch{}try{v.displayName||(v.displayName="CopilotChatProvider")}catch{}try{L.displayName||(L.displayName="ChatStateContext")}catch{}try{P.displayName||(P.displayName="ChatStateProvider")}catch{}},7426:(e,t,s)=>{s.d(t,{b:()=>g,v:()=>p});var a=s(74848),r=s(70170),i=s(96540),n=s(2914),o=s(44848),l=s(53914),c=s(2622),d=s(37937),h=s(22232);let u=(0,i.createContext)(null);function p({apiURL:e,state:t,dispatch:s,ssoOrganizations:p,children:g,realIp:m,hasCEorCBAccess:E,apiVersion:f}){let _=(0,h.tD)(),S=(0,o.qw)(),T=(0,i.useMemo)(()=>new l.e8(s,e,p,_,m,void 0,E,S,f),[s,e,p,_,m,E,S,f]),{licenseType:I}=(0,n.xR)();return(0,i.useEffect)(()=>{t.chatIsOpen&&!c.W.topicsAsReferences&&(async()=>{if(t.selectedThreadID&&t.messages.length>0&&!t.currentTopic){let e=d.J.getSelectedTopic(t.selectedThreadID),s=Number(e);e&&!isNaN(s)?await T.fetchCurrentRepo(s):T.clearCurrentTopic()}})()},[t.selectedThreadID,T,t.messages.length,t.currentTopic,t.chatIsOpen]),(0,i.useEffect)(()=>{let e=new AbortController,s=async()=>{let e=window.location.hash,t=window.location.pathname,s=window.location.hash?`${t}${e}`:t,a=s.slice(1).split("/");if(a.length<2)return;let r=a[0],i=a[1];r&&i&&await T.fetchImplicitContext(s,r,i)},a=(0,r.s)(()=>{s()},500);return t.chatIsOpen&&(a(),function(){let{replaceState:t,pushState:s}=window.history;window.history.replaceState=function(...e){t.apply(window.history,e),T.clearSuggestions(),window.dispatchEvent(new Event("replaceState"))},window.history.pushState=function(...e){s.apply(window.history,e),T.clearSuggestions(),window.dispatchEvent(new Event("pushState"))},window.addEventListener("popstate",a,{signal:e.signal}),window.addEventListener("replaceState",a,{signal:e.signal}),window.addEventListener("pushState",a,{signal:e.signal})}()),()=>{e.abort()}},[T,t.chatIsOpen,I]),(0,a.jsx)(u.Provider,{value:T,children:g})}function g(){let e=(0,i.useContext)(u);if(!e)throw Error("useChatManager must be used within a CopilotChatManagerProvider");return e}try{u.displayName||(u.displayName="CopilotChatManagerContext")}catch{}try{p.displayName||(p.displayName="CopilotChatManagerProvider")}catch{}},22232:(e,t,s)=>{s.d(t,{rE:()=>o,sw:()=>i,tD:()=>n});var a=s(96540);let r=(0,a.createContext)(null),i=r.Provider;function n(){let e=(0,a.useContext)(r);if(!e)throw Error("useGetChatState can only be used inside a CopilotChatProvider");return(0,a.useCallback)(()=>e.value,[e])}function o(){return(0,a.useContext)(r)}try{r.displayName||(r.displayName="ObservableChatStateContext")}catch{}},53914:(e,t,s)=>{s.d(t,{e8:()=>CopilotChatManager,L9:()=>N});var a,r=s(74848),i=s(46988),n=s(57572),o=s(96558),l=s(82610),c=s(55854),d=s(37404),h=s(93589),u=s(77342),p=s(2622),g=s(37937),m=s(68956),E=s(76303),f=s(27297),_=s(75632);let S={interactDomSkillHighlight:"interact-dom-module__interactDomSkillHighlight--nDwwz"};function T(e,t,s){return t in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}let InteractDomSkill=class InteractDomSkill{requiresConfirmation(){return"click"===JSON.parse(this.rawArguments).action}confirmationMessage(){let e=JSON.parse(this.rawArguments),t="";switch(e.action){case"click":t=`Click on ${e.element}`;break;case"type":t=`Type "${e.value}" into ${e.element}`}return t}static schema(){return{type:"function",function:{name:"interact-dom",description:"This function gives you the ability to interact with the DOM. Perform an action like clicking on an element, typing into an input, or filling out a form on the current html page. Call this function to fulfill the user request after receiving the current url and tag map of accessible element names to their tags from invoking the read-dom function. For the type action, if there is existing text in the element (passed in the tag map), you should modify that text how the user requests and return the new text contents. Do no just return the new text the user asked you to type unless they are explicitly trying to overwrite the current value. Afterwards, you should send a message letting the user know the actions you performed. If the user makes multiple requests in one message, you should invoke this function multiple times in a single reposnse.",parameters:{type:"object",required:["action","element"],properties:{action:{type:"string",description:'The DOM action to take on an element on the current page. The action property can either be "click" or "type". If it is "type" then the value property should be the string to type into the input element.'},element:{type:"string",description:"The accessible name of the element to perform the DOM action on. This must be one of the keys in the tag map returned from read-dom."},value:{type:"string",description:"If the action is 'type', then value is the string to type into the text input element. The text input's value will be set to this, so if the element has an existing value from the tag map passed in, make sure to include that in this paramter."}}}}}}async execute(){try{let e=JSON.parse(this.rawArguments),t=this.chatState?.elementMap?.get(e.element),s="";if(t instanceof HTMLElement)switch(t.classList.add(S.interactDomSkillHighlight),document.addEventListener("click",()=>{t.classList.remove(S.interactDomSkillHighlight)},{once:!0}),e.action){case"click":t.click(),s=`${e.element} was clicked.`;break;case"type":"value"in t?(t.value="",await function(e,t,s=0){return new Promise(a=>{!function s(r){if(r<t.length){let a=t.charAt(r),i=new KeyboardEvent("keydown",{key:a,code:`Key${a.toUpperCase()}`,keyCode:a.charCodeAt(0),charCode:a.charCodeAt(0),bubbles:!0});e.dispatchEvent(i),e.value+=a,setTimeout(()=>s(r+1),10)}else{let t=new Event("input",{bubbles:!0});e.dispatchEvent(t),a()}}(s)})}(t,e.value||""),s=`${e.value} was typed into ${e.element}.`):s=`${e.element} could not be typed into because it was not an element that accepts a value like textarea or input.`}else s=`${e.element} could not be located.`;return{result:s,ok:!0}}catch(e){return{ok:!1,result:`Error: ${e instanceof Error?e.message:`Error executing ${this.name} skill`}`}}}constructor(e,t,s,a){T(this,"id",void 0),T(this,"name",void 0),T(this,"rawArguments",void 0),T(this,"chatState",void 0),this.id=e,this.name=t,this.rawArguments=s,this.chatState=a}};function I(e,t,s){return t in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}let C={workbench:!0};let NavigateInternallySkill=class NavigateInternallySkill{requiresConfirmation(){return!1}confirmationMessage(){return"Navigate to the specified location"}static schema(){return{type:"function",function:{name:"navigate-internally",description:`
This tool is used to redirect the user to a handful of internal locations that have been predefined. Only the predefined list of locations will be allowed, and any other location will be rejected and cause an error.
Locations are defined as [slug]: [description]. Use the slug when calling this tool.
Locations:
- workbench: A specialized location for helping the user with creating, building, testing, and running code, websites and more. This area should be preferred for any situation where the user wants to build an app, website, or do any sort of extensive coding.
`,parameters:{type:"object",required:["location","reasoning"],properties:{location:{description:"The location slug to navigate the user.",type:"string",enum:["workbench"]},reasoning:{type:"string",description:`The reasoning for why this task is a good candidate for the location. We will display this to the user for confirmation.
This field should be formatted as follows: "We think this would be a good task for [location] [because] <reasoning>."
`}}}}}}execute(){try{let e=JSON.parse(this.rawArguments);if(!this.chatState?.selectedThreadID)return{ok:!1,result:"No active thread found. Cannot redirect."};if(!C[e.location])return{ok:!1,result:`Location ${e.location} is not valid.`};if("workbench"===e.location){let e=this.chatState?.messages.find(e=>"user"===e.role&&"temp"===e.threadID);if(!e||!e.content)return{ok:!1,result:"We couldn't find the last user message, so we can't redirect, let's build here"};let t=encodeURIComponent(e.content);return window.location.href=`/copilot/spark?initialPrompt=${t}`,{ok:!0,result:"The user is now in the workbench. Our job is done, wish them luck in less than 5 words."}}return{ok:!1,result:"Location is not valid."}}catch(e){return{ok:!1,result:`Error: ${e instanceof Error?e.message:"Error executing redirect to workbench"}`}}}constructor(e,t,s,a,r){I(this,"id",void 0),I(this,"name",void 0),I(this,"rawArguments",void 0),I(this,"chatState",void 0),I(this,"dispatch",void 0),this.id=e,this.name=t,this.rawArguments=s,this.chatState=a,this.dispatch=r}};var y=s(6786);function R(e,t,s){return t in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}let ReadDomSkill=class ReadDomSkill{requiresConfirmation(){return!1}confirmationMessage(){return"Read the DOM for the current page"}static schema(){return{type:"function",function:{name:"read-dom",description:"Allows you to interact with the DOM to perform actions like filling out forms, submitting forms, clicking on buttons, and typing into inputs on the current web page. This function requests a list of all interactable elements on the current html page, keyed by their accessible name. If the user makes a request to interact with elements on the current web page, but has not provided any DOM elements in clientToolResults, call this function. After the results are returned, call interact-dom to actually perform the desired interactions. If the user asks a question about the DOM, you can call this to read its state, but do not follow up with an interact-dom function call in that case. Finally, let the user know what actions you performed",parameters:{type:"object",properties:{}}}}}execute(){try{let e={},t=new Map;for(let s of document.querySelectorAll('input, select, textarea, button, [role="button"], a, [tabindex]')){let a=(0,y.G3)(s);t.set(a,s);let r=s.tagName,i=s instanceof HTMLInputElement||s instanceof HTMLTextAreaElement?s.value:null;e[a]={tag:r,value:i}}return this.dispatch?.({type:"READ_DOM_SKILL_INVOKED",elementMap:t}),{result:JSON.stringify({tagMap:e,url:window.location.href}),ok:!0}}catch(e){return{ok:!1,result:`Error: ${e instanceof Error?e.message:`Error executing ${this.name} skill`}`}}}constructor(e,t,s,a,r){R(this,"id",void 0),R(this,"name",void 0),R(this,"rawArguments",void 0),R(this,"dispatch",void 0),this.id=e,this.name=t,this.rawArguments=s,this.dispatch=r}};var w=s(84310);let A=/^\/settings\/.*/,O={"read-local-workspace-file":{constructor:w.K,schema:w.K.schema(),includePaths:[/^\/[^/]+\/[^/]+\/pull\/\d+\/edit$/],featureFlag:"workspace_editor_fix_a_build_function_calling"},"read-dom":{constructor:ReadDomSkill,schema:ReadDomSkill.schema(),excludePaths:[A],featureFlag:"copilot_client_dom_skills"},"interact-dom":{constructor:InteractDomSkill,schema:InteractDomSkill.schema(),excludePaths:[A],featureFlag:"copilot_client_dom_skills"},"navigate-internally":{constructor:NavigateInternallySkill,schema:NavigateInternallySkill.schema(),includePaths:[/^\/copilot(\/.*)?$/],featureFlag:"copilot_workbench_redirect"}},D=e=>Object.keys(O).reduce((t,s)=>{let a=O[s];if(!a||a.featureFlag&&!(0,_.G7)(a.featureFlag))return t;if(L(a)){if(a.excludePaths.some(t=>t.test(e)))return t}else if(!v(a))return t;else if(!a.includePaths.some(t=>t.test(e)))return t;return t.push(a.schema),t},[]),v=e=>"includePaths"in e,L=e=>"excludePaths"in e;function P(e,t,s){return t in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}let UnknownClientSkill=class UnknownClientSkill{requiresConfirmation(){return!1}confirmationMessage(){return"Unknown function"}execute(){return{ok:!0,result:`Unknown function: ${this.name} called with args: ${this.rawArguments}`}}schema(){return{type:"function",function:{name:"unknown-client-skill",description:"This is a fallback skill if the skill is not found"}}}constructor(e,t,s,a,r){P(this,"id",void 0),P(this,"name",void 0),P(this,"rawArguments",void 0),P(this,"chatState",void 0),P(this,"dispatch",void 0),this.id=e,this.name=t,this.rawArguments=s,this.chatState=a,this.dispatch=r}};function b(e,t,s){return t in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}let SkillExecutor=class SkillExecutor{async run(){if(this.requiresConfirmation()){let e=this.clientSkillConfirmation();this.dispatch({type:"CLIENT_SKILL_CONFIRMATION_REQUEST",confirmation:e})}else await this.executeSkills()}setParentMessageId(e){this.parentMessageId=e}resetExecution(){this.parentMessageId=void 0,this.skillsToExecute=[]}clientSkillConfirmation(){return{title:"Confirm actions",message:this.confirmationMessage(),onSubmit:e=>{this.dispatch({type:"CLIENT_SKILL_CONFIRMATION_REQUEST",confirmation:void 0}),e?this.executeSkills():this.sendChatMessage({thread:this.thread,content:"",references:[],clientToolResults:this.confirmationDeclinedResults()}),this.resetExecution()},confirmation:{toolCalls:this.toolCalls}}}confirmationDeclinedResults(){return this.skillsToExecute.map(e=>({id:e.id,type:"function",functionCallResult:{name:e.name,arguments:e.rawArguments,result:`Failed to execute ${e.name}: Permission denied by user`}}))}validateSkillEntry(e){if(e&&(!e.featureFlag||(0,_.G7)(e.featureFlag)))return e.constructor}toolCallsToSkills(){return this.toolCalls.map(e=>{let t=O[e.function.name],s=this.validateSkillEntry(t);return s?new s(e.id,e.function.name,e.function.arguments,this.chatState,this.dispatch):new UnknownClientSkill(e.id,e.function.name,e.function.arguments,void 0,void 0)})}requiresConfirmation(){return this.skillsToExecute.some(e=>e.requiresConfirmation())}confirmationMessage(){let e="";for(let t of this.skillsToExecute)e+=`${t.confirmationMessage()}
`;return e}async executeSkills(){if(0===this.skillsToExecute.length)return;let e=[];for(let t of this.skillsToExecute){let s=await this.executeSkill(t),a={id:t.id,type:"function",functionCallResult:s};e.push(a)}this.sendChatMessage({thread:this.thread,content:"",references:[],clientToolResults:e,parentMessageId:this.parentMessageId}),this.resetExecution()}async executeSkill(e){try{let{ok:t,result:s}=await e.execute();return(0,i.BI)("dotcom_chat.client_skill_execution",{skillName:e.name,success:t}),{name:e.name,arguments:e.rawArguments,result:s}}catch{return(0,i.BI)("dotcom_chat.client_skill_execution",{skillName:e.name,success:!1}),{name:e.name,arguments:e.rawArguments,result:`Failed to execute ${e.name}`}}}constructor(e,t,s,a,r){b(this,"toolCalls",void 0),b(this,"sendChatMessage",void 0),b(this,"thread",void 0),b(this,"skillsToExecute",void 0),b(this,"chatState",void 0),b(this,"dispatch",void 0),b(this,"parentMessageId",void 0),this.thread=e,this.toolCalls=t,this.sendChatMessage=s,this.chatState=a,this.dispatch=r,this.skillsToExecute=this.toolCallsToSkills()}};var M=s(31747);function k(e,t,s){return t in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}let N=99,G=null;let CopilotChatManager=class CopilotChatManager{async openChat(e,t,s,a,r){if(this.dispatch({type:"OPEN_COPILOT_CHAT",source:s}),"thread"===t&&await this.findOrStartNewThread(e,r),g.J.setCollapsedState(!1),F(this.getChatState().entryPointId??o.fv,!0),a){let e=new FormData;e.set("copilot_chat_visible","true"),(0,n.DI)(a,{method:"PUT",body:e})}}closeChat(){this.dispatch({type:"CLOSE_COPILOT_CHAT"}),g.J.setCollapsedState(!0),F(this.getChatState().entryPointId??o.fv,!1)}hideChat(e){if(this.dispatch({type:"HIDE_COPILOT_CHAT"}),this.closeChat(),e){let t=new FormData;t.set("copilot_chat_visible","false"),(0,n.DI)(e,{method:"PUT",body:t})}}toggleRepoCustomInstructions(e){this.dispatch({type:"TOGGLE_REPO_CUSTOM_INSTRUCTIONS",value:e}),g.J.setRepoCustomInstructionsState(e)}viewAllThreads(){this.dispatch({type:"VIEW_ALL_THREADS"})}viewCurrentThread(){this.dispatch({type:"VIEW_CURRENT_THREAD"})}maxMessagesReached(){return this.getChatState().messages.length>=3e3}async sendChatMessage({thread:e,content:t,references:s,topic:a,context:r,confirmations:i,customInstructions:n,model:o,customCopilotId:c,intent:d=u.wh.conversation,tools:h,clientToolResults:g,parentMessageId:m,modeOverride:E,skillOptions:f}){let _=(0,l.P)(a),S=_?void 0:a;_&&!s.some(e=>"docset"===e.type&&e.name===a.name)&&s.push({type:"docset",name:a.name,id:a.id,avatarUrl:a.avatarUrl,repos:a.repos,description:a.description});let T=p.W.attachImagesImmersive?await Promise.all(s.filter(e=>"image"===e.type).map(e=>e.attachment).map(async e=>{let t=await e.url(),s=e.file;return{mediaType:s.type,name:s.name,url:t,chatAttachmentUrl:t,width:e.width,height:e.height}})):[],I=s.filter(e=>"image"!==e.type);return I=I.filter(e=>"figma"!==e.type||!e.authenticationRequired),this.sendNewMessage(e,t,T,d,I,S,r,i,n,o,c,h,g,m,E,f)}FindLastMessageID(){let e=(0,h.B)(this.getChatState().messages);return e[e.length-1]?.id||"root"}async retryLastUnsuccessfulChatMessage(e){let{currentTopic:t,context:s,customInstructions:a,model:r}=this.getChatState(),i=(0,l.P)(t)?void 0:t,n=(0,h.B)(this.getChatState().messages).findLast(e=>"user"===e.role);if(!n?.content)return;let o=e.currentReferences||[],c=n.mediaContent||[];this.dispatch({type:"MESSAGES_CLEAR_LAST_ERROR"}),this.unselectPreviousChildMessage(n);let d="";if(n.clientSide){let e=(0,h.B)(this.getChatState().messages).findLast(e=>!e.clientSide);d=e?"user"===e.role?e.parentMessageID||"root":e.id:"root"}else d=n.id;return this.sendMessage(e,n.content,c,o,u.wh.conversation,s,i,a,r,void 0,d)}async retryUserChatMessage(e,t,s){let a;let{currentTopic:r,context:i,customInstructions:n,model:o}=this.getChatState(),c=(0,l.P)(r)?void 0:r;if(t.parentMessageID&&(a=this.getChatState().messages.findLast(e=>e.id===t.parentMessageID)),!a||!a.content)return;this.unselectPreviousChildMessage(a);let d=a.references||[],h=a.mediaContent||[];return this.sendMessage(e,a.content,h,d,u.wh.conversation,i,c,n,s||o,void 0,a.id)}async editUserChatMessage(e,t,s){if(!s)return;let{currentTopic:a,context:r,customInstructions:i,messages:n,model:o}=this.getChatState(),c=(0,l.P)(a)?void 0:a,d=(0,h.CX)(n,t);if(!d)return;let p=d?.id||"",g=t.clientConfirmations??[],m=t.references||[],E=t.mediaContent||[],f=(0,l.Y6)({role:"user",content:s,mediaContent:E,references:m,thread:e,confirmationResponses:g,parentMessageID:p}),_=(0,l.lG)(c,m);if(this.dispatch({type:"MESSAGE_ADDED",message:f,repoHasCustomInstructions:!!_,usedRepoCustomInstructions:!!(_&&this.repoInstructionsEnabled())}),this.reloadingThreadPromise&&(this.dispatch({type:"WAITING_ON_COPILOT",loading:!0}),this.afterThreadReloadCallback=()=>{this.dispatch({type:"MESSAGE_ADDED",message:f,repoHasCustomInstructions:!!_,usedRepoCustomInstructions:!!(_&&this.repoInstructionsEnabled())})},!await this.reloadingThreadPromise))return;let S=d;for(;S&&S.clientSide;)S=(0,h.CX)(n,S);return this.sendMessage(e,s,E,m,u.wh.conversation,r,c,i,o,void 0,S?.id||"")}handleFeedback(e,t){this.dispatch({type:"MESSAGE_FEEDBACK",message:e,feedback:t})}setSelectedMessage(e){this.dispatch({type:"MESSAGES_SET_SELECTED_MESSAGE",message:e})}unselectPreviousChildMessage(e){this.dispatch({type:"MESSAGES_UNSELECT_PREVIOUS_MESSAGE",message:e})}async stopStreaming(){this.streamer?(await this.streamer.stop(),this.streamer=void 0):this.messageAbortController?.abort(),this.dispatch({type:"MESSAGE_STREAMING_STOPPED",timings:this.completeTiming()})}async getSystemPrompt(){let{mode:e}=this.getChatState();return await this.systemPrompt(e)}async createThread(e){let t;let s=await this.service.createThread(e);if(s.ok)return t=s.payload,g.J.migrateNullThreadToNewThread(t.id),this.dispatch({type:"THREAD_CREATED",thread:t}),t;throw Error(s.error)}async sendNewMessage(e,t,s,a,r,i,n,o,c,d,u,p,m,E,f,_){let{clientSkillConfirmation:S}=this.getChatState();S&&(this.dispatch({type:"CLIENT_SKILL_CONFIRMATION_REQUEST",confirmation:void 0}),this.skillExecutor?.resetExecution());let T=(0,l.Y6)({role:"user",content:t,mediaContent:s,references:r,thread:e,confirmationResponses:o?[o]:[],parentMessageID:E||this.FindLastMessageID(),clientToolResults:m,skillOptions:_}),I=(0,l.lG)(i,r);if(this.dispatch({type:"MESSAGE_ADDED",message:T,repoHasCustomInstructions:!!I,usedRepoCustomInstructions:!!(I&&this.repoInstructionsEnabled())}),!e)try{e=await this.createThread(u)}catch(a){let s="An unexpected error has occurred.";a instanceof Error&&(s=a.message),this.handleSendMessageError(e,B(s),t);return}this.dispatch({type:"THREAD_UPDATED",thread:{id:e.id,updatedAt:new Date().toISOString()}}),this.dispatch({type:"CLEAR_CURRENT_REFERENCES",keepTypes:["docset","magic-knowledge-base"]}),d&&g.J.setModel(e.id,d);let C="";if(!E){let e=(0,h.B)(this.getChatState().messages),t=e[e.length-1];if(E=t?t.clientSide?e.findLast(e=>!e.clientSide&&"assistant"===e.role)?.id||"root":t.id:"root",this.reloadingThreadPromise&&(this.dispatch({type:"WAITING_ON_COPILOT",loading:!0}),this.afterThreadReloadCallback=e=>{0!==e.length&&(C=e[e.length-1].id,T.parentMessageID=C,this.dispatch({type:"MESSAGE_ADDED",message:T,repoHasCustomInstructions:!!I,usedRepoCustomInstructions:!!(I&&this.repoInstructionsEnabled())}))},!await this.reloadingThreadPromise))return}return this.sendMessage(e,t,s,r,a,n,i,c,d,o,C||E,p,m,f,_)}async sendMessage(e,t,s,a,r,n,o,d,h,u,g,E=[],f,_,S){let T=(0,l.Y6)({role:"assistant",content:"",mediaContent:[],thread:e,parentMessageID:g});T.messageIndex=-1,this.dispatch({type:"WAITING_ON_COPILOT",loading:!0});let I=a.length&&(1!==a.length||a[0]?.type!=="repository")?void 0:n;(0,i.BI)("copilot.implicit_context",{usedImplicitContext:!!I,type:I?.[0]?.type,count:I?.length}),!a.length&&o&&(a=[(0,l.qS)(o)]);let C=[];if(this.repoInstructionsEnabled()){if(p.W.topicsAsReferences){let e=(0,l.NJ)(a);C.push(...e)}else o?.customInstructions&&C.push(...o.customInstructions)}d?.type!=="Organization"||C.find(e=>"Organization"===e.type)||C.push(d),d?.type==="Assistant"&&C.push(d);let y=C.find(e=>"Organization"===e.type);y&&a.push((0,l.lj)(y.owner));let R=C.map(e=>e.prompt),{mode:w}=this.getChatState();this.timings={startTime:Date.now()},this.streamer=void 0,this.messageAbortController=new AbortController;let A=[...E,...D(window.location.pathname)];try{let i={threadID:e.id,messageID:T.id,content:t,mediaContent:s,intent:r,mode:_||w,references:a,context:I??[],confirmations:u?[u]:[],customInstructions:R,model:h?.id,customCopilotID:(0,m.Xw)(e),parentMessageID:g,tools:A,clientToolResults:f,signal:this.messageAbortController.signal,skillOptions:S},n=this.activePlugin?.overrideCreateMessageOptions?await this.activePlugin.overrideCreateMessageOptions(i):i,o=await this.service.createMessageStreaming(n);if(o.ok){let s=o.response.body?.getReader();if(!s){this.handleSendMessageError(e,B(l.DW),t);return}T.requestID=o.response.headers.get("x-github-request-id")||void 0;let a=new c.X(s);this.streamer=a,this.dispatch({type:"MESSAGE_STREAMING_STARTED",message:T}),await this.handleStreamingMessage(e,a)}else{if(this.messageAbortController.signal.aborted)return;this.handleSendMessageError(e,B(o.error),t)}}finally{this.streamer=void 0,this.messageAbortController=void 0}}repoInstructionsEnabled(){return(p.W.repoCustomInstructions||p.W.repoCustomInstructionsPreview)&&g.J.getRepoCustomInstructionsState()}async populateReferenceLanguage(e){let t=await this.service.fetchLanguageForFileReference(e);if(t.ok&&t.payload.language){let{languageName:s,languageId:a}=t.payload.language;this.replaceReference(e,{...e,languageName:s,languageId:a})}}addReference(e,t){this.dispatch({type:"ADD_REFERENCE",reference:e,source:t}),(0,l.SI)(e)&&(void 0===e.languageId||void 0===e.languageName)&&this.populateReferenceLanguage(e)}removeReference(e){e&&($([e]),this.dispatch({type:"REMOVE_REFERENCES",references:[e]}))}removeReferences(e){$(e),this.dispatch({type:"REMOVE_REFERENCES",references:e})}replaceReference(e,t){this.dispatch({type:"REPLACE_REFERENCE",referenceToDelete:e,referenceToInsert:t})}setImageAttachmentUploaded(e,t){this.dispatch({type:"IMAGE_UPLOADED",referenceId:e,dotcomAttachment:t})}selectModel(e,t){this.dispatch({type:"SELECT_MODEL",model:e}),"url"!==t&&g.J.setModel(this.getChatState().selectedThreadID,e)}selectPlugin(e){(this.getChatState().activePlugin??null)!==e&&(!e||this.plugins.find(t=>t.id===e))&&this.dispatch({type:"SELECT_PLUGIN",plugin:e})}get activePlugin(){return this.plugins.find(e=>e.id===this.getChatState().activePlugin)}setCopilotSettings(e){g.J.settings=e}async dismissAttachKnowledgeBaseHerePopover(){this.dispatch({type:"DISMISS_ATTACH_KNOWLEDGE_BASE_HERE_POPOVER"}),await (0,n.DI)("/settings/dismiss-notice/copilot_for_docs_attach_knowledge_base_here",{method:"POST"})}async dismissKnowledgeBaseAttachedToChatPopover(){this.dispatch({type:"DISMISS_KNOWLEDGE_BASE_ATTACHED_TO_CHAT_POPOVER"}),await (0,n.DI)("/settings/dismiss-notice/copilot_for_docs_knowledge_base_attached_to_chat",{method:"POST"})}async selectThread(e,t){let{clearTopic:s,includeThreads:a=!0}=t??{};await this.fetchModels(),await this.stopStreaming(),this.dispatch({type:"CLEAR_SHARED_THREAD_CHANNEL"}),this.dispatch({type:"SELECT_THREAD",thread:e,clearTopic:s});let r=[];r.push(this.fetchMessages(e?.id||null)),a&&r.push(this.fetchThreads()),await Promise.all(r)}addMessage(e,t,s,a,r,i,n){let o=(0,l.Y6)({role:e,content:s,mediaContent:a,references:r,thread:t,confirmationResponses:i,clientSkillConfirmations:n,parentMessageID:this.FindLastMessageID()});this.dispatch({type:"MESSAGE_ADDED",message:o})}async renameThread(e,t){(await this.service.renameThread(e.id,t)).ok&&this.dispatch({type:"THREAD_UPDATED",thread:{id:e.id,name:t}})}dismissAmbientError(){this.dispatch({type:"DISMISS_AMBIENT_ERROR"})}addAmbientError(e){this.dispatch({type:"ADD_AMBIENT_ERROR",message:e})}async clearThread(e){(await this.service.clearThread(e.id)).ok&&this.dispatch({type:"CLEAR_THREAD",threadID:e.id})}async deleteThreadKeepSelection(e){this.dispatch({type:"DELETE_THREAD_KEEP_SELECTION",thread:e});let t=await this.service.deleteThread(e.id);t.ok||this.dispatch({type:"DELETE_THREAD_ERROR",thread:e,error:t.error})}async deleteAllThreadKeepSelection(e){this.dispatch({type:"DELETE_ALL_THREADS_KEEP_SELECTION",threads:e});let t=e.map(e=>e.id);for(let s=0;s<t.length;s+=100){let a=t.slice(s,s+100),r=await this.service.deleteAllThreads({threadIDs:a});r.ok||this.dispatch({type:"DELETE_ALL_THREADS_ERROR",threads:e,error:r.error})}}async deleteThread(e){this.dispatch({type:"DELETE_THREAD",thread:e});let t=await this.service.deleteThread(e.id);t.ok||this.dispatch({type:"DELETE_THREAD_ERROR",thread:e,error:t.error})}generateSuggestions(e){let t=(0,l.mx)(e);this.dispatch({type:"SUGGESTIONS_GENERATED",suggestions:t})}clearSuggestions(){this.dispatch({type:"CLEAR_SUGGESTIONS"})}async handleOpenPanelEvent(e,t,s,a){let r=t.payload,n=!e&&s,c=e&&s;if(U(r)||x(r,[u.wh.conversation])&&"newThread"in r&&r.newThread?(await this.selectThread(null),e=null):x(r,[u.wh.reviewPr])?(this.addMessage("user",r.thread,o.Bc,[],r.references),this.addMessage("assistant",r.thread,r.completion,[],r.references),this.selectThread(r.thread,{includeThreads:!1})):n||(p.W.copilotChatOpeningThreadSwitch?x(r,[u.wh.conversation])&&"attachThread"in r&&r.attachThread&&!s||c?e=await this.findOrStartNewThread(e):(await this.selectThread(null),e=null):e=await this.findOrStartNewThread(e)),this.dispatch({type:"HANDLE_EVENT_START",references:r.references,id:r.id}),x(r,[u.wh.conversation,u.wh.discussFileDiff,u.wh.reviewPr])&&!U(r))return;let d=`blob ${r.intent}`;r.id&&(d=`element ${t.payload.id}`),(0,i.BI)("copilot.open_copilot_chat",{source:d}),await this.sendNewMessage(e,r.content,[],r.intent,r.references??[],(0,l.Z6)(a)?a:void 0,void 0,void 0,void 0,null,void 0)}async handleSearchCopilotEvent(e){let t=await this.fetchCurrentRepo(e.repoNwo),s=t?[{type:"repository",...t}]:[];this.openChat(null,"thread","search-bar"),await this.sendNewMessage(null,e.content,[],u.wh.conversation,s),(0,i.BI)("copilot.open_copilot_chat",{source:"search-bar"})}handleAddReferenceEvent(e){this.addReference(e.reference,"event"),e.openPanel&&this.dispatch({type:"OPEN_COPILOT_CHAT",source:"event",id:e.id})}handleSymbolChangedEvent(e){let t=e.context;this.dispatch({type:"IMPLICIT_CONTEXT_UPDATED",context:[t]})}getSelectedThread(e){return e.selectedThreadID&&e.threads.get(e.selectedThreadID)||null}sortThreads(e){return Array.from(e.values()).sort((e,t)=>new Date(t.updatedAt).getTime()-new Date(e.updatedAt).getTime())}async sendMessageToNewThread(e,t,s,a){if(""===t.trim()){let[e,a]=this.tryInferMessage(s);if(!e||!a)return;t=a}e&&(g.J.setSavedMessageFast(e,null),g.J.clearCurrentReferences(e)),await this.sendNewMessage(null,t,[],u.wh.conversation,s,void 0,a)}startThreadReload(){this.reloadingThreadPromise=new Promise(e=>{this.resolvePromise=e})}cancelThreadReload(){this.resolvePromise(!1),this.resolvePromise=()=>{},this.reloadingThreadPromise=void 0,this.afterThreadReloadCallback=void 0,this.fetchingThreadID=null}async fetchMessages(e,t=!1,s=!1){let a=g.J.getCurrentReferences(e);if(!e)return this.threadDataLoaded(e,[],a||[]),()=>{};t||this.dispatch({type:"MESSAGES_UPDATED",state:"loading"});let r=this.getChatState().messages;this.fetchingThreadID=e;let i=async s=>{let n=await this.service.listMessages(e);if(t&&this.fetchingThreadID!==e)return!1;if(!n.ok)return this.dispatch({type:"MESSAGES_UPDATED",state:"error",...404===n.status?{notFound:!0,missingOrgIds:n.payload?.missingOrgIds}:{}}),this.afterThreadReloadCallback=void 0,!1;if(s&&n.payload.messages.length===r.length)return i(!1);{let t=n.payload.thread;return this.threadDataLoaded(e,n.payload.messages,a||t.currentReferences||[]),this.afterThreadReloadCallback&&(this.afterThreadReloadCallback(n.payload.messages),this.afterThreadReloadCallback=void 0),!0}},n=await i(s);return()=>{this.resolvePromise(n),this.resolvePromise=()=>{},this.reloadingThreadPromise=void 0}}async fetchSharedThreadMessages(e){if(!e)return;this.dispatch({type:"MESSAGES_UPDATED",state:"loading"});let t=await this.service.listSharedThreadMessages(e);if(this.dispatch({type:"FETCH_SHARED_THREAD_MESSAGES",ok:t.ok,status:t.status,shareId:e}),t.ok){this.threadDataLoaded(e,t.payload.messages,[]),await this.fetchModels();let s=t.payload.messages?.at(-1)?.model,a=s&&this.getChatState().availableModels?.find(e=>e.id===s);a&&this.selectModel(a)}else this.dispatch({type:"MESSAGES_UPDATED",state:"error"})}selectReference(e){this.dispatch({type:"SELECT_REFERENCE",reference:e})}setTopRepositoryTopics(e){this.dispatch({type:"SET_TOP_REPOSITORIES",topics:e})}async handleStreamingMessage(e,t){try{for await(let s of t.stream())await this.processStreamingMessage(e,s)}catch(s){let t=this.isWrappedStreamingResponseError(s)?this.getStreamingErrorMessage(s.error):B(l.DW);this.handleSendMessageError(e,t);return}}isWrappedStreamingResponseError(e){return!!e&&"object"==typeof e&&"error"in e&&!!e.error&&"object"==typeof e.error&&"errorType"in e.error&&"string"==typeof e.error.errorType&&u.C6.includes(e.error.errorType)}async processStreamingMessage(e,t){var s,a,r;switch((s=this.timings).firstByte??(s.firstByte=Date.now()),t.type){case"content":(a=this.timings).firstToken??(a.firstToken=Date.now()),this.dispatch({type:"MESSAGE_STREAMING_TOKEN_ADDED",token:t.body});break;case"functionCall":r=t.name,u.xP.includes(r)&&this.dispatch({type:"MESSAGE_STREAMING_FUNCTION_CALLED",name:t.name,status:t.status,arguments:t.arguments,errorMessage:t.errorMessage,references:t.references,statusMessage:t.statusMessage});break;case"clientSkillsRequest":if(p.W.dotcomChatClientSideSkills){let e=this.getChatState(),s=this.getSelectedThread(e);this.skillExecutor=new SkillExecutor(s,t.toolCalls,e=>void this.sendChatMessage(e),e,this.dispatch),this.dispatch({type:"CLIENT_SKILLS_REQUEST",toolCalls:t.toolCalls})}break;case"confirmation":this.dispatch({type:"MESSAGE_STREAMING_CONFIRMATION",title:t.title,message:t.message,confirmation:t.confirmation});break;case"complete":p.W.customCopilots&&(t.references=(0,E.q)(t.references)),this.dispatch({type:"MESSAGE_STREAMING_COMPLETED",messageResponse:t,timings:this.completeTiming()}),await this.handleSendMessageSuccess(e),p.W.dotcomChatClientSideSkills&&(this.skillExecutor?.setParentMessageId(t.id),await this.skillExecutor?.run());break;case"error":{let s=this.getStreamingErrorMessage(t);this.handleSendMessageError(e,s);break}case"debug":console.log("Prompt Body:",t.body);break;case"agentError":this.dispatch({type:"AGENT_ERROR",error:{type:t.agentErrorType,code:t.code,message:t.message,identifier:t.identifier}})}}getStreamingErrorMessage(e){switch(e.errorType){case"publicCode":{let e="https://docs.github.com/en/copilot/managing-copilot/managing-copilot-as-an-individual-subscriber/managing-copilot-policies-as-an-individual-subscriber",t=(0,r.jsxs)(r.Fragment,{children:["This response cannot be shown because it references public code, which is restricted by"," ",(0,r.jsx)("a",{href:e,children:"your Copilot settings"}),"."]});return this.hasCEorCBAccess&&(e="https://docs.github.com/en/enterprise-cloud@latest/copilot/managing-copilot/managing-github-copilot-in-your-organization/managing-policies-for-copilot-in-your-organization",t=(0,r.jsxs)(r.Fragment,{children:["This response cannot be shown because it references public code, which is restricted by"," ",(0,r.jsx)("a",{href:e,children:"your organization's Copilot settings"}),"."]})),{type:"publicCode",isError:!0,message:t,retryable:!1}}case"filtered":return H(l.nN[403]||l.DW,"filtered");case"contentTooLarge":return H(l.nN[413]||l.DW);case"rateLimit":return B(l.nN[429]||l.DW);case"agentUnauthorized":{let t=JSON.parse(e.description);return{type:"agentUnauthorized",isError:!0,message:`You haven't authorized ${t.name} to access your account. You can do that by going here: ${window.location.origin}/login/oauth/authorize?client_id=${t.client_id}`,details:t}}case"agentRequest":{let t=JSON.parse(e.description);return{type:"agentRequest",isError:!0,message:t.message,details:t}}case"multipleAgentsAttempt":return B("Only one agent is allowed per thread, and their context can't be shared. If you want to interact with another agent, please start a new thread and @ mention the new agent.");case"networkError":return B(l.nN[408]||l.DW);default:return B(l.FF[e.errorType]||l.DW)}}async handleSendMessageSuccess(e){g.J.setSavedMessageFast(e.id,null),g.J.clearCurrentReferences(e.id),this.dispatch({type:"WAITING_ON_COPILOT",loading:!1}),e=await this.generateThreadName(e),this.dispatch({type:"THREAD_UPDATED",thread:{id:e.id,updatedAt:new Date().toISOString()}})}handleSendMessageError(e,t,s){e&&s&&g.J.setSavedUserMessageOnError(e.id,s);let a=h.B(this.getChatState().messages).findLast(e=>"user"===e.role)?.id||"root",r=(0,l.Y6)({role:"assistant",content:"",mediaContent:[],error:t,thread:e,parentMessageID:a});this.dispatch({type:"MESSAGE_ADDED",message:r}),this.dispatch({type:"WAITING_ON_COPILOT",loading:!1}),this.dispatch({type:"MESSAGE_STREAMING_FAILED",timings:this.completeTiming()})}async fetchModels(){if(G){let{availableModels:e}=this.getChatState();(!e||G.length>e.length)&&this.dispatch({type:"MODELS_LOADED",models:G});return}this.dispatch({type:"MODELS_LOADING"});let e=await this.service.listModels();if(e.ok){let t=(0,f.eW)(e.payload);G=t,this.dispatch({type:"MODELS_LOADED",models:t});let s=g.J.getModel(this.getChatState().selectedThreadID)?.id,a=t.find(e=>e.id===s);a&&this.dispatch({type:"SELECT_MODEL",model:a})}else this.dispatch({type:"MODELS_LOADING_ERROR",error:e.error})}async acceptModelPolicy(e){e.policy&&"enabled"!==e.policy.state&&(await this.service.setModelPolicyState(e.id,"enabled"),G=null,this.fetchModels())}async fetchThreads(){this.dispatch({type:"THREADS_LOADING"});let e=await this.service.fetchThreads();return e.ok?(setTimeout(()=>this.dispatch({type:"THREADS_LOADED",threads:e.payload}),100),e.payload):(setTimeout(()=>this.dispatch({type:"THREADS_LOADING_ERROR",message:e.error,status:e.status}),100),null)}async fetchSharedThreads(){this.dispatch({type:"SHARED_THREADS_LOADING"});let e=await this.service.fetchSharedThreads();return e.ok?(setTimeout(()=>this.dispatch({type:"SHARED_THREADS_LOADED"}),100),e.payload):(setTimeout(()=>this.dispatch({type:"SHARED_THREADS_LOADING_ERROR",message:e.error}),100),null)}async fetchLatestThread(e){let t=await this.service.fetchLatestThread(e);return t.ok?(t.payload&&this.dispatch({type:"LATEST_THREAD_LOADED",latestThread:t.payload}),t.payload):null}async continueSharedThread(e){if(!e)return this.dispatch({type:"THREAD_CONTINUED_FAILED"}),null;this.dispatch({type:"MESSAGES_UPDATED",state:"loading"});let t=await this.service.continueSharedThread(e);if(!t.ok)return null;{let{thread:e,messages:s}=t.payload;this.dispatch({type:"THREAD_CONTINUED",thread:e}),this.dispatch({type:"MESSAGES_UPDATED",state:"loaded",messages:s})}return t.payload}async unshareAllThreads(){let e=await this.service.unshareAllThreads();if(!e.ok)return this.dispatch({type:"ADD_AMBIENT_ERROR",message:e.error||"Failed to unshare all threads"}),e;for(let e of Array.from(this.getChatState().threads.values()))e.sharedAt&&this.dispatch({type:"THREAD_UPDATED",thread:{id:e.id,sharedAt:void 0,sharedID:void 0}});return e}async findOrStartNewThread(e,t){let s=null;if(e)s=e;else{let e=g.J.selectedThreadID||void 0;s=await this.fetchLatestThread(e)}if(s&&((0,l.F2)(s)||s.customCopilotID)&&(s=null),s&&t){let e=await this.service.listMessages(s.id);if(e.ok){let a=e.payload.messages,r=a?.length;r>=2&&!a[r-2]?.references?.find(e=>l.x_(e,t))&&(s=null)}}return await this.selectThread(s,{includeThreads:!1}),s}async generateThreadName(e){if(e.name)return e;let t=await this.service.generateThreadName(e.id);return t.ok&&(e={...e,name:t.payload}),e}async systemPrompt(e){let t=await this.service.getSystemPrompt(e);return t.ok?t.payload.prompt:""}async fetchAgents(e){let t=await this.service.listAgents(e),s=[];return t.ok&&(s=t.payload,this.dispatch({type:"SET_AGENTS",agents:s})),s}async fetchCustomCopilot(e){if(!p.W.customCopilots)return{};let t=await this.service.fetchCustomCopilot(e),s={};return t.ok&&(s=t.payload),s}async fetchCurrentRepo(e){if(p.W.topicsAsReferences){let t=await this.service.fetchRepo(e);return t.ok?(this.dispatch({type:"ADD_REFERENCE",reference:(0,l.qS)(t.payload),source:"currentRepo"}),t.payload):void 0}this.dispatch({type:"CURRENT_TOPIC_UPDATED",topic:void 0,state:"loading"});let t=await this.service.fetchRepo(e);if(t.ok)return this.dispatch({type:"CURRENT_TOPIC_UPDATED",topic:t.payload,state:"loaded"}),t.payload;this.dispatch({type:"CURRENT_TOPIC_UPDATED",topic:void 0,state:"error"})}async fetchKnowledgeBases(){this.dispatch({type:"KNOWLEDGE_BASES_LOADING"});let e=await this.service.listDocsets();return e.ok?this.dispatch({type:"KNOWLEDGE_BASES_LOADED",knowledgeBases:e.payload}):this.dispatch({type:"KNOWLEDGE_BASES_LOADING_ERROR",message:e.error}),e}async fetchImplicitContext(e,t,s){let a=await this.service.fetchImplicitContext(e,t,s);if(a.ok){let e=a.payload?Array.isArray(a.payload)?a.payload:[a.payload]:void 0;this.dispatch({type:"IMPLICIT_CONTEXT_UPDATED",context:e}),e&&e.length>0&&void 0!==e[0]&&this.generateSuggestions(e[0])}}async deleteDocset(e){return(await this.service.deleteDocset(e)).ok}threadDataLoaded(e,t,s){let{activePlugin:a}=this.getChatState();if(e){let r=this.plugins.find(a=>a.matchThread?.(e,t,s));r?.id!==a&&this.dispatch({type:"SELECT_PLUGIN",plugin:r?.id})}this.dispatch({type:"MESSAGES_UPDATED",messages:t,state:"loaded"}),this.dispatch({type:"REFERENCES_LOADED",references:s})}dismissEditorUpsellBanner(){let e=new FormData;e.set("copilot_editor_upsell_banner_dismissed","true"),(0,n.DI)("/github-copilot/preferences",{method:"PUT",body:e}),this.dispatch({type:"DISMISS_EDITOR_UPSELL_BANNER"})}tryInferMessage(e){return e&&e.find(e=>"image"===e.type)?[!0,"Describe this image"]:[!1,void 0]}setWrapCodeLines(e){this.dispatch({type:"SET_WRAP_CODE_LINES",value:e}),g.J.setWrapCodeLines(e)}completeTiming(){return{...this.timings,endTime:Date.now()}}constructor(e,t,s,a,r,i,n,o,l){k(this,"dispatch",void 0),k(this,"service",void 0),k(this,"getChatState",void 0),k(this,"hasCEorCBAccess",void 0),k(this,"timings",{startTime:0}),k(this,"skillExecutor",void 0),k(this,"streamer",void 0),k(this,"messageAbortController",void 0),k(this,"reloadingThreadPromise",void 0),k(this,"fetchingThreadID",null),k(this,"afterThreadReloadCallback",void 0),k(this,"plugins",void 0),k(this,"clearCurrentReferences",e=>{e&&e.includes("image")||$(this.getChatState().currentReferences),this.dispatch({type:"CLEAR_CURRENT_REFERENCES",keepTypes:e})}),k(this,"resolvePromise",()=>{}),k(this,"clearCurrentTopic",()=>{this.dispatch({type:"CURRENT_TOPIC_UPDATED",topic:void 0,state:"loaded"})}),k(this,"showTopicPicker",(e=!0)=>{this.dispatch({type:"SHOW_TOPIC_PICKER",show:e})}),k(this,"startEditingMessage",e=>this.dispatch({type:"START_EDITING_MESSAGE",messageId:e})),k(this,"cancelEditingMessage",()=>this.dispatch({type:"CANCEL_EDITING_MESSAGE"})),this.dispatch=e,this.service=i??new d.k(t,s,r,l),this.getChatState=a,this.hasCEorCBAccess=!!n,this.plugins=o}};function U(e){var t;return x(e,[u.wh.explain,u.wh.suggest])||x(e,[u.wh.conversation])&&"content"in(t=e)&&"string"==typeof t.content}function x(e,t){return new Set(t).has(e.intent)}function B(e){return{isError:!0,message:e,type:"basic",retryable:!0}}function H(e,t){return{isError:!0,message:e,type:t||"basic",retryable:!1}}function F(e,t){let s=document.getElementById(e);s?.setAttribute("aria-expanded",t?"true":"false")}function $(e){for(let t of e)if("image"===t.type){let e=t.attachment;e instanceof M.N&&e.abortController.abort("Reference removed before upload completed")}}try{(a=Intent).displayName||(a.displayName="Intent")}catch{}},59937:(e,t,s)=>{s.d(t,{T:()=>BlobService});var a=s(56244),r=s(82610),i=s(57572),n=s(70586);let BlobService=class BlobService{async fetchBlob(e,t,s,a,o){try{let l=(0,n.WN)({commitOid:o,owner:t,path:e,pullNumber:s,repo:a}),c=await (0,i.Sr)(l,{method:"GET"});if(c.ok){let e=await c.json();return{status:c.status,ok:!0,payload:e}}return{status:c.status,ok:!1,error:r.DW}}catch{return{status:500,ok:!1,error:r.DW}}}async getBlob(e,t,s,a,r){return this.blobCache.get(e,t,s,a,r)}constructor(){!function(e,t,s){t in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s}(this,"blobCache",new a.d(this.fetchBlob))}}},42261:(e,t,s)=>{s.d(t,{kk:()=>i,mL:()=>l,qm:()=>o,sT:()=>r,t:()=>n});var a=s(4460);let r="open_panel",i="pull_request_review_comment_id",n="initial_path";function o(e){let t=new URL(window.location.href,window.location.origin);t.searchParams.delete(e),(0,a.kd)(t.toString())}function l(e,t,s){let r=new URL(window.location.href,window.location.origin);r.searchParams.set(e,t),s?s(r.searchParams):(0,a.kd)(r.toString())}},70586:(e,t,s)=>{s.d(t,{KD:()=>h,PW:()=>d,WN:()=>u,Wd:()=>i,ic:()=>m,iw:()=>c,sy:()=>g,tH:()=>l,uY:()=>p});var a=s(5796),r=s(42261);let i="edit";function n({owner:e,repo:t,pullNumber:s}){return`/${encodeURIComponent(e)}/${encodeURIComponent(t)}/pull/${s}`}function o({owner:e,repo:t,pullNumber:s}){return`${n({owner:e,repo:t,pullNumber:s})}/${i}`}function l({owner:e,repo:t,pullNumber:s,location:a}){return o({owner:e,repo:t,pullNumber:s})+(a?.search||"")}function c({owner:e,repo:t,pullNumber:s,path:r,location:i}){return`${o({owner:e,repo:t,pullNumber:s})}/file/${(0,a.QU3)(r)}`+(i?.search||"")}function d({owner:e,repo:t,pullNumber:s}){return`${n({owner:e,repo:t,pullNumber:s})}/workspace_editor/suggestions`}function h({owner:e,repo:t,pullNumber:s,pullRequestReviewCommentId:a}){return`${n({owner:e,repo:t,pullNumber:s})}/workspace_editor/suggestions/${a}`}function u({commitOid:e,owner:t,repo:s,pullNumber:a,path:r,location:i}){return`${n({owner:t,repo:s,pullNumber:a})}/workspace_editor/files/${encodeURIComponent(e)}/${encodeURIComponent(r)}`+(i?.search||"")}function p({owner:e,repo:t,pullNumber:s,location:a,path:i}){let n=`${o({owner:e,repo:t,pullNumber:s})}/new`,l=new URLSearchParams(a?.search||"");if(i&&i.includes("/")){let e=i.substring(0,i.lastIndexOf("/")+1);l.set(r.t,e)}return n+(l.toString()?`?${l.toString()}`:"")}function g({owner:e,repo:t,pullNumber:s}){return`${o({owner:e,repo:t,pullNumber:s})}/commit_changes`}function m({owner:e,repo:t,pullNumber:s,analyzeDiffs:a=!1,detectRisk:r=!1}){let i=`${n({owner:e,repo:t,pullNumber:s})}/diff`,o=new URLSearchParams({analyze_diffs:a.toString(),detect_risk:r.toString()});return`${i}?${o.toString()}`}}}]);
//# sourceMappingURL=ui_packages_copilot-chat_utils_CopilotChatContext_tsx-09d4532d9a84.js.map