@github/copilot 0.0.352-1 → 0.0.352-3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.js +2 -2
- package/package.json +2 -2
- package/sdk/index.js +1 -1
package/index.js
CHANGED
|
@@ -1903,7 +1903,7 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
|
1903
1903
|
Body doesn't contain an array property with name: ${e}`);return l??[]}function t0n(t,e){if(!e.includes(t.status))throw Sh(`Pagination failed with unexpected statusCode ${t.status}`,t)}function k8(t,e,l){return(e??l==="+")||l==="#"?wOt(t):QOt(t)}function wOt(t){return t.split(/(%[0-9A-Fa-f]{2})/g).map(e=>/%[0-9A-Fa-f]/.test(e)?e:encodeURI(e)).join("")}function QOt(t){return encodeURIComponent(t).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function Bde(t){return t!=null}function E6e(t){return[!!t&&[";","?","&"].includes(t),t&&["?","&"].includes(t)?"=":""]}function Q1e(t,e=!1){return e?!t||t==="+"?"":t:!t||t==="+"||t==="#"?",":t==="?"?"&":t}function l0n(t){let e=t.isFirst,{op:l,varName:n,varValue:r,reserved:a}=t,I=[],[s,o]=E6e(l);if(Array.isArray(r))for(let c of r.filter(Bde))I.push(`${Q1e(l,e)}`),s&&n&&(I.push(`${encodeURIComponent(n)}`),c===""?I.push(o):I.push("=")),I.push(k8(c,a,l)),e=!1;else if(typeof r=="object")for(let c of Object.keys(r)){let d=r[c];Bde(d)&&(I.push(`${Q1e(l,e)}`),c&&(I.push(`${encodeURIComponent(c)}`),s&&d===""?I.push(o):I.push("=")),I.push(k8(d,a,l)),e=!1)}return I.join("")}function n0n(t){let{op:e,varName:l,varValue:n,isFirst:r,reserved:a}=t,I=[],s=Q1e(e,r),[o,c]=E6e(e);if(o&&l){if(I.push(k8(l,a,e)),n==="")return c||I.push(c),I.join("")?`${s}${I.join("")}`:void 0;I.push("=")}let d=[];if(Array.isArray(n))for(let m of n.filter(Bde))d.push(k8(m,a,e));else if(typeof n=="object")for(let m of Object.keys(n))Bde(n[m])&&(d.push(QOt(m)),d.push(k8(n[m],a,e)));return I.push(d.join(",")),I.join(",")?`${s}${I.join("")}`:void 0}function r0n(t){let{op:e,varName:l,modifier:n,isFirst:r,reserved:a,varValue:I}=t;if(Bde(I))if(["string","number","boolean"].includes(typeof I)){let s=I.toString(),[o,c]=E6e(e),d=[Q1e(e,r)];return o&&l&&(d.push(l),s===""?d.push(c):d.push("=")),n&&n!=="*"&&(s=s.substring(0,parseInt(n,10))),d.push(k8(s,a,e)),d.join("")}else return n==="*"?l0n(t):n0n(t);else return}function ay(t,e,l){return t.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g,(n,r,a)=>{if(!r)return wOt(a);let I;["+","#",".","/",";","?","&"].includes(r[0])&&(I=r[0],r=r.slice(1));let s=r.split(/,/g),o=[];for(let c of s){let d=/([^:\*]*)(?::(\d+)|(\*))?/.exec(c);if(!d||!d[1])continue;let m=r0n({isFirst:o.length===0,op:I,varValue:e[d[1]],varName:d[1],modifier:d[2]||d[3],reserved:l?.allowReserved});m&&o.push(m)}return o.join("")})}function a0n(t,e,l={requestOptions:{}}){var n,r;let a=ay("/secrets/restore{?api%2Dversion}",{"api%2Dversion":t.apiVersion},{allowReserved:(n=l?.requestOptions)===null||n===void 0?void 0:n.skipUrlEncoding});return t.path(a).post(Object.assign(Object.assign({},eN(l)),{contentType:"application/json",headers:Object.assign({accept:"application/json"},(r=l.requestOptions)===null||r===void 0?void 0:r.headers),body:VOt(e)}))}async function I0n(t){if(!["200"].includes(t.status)){let l=Sh(t);throw l.details=ry(t.body),l}return X8(t.body)}async function R6e(t,e,l={requestOptions:{}}){let n=await a0n(t,e,l);return I0n(n)}function s0n(t,e,l={requestOptions:{}}){var n,r;let a=ay("/secrets/{secret-name}/backup{?api%2Dversion}",{"secret-name":e,"api%2Dversion":t.apiVersion},{allowReserved:(n=l?.requestOptions)===null||n===void 0?void 0:n.skipUrlEncoding});return t.path(a).post(Object.assign(Object.assign({},eN(l)),{headers:Object.assign({accept:"application/json"},(r=l.requestOptions)===null||r===void 0?void 0:r.headers)}))}async function o0n(t){if(!["200"].includes(t.status)){let l=Sh(t);throw l.details=ry(t.body),l}return YOt(t.body)}async function Y6e(t,e,l={requestOptions:{}}){let n=await s0n(t,e,l);return o0n(n)}function i0n(t,e,l={requestOptions:{}}){var n,r;let a=ay("/deletedsecrets/{secret-name}/recover{?api%2Dversion}",{"secret-name":e,"api%2Dversion":t.apiVersion},{allowReserved:(n=l?.requestOptions)===null||n===void 0?void 0:n.skipUrlEncoding});return t.path(a).post(Object.assign(Object.assign({},eN(l)),{headers:Object.assign({accept:"application/json"},(r=l.requestOptions)===null||r===void 0?void 0:r.headers)}))}async function c0n(t){if(!["200"].includes(t.status)){let l=Sh(t);throw l.details=ry(t.body),l}return X8(t.body)}async function V6e(t,e,l={requestOptions:{}}){let n=await i0n(t,e,l);return c0n(n)}function d0n(t,e,l={requestOptions:{}}){var n,r;let a=ay("/deletedsecrets/{secret-name}{?api%2Dversion}",{"secret-name":e,"api%2Dversion":t.apiVersion},{allowReserved:(n=l?.requestOptions)===null||n===void 0?void 0:n.skipUrlEncoding});return t.path(a).delete(Object.assign(Object.assign({},eN(l)),{headers:Object.assign({accept:"application/json"},(r=l.requestOptions)===null||r===void 0?void 0:r.headers)}))}async function u0n(t){if(!["204"].includes(t.status)){let l=Sh(t);throw l.details=ry(t.body),l}}async function w6e(t,e,l={requestOptions:{}}){let n=await d0n(t,e,l);return u0n(n)}function m0n(t,e,l={requestOptions:{}}){var n,r;let a=ay("/deletedsecrets/{secret-name}{?api%2Dversion}",{"secret-name":e,"api%2Dversion":t.apiVersion},{allowReserved:(n=l?.requestOptions)===null||n===void 0?void 0:n.skipUrlEncoding});return t.path(a).get(Object.assign(Object.assign({},eN(l)),{headers:Object.assign({accept:"application/json"},(r=l.requestOptions)===null||r===void 0?void 0:r.headers)}))}async function b0n(t){if(!["200"].includes(t.status)){let l=Sh(t);throw l.details=ry(t.body),l}return N6e(t.body)}async function Q6e(t,e,l={requestOptions:{}}){let n=await m0n(t,e,l);return b0n(n)}function G0n(t,e={requestOptions:{}}){var l,n;let r=ay("/deletedsecrets{?api%2Dversion,maxresults}",{"api%2Dversion":t.apiVersion,maxresults:e?.maxresults},{allowReserved:(l=e?.requestOptions)===null||l===void 0?void 0:l.skipUrlEncoding});return t.path(r).get(Object.assign(Object.assign({},eN(e)),{headers:Object.assign({accept:"application/json"},(n=e.requestOptions)===null||n===void 0?void 0:n.headers)}))}async function p0n(t){if(!["200"].includes(t.status)){let l=Sh(t);throw l.details=ry(t.body),l}return ROt(t.body)}function F6e(t,e={requestOptions:{}}){return w1e(t,()=>G0n(t,e),p0n,["200"],{itemName:"value",nextLinkName:"nextLink"})}function h0n(t,e,l={requestOptions:{}}){var n,r;let a=ay("/secrets/{secret-name}/versions{?api%2Dversion,maxresults}",{"secret-name":e,"api%2Dversion":t.apiVersion,maxresults:l?.maxresults},{allowReserved:(n=l?.requestOptions)===null||n===void 0?void 0:n.skipUrlEncoding});return t.path(a).get(Object.assign(Object.assign({},eN(l)),{headers:Object.assign({accept:"application/json"},(r=l.requestOptions)===null||r===void 0?void 0:r.headers)}))}async function A0n(t){if(!["200"].includes(t.status)){let l=Sh(t);throw l.details=ry(t.body),l}return W6e(t.body)}function C6e(t,e,l={requestOptions:{}}){return w1e(t,()=>h0n(t,e,l),A0n,["200"],{itemName:"value",nextLinkName:"nextLink"})}function g0n(t,e={requestOptions:{}}){var l,n;let r=ay("/secrets{?api%2Dversion,maxresults}",{"api%2Dversion":t.apiVersion,maxresults:e?.maxresults},{allowReserved:(l=e?.requestOptions)===null||l===void 0?void 0:l.skipUrlEncoding});return t.path(r).get(Object.assign(Object.assign({},eN(e)),{headers:Object.assign({accept:"application/json"},(n=e.requestOptions)===null||n===void 0?void 0:n.headers)}))}async function Z0n(t){if(!["200"].includes(t.status)){let l=Sh(t);throw l.details=ry(t.body),l}return W6e(t.body)}function v6e(t,e={requestOptions:{}}){return w1e(t,()=>g0n(t,e),Z0n,["200"],{itemName:"value",nextLinkName:"nextLink"})}function N0n(t,e,l,n={requestOptions:{}}){var r,a;let I=ay("/secrets/{secret-name}/{secret-version}{?api%2Dversion}",{"secret-name":e,"secret-version":l,"api%2Dversion":t.apiVersion},{allowReserved:(r=n?.requestOptions)===null||r===void 0?void 0:r.skipUrlEncoding});return t.path(I).get(Object.assign(Object.assign({},eN(n)),{headers:Object.assign({accept:"application/json"},(a=n.requestOptions)===null||a===void 0?void 0:a.headers)}))}async function W0n(t){if(!["200"].includes(t.status)){let l=Sh(t);throw l.details=ry(t.body),l}return X8(t.body)}async function f6e(t,e,l,n={requestOptions:{}}){let r=await N0n(t,e,l,n);return W0n(r)}function y0n(t,e,l,n,r={requestOptions:{}}){var a,I;let s=ay("/secrets/{secret-name}/{secret-version}{?api%2Dversion}",{"secret-name":e,"secret-version":l,"api%2Dversion":t.apiVersion},{allowReserved:(a=r?.requestOptions)===null||a===void 0?void 0:a.skipUrlEncoding});return t.path(s).patch(Object.assign(Object.assign({},eN(r)),{contentType:"application/json",headers:Object.assign({accept:"application/json"},(I=r.requestOptions)===null||I===void 0?void 0:I.headers),body:EOt(n)}))}async function E0n(t){if(!["200"].includes(t.status)){let l=Sh(t);throw l.details=ry(t.body),l}return X8(t.body)}async function H6e(t,e,l,n,r={requestOptions:{}}){let a=await y0n(t,e,l,n,r);return E0n(a)}function R0n(t,e,l={requestOptions:{}}){var n,r;let a=ay("/secrets/{secret-name}{?api%2Dversion}",{"secret-name":e,"api%2Dversion":t.apiVersion},{allowReserved:(n=l?.requestOptions)===null||n===void 0?void 0:n.skipUrlEncoding});return t.path(a).delete(Object.assign(Object.assign({},eN(l)),{headers:Object.assign({accept:"application/json"},(r=l.requestOptions)===null||r===void 0?void 0:r.headers)}))}async function Y0n(t){if(!["200"].includes(t.status)){let l=Sh(t);throw l.details=ry(t.body),l}return N6e(t.body)}async function X6e(t,e,l={requestOptions:{}}){let n=await R0n(t,e,l);return Y0n(n)}function V0n(t,e,l,n={requestOptions:{}}){var r,a;let I=ay("/secrets/{secret-name}{?api%2Dversion}",{"secret-name":e,"api%2Dversion":t.apiVersion},{allowReserved:(r=n?.requestOptions)===null||r===void 0?void 0:r.skipUrlEncoding});return t.path(I).put(Object.assign(Object.assign({},eN(n)),{contentType:"application/json",headers:Object.assign({accept:"application/json"},(a=n.requestOptions)===null||a===void 0?void 0:a.headers),body:NOt(l)}))}async function w0n(t){if(!["200"].includes(t.status)){let l=Sh(t);throw l.details=ry(t.body),l}return X8(t.body)}async function k6e(t,e,l,n={requestOptions:{}}){let r=await V0n(t,e,l,n);return w0n(r)}var Tde=class{constructor(e,l,n={}){var r;let a=(r=n?.userAgentOptions)===null||r===void 0?void 0:r.userAgentPrefix,I=a?`${a} azsdk-js-client`:"azsdk-js-client";this._client=Z6e(e,l,Object.assign(Object.assign({},n),{userAgentOptions:{userAgentPrefix:I}})),this.pipeline=this._client.pipeline}restoreSecret(e,l={requestOptions:{}}){return R6e(this._client,e,l)}backupSecret(e,l={requestOptions:{}}){return Y6e(this._client,e,l)}recoverDeletedSecret(e,l={requestOptions:{}}){return V6e(this._client,e,l)}purgeDeletedSecret(e,l={requestOptions:{}}){return w6e(this._client,e,l)}getDeletedSecret(e,l={requestOptions:{}}){return Q6e(this._client,e,l)}getDeletedSecrets(e={requestOptions:{}}){return F6e(this._client,e)}getSecretVersions(e,l={requestOptions:{}}){return C6e(this._client,e,l)}getSecrets(e={requestOptions:{}}){return v6e(this._client,e)}getSecret(e,l,n={requestOptions:{}}){return f6e(this._client,e,l,n)}updateSecret(e,l,n,r={requestOptions:{}}){return H6e(this._client,e,l,n,r)}deleteSecret(e,l={requestOptions:{}}){return X6e(this._client,e,l)}setSecret(e,l,n={requestOptions:{}}){return k6e(this._client,e,l,n)}};var Q0n=["authorization","authorization_url","resource","scope","tenantId","claims","error"];function L6e(t){let e=/,? +/,l=t.split(e).reduce((n,r)=>{if(r.match(/\w="/)){let[a,...I]=r.split("=");if(Q0n.includes(a))return Object.assign(Object.assign({},n),{[a]:I.join("=").slice(1,-1)})}return n},{});if(l.authorization)try{let n=new URL(l.authorization).pathname.substring(1);n&&(l.tenantId=n)}catch{throw new Error(`The challenge authorization URI '${l.authorization}' is invalid.`)}return l}var F0n={forcedRefreshWindowInMs:1e3,retryIntervalInMs:3e3,refreshWindowInMs:1e3*60*2};async function C0n(t,e,l){async function n(){if(Date.now()<l)try{return await t()}catch{return null}else{let a=await t();if(a===null)throw new Error("Failed to refresh access token.");return a}}let r=await n();for(;r===null;)await Zk(e),r=await n();return r}function FOt(t,e){let l=null,n=null,r,a=Object.assign(Object.assign({},F0n),e),I={get isRefreshing(){return l!==null},get shouldRefresh(){var o;return I.isRefreshing?!1:n?.refreshAfterTimestamp&&n.refreshAfterTimestamp<Date.now()?!0:((o=n?.expiresOnTimestamp)!==null&&o!==void 0?o:0)-a.refreshWindowInMs<Date.now()},get mustRefresh(){return n===null||n.expiresOnTimestamp-a.forcedRefreshWindowInMs<Date.now()}};function s(o,c){var d;return I.isRefreshing||(l=C0n(()=>t.getToken(o,c),a.retryIntervalInMs,(d=n?.expiresOnTimestamp)!==null&&d!==void 0?d:Date.now()).then(G=>(l=null,n=G,r=c.tenantId,n)).catch(G=>{throw l=null,n=null,r=void 0,G})),l}return async(o,c)=>{let d=!!c.claims,m=r!==c.tenantId;return d&&(n=null),m||d||I.mustRefresh?s(o,c):(I.shouldRefresh&&s(o,c),n)}}var COt=Fh("keyvault-common");function v0n(t,e){let l;try{l=new URL(t)}catch{throw new Error(`The challenge contains invalid scope '${t}'`)}if(!new URL(e.url).hostname.endsWith(`.${l.hostname}`))throw new Error(`The challenge resource '${l.hostname}' does not match the requested domain. Set disableChallengeResourceVerification to true in your client options to disable. See https://aka.ms/azsdk/blog/vault-uri for more information.`)}var f0n="keyVaultAuthenticationPolicy";function vOt(t,e={}){let{disableChallengeResourceVerification:l}=e,n={status:"none"},r=FOt(t);function a(d){return{abortSignal:d.abortSignal,requestOptions:{timeout:d.timeout>0?d.timeout:void 0},tracingOptions:d.tracingOptions}}async function I(d){let m=a(d);switch(n.status){case"none":n={status:"started",originalBody:d.body},d.body=null;break;case"started":break;case"complete":{let G=await r(n.scopes,Object.assign(Object.assign({},m),{enableCae:!0,tenantId:n.tenantId}));G&&d.headers.set("authorization",`Bearer ${G.token}`);break}}}async function s(d,m,G){if(m.status!==401)return m;d.body===null&&n.status==="started"&&(d.body=n.originalBody);let p=a(d),A=m.headers.get("WWW-Authenticate");if(!A)return COt.warning("keyVaultAuthentication policy encountered a 401 response without a corresponding WWW-Authenticate header. This is unexpected. Not handling the 401 response."),m;let Z=L6e(A),W=Z.resource?Z.resource+"/.default":Z.scope;if(!W)return m;l||v0n(W,d);let R=await r([W],Object.assign(Object.assign({},p),{enableCae:!0,tenantId:Z.tenantId}));return R?(d.headers.set("Authorization",`Bearer ${R.token}`),n={status:"complete",scopes:[W],tenantId:Z.tenantId},G(d)):m}async function o(d,m,G){if(n.status!=="complete"||m.status!==401)return m;let p=a(d),A=m.headers.get("WWW-Authenticate");if(!A)return m;let{claims:Z,error:W}=L6e(A);if(W!=="insufficient_claims"||Z===void 0)return m;let R=atob(Z),V=await r(n.scopes,Object.assign(Object.assign({},p),{enableCae:!0,tenantId:n.tenantId,claims:R}));return d.headers.set("Authorization",`Bearer ${V.token}`),G(d)}async function c(d,m){await I(d);let G=await m(d);return G=await s(d,G,m),G=await o(d,G,m),G}return{name:f0n,sendRequest:c}}function fOt(t,e){if(typeof t!="string"||!(t=t.trim()))throw new Error("Invalid collection argument");if(typeof e!="string"||!(e=e.trim()))throw new Error("Invalid identifier argument");let l;try{l=new URL(e)}catch{throw new Error(`Invalid ${t} identifier: ${e}. Not a valid URI`)}let n=(l.pathname||"").split("/");if(n.length!==3&&n.length!==4)throw new Error(`Invalid ${t} identifier: ${e}. Bad number of segments: ${n.length}`);if(t!==n[1])throw new Error(`Invalid ${t} identifier: ${e}. segment [1] should be "${t}", found "${n[1]}"`);let r=`${l.protocol}//${l.host}`,a=n[2],I=n.length===4?n[3]:void 0;return{vaultUrl:r,name:a,version:I}}function J6e(t){let l=t.split("/")[3];return Object.assign({sourceId:t},fOt(l,t))}function Yg(t){let e=t,l=t,n=J6e(e.id),r=e.attributes;delete e.attributes;let a={value:e.value,name:n.name,properties:{expiresOn:r?.expires,createdOn:r?.created,updatedOn:r?.updated,enabled:r?.enabled,notBefore:r?.notBefore,recoverableDays:r?.recoverableDays,recoveryLevel:r?.recoveryLevel,id:e.id,contentType:e.contentType,tags:e.tags,managed:e.managed,vaultUrl:n.vaultUrl,version:n.version,name:n.name,certificateKeyId:e.kid}};return l.recoveryId&&(a.properties.recoveryId=l.recoveryId,a.properties.scheduledPurgeDate=l.scheduledPurgeDate,a.properties.deletedOn=l.deletedDate,a.recoveryId=l.recoveryId,a.scheduledPurgeDate=l.scheduledPurgeDate,a.deletedOn=l.deletedDate),r&&(r.vaultUrl&&delete a.properties.vaultUrl,r.expires&&delete a.properties.expires,r.created&&delete a.properties.created,r.updated&&delete a.properties.updated),a}function F1e(t,e,l){let n;return{async next(){n??(n=t(Object.assign(Object.assign({},e),{maxresults:void 0})));let r=await n.next();return Object.assign(Object.assign({},r),{value:r.value&&l(r.value)})},[Symbol.asyncIterator](){return this},byPage(r){return Wk(this,arguments,function*(){var I,s,o,c;let d=t(Object.assign(Object.assign({},e),{maxresults:r?.maxPageSize})).byPage(r);try{for(var m=!0,G=C9(d),p;p=yield Sc(G.next()),I=p.done,!I;m=!0)c=p.value,m=!1,yield yield Sc(c.map(l))}catch(A){s={error:A}}finally{try{!m&&!I&&(o=G.return)&&(yield Sc(o.call(G)))}finally{if(s)throw s.error}}})}}}var C1e="4.10.0";var tN=kB({namespace:"Microsoft.KeyVault",packageName:"@azure/keyvault-secrets",packageVersion:C1e});var x6e=Fh("core-lro");var S6e=class t extends Error{constructor(e){super(e),this.name="PollerStoppedError",Object.setPrototypeOf(this,t.prototype)}},B6e=class t extends Error{constructor(e){super(e),this.name="PollerCancelledError",Object.setPrototypeOf(this,t.prototype)}},Ode=class{constructor(e){this.resolveOnUnsuccessful=!1,this.stopped=!0,this.pollProgressCallbacks=[],this.operation=e,this.promise=new Promise((l,n)=>{this.resolve=l,this.reject=n}),this.promise.catch(()=>{})}async startPolling(e={}){for(this.stopped&&(this.stopped=!1);!this.isStopped()&&!this.isDone();)await this.poll(e),await this.delay()}async pollOnce(e={}){this.isDone()||(this.operation=await this.operation.update({abortSignal:e.abortSignal,fireProgress:this.fireProgress.bind(this)})),this.processUpdatedState()}fireProgress(e){for(let l of this.pollProgressCallbacks)l(e)}async cancelOnce(e={}){this.operation=await this.operation.cancel(e)}poll(e={}){if(!this.pollOncePromise){this.pollOncePromise=this.pollOnce(e);let l=()=>{this.pollOncePromise=void 0};this.pollOncePromise.then(l,l).catch(this.reject)}return this.pollOncePromise}processUpdatedState(){if(this.operation.state.error&&(this.stopped=!0,!this.resolveOnUnsuccessful))throw this.reject(this.operation.state.error),this.operation.state.error;if(this.operation.state.isCancelled&&(this.stopped=!0,!this.resolveOnUnsuccessful)){let e=new B6e("Operation was canceled");throw this.reject(e),e}this.isDone()&&this.resolve&&this.resolve(this.getResult())}async pollUntilDone(e={}){return this.stopped&&this.startPolling(e).catch(this.reject),this.processUpdatedState(),this.promise}onProgress(e){return this.pollProgressCallbacks.push(e),()=>{this.pollProgressCallbacks=this.pollProgressCallbacks.filter(l=>l!==e)}}isDone(){let e=this.operation.state;return!!(e.isCompleted||e.isCancelled||e.error)}stopPolling(){this.stopped||(this.stopped=!0,this.reject&&this.reject(new S6e("This poller is already stopped")))}isStopped(){return this.stopped}cancelOperation(e={}){if(!this.cancelPromise)this.cancelPromise=this.cancelOnce(e);else if(e.abortSignal)throw new Error("A cancel request is currently pending");return this.cancelPromise}getOperationState(){return this.operation.state}getResult(){return this.operation.state.result}toString(){return this.operation.toString()}};var L8=class extends Ode{constructor(){super(...arguments),this.intervalInMs=2e3}async delay(){return Zk(this.intervalInMs)}},J8=class{constructor(e,l={}){this.state=e,this.cancelMessage="",l.cancelMessage&&(this.cancelMessage=l.cancelMessage)}async update(){throw new Error("Operation not supported.")}async cancel(){throw new Error(this.cancelMessage)}toString(){return JSON.stringify({state:this.state})}};var v1e=class extends J8{constructor(e,l,n={}){super(e,{cancelMessage:"Canceling the deletion of a secret is not supported."}),this.state=e,this.client=l,this.operationOptions=n}deleteSecret(e,l={}){return tN.withSpan("DeleteSecretPoller.deleteSecret",l,async n=>{let r=await this.client.deleteSecret(e,n);return Yg(r)})}getDeletedSecret(e,l={}){return tN.withSpan("DeleteSecretPoller.getDeletedSecret",l,async n=>{let r=await this.client.getDeletedSecret(e,n);return Yg(r)})}async update(e={}){let l=this.state,{name:n}=l;if(e.abortSignal&&(this.operationOptions.abortSignal=e.abortSignal),!l.isStarted){let r=await this.deleteSecret(n,this.operationOptions);l.isStarted=!0,l.result=r,r.properties.recoveryId||(l.isCompleted=!0)}if(!l.isCompleted)try{l.result=await this.getDeletedSecret(n,this.operationOptions),l.isCompleted=!0}catch(r){if(r.statusCode===403)l.isCompleted=!0;else if(r.statusCode!==404)throw l.error=r,l.isCompleted=!0,r}return this}};var f1e=class extends L8{constructor(e){let{client:l,name:n,operationOptions:r,intervalInMs:a=2e3,resumeFrom:I}=e,s;I&&(s=JSON.parse(I).state);let o=new v1e(Object.assign(Object.assign({},s),{name:n}),l,r);super(o),this.intervalInMs=a}};var H1e=class extends J8{constructor(e,l,n={}){super(e,{cancelMessage:"Canceling the recovery of a deleted secret is not supported."}),this.state=e,this.client=l,this.options=n}getSecret(e,l={}){return tN.withSpan("RecoverDeletedSecretPoller.getSecret",l,async n=>{let r=await this.client.getSecret(e,l&&l.version?l.version:"",n);return Yg(r)})}recoverDeletedSecret(e,l={}){return tN.withSpan("RecoverDeletedSecretPoller.recoverDeletedSecret",l,async n=>{let r=await this.client.recoverDeletedSecret(e,n);return Yg(r)})}async update(e={}){let l=this.state,{name:n}=l;if(e.abortSignal&&(this.options.abortSignal=e.abortSignal),!l.isStarted){try{l.result=(await this.getSecret(n,this.options)).properties,l.isCompleted=!0}catch{}l.isCompleted||(l.result=(await this.recoverDeletedSecret(n,this.options)).properties,l.isStarted=!0)}if(!l.isCompleted)try{l.result=(await this.getSecret(n,this.options)).properties,l.isCompleted=!0}catch(r){if(r.statusCode===403)l.isCompleted=!0;else if(r.statusCode!==404)throw l.error=r,l.isCompleted=!0,r}return this}};var X1e=class extends L8{constructor(e){let{client:l,name:n,operationOptions:r,intervalInMs:a=2e3,resumeFrom:I}=e,s;I&&(s=JSON.parse(I).state);let o=new H1e(Object.assign(Object.assign({},s),{name:n}),l,r);super(o),this.intervalInMs=a}};var k1e=class{constructor(e,l,n={}){var r,a;this.vaultUrl=e;let I=Object.assign(Object.assign({},n),{userAgentOptions:{userAgentPrefix:`${(a=(r=n.userAgentOptions)===null||r===void 0?void 0:r.userAgentPrefix)!==null&&a!==void 0?a:""} azsdk-js-keyvault-secrets/${C1e}`},apiVersion:n.serviceVersion||"7.6",loggingOptions:{logger:bOt.info,additionalAllowedHeaderNames:["x-ms-keyvault-region","x-ms-keyvault-network-info","x-ms-keyvault-service-version"]}});this.client=new Tde(this.vaultUrl,l,I),this.client.pipeline.removePolicy({name:m2e}),this.client.pipeline.addPolicy(vOt(l,n),{}),this.client.pipeline.addPolicy({name:"ContentTypePolicy",sendRequest(s,o){var c;return((c=s.headers.get("Content-Type"))!==null&&c!==void 0?c:"").startsWith("application/json")&&s.headers.set("Content-Type","application/json"),o(s)}})}setSecret(e,l,n={}){let{enabled:r,notBefore:a,expiresOn:I,tags:s}=n,o=Die(n,["enabled","notBefore","expiresOn","tags"]);return tN.withSpan("SecretClient.setSecret",o,async c=>{let d=await this.client.setSecret(e,{value:l,secretAttributes:{enabled:r,notBefore:a,expires:I},tags:s},c);return Yg(d)})}async beginDeleteSecret(e,l={}){let n=new f1e(Object.assign(Object.assign({name:e,client:this.client},l),{operationOptions:l}));return await n.poll(),n}async updateSecretProperties(e,l,n={}){let{enabled:r,notBefore:a,expiresOn:I,tags:s}=n,o=Die(n,["enabled","notBefore","expiresOn","tags"]);return tN.withSpan("SecretClient.updateSecretProperties",o,async c=>{let d=await this.client.updateSecret(e,l,{secretAttributes:{enabled:r,notBefore:a,expires:I},tags:s},c);return Yg(d).properties})}getSecret(e,l={}){return tN.withSpan("SecretClient.getSecret",l,async n=>{let r=await this.client.getSecret(e,l&&l.version?l.version:"",n);return Yg(r)})}getDeletedSecret(e,l={}){return tN.withSpan("SecretClient.getDeletedSecret",l,async n=>{let r=await this.client.getDeletedSecret(e,n);return Yg(r)})}purgeDeletedSecret(e,l={}){return tN.withSpan("SecretClient.purgeDeletedSecret",l,async n=>{await this.client.purgeDeletedSecret(e,n)})}async beginRecoverDeletedSecret(e,l={}){let n=new X1e(Object.assign(Object.assign({name:e,client:this.client},l),{operationOptions:l}));return await n.poll(),n}backupSecret(e,l={}){return tN.withSpan("SecretClient.backupSecret",l,async n=>(await this.client.backupSecret(e,n)).value)}restoreSecretBackup(e,l={}){return tN.withSpan("SecretClient.restoreSecretBackup",l,async n=>{let r=await this.client.restoreSecret({secretBundleBackup:e},n);return Yg(r).properties})}listPropertiesOfSecretVersions(e,l={}){return F1e(n=>this.client.getSecretVersions(e,n),l,n=>Yg(n).properties)}listPropertiesOfSecrets(e={}){return F1e(this.client.getSecrets.bind(this.client),e,l=>Yg(l).properties)}listDeletedSecrets(e={}){return F1e(this.client.getDeletedSecrets.bind(this.client),e,Yg)}};var T6e=class{client;logger;constructor(e,l){if(this.logger=l,e){this.logger.debug(`Using Azure Key Vault at ${e}`);let n=new pw;this.client=new k1e(e,n)}else this.logger.debug("No Azure Key Vault URI provided, secret provider disabled")}async getSecret(e){if(this.client)try{return(await this.client.getSecret(e)).value}catch(l){if(this.logger.warning(`Error fetching secret ${e}: ${l}`),l?.code==="SecretNotFound")return;throw l}}};function HOt(t,e){let l=t.api?.copilot?.azureKeyVaultUri;return O6e(l,e)}function O6e(t,e){return new T6e(t,e)}import{createHmac as x0n}from"crypto";var L1e=class t{static encode(e){let l=t.hmacGetBytes(e),I=(Math.floor(Date.now()/1e3)+30).toString(),s=Buffer.from(I,"ascii"),d=x0n("sha256",l).update(s).digest().toString("hex").toUpperCase();return`${I}.${d}`}static hmacGetBytes(e){return Buffer.from(e,"ascii")}};var S0n="X-GitHub-Api-Version",B0n="2025-05-01",yT=class t extends ia{constructor(l,n,r,a){super({baseURL:l,apiKey:"",logLevel:Ute()?"debug":"info"});this.headers=n;this.runnerLogger=r;this.hmacKey=a}static baseHeaders={"Content-Type":"application/json",Accept:"application/json","X-Interaction-Type":"conversation-agent","Openai-Intent":"conversation-agent","X-Initiator":"user",[S0n]:B0n};hmacKey;additionalHeaders={};static createWithOAuthToken(l,n,r,a,I,s){let o={...this.defaultHeaders(r,I),Authorization:`Bearer ${a}`,...s??{}};return l.debug(`Creating copilot-client for integration ID ${r} with token authentication. User-agent: ${o["User-Agent"]}`),new t(n,o,l)}static createWithHmac(l,n,r,a,I,s,o){let c={...this.defaultHeaders(r,I),Authorization:"",...o??{}};return s&&(c["X-GitHub-User"]=s),l.debug(`Creating copilot-client for integration ID ${r} with key authentication. User-agent: ${c["User-Agent"]}`),new t(n,c,l,a)}static defaultHeaders(l,n){let r=d0();return{...t.baseHeaders,"Copilot-Integration-Id":l,"User-Agent":`${r.nameNoScope}/${r.version} (${process.platform} ${process.version}) OpenAI/${vw}`,"X-Interaction-Id":n}}async prepareOptions(l){this.hmacKey&&(this.headers["Request-HMAC"]=L1e.encode(this.hmacKey)),l.headers={...this.headers,...this.additionalHeaders,...l.headers},await super.prepareOptions(l)}setInitiatorHeader(l){this.headers["X-Initiator"]=l}setAdditionalHeaders(l){this.additionalHeaders=l}async listModels(){let l={method:"get",path:""};await this.prepareOptions(l);let n={};if(l.headers)for(let[s,o]of Object.entries(l.headers))typeof o=="string"&&(n[s]=o);let r=`${this.baseURL}/models`,a=await fetch(r,{method:l.method,headers:n});if(!a.ok)return this.runnerLogger.error(`Failed to list models: ${a.status} ${a.statusText}: ${await a.text()}`),a.status===421&&this.runnerLogger.error(`Verify the authenticated user against subscription-based Copilot API endpoint used: ${this.baseURL}`),[];let I=await a.json();return this.runnerLogger.debug(`Successfully listed ${I.data.length} models`),I.data}},x8=class{async createClient(e,l,n){l.startGroup("configured settings:",8),l.debug(JSON.stringify(e,null,2)),l.endGroup(8);let r=e.api?.copilot?.token,a=e.api?.copilot?.hmacKey,I=!!(a||r);if(!I){l.debug("No Copilot HMAC key or GitHub OAuth token provided, trying secret provider");let m=HOt(e,l);try{a=await m.getSecret("capi-hmac-key")}catch(G){l.debug(`Failed to get Copilot HMAC key from secret provider:
|
|
1904
1904
|
${G}`)}try{r=await m.getSecret("capi-token")}catch(G){l.debug(`Failed to get Copilot GitHub OAuth token from secret provider:
|
|
1905
1905
|
${G}`)}I=!!(a||r)}let s,o=dZt(e),c=_te(e),d=e.api?.copilot?.sessionId??$F(e);if(l.debug(`Using Copilot API at ${o} with integration ID ${c}`),r&&(l.debug("Using GitHub OAuth token for Copilot API"),s=yT.createWithOAuthToken(l,o,c,r,d,n?.requestHeaders)),a){l.debug("Using Copilot HMAC key for Copilot API");let m=process.env.GITHUB_USER_ID;m?l.debug(`Using user ID ${m} for Copilot HMAC key`):l.debug("No user ID provided for Copilot HMAC key"),s=yT.createWithHmac(l,o,c,a,d,m,n?.requestHeaders)}if(s===void 0)throw new Error("No GitHub OAuth token or Copilot HMAC key provided");return s}},S8=class t extends Ru{request_id;constructor(e){super(e.status,e.error,e.message,e.headers),this.name="CAPIError",this.cause=e.cause,this.ghRequestId=e.headers?.get("x-github-request-id")||this.requestID,this.request_id=this.requestID}ghRequestId;static fromAPIError(e){if(!(!e||!(e instanceof Ru)))return new t(e)}};var U6e={type:"ephemeral"},bL=class t{constructor(e,l,n,r){this.settings=l;this.logger=n;this.clientOptions=t.initDefaultOptions(r),n.info(" "),n.debug(`Using model: ${this.model}`),this.clientPromise=e.createClient(l,n,r),this.modelPromise=this.clientPromise.then(async()=>{let a=await this.getModel();return n.debug(`Got model info: ${JSON.stringify(a,null,2)}`),a})}clientOptions;clientPromise;modelPromise;get model(){return this.clientOptions.model}static initDefaultOptions(e){return{model:e?.model||bMe.model,toolTokenBudgetProportion:e?.toolTokenBudgetProportion??.25,retryPolicy:{maxRetries:e?.retryPolicy?.maxRetries??5,errorCodesToRetry:e?.retryPolicy?.errorCodesToRetry??[],rateLimitRetryPolicy:{defaultRetryAfterSeconds:e?.retryPolicy?.rateLimitRetryPolicy?.defaultRetryAfterSeconds??5,initialRetryBackoffExtraSeconds:e?.retryPolicy?.rateLimitRetryPolicy?.initialRetryBackoffExtraSeconds??1,retryBackoffExtraGrowth:e?.retryPolicy?.rateLimitRetryPolicy?.retryBackoffExtraGrowth??2,maxRetryAfterSeconds:e?.retryPolicy?.rateLimitRetryPolicy?.maxRetryAfterSeconds??180}},thinkingMode:e?.thinkingMode??!1,requestHeaders:e?.requestHeaders??{}}}getCompletionOptions(e,l){let n={snippy:{enabled:!1}};return{temperature:0,top_p:.95,frequency_penalty:0,presence_penalty:0,tool_choice:l?.toolChoice,...n}}makeRequest(e,l,n,r,a,I,s){return e.chat.completions.create({model:l,messages:[...n],...r,tools:a},{maxRetries:I,headers:s?.requestHeaders,signal:s?.abortSignal}).withResponse()}makeRequestStreaming(e,l,n,r,a,I,s){return e.chat.completions.create({model:l,messages:[...n],...r,tools:a,stream:!0,stream_options:{include_usage:!0}},{maxRetries:I,headers:s?.requestHeaders,signal:s?.abortSignal}).withResponse()}async*getCompletionWithTools(e,l,n,r){let a=this.model,I=await this.clientPromise,s=await this.modelPromise,o=g5(n),c=[{role:"system",content:e,copilot_cache_control:U6e},...l.map(Z=>eoe(Z))],d=n.map((Z,W)=>({type:"function",function:{name:Z.name,description:Z.description,parameters:Z.input_schema},copilot_cache_control:W===n.length-1?U6e:void 0}));this.logger.startGroup("Completion request configuration: ",8),this.logger.debug("Client options: "),this.logger.debug(JSON.stringify(this.clientOptions,null,2)),this.logger.debug("Request options: "),this.logger.debug(JSON.stringify(r??{},null,2)),this.logger.debug("Tools: "),this.logger.debug(JSON.stringify(d,null,2)),this.logger.endGroup(8);let m=this.getCompletionOptions(n,r),G=r?.initialTurnCount!==void 0?r.initialTurnCount+1:0,p=!1,A=!1;for(;!p&&!A;){let Z=Date.now();yield{kind:"turn_started",model:a,modelInfo:s,turn:G,timestampMs:Z};let W=0,R=0,V=0,v=[429,503,500,400],X=this.clientOptions.retryPolicy.maxRetries,S=this.clientOptions.retryPolicy.rateLimitRetryPolicy.initialRetryBackoffExtraSeconds,O=0,T=this.clientOptions.retryPolicy.rateLimitRetryPolicy.maxRetryAfterSeconds,P,x;try{let D=[],ae;do{V>0&&(yield{kind:"turn_retry",model:a,modelInfo:s,turn:G,timestampMs:Date.now()});try{let Ge={};for(let U of r?.processors?.preRequest||[]){let re=U.preRequest({turn:G,retry:V,messages:c,toolDefinitions:d,modelInfo:s,additionalRequestHeaders:Ge,getCompletionWithToolsOptions:r});for await(let se of re)yield se}if(this.logger.startGroup("Sending request to the AI model",8),to(this.settings,"copilot_swe_agent_request_logging")){let U=JSON.stringify(c,null,2),re=JSON.stringify(m,null,2);this.logger.debug(`Request messages: ${U}`),this.logger.debug(`Request options: ${re}`)}D=c.map((U,re)=>re===c.length-1?{...U,copilot_cache_control:U6e}:U),W=Date.now(),I.setAdditionalHeaders(Ge);let he;if(r?.stream){let U=await this.makeRequestStreaming(I,a,D,m,d,X,r);he=await O0n(U,I,r)}else he=await this.makeRequest(I,a,D,m,d,X,r);R=Date.now()-W,P=he.data,ae={model:a,api_id:P.id,request_id:he.response.headers.get("x-github-request-id")||void 0,initiator:r?.requestHeaders?.["X-Initiator"]||Ge["X-Initiator"]};let K={};he.response.headers.forEach((U,re)=>{if(re.toLowerCase().startsWith(n6e)){let se=kTt(U);se&&(K[re.replace(n6e,"")]=se)}}),yield{kind:"model_call_success",turn:G,callId:r?.callId,modelCallDurationMs:R,modelCall:ae,responseChunk:HXt(P),responseUsage:P.usage,requestMessages:JSON.stringify(D),quotaSnapshots:K},this.logger.debug(`response (Request-ID ${he.request_id}):`),this.logger.debug("data:"),this.logger.debug(JSON.stringify(he.data,null,2))}catch(Ge){R=Date.now()-W;let he=S8.fromAPIError(Ge),K=he?.error;if(he){yield{kind:"model_call_failure",turn:G,callId:r?.callId,modelCallDurationMs:R,requestMessages:JSON.stringify(D),modelCall:{model:a,status:he.status,error:JSON.stringify(he?.error||he?.message||"unknown error"),api_id:he.requestID||void 0,request_id:he.headers?.get("x-github-request-id")||""}},x=he;let re=he.ghRequestId||he.headers?.get("x-github-request-id")||he.requestID;this.logger.error(`error (Request-ID ${re})`),this.logger.error(JSON.stringify(he,Object.getOwnPropertyNames(he),2)),this.logger.debug(`Failed to get response from the AI model: ${he}`),K&&this.logger.debug(`Inner error: ${JSON.stringify(K,null,2)}`);let se;for(let Re of r?.processors?.onRequestError||[])se=await Re.onRequestError({turn:G,retry:V,maxRetries:X,error:K,modelInfo:s,getCompletionWithToolsOptions:r})||se;let We=he.status,me=We?this.clientOptions.retryPolicy.errorCodesToRetry.some(Re=>Array.isArray(Re)?We>=Re[0]&&(Re[1]===void 0||We<=Re[1]):We===Re):!1,ve;if(se)ve=se.retryAfter;else if(he.status!==402){if(he.status===413){this.logger.debug("Request is too large, trying to remove images from the request");let Re=0;for(let ye=c.length-1;ye>=0;ye--)P4(c[ye])&&(c.splice(ye,1),Re++,yield{kind:"images_removed",turn:G,imagesRemoved:1,largeImagesRemoved:1});Re>0?(this.logger.info(`Images have been removed from the request due to size constraints. Please resize images to be smaller than ${EE(s.capabilities.limits.vision?.max_prompt_image_size||0)}.`),this.logger.debug(`Removed ${Re} image messages from the request`),ve=1):this.logger.debug("No image messages found in the request - unsure why the request is too large - will fail")}else if((typeof he.status=="number"&&v.includes(he.status)||me)&&(ve=parseInt(he.headers?.get("retry-after")||`${this.clientOptions.retryPolicy.rateLimitRetryPolicy.defaultRetryAfterSeconds}`,10)+S,S*=this.clientOptions.retryPolicy.rateLimitRetryPolicy.retryBackoffExtraGrowth,V==X-1))for(let Re=c.length-1;Re>=0;Re--)P4(c[Re])&&(this.logger.debug(`Removing image message at index ${Re} to avoid failure`),c.splice(Re,1),yield{kind:"images_removed",turn:G,imagesRemoved:1})}if(ve!==void 0&&ve<=T){let Re=.8+Math.random()*.4,ye=ve*Re;this.logger.debug(`Retrying after ${ye} seconds...`),await new Promise(Ie=>setTimeout(Ie,ye*1e3)),O+=ye,this.logger.debug(`Retrying after ${ve} seconds... Will try again now!`);continue}else ve?this.logger.error(`Retry after ${ve} seconds is too long. Giving up.`):this.logger.error("Retry after is not set. Giving up.")}let U=he||Ge;for(let re of r?.processors?.onRequestError||[])await re.preErrorThrow(Ge);throw this.logger.error("error"),this.logger.error(JSON.stringify(U,null,2)),U}finally{I.setAdditionalHeaders({}),this.logger.endGroup(8)}}while(!P&&V++<X);if(!P){this.logger.debug("Recent messages prior to failure:");for(let he=Math.max(0,c.length-6);he<c.length;he++)this.logger.debug(`${he}: ${JSON.stringify(c[he],null,2)}`);let Ge=new Error(`Failed to get response from the AI model; retried ${V-1} times (total retry wait time: ${O} seconds)`,{cause:x});throw this.isRateLimitExceededError(Ge)&&(this.logger.info(`Rate limit exceeded after ${V-1} retries, will fail job but skip Sentry reporting`),Ge.skipReport=!0),Ge}for(let Ge of P.choices.map(he=>he.message))T0n(Ge.tool_calls||[]),c.push(Ge),yield{kind:"message",turn:G,callId:r?.callId,modelCall:ae,message:eoe(F6(Ge))};if(this.isToolCallResponse(P)){let he=(s.capabilities.limits.max_prompt_tokens||s.capabilities.limits.max_context_window_tokens)*this.clientOptions.toolTokenBudgetProportion,K=LRt(a,he,this,this.settings),re=P.choices.filter(ve=>ve.message.tool_calls!==void 0).flatMap(ve=>ve.message.tool_calls||[]).filter(kA),se=new Map;for(let ve of r?.processors?.preToolsExecution||[]){let Re=await ve.preToolsExecution({turn:G,toolCalls:re,modelInfo:s});if(Re)for(let[ye,Ie]of Re)se.set(ye,Ie)}let We=re.filter(ve=>!se.has(ve.id)),me=this.mergeToolResults(se,re,We,o,K,r?.executeToolsInParallel);for await(let ve of me){ve.toolResult.resultType==="rejected"&&(A=!0);let Re={role:"tool",tool_call_id:ve.originalCall.id,content:ve.toolResult.textResultForLlm};c.push(Re),yield{kind:"message",turn:G,callId:r?.callId,modelCall:ae,message:eoe(Re)},yield{kind:"tool_execution",turn:G,callId:r?.callId,toolCallId:ve.originalCall.id,toolResult:ve.toolResult,durationMs:ve.durationMs};for(let ye of r?.processors?.postToolExecution||[])await ye.postToolExecution({toolCall:ve.originalCall,toolResult:ve.toolResult,turn:G,modelInfo:s})}}else for(let Ge of P.choices.map(he=>he.message))yield{kind:"response",turn:G,callId:r?.callId,modelCall:{model:a,api_id:P.id},response:eoe(F6(Ge))},p=!0}catch(D){let ae;throw D instanceof Error&&D.cause&&D.cause instanceof S8?ae=`${D} (Cause: ${D.cause})`:ae=`${D}`,yield{kind:"turn_failed",model:a,modelInfo:s,turn:G,error:ae,timestampMs:Date.now()},D}finally{let D=Date.now();yield{kind:"turn_ended",model:a,modelInfo:s,turn:G,timestampMs:D},G++}}}async*mergeToolResults(e,l,n,r,a,I=!1){for(let[s,o]of e){let c=l.find(d=>d.id===s);c&&(yield{durationMs:0,originalCall:c,toolResult:o})}n.length>0&&(yield*this.callTools(n,r,a,I))}async*callTools(e,l,n,r=!1){if(e.length===0)throw new Error("Tool call is missing");this.logger.debug(`Tool calls count: ${e.length}`);let a=e.some(s=>{let o=l[s.function.name];return $k(o)}),I=r&&!a;if(a&&r&&this.logger.debug("Custom agent detected in tool calls, forcing sequential execution"),I)this.logger.debug("Running tool calls in parallel"),yield*FRt(e.map(s=>()=>this.callTool(s,l,n)));else{this.logger.debug("Running tool calls sequentially");for(let s of e)yield await this.callTool(s,l,n)}}async callTool(e,l,n){let r=0,a=e?.function.name;if(!a)throw new Error("Tool name is missing");let I=e?.function.arguments;if(I==null)throw new Error("Tool call arguments are missing");let s=e?.id;if(!s)throw new Error("Tool call id is missing");let o,c=l[a];try{let d=eL(I);if(!c||!c.callback)o={textResultForLlm:`Tool '${a}' does not exist. Available tools that can be called are ${Object.keys(l).join(", ")}.`,resultType:"failure",error:`Tool '${a}' does not exist.`,sessionLog:`<error>Tool '${a}' does not exist.</error>`,toolTelemetry:{}};else{let m=c.callback,G=Date.now(),p={...n,toolCallId:s,toolOptions:this.settings.service?.tools?.[a]},A=await m({...d},p);r=Date.now()-G,o=typeof A=="string"?{textResultForLlm:A,resultType:"success",toolTelemetry:{}}:A}}catch(d){d instanceof SyntaxError?(o={textResultForLlm:`The arguments for the tool call '${a}' were not valid JSON. The arguments have been cleared. Arguments: ${I}. JSON parse error: ${d.message}`,resultType:"failure",error:`${d.message}`,sessionLog:`<error>Failed to execute \`${a}\` tool with arguments: ${I} due to syntax error: ${d.message}</error>`,toolTelemetry:{properties:{wasSyntaxError:"true"}}},e.function.arguments="{}"):o={textResultForLlm:`Failed to execute \`${a}\` tool with arguments: ${I} due to error: ${d}`,resultType:"failure",error:d instanceof Error?d.message:`${d}`,sessionLog:`<error>Failed to execute \`${a}\` tool with arguments: ${I}</error>`,toolTelemetry:{}}}return{durationMs:r,originalCall:e,toolResult:o}}isToolCallResponse(e){return e.choices.find(l=>l.message.tool_calls!==void 0)!==void 0}isRateLimitExceededError(e){if(e instanceof Error){if(e.message?.includes("exceeded maximum number of retries")&&e.message?.includes("rate-limited requests"))return!0;if(e.message?.includes("Failed to get response from the AI model")&&e.cause instanceof S8)return e.cause.status===429}return!1}async getModel(){let e=this.clientOptions.model,l={id:e,name:e,capabilities:{supports:{vision:!1},limits:{max_prompt_tokens:9e4,max_context_window_tokens:128e3,vision:{max_prompt_image_size:3145728,max_prompt_images:1,supported_media_types:["image/jpeg","image/png","image/webp"]}}}};return(await(await this.clientPromise).listModels()).filter(I=>I.id===e).at(0)||l}};function T0n(t){for(let e of t)e.function.name=e.function.name.replace(/[^a-zA-Z0-9_-]+/g,"_")}async function O0n(t,e,l){let n=U0n(t.data,e).toReadableStream(),r=nf.fromReadableStream(n),a=l?.processors?.onStreamingChunk;if(a?.length)for await(let I of r){l?.abortSignal?.throwIfAborted();let s={chunk:I};for(let o of a)o.onStreamingChunk(s)}return{data:await r.finalChatCompletion(),response:t.response,request_id:t.request_id}}function U0n(t,e){let l=new Map;return new c0(async function*(){for await(let n of t)n.choices?.forEach(r=>{if(r.delta.role??="assistant",!!r.delta?.tool_calls?.length){r.finish_reason??="tool_calls";let I=l.get(r.index);I||(I={nextSequenceNumber:0,mappings:new Map},l.set(r.index,I)),r.delta.tool_calls?.forEach(s=>{let o=I.mappings.get(s.index);if(o!==void 0)s.id&&o.callId!==s.id&&(o.sequenceNumber=I.nextSequenceNumber++,o.callId=s.id),s.index=o.sequenceNumber;else{let c={callId:s.id,sequenceNumber:I.nextSequenceNumber++};I.mappings.set(s.index,c),s.index=c.sequenceNumber}})}}),yield n},t.controller,e)}var J1e=class extends bL{constructor(e,l,n){let r=new x8;super(r,e,l,n)}};var x1e=class t{constructor(e,l,n,r){this.settings=l;this.logger=n;this.clientOptions=t.initDefaultOptions(r),this.logger.info(`Using responses with model: ${this.model}`),this.clientPromise=e.createClient(l,n,this.clientOptions)}clientOptions;clientPromise;get model(){return this.clientOptions.model}static initDefaultOptions(e){return{model:e?.model||"o4-mini",toolTokenBudgetProportion:e?.toolTokenBudgetProportion??.25,retryPolicy:{maxRetries:e?.retryPolicy?.maxRetries??5,errorCodesToRetry:e?.retryPolicy?.errorCodesToRetry??[],rateLimitRetryPolicy:{defaultRetryAfterSeconds:e?.retryPolicy?.rateLimitRetryPolicy?.defaultRetryAfterSeconds??5,initialRetryBackoffExtraSeconds:e?.retryPolicy?.rateLimitRetryPolicy?.initialRetryBackoffExtraSeconds??1,retryBackoffExtraGrowth:e?.retryPolicy?.rateLimitRetryPolicy?.retryBackoffExtraGrowth??2,maxRetryAfterSeconds:e?.retryPolicy?.rateLimitRetryPolicy?.maxRetryAfterSeconds??60}},thinkingMode:e?.thinkingMode??!0,requestHeaders:e?.requestHeaders??{}}}makeRequest(e,l,n,r,a,I,s,o){return e.responses.create({model:l,previous_response_id:I,instructions:n,input:r,parallel_tool_calls:a.length>0?!0:void 0,tools:a,reasoning:{summary:"auto",effort:"medium"},store:!1,include:["reasoning.encrypted_content"]},{maxRetries:s||this.clientOptions.retryPolicy.maxRetries,headers:o?.requestHeaders,signal:o?.abortSignal}).withResponse()}async*getCompletionWithTools(e,l,n,r){let a=await this.clientPromise,I=g5(n),s=n.map(W=>({name:W.name,description:W.description,parameters:W.input_schema,strict:!1,type:"function"})),o=0,c=this.clientOptions.retryPolicy.maxRetries,d=this.clientOptions.retryPolicy.rateLimitRetryPolicy.initialRetryBackoffExtraSeconds,m=0,G=this.clientOptions.retryPolicy.rateLimitRetryPolicy.maxRetryAfterSeconds,p=l.flatMap(_6e),A,Z=!1;for(;!Z;){let W;do{W=void 0;try{let R=await this.makeRequest(a,this.model,e,p,s,void 0,c,r);A=R.data,p.push(...A.output),this.logger.debug(`response (Request-ID ${R.request_id}):`),this.logger.debug("data:"),this.logger.debug(JSON.stringify(R.data,null,2))}catch(R){let V=R,v=V.error;if(V){W=V,this.logger.error(`error (Request-ID ${V.requestID})`),this.logger.error(JSON.stringify(V,null,2)),this.logger.debug(`Failed to get response from the AI model: ${V}`),v&&this.logger.debug(`Inner error: ${JSON.stringify(v,null,2)}`);let X=V.status,S=X?this.clientOptions.retryPolicy.errorCodesToRetry.some(T=>Array.isArray(T)?X>=T[0]&&(T[1]===void 0||X<=T[1]):X===T):!1,O;if((V.status===429||S)&&(O=parseInt(V.headers?.get("retry-after")||`${this.clientOptions.retryPolicy.rateLimitRetryPolicy.defaultRetryAfterSeconds}`,10)+d,d*=this.clientOptions.retryPolicy.rateLimitRetryPolicy.retryBackoffExtraGrowth),O!==void 0&&O<=G){this.logger.debug(`Retrying after ${O} seconds...`),await new Promise(T=>setTimeout(T,O*1e3)),m+=O,this.logger.debug(`Retrying after ${O} seconds... Will try again now!`);continue}else O?this.logger.error(`Retry after ${O} seconds is too long. Giving up.`):this.logger.error("Retry after is not set. Giving up.")}throw this.logger.error("error"),this.logger.error(JSON.stringify(R,null,2)),R}finally{this.logger.endGroup(8)}}while(W&&o++<c);if(!A||W){this.logger.debug("Recent messages prior to failure:");for(let R=Math.max(0,p.length-6);R<p.length;R++)this.logger.debug(`${R}: ${JSON.stringify(p[R],null,2)}`);throw new Error(`Failed to get response from the AI model; retried ${o-1} times (total retry wait time: ${m} seconds)`,{cause:W})}for(let R of A.output)yield{kind:"message",message:M6e(R)};if(this.requiresToolOutput(A)){let V=(await this.runTool(A,I)).map(v=>({type:"function_call_output",call_id:v.toolCallId,output:v.textResultForLlm}));p.push(...V);for(let v of V)yield{kind:"message",message:M6e(v)}}else yield{kind:"response",response:{content:A.output_text,refusal:null,role:"assistant"}},Z=!0}}async runTool(e,l,n){let r=e.output.filter(I=>I.type==="function_call");if(!r||r.length===0)throw new Error("Tool calls in response are missing");let a=[];for(let I of r){let s=I.name;if(!s)throw new Error("Tool name is missing");let o=I.arguments;if(!o)throw new Error("Tool call arguments are missing");let c=I.call_id;if(!c)throw new Error("Tool call id is missing");let d,m=l[s];try{let G=eL(o);if(!m||!m.callback)d={textResultForLlm:`Tool '${s}' does not exist. Available tools that can be called are ${Object.keys(l).join(", ")}.`,resultType:"failure",error:`Tool '${s}' does not exist.`,sessionLog:`<error>Tool '${s}' does not exist.</error>`,toolTelemetry:{}};else{let p=m.callback,A={...n,toolCallId:c,toolOptions:this.settings.service?.tools?.[s],settings:this.settings},Z=await p({...G},A);d=typeof Z=="string"?{textResultForLlm:Z,resultType:"success",toolTelemetry:{}}:Z}}catch(G){d={textResultForLlm:`Failed to execute \`${s}\` tool with arguments: ${o} due to error: ${G}`,resultType:"failure",error:G instanceof Error?G.message:`${G}`,sessionLog:`<error>Failed to execute \`${s}\` tool with arguments: ${o}</error>`,toolTelemetry:{properties:{wasSyntaxError:G instanceof SyntaxError?"true":"false"}}}}a.push({toolCallId:c,textResultForLlm:d.textResultForLlm,sessionLog:d.resultType=="success"?d.sessionLog:d.error?`<error>${d.error}</error>`:void 0})}return a}requiresToolOutput(e){return e.output.filter(l=>l.type==="function_call").length>0}};function _6e(t){if(t.role==="function")throw new Error("Function role is not supported");let e=[];if(t.reasoning_opaque&&e.push({id:t.reasoning_opaque,type:"reasoning",summary:t.reasoning_text?[{text:t.reasoning_text,type:"summary_text"}]:[],encrypted_content:t.encrypted_content}),t.role==="assistant"&&t.tool_calls&&t.tool_calls.length>0&&kA(t.tool_calls[0])){let l=t.tool_calls[0];return[...e,{type:"function_call",id:t.id,name:l.function.name,arguments:l.function.arguments,call_id:l.id}]}if(t.role==="tool")return[...e,{type:"function_call_output",id:`fc_${t.tool_call_id}`,call_id:t.tool_call_id,output:typeof t.content=="string"?t.content:t.content.map(l=>l.text).join(" ")??""}];if(!t.content)return e;if(t.role==="assistant"){let l=t.id||crypto.randomUUID();return l.startsWith("msg_")||(l=`msg_${l}`),[...e,{type:"message",id:l,role:t.role,content:[{annotations:[],type:"output_text",text:typeof t.content=="string"?t.content:t.content?.map(n=>n.type==="text"?n.text:"").join(" ")??""}],status:"completed"}]}return[...e,{role:t.role,content:typeof t.content=="string"?[{type:"input_text",text:t.content}]:t.content.map(l=>{if(l.type==="text")return{type:"input_text",text:l.text};if(l.type==="image_url")return{type:"input_image",detail:l.image_url.detail||"auto",image_url:l.image_url.url}}).filter(l=>l!==void 0),type:"message"}]}function M6e(t){if(t.type==="reasoning")return{role:"assistant",reasoning_opaque:t.id,reasoning_text:t.summary?t.summary.map(e=>e.text).join(" "):void 0,content:"",encrypted_content:t.encrypted_content};if(t.type==="function_call")return{role:"assistant",id:t.id,tool_calls:[{id:t.call_id,type:"function",function:{name:t.name,arguments:t.arguments}}],content:""};if(t.type==="function_call_output")return{role:"tool",content:t.output,tool_call_id:t.call_id};if(t.type==="message")return{id:"id"in t?t.id:void 0,role:t.role,content:typeof t.content=="string"?t.content:t.content?.map(e=>e.type==="input_text"||e.type==="output_text"?e.text:"").join(" ")??""};throw new Error(`Unknown item type: ${t.type}`)}function M0n(t){let e;t.incomplete_details?.reason==="content_filter"?e="content_filter":t.incomplete_details?.reason==="max_output_tokens"?e="length":e=t.output.some(r=>r.type==="function_call")?"tool_calls":"stop";let n=t.output.filter(r=>r.type==="message"||r.type==="reasoning"||r.type==="function_call").map(r=>M6e(r)).filter(r=>r.role==="assistant").map((r,a)=>({message:{content:Array.isArray(r.content)?r.content.map(I=>typeof I=="string"?I:"text"in I?I.text:"").join(" "):r.content||null,refusal:r.refusal||null,role:r.role||null,tool_calls:r.tool_calls?.filter(I=>I.type==="function"),reasoning_opaque:r.reasoning_opaque,reasoning_text:r.reasoning_text,encrypted_content:r.encrypted_content},index:a,finish_reason:e,logprobs:null}));return{id:t.id,choices:n,created:t.created_at,model:t.model,object:"chat.completion",usage:{completion_tokens:t.usage?.output_tokens||0,prompt_tokens:t.usage?.input_tokens||0,total_tokens:t.usage?.total_tokens||0}}}function XOt(t){return{request_id:t.request_id,data:M0n(t.data),response:t.response}}var S1e=class extends bL{makeResponsesRequest(e,l,n,r,a,I,s){let o=n.find(p=>p.role==="system")?.content||"",c=Array.isArray(o)?o.join(`
|
|
1906
|
-
`):o,m=n.filter(p=>p.role!=="system").flatMap(_6e),G=a.filter(p=>p.type==="function").map(p=>({name:p.function.name,description:p.function.description,parameters:p.function.parameters||null,strict:!1,type:"function"}));return this.logger.debug(`Making responses request with input: ${JSON.stringify(m,null,2)}`),e.responses.create({model:l,previous_response_id:void 0,instructions:c,input:m,parallel_tool_calls:a.length>0?!0:void 0,tools:G,reasoning:{summary:"auto",effort:"medium"},store:!1,include:["reasoning.encrypted_content"]},{maxRetries:I||this.clientOptions.retryPolicy.maxRetries,headers:s?.requestHeaders,signal:s?.abortSignal}).withResponse()}makeRequest(e,l,n,r,a,I,s){return this.makeResponsesRequest(e,l,n,r,a,I,s).then(XOt)}};var B1e=class extends S1e{constructor(e,l,n){let r=new x8;super(r,e,l,n)}};var Ude=class{constructor(e,l,n){this.settings=e;this.logger=l;this.clientOptions=n;this.chatClient=new J1e(e,l,n)}chatClient;get model(){return this.chatClient.model}async*getCompletionWithTools(e,l,n,r){let a=await this.chatClient.modelPromise;(this.clientOptions?.thinkingMode||to(this.settings,"copilot_swe_agent_enable_responses_api"))&&a&&a.supported_endpoints?.includes("/responses")?yield*new B1e(this.settings,this.logger,{model:this.chatClient.model,...this.clientOptions}).getCompletionWithTools(e,l,n,r):yield*this.chatClient.getCompletionWithTools(e,l,n,r)}};var T1e=class extends bL{constructor(e,l,n,r){super(e,l,n,r)}getCompletionOptions(e,l){return{...this.model.startsWith("gpt-4")?{temperature:0,top_p:.95,frequency_penalty:0,presence_penalty:0,parallel_tool_calls:e?!1:void 0}:{},tool_choice:l?.toolChoice}}async*getCompletionWithTools(e,l,n,r){let a=await super.getCompletionWithTools(e,l,n,r);for await(let I of a)I.kind==="message"?yield{...I,message:F6({...I.message,reasoning_text:I.message?.cot_summary})}:yield I}};var O1e=class extends x1e{constructor(e,l,n,r){super(e,l,n,r)}};var D6e=class extends Lde{constructor(e){super(e)}setInitiatorHeader(e){}setAdditionalHeaders(e){}listModels(){return Promise.resolve([])}},U1e=class{async createClient(e,l,n){l.startGroup("configured settings:",8),l.debug(JSON.stringify(e,null,2)),l.endGroup(8);let r=e.api?.openai?.apiKey,a=e.api?.openai?.azureKeyVaultUri,I=e.api?.openai?.azureSecretName;if(!r&&a){l.debug("No API_KEY provided, trying secret provider");let d=O6e(a,l);try{r=await d.getSecret(I||"azure-openai-api-key")}catch(m){l.debug(`Failed to get API Key from secret provider:
|
|
1906
|
+
`):o,m=n.filter(p=>p.role!=="system").flatMap(_6e),G=a.filter(p=>p.type==="function").map(p=>({name:p.function.name,description:p.function.description,parameters:p.function.parameters||null,strict:!1,type:"function"}));return this.logger.debug(`Making responses request with input: ${JSON.stringify(m,null,2)}`),e.responses.create({model:l,previous_response_id:void 0,instructions:c,input:m,parallel_tool_calls:a.length>0?!0:void 0,tools:G,reasoning:{summary:"auto",effort:"medium"},store:!1,include:["reasoning.encrypted_content"]},{maxRetries:I||this.clientOptions.retryPolicy.maxRetries,headers:s?.requestHeaders,signal:s?.abortSignal}).withResponse()}makeRequest(e,l,n,r,a,I,s){return this.makeResponsesRequest(e,l,n,r,a,I,s).then(XOt)}async*getCompletionWithTools(e,l,n,r){yield*super.getCompletionWithTools(e,l,n,{...r,stream:!1})}};var B1e=class extends S1e{constructor(e,l,n){let r=new x8;super(r,e,l,n)}};var Ude=class{constructor(e,l,n){this.settings=e;this.logger=l;this.clientOptions=n;this.chatClient=new J1e(e,l,n)}chatClient;get model(){return this.chatClient.model}async*getCompletionWithTools(e,l,n,r){let a=await this.chatClient.modelPromise;(this.clientOptions?.thinkingMode||to(this.settings,"copilot_swe_agent_enable_responses_api"))&&a&&a.supported_endpoints?.includes("/responses")?yield*new B1e(this.settings,this.logger,{model:this.chatClient.model,...this.clientOptions}).getCompletionWithTools(e,l,n,r):yield*this.chatClient.getCompletionWithTools(e,l,n,r)}};var T1e=class extends bL{constructor(e,l,n,r){super(e,l,n,r)}getCompletionOptions(e,l){return{...this.model.startsWith("gpt-4")?{temperature:0,top_p:.95,frequency_penalty:0,presence_penalty:0,parallel_tool_calls:e?!1:void 0}:{},tool_choice:l?.toolChoice}}async*getCompletionWithTools(e,l,n,r){let a=await super.getCompletionWithTools(e,l,n,r);for await(let I of a)I.kind==="message"?yield{...I,message:F6({...I.message,reasoning_text:I.message?.cot_summary})}:yield I}};var O1e=class extends x1e{constructor(e,l,n,r){super(e,l,n,r)}};var D6e=class extends Lde{constructor(e){super(e)}setInitiatorHeader(e){}setAdditionalHeaders(e){}listModels(){return Promise.resolve([])}},U1e=class{async createClient(e,l,n){l.startGroup("configured settings:",8),l.debug(JSON.stringify(e,null,2)),l.endGroup(8);let r=e.api?.openai?.apiKey,a=e.api?.openai?.azureKeyVaultUri,I=e.api?.openai?.azureSecretName;if(!r&&a){l.debug("No API_KEY provided, trying secret provider");let d=O6e(a,l);try{r=await d.getSecret(I||"azure-openai-api-key")}catch(m){l.debug(`Failed to get API Key from secret provider:
|
|
1907
1907
|
${m}`)}}let s=cZt(e);l.debug(`Using Azure Open API at ${s}`);let c={baseURL:`${new URL(s).origin}/openai`,apiVersion:e.api?.openai?.azure?.apiVersion||"2024-10-21",deployment:n?.model,defaultHeaders:n?.requestHeaders};if(r)c={...c,apiKey:r},l.debug("Using Azure OpenAI API Key");else{let d=new pw,G=Pze(d,"https://cognitiveservices.azure.com/.default");c={...c,azureADTokenProvider:G},l.debug("Using Azure Managed Identity")}return new D6e(c)}};var z6e=class extends ia{constructor(e){super(e)}setInitiatorHeader(e){}setAdditionalHeaders(e){}listModels(){return Promise.resolve([])}},M1e=class{async createClient(e,l,n){l.startGroup("configured settings:",8),l.debug(JSON.stringify(e,null,2)),l.endGroup(8);let r=iZt(e),a=e.api?.openai?.baseUrl,I=n?.requestHeaders;return new z6e({baseURL:a,apiKey:r,defaultHeaders:I})}};function Mde(t,e,l,n){switch(l){case"sweagent-aip":return new V2e(t,e,n);case"sweagent-anthropic":return new PYe(t,e,n);case"sweagent-capi":return new Ude(t,e,n);case"sweagent-openai":return n?.thinkingMode?new O1e(kOt(t),t,e,n):new T1e(kOt(t),t,e,n);default:return new Ude(t,e,n)}}function kOt(t){return t.api?.openai?.azure?.url?new U1e:new M1e}var ET=class{logger;forcePremiumRequest=!1;constructor(e){this.logger=e}async*preRequest(e){e.turn===0||this.forcePremiumRequest?(e.additionalRequestHeaders["X-Initiator"]="user",this.logger.debug("InitiatorHeaderProcessor: Setting X-Initiator to 'user'")):(e.additionalRequestHeaders["X-Initiator"]="agent",this.logger.debug("InitiatorHeaderProcessor: Setting X-Initiator to 'agent'")),this.resetPremiumRequest(),yield*[]}setForcePremiumRequest(){this.forcePremiumRequest=!0}toJSON(){return JSON.stringify({type:"InitiatorHeaderProcessor"})}resetPremiumRequest(){this.forcePremiumRequest=!1}},B8=class{logger;constructor(e){this.logger=e}async*preRequest(e){e.additionalRequestHeaders["X-Initiator"]="agent",this.logger.debug("FreeRequestProcessor: Setting X-Initiator to 'agent'"),yield*[]}setForcePremiumRequest(){}toJSON(){return JSON.stringify({type:"FreeRequestProcessor"})}};function GL(t){return t.kind==="message"&&t.message.role==="assistant"}function LOt(t){return t.kind==="message"&&t.message.role==="user"}function T8(t){return t.kind==="message"&&t.message.role==="assistant"&&!!t.message.tool_calls}function _1e(t){return t.kind==="message"&&t.message.role==="tool"}function _0n(t,e){return t.toolCalls.find(l=>l.toolCallId===e)}function D0n(t,e,l){let n=l.function.name;try{let r=JSON.parse(l.function.arguments||"{}"),a=e.find(c=>c.name===n),I=a?.safeForTelemetry||{name:!1,inputsNames:!1},s=$k(a),o;if(s&&t.customAgents&&t.settings){let c=t.customAgents.find(d=>d.name===n);if(c){let d=t.settings.github?.repo?.name??"",m=d.split("/"),G=m.length===2?m[0]:"",p=m.length===2?m[1]:d,A=c.mcpServers?Object.keys(c.mcpServers).join(","):"",Z=c.mcpServers?Object.keys(c.mcpServers).length:0;o={repoOwner:G,repoName:p,displayName:c.name,mcpServerNames:A,mcpServerCount:Z}}}return{toolCallId:l.id,toolName:n,arguments:l.function.arguments,safeForTelemetryToolName:I===!0||I.name?n:IS(n),safeForTelemetryArguments:I===!0||I.inputsNames?XTt(r):"",isCustomAgent:s,customAgentInfo:o}}catch{return{toolCallId:l.id,toolName:n,arguments:l.function.arguments,safeForTelemetryToolName:IS(n),safeForTelemetryArguments:"",isCustomAgent:!1,customAgentInfo:void 0}}}var D1e=class{constructor(e,l,n){this.runtimeContext=e;this.forAgent=l;this.toolsInUse=n}turnDataCache=new Map;emittedTurns=new Set;getTurnData(){return this.turnDataCache}async ingestEvent(e){let l,n;if("turn"in e&&typeof e.turn=="number"){if(l=e.turn+1,this.emittedTurns.has(l))return;this.turnDataCache.has(l)||this.turnDataCache.set(l,{featureFlagsAsString:WJe(this.runtimeContext.settings),toolCalls:[],toolCallExecutions:[],turn:l}),n=this.turnDataCache.get(l)}else return;e.kind==="tool_execution"?await this.ingestToolExecutionEventAndEmitToolCallExecutedTelemetry(n,e):e.kind==="turn_started"||e.kind==="turn_failed"||e.kind==="turn_retry"||e.kind==="turn_ended"?(n={...n,model:e.model,modelInfo:JSON.stringify(e.modelInfo)},e.kind==="turn_started"?n={...n,startTimeMs:e.timestampMs}:e.kind==="turn_retry"?n={...n,endTimeMs:e.timestampMs,retriesUsed:(n.retriesUsed??0)+1}:e.kind==="turn_failed"?n={...n,endTimeMs:e.timestampMs,error:e.error}:e.kind==="turn_ended"&&(n={...n,endTimeMs:e.timestampMs})):e.kind==="history_truncated"?n={...n,truncateEvent:e}:e.kind==="image_processing"?n={...n,imageProcessingMetrics:e.imageProcessingMetrics}:e.kind==="images_removed"?n={...n,largeImagesRemoved:(n.largeImagesRemoved??0)+(e.largeImagesRemoved?1:0),imagesRemoved:(n.imagesRemoved??0)+(e.imagesRemoved?1:0)}:e.kind==="model_call_success"||e.kind==="model_call_failure"?(n={...n,callId:e.callId,modelCallDurationMs:e.modelCallDurationMs,api_call_id:e.modelCall.api_id,provider_call_id:e.modelCall.request_id,conversationStructureSummary:fXt(e.requestMessages)},e.kind==="model_call_success"&&(n={...n,responsePromptTokens:e.responseUsage?.prompt_tokens,responseCompletionTokens:e.responseUsage?.completion_tokens,responseTotalTokens:e.responseUsage?.total_tokens})):LOt(e)&&e.source==="jit-instruction"?n={...n,jitInstructionsAdded:(n?.jitInstructionsAdded??0)+1}:GL(e)&&e.message.tool_calls?n={...n,toolCalls:n.toolCalls.concat(e.message.tool_calls.map(r=>({...D0n(this.runtimeContext,this.toolsInUse,r)})))}:_1e(e)&&(n={...n,toolCallExecutions:n.toolCallExecutions.concat([e.message.tool_call_id])}),this.turnDataCache.set(l,n),e.kind==="turn_ended"&&(await this.emitTurnTelemetry(l),this.emittedTurns.add(l),this.turnDataCache.delete(l))}async emitTurnTelemetry(e){let l=this.turnDataCache.get(e);if(l){let n={kind:"telemetry",telemetry:{event:"get_completion_with_tools_turn",properties:{callId:l.callId,model:l.model||"default",modelInfo:l.modelInfo||"{}",api_call_id:l.api_call_id,provider_call_id:l.provider_call_id,agent:this.forAgent,toolCalls:JSON.stringify(l.toolCalls.map(r=>({toolCallId:r.toolCallId,toolName:r.safeForTelemetryToolName}))),toolCallExecutions:JSON.stringify(l.toolCallExecutions),error:l.error,featureFlags:WJe(this.runtimeContext.settings),conversationStructureSummary:l.conversationStructureSummary,truncationPerformedBy:l.truncateEvent?.performedBy},metrics:{turn:e,turnDurationMs:l.endTimeMs!==void 0&&l.startTimeMs!==void 0?l.endTimeMs-l.startTimeMs:0,modelCallDurationMs:l.modelCallDurationMs,retriesUsed:l.retriesUsed??0,numToolCalls:l.toolCalls.length,numToolExecutions:l.toolCallExecutions.length,largeImagesRemoved:l.largeImagesRemoved,imagesRemoved:l.imagesRemoved,responsePromptTokens:l.responsePromptTokens,responseCompletionTokens:l.responseCompletionTokens,responseTotalTokens:l.responseTotalTokens,jitInstructionsAdded:l.jitInstructionsAdded,...l.truncateEvent?.truncateResult,...l.imageProcessingMetrics},restrictedProperties:{}}};await this.runtimeContext.callback?.progress(n)}}async ingestToolExecutionEventAndEmitToolCallExecutedTelemetry(e,l){let n=l.toolCallId,r=_0n(e,n);if(r){let a=l.toolResult,I={kind:"telemetry",telemetry:{event:"tool_call_executed",properties:{...a.toolTelemetry.properties,completionWithToolsCallId:l.callId,resultType:a.resultType,toolCallId:n,arguments:r.safeForTelemetryArguments,toolName:r.safeForTelemetryToolName,api_call_id:e.api_call_id,isCustomAgent:r.isCustomAgent?"true":"false"},restrictedProperties:{...a.toolTelemetry.restrictedProperties,arguments:r.arguments,result:a.textResultForLlm,toolName:r.toolName,error:a.error,customAgent:r.customAgentInfo?JSON.stringify({repoOwner:r.customAgentInfo.repoOwner,repoName:r.customAgentInfo.repoName,displayName:r.customAgentInfo.displayName,mcpServerNames:r.customAgentInfo.mcpServerNames}):void 0},metrics:{...a.toolTelemetry.metrics,durationMs:l.durationMs,customAgentMcpServerCount:r.customAgentInfo?.mcpServerCount}}};await this.runtimeContext.callback?.progress(I)}}};var JOt={shell:["bash","powershell"],bash:["bash"],powershell:["powershell"],read:["view"],NotebookRead:["view"],edit:["str_replace_editor","create","edit"],MultiEdit:["str_replace_editor","create","edit"],Write:["str_replace_editor","create","edit"],NotebookEdit:["str_replace_editor","create","edit"],search:["search"],Grep:["search"],Glob:["search"],"custom-agent":[]};function z0n(t,e,l){if(!t.endsWith("/*"))return!1;t=SOt(t);let n=t.slice(0,-2).toLowerCase();for(let r of e)P6e(r).startsWith(n+"/")&&l.add(r);return!0}function P0n(t,e,l){t=SOt(t);let n=e.get(t.toLowerCase());return n?(l.add(n),!0):!1}function j0n(t,e,l,n){if(!t.includes("/"))return!1;let[r,a]=t.split("/",2),I=a.toLowerCase(),s=e.get(I);if(s)return l.add(s),!0;let o=!1,c=n[I];if(c)for(let d of c){let m=e.get(d.toLowerCase());m&&(l.add(m),o=!0)}return o}function K0n(t,e,l){if(t!=="shell")return!1;let n=process.platform==="win32"?"powershell":"bash",r=process.platform==="win32"?"bash":"powershell",a=e.get(n.toLowerCase());return a||(a=e.get(r.toLowerCase())),a?(l.add(a),!0):!1}function q0n(t,e,l,n){let r=n[t.toLowerCase()];if(!r)return!1;let a=!1;for(let I of r){let s=e.get(I.toLowerCase());s&&(l.add(s),a=!0)}return a}function xOt(t,e,l=[]){let n=new Map,r=new Set;for(let s of e)n.set(P6e(s),s);let a=[...JOt["custom-agent"]];for(let s of l)$k(s)&&a.push(P6e(s));let I={};for(let[s,o]of Object.entries(JOt))I[s.toLowerCase()]=o;I["custom-agent"]=a,I.task=a;for(let s of t){let o=s.toLowerCase().split("/"),c=o.length>2?o[0]+"__"+o.slice(1).join("/"):s.toLowerCase();z0n(c,e,r)||q0n(c,n,r,I)||P0n(c,n,r)||j0n(c,n,r,I)||K0n(c,n,r)}return Array.from(r)}function SOt(t){return t.startsWith("github__github-mcp-server/")?t.replace("github__github-mcp-server/","github-mcp-server/"):t.startsWith("microsoft__playwright-mcp/")?t.replace("microsoft__playwright-mcp/","playwright/"):t.startsWith("github/")?t.replace("github/","github-mcp-server/"):t}var P6e=t=>(t.namespacedName||t.name).toLowerCase();var _de=class{async*preRequest(e){yield*[]}handleCallbackResponse(e){}getUserMessages(){return[]}clearUserMessages(){}canProcessUserMessages(){return!1}toJSON(){return JSON.stringify({type:"NoopUserMessageProcessor"})}};var z1e={start:"\u25B6\uFE0F Begin custom agent",end:"\u23F9\uFE0F End custom agent"},$0n=void 0,Dde=class{constructor(e,l=$0n){this.runtimeContext=e;this.agentId=l;this.gitHandlers={silent:new pZ(new xd,this.runtimeContext.exec),logging:new pZ(this.runtimeContext.logger,this.runtimeContext.exec)}}gitHandlers;async agent(e,l,n,r,a,I,s,o=new _de,c){let d=async(A,Z,W)=>{let R={role:"user",content:A};return await this.runtimeContext.callback?.progress({kind:"message",turn:0,callId:this.agentId,message:R}),await this.runCompletionWithTools(e,l,[...Z??[],R],I,s,a,{executeToolsInParallel:to(this.runtimeContext.settings,"copilot_swe_agent_parallel_tool_execution"),initialTurnCount:W},c,o)},m=r,G=n??[],p;for(;m;){let A=await d(m,G,p);p=A.finalTurnCount,G=A.messages,m=await c?.onResult(A.postCompletionWithToolsCommitHash)}for(let A of I)if(A.shutdown){let Z=await A.shutdown();Z&&await this.runtimeContext.callback?.progress(Z)}return{finalTurnCount:p||0,messages:G}}async runCompletionWithTools(e,l,n,r,a,I,s,o,c=new _de){let d=this.runtimeContext.callback?new D1e(this.runtimeContext,"sweagent-capi",r):void 0,m=this.gitHandlers.logging,G=await m.getCurrentCommitHash(e),p=n.filter(X=>X.role==="user").at(-1),A=this.createCompletionWithToolsProcessors(e,G,r,a,c,I,o,p),Z=this.runtimeContext.client.getCompletionWithTools(l,n,r,{...s,callId:this.agentId,processors:A}),W=0,R=[...n],V=[];for await(let X of Z){if(to(this.runtimeContext.settings,"copilot_swe_agent_progress_commands")){let S=await this.runtimeContext.callback?.progress(X,{accepts_user_messages:c.canProcessUserMessages()});c.handleCallbackResponse(S)}else await this.runtimeContext.callback?.progress(X);d&&await d.ingestEvent(X),(X.kind==="message"||X.kind==="response")&&(X.kind==="message"&&R.push(X.message),X.kind==="response"&&V.push(X.response),W=Math.max(W,X.turn??0))}let v=await m.getCurrentCommitHash(e);return{finalTurnCount:W,messages:R,resultMessages:V,preCompletionWithToolsCommitHash:G,postCompletionWithToolsCommitHash:v}}createCompletionWithToolsProcessors(e,l,n,r,a,I,s,o){let c=new d0e(this.runtimeContext.logger,this.runtimeContext.settings,n.find(p=>p.name==="github-mcp-server-get_file_contents")),d=new b0e(this.runtimeContext.settings,this.runtimeContext.logger,this.gitHandlers.silent,e,l,I),m=new j4(o,this.runtimeContext.logger),G=[d,c,m];return to(this.runtimeContext.settings,"copilot_swe_agent_progress_commands")&&G.push(a),G.push(r),{preRequest:G.filter(p=>p!==void 0),preToolsExecution:[s].filter(p=>p!==void 0),postToolExecution:[c,s].filter(p=>p!==void 0),onRequestError:[c,m].filter(p=>p!==void 0)}}};function eRn(t){let e=t.content;if(typeof e=="string")return e;if(!Array.isArray(e)||e.length===0||!("text"in e[0]))throw new Error("Expected text content in response");return e[0].text}async function tRn(t,e,l,n){if(!e.mcpServers||Object.keys(e.mcpServers).length===0||!n)return l;t.info(`Custom agent ${e.name} is using MCP servers: ${Object.keys(e.mcpServers).join(", ")}`);let r=l;for(let[a,I]of Object.entries(e.mcpServers))try{t.info(`Adding MCP server '${a}' for custom agent '${e.name}'`),r=await lRn(t,e,a,I,r,n)}catch(s){t.error(`Encountered an issue when trying to add MCP ${a} for custom agent '${e.name}': ${s}`)}return r}async function lRn(t,e,l,n,r,a){let I=await a.addServerAndGetTools(l,n,t);if(I.length>0){t.info(`Adding ${I.length} new tools from server '${l}' for custom agent '${e.name}'`);for(let s of I)t.info(`Adding new tool: ${s.name}`),r.push(s)}return r}async function BOt(t,e,l){!t.callback||!l||(e==="begin"?await t.callback.progress({kind:"title_and_body_content",title:`${z1e.start}: ${l}`,body:`All messages from here to '${z1e.end}' are from the ${l} custom agent.`}):await t.callback.progress({kind:"title_and_body_content",title:`${z1e.end}: ${l}`,body:`All messages from here back to '${z1e.start}' are from the ${l} custom agent.`}))}function OOt(t,e,l,n,r,a,I){async function s(o,c){let d=c?.toolCallId;await BOt(r,"begin",l.name);let m=await l.prompt();r.logger.info(`Starting custom agent as tool: ${l.name}`),r.logger.info(`Custom agent system prompt: ${m}`),r.logger.info(`Candidate tools for custom agent: ${a.map(X=>X.namespacedName||X.name).join(", ")}`),r.logger.info(`Requested tools for custom agent: ${l.tools?.join(", ")??"none"}`),a=await tRn(r.logger,l,a,I);let G=aRn(a,l,"tool");r.logger.info(`Custom agent tools after filtering: ${G.map(X=>X.name).join(", ")}`);let p=new Dde(r,d),A=await t(G),Z=new B8(r.logger),W=e(m,o.prompt),R=await p.agent(n,A,void 0,W,{},G,Z),V=R.messages[R.messages.length-1],v=V?eRn(V):"No response from tool";return await BOt(r,"end",l.name),{textResultForLlm:v,resultType:"success",toolTelemetry:{}}}return{name:l.name,description:`${l6e} ${l.description}`,input_schema:{type:"object",properties:{prompt:{type:"string",description:"The prompt for the agent."}},required:["prompt"]},callback:s}}var P1e=class{constructor(e,l,n={requestRequired:!1}){this.mcpHost=e;this.settings=l;this.permissions=n}async addServerAndGetTools(e,l,n){try{await this.mcpHost.startServer(e,l),n.info(`Successfully started MCP server '${e}'`);let a=(await this.mcpHost.getTools(this.settings,n,this.permissions)).filter(I=>I.name.startsWith(`${e}-`)||I.namespacedName?.startsWith(`${e}/`));return n.info(`Found ${a.length} MCP tools from server '${e}'`),a}catch(r){return n.error(`Failed to add MCP server '${e}': ${r}`),[]}}},nRn=[aS,bWe],rRn=[HRt],TOt=[aS,bWe];function aRn(t,e,l){if(!e?.tools||e.tools.length===1&&e.tools[0]==="*")return t.filter(s=>l==="top-level"||!TOt.includes(s.name));let n=t.filter(s=>$k(s)),r=l==="top-level"?nRn:rRn;return xOt([...e.tools,...r],t,n).filter(s=>l==="top-level"||!TOt.includes(s.name))}async function j6e(t,e,l,n,r){try{return(await n.invokeTool("blackbird-mcp-server/search_repository_with_agent",{task:t,depth:2,owner:e,repo:l,numSnippets:10},"hidden_characters")).textResultForLlm}catch(a){return r.error(`Error during Blackbird search: ${a}`),""}}var MOt=t=>to(t,"copilot_swe_agent_search")||Pgt(t,"SearchAgentExperiment")==="enabled",UOt="search";function K6e(t){return t!==null&&typeof t=="object"&&"question"in t&&"reason"in t&&"searchCommand"in t}var IRn=(t,e,l)=>`
|
|
1908
1908
|
You are a question answering agent that is a component of GitHub Copilot coding agent. Your task is to take the given question
|
|
1909
1909
|
and answer it using the given facts.
|
|
@@ -2036,7 +2036,7 @@ ${a}`;await r.createOrUpdateMCPStartupToolCall({serverName:e,content:o,toolNames
|
|
|
2036
2036
|
`).filter(A=>A.trim()),p=[];for(let A=0;A<G.length;A++)try{let Z=JSON.parse(G[A]),W=t(Z);p.push(W)}catch(Z){throw new Error(`Invalid event at line ${A+1} in ${d}: ${Z}`)}return p}catch(m){throw new Error(`Failed to read JSONL from ${d}: ${m}`)}},append:async(c,d)=>{let m=r(d),G=Array.isArray(c)?c:[c];try{await jzt(m);let p=G.map(A=>JSON.stringify(A)).join(`
|
|
2037
2037
|
`)+`
|
|
2038
2038
|
`;await kwe.runExclusive(m,()=>Vfn(m,p,{mode:384}))}catch(p){throw new Error(`Failed to append to JSONL file ${m}: ${p}`)}},path:r,directoryFiles:async()=>{let c=cN(l(),n());try{let m=(await fwe(c,{withFileTypes:!0})).filter(p=>p.isFile()&&p.name.endsWith(".jsonl")).map(p=>p.name),G=await Promise.all(m.map(async p=>{let A=cN(c,p);try{let Z=await Hwe(A);return{file:p,mtime:Z.mtime}}catch{return{file:p,mtime:new Date}}}));return G.sort((p,A)=>A.mtime.getTime()-p.mtime.getTime()),G.map(p=>p.file)}catch{return[]}},directoryFilesWithMetadata:async()=>{let c=cN(l(),n());try{let m=(await fwe(c,{withFileTypes:!0})).filter(p=>p.isFile()&&p.name.endsWith(".jsonl")).map(p=>p.name),G=await Promise.all(m.map(async p=>{let A=cN(c,p);try{let Z=await Hwe(A);return{file:p,mtime:Z.mtime,birthtime:Z.birthtime}}catch{return{file:p,mtime:new Date,birthtime:new Date}}}));return G.sort((p,A)=>A.mtime.getTime()-p.mtime.getTime()),G}catch{return[]}},home:l,directory:n}};var $zt=zl({host:Qt(),login:Qt()}),ffn=zl({banner:G0(["always","once","never"]).optional(),beep:ro().optional(),last_logged_in_user:$zt.optional(),logged_in_users:Od($zt).optional(),model:Qt().optional(),render_markdown:ro().optional(),screen_reader:ro().optional(),theme:Qt().optional(),trusted_folders:Od(Qt()).optional(),store_token_plaintext:ro().optional(),stream:ro().optional(),parallel_tool_execution:ro().optional(),feature_flags:zl({enabled:Od(Qt()).optional()}).optional(),asked_setup_terminals:Od(Qt()).optional(),capi_hmac_key:Qt().optional(),copilot_hmac_key:Qt().optional(),copilot_integration_id:Qt().optional(),copilot_tokens:rY(Qt(),Qt()).optional(),copilot_url:Qt().optional(),staff:ro().optional(),log_level:G0(["none","error","warning","info","debug","all","default"]).optional()}),Hfn=rY(Qt(),lKe()),Xfn=Hfn.transform(t=>(0,ePt.default)(t,(e,l)=>{let n=l.toLowerCase();return n==="github_copilot_integration_id"?"copilot_integration_id":n})),kfn=Xfn.pipe(ffn),Sr=Jwe(kfn.parse,"config");function xL(){return process.env.COPILOT_ENABLE_ALT_PROVIDERS==="true"}var oO=["claude-sonnet-4.5","claude-sonnet-4","claude-haiku-4.5","gpt-5"];function tPt(t,e){let l=" ".repeat(e);return t.map(n=>`${l}- "${n}"`).join(`
|
|
2039
|
-
`)}function wq(t){return oO.includes(t)||xL()}function sO(t,e){if(!e)return!0;let l=e.find(n=>n.id===t);return l?l.policy?l.policy.state!=="disabled":!0:!1}function Uqe(t){return oO.find(e=>sO(e,t))}function Qq(t,e){if(e&&e.length>0){let n=e.find(r=>r.id===t);if(n?.billing?.multiplier!==void 0)return n.billing.multiplier}return{"claude-sonnet-4":1,"gpt-5":1,"claude-sonnet-4.5":1,"claude-haiku-4.5":.33}[t]??1}async function iO(t,e,l,n){if(xL()&&process.env.COPILOT_AGENT_MODEL){let{model:I}=HB(process.env.COPILOT_AGENT_MODEL);if(I)return I}if(t){if(sO(t,l))return t;n?.warning(`Model '${t}' from CLI argument is not available. Falling back to next option.`)}if(e){let I=await e?.getSelectedModel?.();if(I){if(sO(I,l))return I;n?.warning(`Model '${I}' from session is not available. Falling back to next option.`)}}let r=process.env.COPILOT_MODEL;if(r&&wq(r)){if(sO(r,l))return r;n?.warning(`Model '${r}' from COPILOT_MODEL environment variable is not available. Falling back to next option.`)}try{let s=(await Sr.load()||{}).model;if(typeof s=="string"&&s&&wq(s)){if(sO(s,l))return s;n?.warning(`Model '${s}' from config file is not available. Falling back to default.`)}}catch{}let a=Uqe(l);return a&&n?.info(`Using default model: ${a}`),a}function _w(t){return"host"in t?t.host:"https://github.com"}function lme(t){return cY(t,{onHMACAuthInfo:()=>"Logged in with HMAC",onEnvAuthInfo:e=>`Logged in with ${e.envVar} as user: ${e.login}`,onUserAuthInfo:e=>`Logged in as user: ${tme(e)}`,onGhCliAuthInfo:e=>`Logged in with gh as user: ${tme(e)}`,onApiKeyAuthInfo:e=>`Logged in with API key to ${e.host}`})}function nme(t){return cY(t,{onHMACAuthInfo:()=>"Unknown (via HMAC)",onEnvAuthInfo:e=>`${e.login} (via ${e.envVar})`,onUserAuthInfo:e=>tme(e),onGhCliAuthInfo:e=>`${e.login} (via gh)`,onApiKeyAuthInfo:e=>`${e.host} (via API key)`})}function Mqe(t,e){return cY(t,{onHMACAuthInfo:l=>e.type==="hmac"&&l.hmac===e.hmac,onEnvAuthInfo:l=>e.type==="env"&&l.envVar===e.envVar&&l.login===e.login,onUserAuthInfo:l=>e.type==="user"&&cO(l,e),onGhCliAuthInfo:l=>e.type==="gh-cli"&&cO(l,e),onApiKeyAuthInfo:l=>e.type==="api-key"&&l.host===e.host&&l.apiKey===e.apiKey})}async function lPt(t,e){let l=await t.getAllAuthAvailable(),n=">",r="-";return l.map(a=>`${e&&Mqe(a.authInfo,e)?n:r} ${nme(a.authInfo)}`)}function tme(t){return t.host!==kL?`${t.login} (${t.host})`:t.login}async function nPt(){let t=await Sr.load()||{};return t?.last_logged_in_user??t.logged_in_users?.[0]??void 0}async function _qe(t){await Sr.writeKey("last_logged_in_user",t)}async function Swe(){return(await Sr.load()||{}).logged_in_users||[]}async function rPt(t,e){await Sr.writeKey("last_logged_in_user",t),await Sr.writeKey("logged_in_users",e)}async function aPt(t){let e=await Swe();return e.some(n=>cO(n,t))?(e=e.filter(n=>!cO(n,t)),await rPt(void 0,e),e.length>0):!1}async function IPt(t){let e=await Swe();e.some(n=>cO(n,t))||(e.push(t),await rPt(t,e))}function cO(t,e){return t.login===e.login&&t.host===e.host}async function sPt(t,e){try{let l=Lfn(),n=await e.execReturn("gh",["auth","token","--hostname",l],{silent:!0,ignoreReturnCode:!0});if(n.exitCode!==0||!n.stdout.trim()){let a=`Failed to retrieve GitHub token from CLI (exit code: ${n.exitCode})`,I=n.stderr?.trim();return I?t.debug(`${a}: ${I}`):t.debug(a),null}let r=n.stdout.trim();return r.startsWith("ghp_")?(t.debug("GitHub token is a classic PAT"),null):(t.debug("GitHub CLI authenticated with valid token"),{token:r,host:l})}catch(l){let n=`Error checking GitHub CLI: ${l}`;return l&&typeof l=="object"&&"stderr"in l&&typeof l.stderr=="string"&&(n+=` (stderr: ${l.stderr.trim()})`),t.debug(n),null}}function Lfn(){return process.env.GH_HOST||"github.com"}function Dqe(){let t=process.env.GH_HOST;return t?t.startsWith("https://")?t:`https://${t}`:kL}import{existsSync as cPt}from"fs";var Bwe="copilot-cli",Twe;async function Owe(){if(Twe)return Twe;let t=await Promise.resolve().then(()=>$e(iPt(),1));return Twe=t.default||t,Twe}var ame=(t,e)=>{if(!(!t||!e))return`${t}:${e}`},Sfn=()=>{let t=new Map,e=async(o,c)=>{let d=ame(o,c);if(d)if(cPt(Sr.path()))try{let p=(await Sr.load())?.copilot_tokens?.[d];t.set(d,p&&p.trim()!==""?p:void 0)}catch{t.set(d,void 0)}else t.set(d,void 0)},l=async()=>{if(cPt(Sr.path()))try{let c=(await Sr.load())?.copilot_tokens;if(c){let d=Object.values(c).filter(m=>m&&m.trim()!=="");if(d.length>0)return d[0]}}catch{return}},n=async(o,c)=>{let d=ame(o,c);if(!d)return;if(t.has(d))return t.get(d);if((await Sr.load())?.store_token_plaintext)return await e(o,c),t.get(d);try{let p=await(await Owe()).getPassword(Bwe,d);p?t.set(d,p):await e(o,c)}catch{await e(o,c)}return t.get(d)},r=async()=>{if(t.size>0)return t.values().next().value;if((await Sr.load())?.store_token_plaintext)return await l();let c;try{c=await(await Owe()).findPassword(Bwe)}catch{}return c||(c=await l()),c},a=async(o,c)=>{let d=ame(o,c);if(d){t.delete(d);try{return(await Owe()).deletePassword(Bwe,d)}catch{let p=(await Sr.load())?.copilot_tokens??{};return delete p[d],await Sr.writeKey("copilot_tokens",p),Promise.resolve(!0)}}},I=async(o,c,d)=>{if(!o)throw new Error("No token provided to store");let m=ame(c,d);if(!m)return;if(t.set(m,o),(await Sr.load())?.store_token_plaintext)return await s(c,d),!0;try{return await(await Owe()).setPassword(Bwe,m,o),!0}catch{return!1}},s=async(o,c)=>{let d=ame(o,c);if(!d)return;let m=t.get(d);if(!m)return;let p=(await Sr.load())?.copilot_tokens??{};p[d]=m,await Sr.writeKey("copilot_tokens",p)};return{getToken:n,getAnyToken:r,removeToken:a,storeToken:I,storeCurrentTokenInConfig:s}},Ef=Sfn();function cY(t,e){switch(t.type){case"hmac":return e.onHMACAuthInfo(t);case"env":return e.onEnvAuthInfo(t);case"user":return e.onUserAuthInfo(t);case"gh-cli":return e.onGhCliAuthInfo(t);case"api-key":return e.onApiKeyAuthInfo(t);default:{let l=t;throw new Error(`unexpected auth info type: ${JSON.stringify(t)}`)}}}async function Iy(t){return await cY(t,{onHMACAuthInfo:async()=>process.env.GITHUB_MCP_SERVER_TOKEN,onEnvAuthInfo:async e=>e.token,onUserAuthInfo:async e=>await Ef.getToken(e.host,e.login)||void 0,onGhCliAuthInfo:async e=>e.token,onApiKeyAuthInfo:async()=>{}})}var zqe=class{currentAuthInfo=null;logger=new xd;authCallbacks=[];setLogger(e){this.logger=e}onAuthChange(e){this.authCallbacks.push(e)}removeAuthCallback(e){let l=this.authCallbacks.indexOf(e);l>-1&&this.authCallbacks.splice(l,1)}async notifyAuthChange(e,l){this.currentAuthInfo=e;for(let n of this.authCallbacks)try{await n(e,l)}catch(r){this.logger.error(`Error in auth change callback: ${r}`)}}async tryHMACLogin(){let e=await Sr.load()||{},l=e.copilot_hmac_key||e.capi_hmac_key||process.env.CAPI_HMAC_KEY||process.env.COPILOT_HMAC_KEY;return l?[{authInfo:{type:"hmac",hmac:l}}]:[]}async tryGitHubTokenLogin(){let e=process.env.GH_TOKEN||process.env.GITHUB_TOKEN;if(!e)return[];if(e.startsWith("ghp_"))return this.logger.error("Classic PATs are not supported. Please use fine-grained PATs or other supported token types."),[];if(!e.startsWith("gho_")&&!e.startsWith("ghu_")&&!e.startsWith("github_pat_"))return this.logger.error("Unsupported token type, ignoring."),[];let l=Dqe();try{let n=await Wq(l,e);return[{authInfo:{type:"env",host:l,login:n,token:e,envVar:process.env.GH_TOKEN?"GH_TOKEN":"GITHUB_TOKEN"},token:e}]}catch(n){n instanceof XL?this.logger.error(`Failed to fetch PAT user login (${n.status}): ${n.message}`):this.logger.error("Failed to fetch PAT user login")}return[]}async tryGhCliTokenLogin(){let e=new XA(this.logger),l=await sPt(this.logger,e);if(!l)return[];let{token:n,host:r}=l;try{let a=r.startsWith("https://")?r:`https://${r}`,I=await Wq(a,n);return[{authInfo:{type:"gh-cli",host:a,login:I,token:n},token:n}]}catch(a){a instanceof XL?this.logger.error(`Failed to fetch GitHub CLI user login (${a.status}): ${a.message}`):this.logger.error("Failed to fetch GitHub CLI user login")}return[]}async tryApiKeyLogin(){if(!xL())return[];let e=process.env.ANTHROPIC_API_KEY||process.env.AZURE_OPENAI_API_KEY,l=process.env.ANTHROPIC_API_KEY?"https://api.anthropic.com":process.env.AZURE_OPENAI_API_KEY?process.env.AZURE_OPENAI_API_ENDPOINT||process.env.OPENAI_BASE_URL||"https://api.openai.com":void 0;return!e||!l?[]:[{authInfo:{type:"api-key",apiKey:e,host:l}}]}async tryLoginToken(){let e=await nPt(),l;if(e){if(l=await Ef.getToken(e.host,e.login),!l||l.trim()==="")return[]}else{if(l=await Ef.getAnyToken(),!l||l.trim()==="")return[];let n=Dqe();e={host:n,login:await Wq(n,l)}}return[{authInfo:{type:"user",host:e.host,login:e.login},token:l}]}async getAllGitHubLoginTokens(){let l=(await this.tryGitHubTokenLogin()).at(0),n=await Swe(),r=[];for(let a of n){if(l?.authInfo.type==="user"&&cO(a,l.authInfo))continue;let I=await Ef.getToken(a.host,a.login);I&&r.push({authInfo:{type:"user",host:a.host,login:a.login},token:I})}return r}async getAllAuthAvailable(){let e=[],l=this.getPrioritizedAuthMethods(!0);for(let n of l){let r=await n();e.push(...r)}return e}getPrioritizedAuthMethods(e){return[this.tryHMACLogin.bind(this),this.tryApiKeyLogin.bind(this),this.tryGitHubTokenLogin.bind(this),e?this.getAllGitHubLoginTokens.bind(this):this.tryLoginToken.bind(this),this.tryGhCliTokenLogin.bind(this)]}async loadAuthInfo(){let e=this.currentAuthInfo!==null;this.currentAuthInfo=null;let l=this.getPrioritizedAuthMethods(!1);for(let n of l){let r=await n();if(r.length>0){let{authInfo:a,token:I}=r[0];a.type==="user"&&_qe({host:a.host,login:a.login}),this.currentAuthInfo=a,e||await this.notifyAuthChange(a,I);return}}}async getCurrentAuthInfo(){return this.currentAuthInfo||await this.loadAuthInfo(),this.currentAuthInfo}async loginUser(e,l){let n={host:e,login:l},r={type:"user",...n};await IPt(n);let a=await Iy(r);await this.notifyAuthChange(r,a)}async switchToAuth(e){this.currentAuthInfo=e.authInfo,e.authInfo.type==="user"&&await _qe({host:e.authInfo.host,login:e.authInfo.login}),await this.notifyAuthChange(e.authInfo,e.token)}async logout(){if(!this.currentAuthInfo)return!1;let e=await cY(this.currentAuthInfo,{onHMACAuthInfo:async()=>!1,onEnvAuthInfo:async()=>!1,onUserAuthInfo:async l=>(await Ef.removeToken(l.host,l.login),await aPt(l)),onGhCliAuthInfo:async()=>!1,onApiKeyAuthInfo:async()=>!1});return await this.notifyAuthChange(null),e}},Bfn=new zqe,Uwe=Bfn;var Rf=class t extends HL{constructor(l,n,r,a,I){super(l,n,a,"direct");this.exec=r;this.enableAllGithubMcpTools=I??!1}static GITHUB_SERVER_NAME="github-mcp-server";static CLI_DEFAULT_GITHUB_MCP_TOOLS=["get_file_contents","search_code","search_repositories","list_branches","list_commits","get_commit","get_issue","list_issues","get_issue_comments","search_issues","pull_request_read","list_pull_requests","search_pull_requests","list_workflow_runs","get_job_logs","get_workflow_run","list_workflows","get_workflow_run_logs","web_search","search_users"];static BUILTIN_SERVERS=[t.GITHUB_SERVER_NAME];static getBuiltInServerNames(){return[...t.BUILTIN_SERVERS]}hasUserConfiguredGitHubServer=!1;lastGitHubAuthInfo=null;githubMcpToken;enableAllGithubMcpTools;async configureGitHubAuth(l){if(this.isServerDisabled(t.GITHUB_SERVER_NAME))return this.logger.debug("GitHub MCP server is disabled, skipping auto-configuration"),!1;if(this.hasUserConfiguredGitHubServer)return this.logger.debug("User has explicitly configured github-mcp-server, ignoring auth changes"),!1;if(await this.shouldHandleGitHubAuth(l)){let r=await Iy(l);if(!r)return this.logger.debug("No token available for GitHub authentication"),!1;if(this.lastGitHubAuthInfo=l,r===this.githubMcpToken)return!1;this.githubMcpToken=r;let a=await this.createGitHubServerConfig(r,l);try{return await this.restartServer(t.GITHUB_SERVER_NAME,a),this.logger.log("GitHub MCP server configured after authentication"),!0}catch(I){return this.logger.error(`Failed to configure GitHub MCP server after auth: ${I}`),!1}}return!1}async removeGitHubAuth(){if(this.hasUserConfiguredGitHubServer)return this.logger.debug("User has explicitly configured github-mcp-server, ignoring auth changes"),!1;this.githubMcpToken=void 0;try{return this.isServerRunning(t.GITHUB_SERVER_NAME)?(await this.stopServer(t.GITHUB_SERVER_NAME),this.logger.debug("Removed GitHub MCP server"),!0):!1}catch(l){return this.logger.error(`Failed to remove GitHub server: ${l}`),!1}}async shouldHandleGitHubAuth(l){return await cY(l,{onHMACAuthInfo:async()=>!!process.env.GITHUB_MCP_SERVER_TOKEN,onEnvAuthInfo:async()=>!0,onUserAuthInfo:async()=>!0,onGhCliAuthInfo:async()=>!0,onApiKeyAuthInfo:async()=>!1})}async createGitHubServerConfig(l,n){let r="https://api.githubcopilot.com/mcp/readonly";try{let a=await cY(n,{onHMACAuthInfo:async()=>"https://github.com",onEnvAuthInfo:async s=>s.host,onUserAuthInfo:async s=>s.host,onGhCliAuthInfo:async s=>s.host,onApiKeyAuthInfo:async s=>s.host}),I=await E0(a,l,this.logger);r=new URL("/mcp/readonly",I).toString()}catch(a){this.logger.error(`Failed to fetch Copilot URL, using default: ${a}`)}return{type:"http",url:r,headers:{Authorization:"Bearer "+l,"X-MCP-Toolsets":"repos,issues,users,pull_requests,code_security,secret_protection,actions,web_search","X-MCP-Host":"copilot-cli"},tools:this.enableAllGithubMcpTools?["*"]:t.CLI_DEFAULT_GITHUB_MCP_TOOLS,isDefaultServer:!0,filterMapping:{get_issue:"markdown",get_issue_comments:"markdown",get_pull_request:"markdown",get_pull_request_comments:"markdown",get_pull_request_reviews:"markdown"}}}async injectDefaultServers(l){if(l.mcpServers[t.GITHUB_SERVER_NAME]){this.hasUserConfiguredGitHubServer=!0,this.logger.debug("User has already configured github-mcp-server, skipping auto-configuration");return}}async startBuiltInServer(l){l===t.GITHUB_SERVER_NAME&&!this.hasUserConfiguredGitHubServer?this.lastGitHubAuthInfo?(this.logger.log("Attempting to configure GitHub MCP server using stored authentication"),await this.configureGitHubAuth(this.lastGitHubAuthInfo)?this.logger.log("GitHub MCP server configured successfully after enabling"):this.logger.log("GitHub MCP server enabled but could not be configured - authentication may be invalid or insufficient")):this.logger.log("GitHub MCP server enabled - will be configured automatically when authentication becomes available"):await super.startBuiltInServer(l)}};var Tfn=zl({commandHistory:Od(Qt())}),Pqe=xwe(Tfn.parse,"command-history");var Ofn=50,jqe=class{commandHistory=[];historyIndex=-1;isNavigatingHistory=!1;unSubmittedCommand=null;async initialize(){try{let e=await Pqe.load();this.commandHistory=e?.commandHistory||[],this.resetNavigation()}catch{this.commandHistory=[]}}async addCommand(e){this.commandHistory=this.commandHistory.filter(l=>l!==e),this.commandHistory.unshift(e),this.commandHistory=this.commandHistory.slice(0,Ofn),this.resetNavigation(),this.unSubmittedCommand=null,await this.saveHistory()}async updateCurrentCommand(e){this.historyIndex!==-1?(this.commandHistory[this.historyIndex]=e,await this.saveHistory()):this.unSubmittedCommand=e}navigateUp(e){if(this.commandHistory.length===0)return;let l=this.historyIndex+1;if(l<this.commandHistory.length){this.historyIndex=l,this.isNavigatingHistory=!0;let n=this.getCurrentHistoryItem();n&&e.setText(n)}}navigateDown(e){if(this.historyIndex===-1)return;if(this.historyIndex===0)this.resetNavigation();else{let n=this.historyIndex-1;this.historyIndex=n,this.isNavigatingHistory=!0}let l=this.getCurrentHistoryItem();l?(e.setText(l),e.setCursorPosition(0)):e.clear()}resetNavigation(){this.historyIndex=-1,this.isNavigatingHistory=!1}getHistoryIndex(){return this.historyIndex}getHistory(){return this.commandHistory}getCurrentHistoryItem(){return this.historyIndex===-1?this.unSubmittedCommand?this.unSubmittedCommand:void 0:this.commandHistory[this.historyIndex]}isNavigating(){return this.isNavigatingHistory}setNavigating(e){this.isNavigatingHistory=e}async saveHistory(){try{await Pqe.write({commandHistory:this.commandHistory})}catch{}}},dY=new jqe;function uPt(t,e){var l=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),l.push.apply(l,n)}return l}function mPt(t){for(var e=1;e<arguments.length;e++){var l=arguments[e]!=null?arguments[e]:{};e%2?uPt(Object(l),!0).forEach(function(n){Ufn(t,n,l[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(l)):uPt(Object(l)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(l,n))})}return t}function Ufn(t,e,l){return e=Mfn(e),e in t?Object.defineProperty(t,e,{value:l,enumerable:!0,configurable:!0,writable:!0}):t[e]=l,t}function Mfn(t){var e=_fn(t,"string");return typeof e=="symbol"?e:String(e)}function _fn(t,e){if(typeof t!="object"||t===null)return t;var l=t[Symbol.toPrimitive];if(l!==void 0){var n=l.call(t,e||"default");if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var Dfn=GPt({}),bPt=Dfn;function GPt(t){return e.withOptions=l=>GPt(mPt(mPt({},t),l)),e;function e(l,...n){let r=typeof l=="string"?[l]:l.raw,{escapeSpecialCharacters:a=Array.isArray(l),trimWhitespace:I=!0}=t,s="";for(let d=0;d<r.length;d++){let m=r[d];a&&(m=m.replace(/\\\n[ \t]*/g,"").replace(/\\`/g,"`").replace(/\\\$/g,"$").replace(/\\\{/g,"{")),s+=m,d<n.length&&(s+=n[d])}let o=s.split(`
|
|
2039
|
+
`)}function wq(t){return oO.includes(t)||xL()}function sO(t,e){if(!e)return!0;let l=e.find(n=>n.id===t);return l?l.policy?l.policy.state!=="disabled":!0:!1}function Uqe(t){return oO.find(e=>sO(e,t))}function Qq(t,e){if(e&&e.length>0){let n=e.find(r=>r.id===t);if(n?.billing?.multiplier!==void 0)return n.billing.multiplier}return{"claude-sonnet-4":1,"gpt-5":1,"claude-sonnet-4.5":1,"claude-haiku-4.5":.33}[t]??1}async function iO(t,e,l,n){if(xL()&&process.env.COPILOT_AGENT_MODEL){let{model:I}=HB(process.env.COPILOT_AGENT_MODEL);if(I)return I}if(t){if(sO(t,l))return t;n?.warning(`Model '${t}' from CLI argument is not available. Falling back to next option.`)}if(e){let I=await e?.getSelectedModel?.();if(I){if(sO(I,l))return I;n?.warning(`Model '${I}' from session is not available. Falling back to next option.`)}}let r=process.env.COPILOT_MODEL;if(r&&wq(r)){if(sO(r,l))return r;n?.warning(`Model '${r}' from COPILOT_MODEL environment variable is not available. Falling back to next option.`)}try{let s=(await Sr.load()||{}).model;if(typeof s=="string"&&s&&wq(s)){if(sO(s,l))return s;n?.warning(`Model '${s}' from config file is not available. Falling back to default.`)}}catch{}let a=Uqe(l);return a&&n?.info(`Using default model: ${a}`),a}function _w(t){return"host"in t?t.host:"https://github.com"}function lme(t){return cY(t,{onHMACAuthInfo:()=>"Logged in with HMAC",onEnvAuthInfo:e=>`Logged in with ${e.envVar} as user: ${e.login}`,onUserAuthInfo:e=>`Logged in as user: ${tme(e)}`,onGhCliAuthInfo:e=>`Logged in with gh as user: ${tme(e)}`,onApiKeyAuthInfo:e=>`Logged in with API key to ${e.host}`})}function nme(t){return cY(t,{onHMACAuthInfo:()=>"Unknown (via HMAC)",onEnvAuthInfo:e=>`${e.login} (via ${e.envVar})`,onUserAuthInfo:e=>tme(e),onGhCliAuthInfo:e=>`${e.login} (via gh)`,onApiKeyAuthInfo:e=>`${e.host} (via API key)`})}function Mqe(t,e){return cY(t,{onHMACAuthInfo:l=>e.type==="hmac"&&l.hmac===e.hmac,onEnvAuthInfo:l=>e.type==="env"&&l.envVar===e.envVar&&l.login===e.login,onUserAuthInfo:l=>e.type==="user"&&cO(l,e),onGhCliAuthInfo:l=>e.type==="gh-cli"&&cO(l,e),onApiKeyAuthInfo:l=>e.type==="api-key"&&l.host===e.host&&l.apiKey===e.apiKey})}async function lPt(t,e){let l=await t.getAllAuthAvailable(),n=">",r="-";return l.map(a=>`${e&&Mqe(a.authInfo,e)?n:r} ${nme(a.authInfo)}`)}function tme(t){return t.host!==kL?`${t.login} (${t.host})`:t.login}async function nPt(){let t=await Sr.load()||{};return t?.last_logged_in_user??t.logged_in_users?.[0]??void 0}async function _qe(t){await Sr.writeKey("last_logged_in_user",t)}async function Swe(){return(await Sr.load()||{}).logged_in_users||[]}async function rPt(t,e){await Sr.writeKey("last_logged_in_user",t),await Sr.writeKey("logged_in_users",e)}async function aPt(t){let e=await Swe();return e.some(n=>cO(n,t))?(e=e.filter(n=>!cO(n,t)),await rPt(void 0,e),e.length>0):!1}async function IPt(t){let e=await Swe();e.some(n=>cO(n,t))||(e.push(t),await rPt(t,e))}function cO(t,e){return t.login===e.login&&t.host===e.host}async function sPt(t,e){try{let l=Lfn(),n=await e.execReturn("gh",["auth","token","--hostname",l],{silent:!0,ignoreReturnCode:!0});if(n.exitCode!==0||!n.stdout.trim()){let a=`Failed to retrieve GitHub token from CLI (exit code: ${n.exitCode})`,I=n.stderr?.trim();return I?t.debug(`${a}: ${I}`):t.debug(a),null}let r=n.stdout.trim();return r.startsWith("ghp_")?(t.debug("GitHub token is a classic PAT"),null):(t.debug("GitHub CLI authenticated with valid token"),{token:r,host:l})}catch(l){let n=`Error checking GitHub CLI: ${l}`;return l&&typeof l=="object"&&"stderr"in l&&typeof l.stderr=="string"&&(n+=` (stderr: ${l.stderr.trim()})`),t.debug(n),null}}function Lfn(){return process.env.GH_HOST||"github.com"}function Dqe(){let t=process.env.GH_HOST;return t?t.startsWith("https://")?t:`https://${t}`:kL}import{existsSync as cPt}from"fs";var Bwe="copilot-cli",Twe;async function Owe(){if(Twe)return Twe;let t=await Promise.resolve().then(()=>$e(iPt(),1));return Twe=t.default||t,Twe}var ame=(t,e)=>{if(!(!t||!e))return`${t}:${e}`},Sfn=()=>{let t=new Map,e=async(o,c)=>{let d=ame(o,c);if(d)if(cPt(Sr.path()))try{let p=(await Sr.load())?.copilot_tokens?.[d];t.set(d,p&&p.trim()!==""?p:void 0)}catch{t.set(d,void 0)}else t.set(d,void 0)},l=async()=>{if(cPt(Sr.path()))try{let c=(await Sr.load())?.copilot_tokens;if(c){let d=Object.values(c).filter(m=>m&&m.trim()!=="");if(d.length>0)return d[0]}}catch{return}},n=async(o,c)=>{let d=ame(o,c);if(!d)return;if(t.has(d))return t.get(d);if((await Sr.load())?.store_token_plaintext)return await e(o,c),t.get(d);try{let p=await(await Owe()).getPassword(Bwe,d);p?t.set(d,p):await e(o,c)}catch{await e(o,c)}return t.get(d)},r=async()=>{if(t.size>0)return t.values().next().value;if((await Sr.load())?.store_token_plaintext)return await l();let c;try{c=await(await Owe()).findPassword(Bwe)}catch{}return c||(c=await l()),c},a=async(o,c)=>{let d=ame(o,c);if(d){t.delete(d);try{return(await Owe()).deletePassword(Bwe,d)}catch{let p=(await Sr.load())?.copilot_tokens??{};return delete p[d],await Sr.writeKey("copilot_tokens",p),Promise.resolve(!0)}}},I=async(o,c,d)=>{if(!o)throw new Error("No token provided to store");let m=ame(c,d);if(!m)return;if(t.set(m,o),(await Sr.load())?.store_token_plaintext)return await s(c,d),!0;try{return await(await Owe()).setPassword(Bwe,m,o),!0}catch{return!1}},s=async(o,c)=>{let d=ame(o,c);if(!d)return;let m=t.get(d);if(!m)return;let p=(await Sr.load())?.copilot_tokens??{};p[d]=m,await Sr.writeKey("copilot_tokens",p)};return{getToken:n,getAnyToken:r,removeToken:a,storeToken:I,storeCurrentTokenInConfig:s}},Ef=Sfn();function cY(t,e){switch(t.type){case"hmac":return e.onHMACAuthInfo(t);case"env":return e.onEnvAuthInfo(t);case"user":return e.onUserAuthInfo(t);case"gh-cli":return e.onGhCliAuthInfo(t);case"api-key":return e.onApiKeyAuthInfo(t);default:{let l=t;throw new Error(`unexpected auth info type: ${JSON.stringify(t)}`)}}}async function Iy(t){return await cY(t,{onHMACAuthInfo:async()=>process.env.GITHUB_MCP_SERVER_TOKEN,onEnvAuthInfo:async e=>e.token,onUserAuthInfo:async e=>await Ef.getToken(e.host,e.login)||void 0,onGhCliAuthInfo:async e=>e.token,onApiKeyAuthInfo:async()=>{}})}var zqe=class{currentAuthInfo=null;logger=new xd;authCallbacks=[];setLogger(e){this.logger=e}onAuthChange(e){this.authCallbacks.push(e)}removeAuthCallback(e){let l=this.authCallbacks.indexOf(e);l>-1&&this.authCallbacks.splice(l,1)}async notifyAuthChange(e,l){this.currentAuthInfo=e;for(let n of this.authCallbacks)try{await n(e,l)}catch(r){this.logger.error(`Error in auth change callback: ${r}`)}}async tryHMACLogin(){let e=await Sr.load()||{},l=e.copilot_hmac_key||e.capi_hmac_key||process.env.CAPI_HMAC_KEY||process.env.COPILOT_HMAC_KEY;return l?[{authInfo:{type:"hmac",hmac:l}}]:[]}async tryGitHubTokenLogin(){let e=process.env.GH_TOKEN||process.env.GITHUB_TOKEN;if(!e)return[];if(e.startsWith("ghp_"))return this.logger.error("Classic PATs are not supported. Please use fine-grained PATs or other supported token types."),[];if(!e.startsWith("gho_")&&!e.startsWith("ghu_")&&!e.startsWith("github_pat_"))return this.logger.error("Unsupported token type, ignoring."),[];let l=Dqe();try{let n=await Wq(l,e);return[{authInfo:{type:"env",host:l,login:n,token:e,envVar:process.env.GH_TOKEN?"GH_TOKEN":"GITHUB_TOKEN"},token:e}]}catch(n){n instanceof XL?this.logger.error(`Failed to fetch PAT user login (${n.status}): ${n.message}`):this.logger.error("Failed to fetch PAT user login")}return[]}async tryGhCliTokenLogin(){let e=new XA(this.logger),l=await sPt(this.logger,e);if(!l)return[];let{token:n,host:r}=l;try{let a=r.startsWith("https://")?r:`https://${r}`,I=await Wq(a,n);return[{authInfo:{type:"gh-cli",host:a,login:I,token:n},token:n}]}catch(a){a instanceof XL?this.logger.error(`Failed to fetch GitHub CLI user login (${a.status}): ${a.message}`):this.logger.error("Failed to fetch GitHub CLI user login")}return[]}async tryApiKeyLogin(){if(!xL())return[];let e,l;return process.env.ANTHROPIC_API_KEY?(e=process.env.ANTHROPIC_API_KEY,l="https://api.anthropic.com"):process.env.OPENAI_API_KEY?(e=process.env.OPENAI_API_KEY,l=process.env.OPENAI_BASE_URL||"https://api.openai.com"):process.env.AZURE_OPENAI_API_KEY&&(e=process.env.AZURE_OPENAI_API_KEY,l=process.env.AZURE_OPENAI_API_ENDPOINT),!e||!l?[]:[{authInfo:{type:"api-key",apiKey:e,host:l}}]}async tryLoginToken(){let e=await nPt(),l;if(e){if(l=await Ef.getToken(e.host,e.login),!l||l.trim()==="")return[]}else{if(l=await Ef.getAnyToken(),!l||l.trim()==="")return[];let n=Dqe();e={host:n,login:await Wq(n,l)}}return[{authInfo:{type:"user",host:e.host,login:e.login},token:l}]}async getAllGitHubLoginTokens(){let l=(await this.tryGitHubTokenLogin()).at(0),n=await Swe(),r=[];for(let a of n){if(l?.authInfo.type==="user"&&cO(a,l.authInfo))continue;let I=await Ef.getToken(a.host,a.login);I&&r.push({authInfo:{type:"user",host:a.host,login:a.login},token:I})}return r}async getAllAuthAvailable(){let e=[],l=this.getPrioritizedAuthMethods(!0);for(let n of l){let r=await n();e.push(...r)}return e}getPrioritizedAuthMethods(e){return[this.tryHMACLogin.bind(this),this.tryApiKeyLogin.bind(this),this.tryGitHubTokenLogin.bind(this),e?this.getAllGitHubLoginTokens.bind(this):this.tryLoginToken.bind(this),this.tryGhCliTokenLogin.bind(this)]}async loadAuthInfo(){let e=this.currentAuthInfo!==null;this.currentAuthInfo=null;let l=this.getPrioritizedAuthMethods(!1);for(let n of l){let r=await n();if(r.length>0){let{authInfo:a,token:I}=r[0];a.type==="user"&&_qe({host:a.host,login:a.login}),this.currentAuthInfo=a,e||await this.notifyAuthChange(a,I);return}}}async getCurrentAuthInfo(){return this.currentAuthInfo||await this.loadAuthInfo(),this.currentAuthInfo}async loginUser(e,l){let n={host:e,login:l},r={type:"user",...n};await IPt(n);let a=await Iy(r);await this.notifyAuthChange(r,a)}async switchToAuth(e){this.currentAuthInfo=e.authInfo,e.authInfo.type==="user"&&await _qe({host:e.authInfo.host,login:e.authInfo.login}),await this.notifyAuthChange(e.authInfo,e.token)}async logout(){if(!this.currentAuthInfo)return!1;let e=await cY(this.currentAuthInfo,{onHMACAuthInfo:async()=>!1,onEnvAuthInfo:async()=>!1,onUserAuthInfo:async l=>(await Ef.removeToken(l.host,l.login),await aPt(l)),onGhCliAuthInfo:async()=>!1,onApiKeyAuthInfo:async()=>!1});return await this.notifyAuthChange(null),e}},Bfn=new zqe,Uwe=Bfn;var Rf=class t extends HL{constructor(l,n,r,a,I){super(l,n,a,"direct");this.exec=r;this.enableAllGithubMcpTools=I??!1}static GITHUB_SERVER_NAME="github-mcp-server";static CLI_DEFAULT_GITHUB_MCP_TOOLS=["get_file_contents","search_code","search_repositories","list_branches","list_commits","get_commit","get_issue","list_issues","get_issue_comments","search_issues","pull_request_read","list_pull_requests","search_pull_requests","list_workflow_runs","get_job_logs","get_workflow_run","list_workflows","get_workflow_run_logs","web_search","search_users"];static BUILTIN_SERVERS=[t.GITHUB_SERVER_NAME];static getBuiltInServerNames(){return[...t.BUILTIN_SERVERS]}hasUserConfiguredGitHubServer=!1;lastGitHubAuthInfo=null;githubMcpToken;enableAllGithubMcpTools;async configureGitHubAuth(l){if(this.isServerDisabled(t.GITHUB_SERVER_NAME))return this.logger.debug("GitHub MCP server is disabled, skipping auto-configuration"),!1;if(this.hasUserConfiguredGitHubServer)return this.logger.debug("User has explicitly configured github-mcp-server, ignoring auth changes"),!1;if(await this.shouldHandleGitHubAuth(l)){let r=await Iy(l);if(!r)return this.logger.debug("No token available for GitHub authentication"),!1;if(this.lastGitHubAuthInfo=l,r===this.githubMcpToken)return!1;this.githubMcpToken=r;let a=await this.createGitHubServerConfig(r,l);try{return await this.restartServer(t.GITHUB_SERVER_NAME,a),this.logger.log("GitHub MCP server configured after authentication"),!0}catch(I){return this.logger.error(`Failed to configure GitHub MCP server after auth: ${I}`),!1}}return!1}async removeGitHubAuth(){if(this.hasUserConfiguredGitHubServer)return this.logger.debug("User has explicitly configured github-mcp-server, ignoring auth changes"),!1;this.githubMcpToken=void 0;try{return this.isServerRunning(t.GITHUB_SERVER_NAME)?(await this.stopServer(t.GITHUB_SERVER_NAME),this.logger.debug("Removed GitHub MCP server"),!0):!1}catch(l){return this.logger.error(`Failed to remove GitHub server: ${l}`),!1}}async shouldHandleGitHubAuth(l){return await cY(l,{onHMACAuthInfo:async()=>!!process.env.GITHUB_MCP_SERVER_TOKEN,onEnvAuthInfo:async()=>!0,onUserAuthInfo:async()=>!0,onGhCliAuthInfo:async()=>!0,onApiKeyAuthInfo:async()=>!1})}async createGitHubServerConfig(l,n){let r="https://api.githubcopilot.com/mcp/readonly";try{let a=await cY(n,{onHMACAuthInfo:async()=>"https://github.com",onEnvAuthInfo:async s=>s.host,onUserAuthInfo:async s=>s.host,onGhCliAuthInfo:async s=>s.host,onApiKeyAuthInfo:async s=>s.host}),I=await E0(a,l,this.logger);r=new URL("/mcp/readonly",I).toString()}catch(a){this.logger.error(`Failed to fetch Copilot URL, using default: ${a}`)}return{type:"http",url:r,headers:{Authorization:"Bearer "+l,"X-MCP-Toolsets":"repos,issues,users,pull_requests,code_security,secret_protection,actions,web_search","X-MCP-Host":"copilot-cli"},tools:this.enableAllGithubMcpTools?["*"]:t.CLI_DEFAULT_GITHUB_MCP_TOOLS,isDefaultServer:!0,filterMapping:{get_issue:"markdown",get_issue_comments:"markdown",get_pull_request:"markdown",get_pull_request_comments:"markdown",get_pull_request_reviews:"markdown"}}}async injectDefaultServers(l){if(l.mcpServers[t.GITHUB_SERVER_NAME]){this.hasUserConfiguredGitHubServer=!0,this.logger.debug("User has already configured github-mcp-server, skipping auto-configuration");return}}async startBuiltInServer(l){l===t.GITHUB_SERVER_NAME&&!this.hasUserConfiguredGitHubServer?this.lastGitHubAuthInfo?(this.logger.log("Attempting to configure GitHub MCP server using stored authentication"),await this.configureGitHubAuth(this.lastGitHubAuthInfo)?this.logger.log("GitHub MCP server configured successfully after enabling"):this.logger.log("GitHub MCP server enabled but could not be configured - authentication may be invalid or insufficient")):this.logger.log("GitHub MCP server enabled - will be configured automatically when authentication becomes available"):await super.startBuiltInServer(l)}};var Tfn=zl({commandHistory:Od(Qt())}),Pqe=xwe(Tfn.parse,"command-history");var Ofn=50,jqe=class{commandHistory=[];historyIndex=-1;isNavigatingHistory=!1;unSubmittedCommand=null;async initialize(){try{let e=await Pqe.load();this.commandHistory=e?.commandHistory||[],this.resetNavigation()}catch{this.commandHistory=[]}}async addCommand(e){this.commandHistory=this.commandHistory.filter(l=>l!==e),this.commandHistory.unshift(e),this.commandHistory=this.commandHistory.slice(0,Ofn),this.resetNavigation(),this.unSubmittedCommand=null,await this.saveHistory()}async updateCurrentCommand(e){this.historyIndex!==-1?(this.commandHistory[this.historyIndex]=e,await this.saveHistory()):this.unSubmittedCommand=e}navigateUp(e){if(this.commandHistory.length===0)return;let l=this.historyIndex+1;if(l<this.commandHistory.length){this.historyIndex=l,this.isNavigatingHistory=!0;let n=this.getCurrentHistoryItem();n&&e.setText(n)}}navigateDown(e){if(this.historyIndex===-1)return;if(this.historyIndex===0)this.resetNavigation();else{let n=this.historyIndex-1;this.historyIndex=n,this.isNavigatingHistory=!0}let l=this.getCurrentHistoryItem();l?(e.setText(l),e.setCursorPosition(0)):e.clear()}resetNavigation(){this.historyIndex=-1,this.isNavigatingHistory=!1}getHistoryIndex(){return this.historyIndex}getHistory(){return this.commandHistory}getCurrentHistoryItem(){return this.historyIndex===-1?this.unSubmittedCommand?this.unSubmittedCommand:void 0:this.commandHistory[this.historyIndex]}isNavigating(){return this.isNavigatingHistory}setNavigating(e){this.isNavigatingHistory=e}async saveHistory(){try{await Pqe.write({commandHistory:this.commandHistory})}catch{}}},dY=new jqe;function uPt(t,e){var l=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),l.push.apply(l,n)}return l}function mPt(t){for(var e=1;e<arguments.length;e++){var l=arguments[e]!=null?arguments[e]:{};e%2?uPt(Object(l),!0).forEach(function(n){Ufn(t,n,l[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(l)):uPt(Object(l)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(l,n))})}return t}function Ufn(t,e,l){return e=Mfn(e),e in t?Object.defineProperty(t,e,{value:l,enumerable:!0,configurable:!0,writable:!0}):t[e]=l,t}function Mfn(t){var e=_fn(t,"string");return typeof e=="symbol"?e:String(e)}function _fn(t,e){if(typeof t!="object"||t===null)return t;var l=t[Symbol.toPrimitive];if(l!==void 0){var n=l.call(t,e||"default");if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var Dfn=GPt({}),bPt=Dfn;function GPt(t){return e.withOptions=l=>GPt(mPt(mPt({},t),l)),e;function e(l,...n){let r=typeof l=="string"?[l]:l.raw,{escapeSpecialCharacters:a=Array.isArray(l),trimWhitespace:I=!0}=t,s="";for(let d=0;d<r.length;d++){let m=r[d];a&&(m=m.replace(/\\\n[ \t]*/g,"").replace(/\\`/g,"`").replace(/\\\$/g,"$").replace(/\\\{/g,"{")),s+=m,d<n.length&&(s+=n[d])}let o=s.split(`
|
|
2040
2040
|
`),c=null;for(let d of o){let m=d.match(/^(\s+)\S+/);if(m){let G=m[1].length;c?c=Math.min(c,G):c=G}}if(c!==null){let d=c;s=o.map(m=>m[0]===" "||m[0]===" "?m.slice(d):m).join(`
|
|
2041
2041
|
`)}return I&&(s=s.trim()),a&&(s=s.replace(/\\n/g,`
|
|
2042
2042
|
`)),s}}import{homedir as xjt}from"node:os";import E4n,{resolve as R4n}from"node:path";function zfn(t){return t.length>0&&/^[0-9a-zA-Z_-]+$/.test(t)}function hPt(t){return!t||t.length===0?{valid:!1,error:"MCP server name cannot be empty"}:/^[0-9a-zA-Z_-]+$/.test(t)?{valid:!0}:{valid:!1,error:"MCP server name must only contain alphanumeric characters, underscores, and hyphens"}}var pPt=G0(["none","markdown","hidden_characters"]),APt=zl({tools:Od(Qt()),type:Qt().optional(),isDefaultServer:ro().optional(),filterMapping:rY(Qt(),pPt).or(pPt).optional()}),Pfn=APt.extend({type:pr("local").optional(),command:Qt(),args:Od(Qt()),env:rY(Qt(),Qt()).optional()}),jfn=APt.extend({type:pr("http").or(pr("sse")),url:Qt(),headers:rY(Qt(),Qt()).optional()}),Kqe=zl({mcpServers:rY(Qt().min(1,"MCP server name cannot be empty").refine(zfn,{message:"MCP server name must only contain alphanumeric characters, underscores, and hyphens"}),Pfn.or(jfn))}),uY=Jwe(Kqe.parse,"mcp");function gPt(t){let e=t.r/255,l=t.g/255,n=t.b/255,r=Math.max(e,l,n),a=Math.min(e,l,n),I=r-a,s=0,o=0,c=(r+a)/2;if(I!==0){switch(o=c>.5?I/(2-r-a):I/(r+a),r){case e:s=(l-n)/I+(l<n?6:0);break;case l:s=(n-e)/I+2;break;case n:s=(e-l)/I+4;break}s/=6}return{h:s*360,s:o,l:c}}function Kfn(t){if(t.length<12||t.length>18)return null;let e=t.match(/rgb:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i);if(!e)return null;let[,l,n,r]=e,a=c=>c.length>=2?parseInt(c.substring(0,2),16):c.length===1?parseInt(c+c,16):0,I=a(l),s=a(n),o=a(r);return{r:I,g:s,b:o}}var ZPt=["#000000","#800000","#008000","#808000","#000080","#800080","#008080","#c0c0c0","#808080","#ff0000","#00ff00","#ffff00","#0000ff","#ff00ff","#00ffff","#ffffff","#000000","#00005f","#000087","#0000af","#0000d7","#0000ff","#005f00","#005f5f","#005f87","#005faf","#005fd7","#005fff","#008700","#00875f","#008787","#0087af","#0087d7","#0087ff","#00af00","#00af5f","#00af87","#00afaf","#00afd7","#00afff","#00d700","#00d75f","#00d787","#00d7af","#00d7d7","#00d7ff","#00ff00","#00ff5f","#00ff87","#00ffaf","#00ffd7","#00ffff","#5f0000","#5f005f","#5f0087","#5f00af","#5f00d7","#5f00ff","#5f5f00","#5f5f5f","#5f5f87","#5f5faf","#5f5fd7","#5f5fff","#5f8700","#5f875f","#5f8787","#5f87af","#5f87d7","#5f87ff","#5faf00","#5faf5f","#5faf87","#5fafaf","#5fafd7","#5fafff","#5fd700","#5fd75f","#5fd787","#5fd7af","#5fd7d7","#5fd7ff","#5fff00","#5fff5f","#5fff87","#5fffaf","#5fffd7","#5fffff","#870000","#87005f","#870087","#8700af","#8700d7","#8700ff","#875f00","#875f5f","#875f87","#875faf","#875fd7","#875fff","#878700","#87875f","#878787","#8787af","#8787d7","#8787ff","#87af00","#87af5f","#87af87","#87afaf","#87afd7","#87afff","#87d700","#87d75f","#87d787","#87d7af","#87d7d7","#87d7ff","#87ff00","#87ff5f","#87ff87","#87ffaf","#87ffd7","#87ffff","#af0000","#af005f","#af0087","#af00af","#af00d7","#af00ff","#af5f00","#af5f5f","#af5f87","#af5faf","#af5fd7","#af5fff","#af8700","#af875f","#af8787","#af87af","#af87d7","#af87ff","#afaf00","#afaf5f","#afaf87","#afafaf","#afafd7","#afafff","#afd700","#afd75f","#afd787","#afd7af","#afd7d7","#afd7ff","#afff00","#afff5f","#afff87","#afffaf","#afffd7","#afffff","#d70000","#d7005f","#d70087","#d700af","#d700d7","#d700ff","#d75f00","#d75f5f","#d75f87","#d75faf","#d75fd7","#d75fff","#d78700","#d7875f","#d78787","#d787af","#d787d7","#d787ff","#d7af00","#d7af5f","#d7af87","#d7afaf","#d7afd7","#d7afff","#d7d700","#d7d75f","#d7d787","#d7d7af","#d7d7d7","#d7d7ff","#d7ff00","#d7ff5f","#d7ff87","#d7ffaf","#d7ffd7","#d7ffff","#ff0000","#ff005f","#ff0087","#ff00af","#ff00d7","#ff00ff","#ff5f00","#ff5f5f","#ff5f87","#ff5faf","#ff5fd7","#ff5fff","#ff8700","#ff875f","#ff8787","#ff87af","#ff87d7","#ff87ff","#ffaf00","#ffaf5f","#ffaf87","#ffafaf","#ffafd7","#ffafff","#ffd700","#ffd75f","#ffd787","#ffd7af","#ffd7d7","#ffd7ff","#ffff00","#ffff5f","#ffff87","#ffffaf","#ffffd7","#ffffff","#080808","#121212","#1c1c1c","#262626","#303030","#3a3a3a","#444444","#4e4e4e","#585858","#626262","#6c6c6c","#767676","#808080","#8a8a8a","#949494","#9e9e9e","#a8a8a8","#b2b2b2","#bcbcbc","#c6c6c6","#d0d0d0","#dadada","#e4e4e4","#eeeeee"];function qfn(t){let e=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return e?{r:parseInt(e[1],16),g:parseInt(e[2],16),b:parseInt(e[3],16)}:{r:0,g:0,b:0}}function $fn(t){return t<0||t>=ZPt.length?{r:0,g:0,b:0}:qfn(ZPt[t])}function NPt(t){if(t.length<15||t.length>30)return null;let e=t;e.endsWith("\x07")?e=e.slice(0,-1):e.endsWith("\x1B\\")?e=e.slice(0,-2):e.endsWith("\x9C")&&(e=e.slice(0,-1));let l=e;return l.startsWith("11;")&&(l=l.substring(3)),l.startsWith("rgb:")?Kfn(l):null}async function eHn(t=100){return new Promise(e=>{if(!process.stdout.isTTY||!process.stdin.isTTY){e(null);return}let l="",n=null,r=()=>{process.stdin.removeListener("data",a),process.stdin.setRawMode(!1),n&&clearTimeout(n)},a=I=>{l+=I.toString();let s=l.match(/\x1b\]11;([^\x07\x1b\x9c]*?)(?:\x07|\x1b\\|\x9c)/);if(s){r();let c=`11;${s[1]}`;e(NPt(c));return}let o=l.match(/11;rgb:([0-9a-f/]+)(?:\x07|\x1b\\|\x9c)/i);if(o){r(),e(NPt(`11;rgb:${o[1]}`));return}};n=setTimeout(()=>{r(),e(null)},t);try{process.stdin.setRawMode(!0),process.stdin.on("data",a),process.stdout.write("\x1B]11;?\x1B\\")}catch{r(),e(null)}})}function tHn(){let t=process.env.COLORFGBG;if(!t||!t.includes(";"))return null;let e=t.split(";"),l=e[e.length-1],n=parseInt(l,10);return isNaN(n)?null:$fn(n)}async function WPt(){try{let t=await eHn();if(t)return gPt(t).l<.5;let e=tHn();return e?gPt(e).l<.5:!0}catch{return!0}}var yPt={FG:"whiteBright",ACCENT:"blue",SUCCESS:"green",DIFF_ADDED_HIGHLIGHT_FG:"black",DIFF_REMOVED_HIGHLIGHT_FG:"whiteBright",ERROR:"red",WARNING:"yellow",COPILOT:"magenta",COPILOT_BRIGHT:"magentaBright",MUTED:"white",SELECTED:"cyan",BORDER:"blackBright"},lHn={FG:"black",ACCENT:"blue",SUCCESS:"green",DIFF_ADDED_HIGHLIGHT_FG:"black",DIFF_REMOVED_HIGHLIGHT_FG:"whiteBright",ERROR:"red",WARNING:"yellow",COPILOT:"magenta",COPILOT_BRIGHT:"magentaBright",MUTED:"blackBright",SELECTED:"cyan",BORDER:"blackBright"};function qqe(t){return t==="auto"||t==="dark"||t==="light"}function Mwe(t){switch(t){case"dark":return yPt;case"light":return lHn;default:return yPt}}var _we=await WPt();async function Dwe(){let e=(await Sr.load())?.theme||"";return qqe(e)?e:"auto"}async function EPt(t){await Sr.writeKey("theme",t)}var RPt=t=>{let e=t?Sl.whiteBright:Sl.black,l=t?Sl.cyanBright:Sl.blueBright,n=t?Sl.magentaBright:Sl.magenta;return{text:e,paragraph:e,html:e,table:e,blockquote:e,heading:Sl.bold,firstHeading:Sl.whiteBright.bold,strong:Sl.bold,em:Sl.italic,del:Sl.strikethrough,hr:Sl.white,link:l,href:l,image:(r,a,I)=>n(I?`Image: ${I} \u2192 ${r}`:`Image: ${r}`),codespan:Sl.cyan,code:Sl.cyan,list:(r,a,I)=>{let s=r.replace(/^(\s*)\* /gm,"$1- ");return I&&(s=s.split(`
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@github/copilot",
|
|
3
3
|
"description": "GitHub Copilot CLI brings the power of Copilot coding agent directly to your terminal.",
|
|
4
|
-
"version": "0.0.352-
|
|
4
|
+
"version": "0.0.352-3",
|
|
5
5
|
"license": "SEE LICENSE IN LICENSE.md",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"repository": {
|
|
@@ -37,6 +37,6 @@
|
|
|
37
37
|
"worker/**/*"
|
|
38
38
|
],
|
|
39
39
|
"buildMetadata": {
|
|
40
|
-
"gitCommit": "
|
|
40
|
+
"gitCommit": "d484d2d"
|
|
41
41
|
}
|
|
42
42
|
}
|
package/sdk/index.js
CHANGED
|
@@ -606,7 +606,7 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
|
606
606
|
Body doesn't contain an array property with name: ${e}`);return I??[]}function W3I(t,e){if(!e.includes(t.status))throw ta(`Pagination failed with unexpected statusCode ${t.status}`,t)}function zX(t,e,I){return(e??I==="+")||I==="#"?_ze(t):$ze(t)}function _ze(t){return t.split(/(%[0-9A-Fa-f]{2})/g).map(e=>/%[0-9A-Fa-f]/.test(e)?e:encodeURI(e)).join("")}function $ze(t){return encodeURIComponent(t).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function Pf(t){return t!=null}function sbe(t){return[!!t&&[";","?","&"].includes(t),t&&["?","&"].includes(t)?"=":""]}function i6(t,e=!1){return e?!t||t==="+"?"":t:!t||t==="+"||t==="#"?",":t==="?"?"&":t}function N3I(t){let e=t.isFirst,{op:I,varName:l,varValue:n,reserved:c}=t,r=[],[s,a]=sbe(I);if(Array.isArray(n))for(let o of n.filter(Pf))r.push(`${i6(I,e)}`),s&&l&&(r.push(`${encodeURIComponent(l)}`),o===""?r.push(a):r.push("=")),r.push(zX(o,c,I)),e=!1;else if(typeof n=="object")for(let o of Object.keys(n)){let G=n[o];Pf(G)&&(r.push(`${i6(I,e)}`),o&&(r.push(`${encodeURIComponent(o)}`),s&&G===""?r.push(a):r.push("=")),r.push(zX(G,c,I)),e=!1)}return r.join("")}function Y3I(t){let{op:e,varName:I,varValue:l,isFirst:n,reserved:c}=t,r=[],s=i6(e,n),[a,o]=sbe(e);if(a&&I){if(r.push(zX(I,c,e)),l==="")return o||r.push(o),r.join("")?`${s}${r.join("")}`:void 0;r.push("=")}let G=[];if(Array.isArray(l))for(let i of l.filter(Pf))G.push(zX(i,c,e));else if(typeof l=="object")for(let i of Object.keys(l))Pf(l[i])&&(G.push($ze(i)),G.push(zX(l[i],c,e)));return r.push(G.join(",")),r.join(",")?`${s}${r.join("")}`:void 0}function V3I(t){let{op:e,varName:I,modifier:l,isFirst:n,reserved:c,varValue:r}=t;if(Pf(r))if(["string","number","boolean"].includes(typeof r)){let s=r.toString(),[a,o]=sbe(e),G=[i6(e,n)];return a&&I&&(G.push(I),s===""?G.push(o):G.push("=")),l&&l!=="*"&&(s=s.substring(0,parseInt(l,10))),G.push(zX(s,c,e)),G.join("")}else return l==="*"?N3I(t):Y3I(t);else return}function Gi(t,e,I){return t.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g,(l,n,c)=>{if(!n)return _ze(c);let r;["+","#",".","/",";","?","&"].includes(n[0])&&(r=n[0],n=n.slice(1));let s=n.split(/,/g),a=[];for(let o of s){let G=/([^:\*]*)(?::(\d+)|(\*))?/.exec(o);if(!G||!G[1])continue;let i=V3I({isFirst:a.length===0,op:r,varValue:e[G[1]],varName:G[1],modifier:G[2]||G[3],reserved:I?.allowReserved});i&&a.push(i)}return a.join("")})}function R3I(t,e,I={requestOptions:{}}){var l,n;let c=Gi("/secrets/restore{?api%2Dversion}",{"api%2Dversion":t.apiVersion},{allowReserved:(l=I?.requestOptions)===null||l===void 0?void 0:l.skipUrlEncoding});return t.path(c).post(Object.assign(Object.assign({},jo(I)),{contentType:"application/json",headers:Object.assign({accept:"application/json"},(n=I.requestOptions)===null||n===void 0?void 0:n.headers),body:qze(e)}))}async function y3I(t){if(!["200"].includes(t.status)){let I=ta(t);throw I.details=oi(t.body),I}return BX(t.body)}async function abe(t,e,I={requestOptions:{}}){let l=await R3I(t,e,I);return y3I(l)}function g3I(t,e,I={requestOptions:{}}){var l,n;let c=Gi("/secrets/{secret-name}/backup{?api%2Dversion}",{"secret-name":e,"api%2Dversion":t.apiVersion},{allowReserved:(l=I?.requestOptions)===null||l===void 0?void 0:l.skipUrlEncoding});return t.path(c).post(Object.assign(Object.assign({},jo(I)),{headers:Object.assign({accept:"application/json"},(n=I.requestOptions)===null||n===void 0?void 0:n.headers)}))}async function F3I(t){if(!["200"].includes(t.status)){let I=ta(t);throw I.details=oi(t.body),I}return Pze(t.body)}async function obe(t,e,I={requestOptions:{}}){let l=await g3I(t,e,I);return F3I(l)}function A3I(t,e,I={requestOptions:{}}){var l,n;let c=Gi("/deletedsecrets/{secret-name}/recover{?api%2Dversion}",{"secret-name":e,"api%2Dversion":t.apiVersion},{allowReserved:(l=I?.requestOptions)===null||l===void 0?void 0:l.skipUrlEncoding});return t.path(c).post(Object.assign(Object.assign({},jo(I)),{headers:Object.assign({accept:"application/json"},(n=I.requestOptions)===null||n===void 0?void 0:n.headers)}))}async function Q3I(t){if(!["200"].includes(t.status)){let I=ta(t);throw I.details=oi(t.body),I}return BX(t.body)}async function Gbe(t,e,I={requestOptions:{}}){let l=await A3I(t,e,I);return Q3I(l)}function w3I(t,e,I={requestOptions:{}}){var l,n;let c=Gi("/deletedsecrets/{secret-name}{?api%2Dversion}",{"secret-name":e,"api%2Dversion":t.apiVersion},{allowReserved:(l=I?.requestOptions)===null||l===void 0?void 0:l.skipUrlEncoding});return t.path(c).delete(Object.assign(Object.assign({},jo(I)),{headers:Object.assign({accept:"application/json"},(n=I.requestOptions)===null||n===void 0?void 0:n.headers)}))}async function X3I(t){if(!["204"].includes(t.status)){let I=ta(t);throw I.details=oi(t.body),I}}async function ibe(t,e,I={requestOptions:{}}){let l=await w3I(t,e,I);return X3I(l)}function E3I(t,e,I={requestOptions:{}}){var l,n;let c=Gi("/deletedsecrets/{secret-name}{?api%2Dversion}",{"secret-name":e,"api%2Dversion":t.apiVersion},{allowReserved:(l=I?.requestOptions)===null||l===void 0?void 0:l.skipUrlEncoding});return t.path(c).get(Object.assign(Object.assign({},jo(I)),{headers:Object.assign({accept:"application/json"},(n=I.requestOptions)===null||n===void 0?void 0:n.headers)}))}async function H3I(t){if(!["200"].includes(t.status)){let I=ta(t);throw I.details=oi(t.body),I}return nbe(t.body)}async function dbe(t,e,I={requestOptions:{}}){let l=await E3I(t,e,I);return H3I(l)}function v3I(t,e={requestOptions:{}}){var I,l;let n=Gi("/deletedsecrets{?api%2Dversion,maxresults}",{"api%2Dversion":t.apiVersion,maxresults:e?.maxresults},{allowReserved:(I=e?.requestOptions)===null||I===void 0?void 0:I.skipUrlEncoding});return t.path(n).get(Object.assign(Object.assign({},jo(e)),{headers:Object.assign({accept:"application/json"},(l=e.requestOptions)===null||l===void 0?void 0:l.headers)}))}async function C3I(t){if(!["200"].includes(t.status)){let I=ta(t);throw I.details=oi(t.body),I}return Kze(t.body)}function bbe(t,e={requestOptions:{}}){return G6(t,()=>v3I(t,e),C3I,["200"],{itemName:"value",nextLinkName:"nextLink"})}function J3I(t,e,I={requestOptions:{}}){var l,n;let c=Gi("/secrets/{secret-name}/versions{?api%2Dversion,maxresults}",{"secret-name":e,"api%2Dversion":t.apiVersion,maxresults:I?.maxresults},{allowReserved:(l=I?.requestOptions)===null||l===void 0?void 0:l.skipUrlEncoding});return t.path(c).get(Object.assign(Object.assign({},jo(I)),{headers:Object.assign({accept:"application/json"},(n=I.requestOptions)===null||n===void 0?void 0:n.headers)}))}async function L3I(t){if(!["200"].includes(t.status)){let I=ta(t);throw I.details=oi(t.body),I}return cbe(t.body)}function mbe(t,e,I={requestOptions:{}}){return G6(t,()=>J3I(t,e,I),L3I,["200"],{itemName:"value",nextLinkName:"nextLink"})}function f3I(t,e={requestOptions:{}}){var I,l;let n=Gi("/secrets{?api%2Dversion,maxresults}",{"api%2Dversion":t.apiVersion,maxresults:e?.maxresults},{allowReserved:(I=e?.requestOptions)===null||I===void 0?void 0:I.skipUrlEncoding});return t.path(n).get(Object.assign(Object.assign({},jo(e)),{headers:Object.assign({accept:"application/json"},(l=e.requestOptions)===null||l===void 0?void 0:l.headers)}))}async function k3I(t){if(!["200"].includes(t.status)){let I=ta(t);throw I.details=oi(t.body),I}return cbe(t.body)}function hbe(t,e={requestOptions:{}}){return G6(t,()=>f3I(t,e),k3I,["200"],{itemName:"value",nextLinkName:"nextLink"})}function x3I(t,e,I,l={requestOptions:{}}){var n,c;let r=Gi("/secrets/{secret-name}/{secret-version}{?api%2Dversion}",{"secret-name":e,"secret-version":I,"api%2Dversion":t.apiVersion},{allowReserved:(n=l?.requestOptions)===null||n===void 0?void 0:n.skipUrlEncoding});return t.path(r).get(Object.assign(Object.assign({},jo(l)),{headers:Object.assign({accept:"application/json"},(c=l.requestOptions)===null||c===void 0?void 0:c.headers)}))}async function B3I(t){if(!["200"].includes(t.status)){let I=ta(t);throw I.details=oi(t.body),I}return BX(t.body)}async function pbe(t,e,I,l={requestOptions:{}}){let n=await x3I(t,e,I,l);return B3I(n)}function z3I(t,e,I,l,n={requestOptions:{}}){var c,r;let s=Gi("/secrets/{secret-name}/{secret-version}{?api%2Dversion}",{"secret-name":e,"secret-version":I,"api%2Dversion":t.apiVersion},{allowReserved:(c=n?.requestOptions)===null||c===void 0?void 0:c.skipUrlEncoding});return t.path(s).patch(Object.assign(Object.assign({},jo(n)),{contentType:"application/json",headers:Object.assign({accept:"application/json"},(r=n.requestOptions)===null||r===void 0?void 0:r.headers),body:Dze(l)}))}async function U3I(t){if(!["200"].includes(t.status)){let I=ta(t);throw I.details=oi(t.body),I}return BX(t.body)}async function ube(t,e,I,l,n={requestOptions:{}}){let c=await z3I(t,e,I,l,n);return U3I(c)}function S3I(t,e,I={requestOptions:{}}){var l,n;let c=Gi("/secrets/{secret-name}{?api%2Dversion}",{"secret-name":e,"api%2Dversion":t.apiVersion},{allowReserved:(l=I?.requestOptions)===null||l===void 0?void 0:l.skipUrlEncoding});return t.path(c).delete(Object.assign(Object.assign({},jo(I)),{headers:Object.assign({accept:"application/json"},(n=I.requestOptions)===null||n===void 0?void 0:n.headers)}))}async function O3I(t){if(!["200"].includes(t.status)){let I=ta(t);throw I.details=oi(t.body),I}return nbe(t.body)}async function Zbe(t,e,I={requestOptions:{}}){let l=await S3I(t,e,I);return O3I(l)}function M3I(t,e,I,l={requestOptions:{}}){var n,c;let r=Gi("/secrets/{secret-name}{?api%2Dversion}",{"secret-name":e,"api%2Dversion":t.apiVersion},{allowReserved:(n=l?.requestOptions)===null||n===void 0?void 0:n.skipUrlEncoding});return t.path(r).put(Object.assign(Object.assign({},jo(l)),{contentType:"application/json",headers:Object.assign({accept:"application/json"},(c=l.requestOptions)===null||c===void 0?void 0:c.headers),body:Mze(I)}))}async function T3I(t){if(!["200"].includes(t.status)){let I=ta(t);throw I.details=oi(t.body),I}return BX(t.body)}async function Wbe(t,e,I,l={requestOptions:{}}){let n=await M3I(t,e,I,l);return T3I(n)}var qf=class{constructor(e,I,l={}){var n;let c=(n=l?.userAgentOptions)===null||n===void 0?void 0:n.userAgentPrefix,r=c?`${c} azsdk-js-client`:"azsdk-js-client";this._client=lbe(e,I,Object.assign(Object.assign({},l),{userAgentOptions:{userAgentPrefix:r}})),this.pipeline=this._client.pipeline}restoreSecret(e,I={requestOptions:{}}){return abe(this._client,e,I)}backupSecret(e,I={requestOptions:{}}){return obe(this._client,e,I)}recoverDeletedSecret(e,I={requestOptions:{}}){return Gbe(this._client,e,I)}purgeDeletedSecret(e,I={requestOptions:{}}){return ibe(this._client,e,I)}getDeletedSecret(e,I={requestOptions:{}}){return dbe(this._client,e,I)}getDeletedSecrets(e={requestOptions:{}}){return bbe(this._client,e)}getSecretVersions(e,I={requestOptions:{}}){return mbe(this._client,e,I)}getSecrets(e={requestOptions:{}}){return hbe(this._client,e)}getSecret(e,I,l={requestOptions:{}}){return pbe(this._client,e,I,l)}updateSecret(e,I,l,n={requestOptions:{}}){return ube(this._client,e,I,l,n)}deleteSecret(e,I={requestOptions:{}}){return Zbe(this._client,e,I)}setSecret(e,I,l={requestOptions:{}}){return Wbe(this._client,e,I,l)}};var j3I=["authorization","authorization_url","resource","scope","tenantId","claims","error"];function Nbe(t){let e=/,? +/,I=t.split(e).reduce((l,n)=>{if(n.match(/\w="/)){let[c,...r]=n.split("=");if(j3I.includes(c))return Object.assign(Object.assign({},l),{[c]:r.join("=").slice(1,-1)})}return l},{});if(I.authorization)try{let l=new URL(I.authorization).pathname.substring(1);l&&(I.tenantId=l)}catch{throw new Error(`The challenge authorization URI '${I.authorization}' is invalid.`)}return I}var D3I={forcedRefreshWindowInMs:1e3,retryIntervalInMs:3e3,refreshWindowInMs:1e3*60*2};async function K3I(t,e,I){async function l(){if(Date.now()<I)try{return await t()}catch{return null}else{let c=await t();if(c===null)throw new Error("Failed to refresh access token.");return c}}let n=await l();for(;n===null;)await UN(e),n=await l();return n}function eUe(t,e){let I=null,l=null,n,c=Object.assign(Object.assign({},D3I),e),r={get isRefreshing(){return I!==null},get shouldRefresh(){var a;return r.isRefreshing?!1:l?.refreshAfterTimestamp&&l.refreshAfterTimestamp<Date.now()?!0:((a=l?.expiresOnTimestamp)!==null&&a!==void 0?a:0)-c.refreshWindowInMs<Date.now()},get mustRefresh(){return l===null||l.expiresOnTimestamp-c.forcedRefreshWindowInMs<Date.now()}};function s(a,o){var G;return r.isRefreshing||(I=K3I(()=>t.getToken(a,o),c.retryIntervalInMs,(G=l?.expiresOnTimestamp)!==null&&G!==void 0?G:Date.now()).then(d=>(I=null,l=d,n=o.tenantId,l)).catch(d=>{throw I=null,l=null,n=void 0,d})),I}return async(a,o)=>{let G=!!o.claims,i=n!==o.tenantId;return G&&(l=null),i||G||r.mustRefresh?s(a,o):(r.shouldRefresh&&s(a,o),l)}}var IUe=Ms("keyvault-common");function P3I(t,e){let I;try{I=new URL(t)}catch{throw new Error(`The challenge contains invalid scope '${t}'`)}if(!new URL(e.url).hostname.endsWith(`.${I.hostname}`))throw new Error(`The challenge resource '${I.hostname}' does not match the requested domain. Set disableChallengeResourceVerification to true in your client options to disable. See https://aka.ms/azsdk/blog/vault-uri for more information.`)}var q3I="keyVaultAuthenticationPolicy";function tUe(t,e={}){let{disableChallengeResourceVerification:I}=e,l={status:"none"},n=eUe(t);function c(G){return{abortSignal:G.abortSignal,requestOptions:{timeout:G.timeout>0?G.timeout:void 0},tracingOptions:G.tracingOptions}}async function r(G){let i=c(G);switch(l.status){case"none":l={status:"started",originalBody:G.body},G.body=null;break;case"started":break;case"complete":{let d=await n(l.scopes,Object.assign(Object.assign({},i),{enableCae:!0,tenantId:l.tenantId}));d&&G.headers.set("authorization",`Bearer ${d.token}`);break}}}async function s(G,i,d){if(i.status!==401)return i;G.body===null&&l.status==="started"&&(G.body=l.originalBody);let b=c(G),m=i.headers.get("WWW-Authenticate");if(!m)return IUe.warning("keyVaultAuthentication policy encountered a 401 response without a corresponding WWW-Authenticate header. This is unexpected. Not handling the 401 response."),i;let h=Nbe(m),u=h.resource?h.resource+"/.default":h.scope;if(!u)return i;I||P3I(u,G);let Z=await n([u],Object.assign(Object.assign({},b),{enableCae:!0,tenantId:h.tenantId}));return Z?(G.headers.set("Authorization",`Bearer ${Z.token}`),l={status:"complete",scopes:[u],tenantId:h.tenantId},d(G)):i}async function a(G,i,d){if(l.status!=="complete"||i.status!==401)return i;let b=c(G),m=i.headers.get("WWW-Authenticate");if(!m)return i;let{claims:h,error:u}=Nbe(m);if(u!=="insufficient_claims"||h===void 0)return i;let Z=atob(h),N=await n(l.scopes,Object.assign(Object.assign({},b),{enableCae:!0,tenantId:l.tenantId,claims:Z}));return G.headers.set("Authorization",`Bearer ${N.token}`),d(G)}async function o(G,i){await r(G);let d=await i(G);return d=await s(G,d,i),d=await a(G,d,i),d}return{name:q3I,sendRequest:o}}function lUe(t,e){if(typeof t!="string"||!(t=t.trim()))throw new Error("Invalid collection argument");if(typeof e!="string"||!(e=e.trim()))throw new Error("Invalid identifier argument");let I;try{I=new URL(e)}catch{throw new Error(`Invalid ${t} identifier: ${e}. Not a valid URI`)}let l=(I.pathname||"").split("/");if(l.length!==3&&l.length!==4)throw new Error(`Invalid ${t} identifier: ${e}. Bad number of segments: ${l.length}`);if(t!==l[1])throw new Error(`Invalid ${t} identifier: ${e}. segment [1] should be "${t}", found "${l[1]}"`);let n=`${I.protocol}//${I.host}`,c=l[2],r=l.length===4?l[3]:void 0;return{vaultUrl:n,name:c,version:r}}function Ybe(t){let I=t.split("/")[3];return Object.assign({sourceId:t},lUe(I,t))}function za(t){let e=t,I=t,l=Ybe(e.id),n=e.attributes;delete e.attributes;let c={value:e.value,name:l.name,properties:{expiresOn:n?.expires,createdOn:n?.created,updatedOn:n?.updated,enabled:n?.enabled,notBefore:n?.notBefore,recoverableDays:n?.recoverableDays,recoveryLevel:n?.recoveryLevel,id:e.id,contentType:e.contentType,tags:e.tags,managed:e.managed,vaultUrl:l.vaultUrl,version:l.version,name:l.name,certificateKeyId:e.kid}};return I.recoveryId&&(c.properties.recoveryId=I.recoveryId,c.properties.scheduledPurgeDate=I.scheduledPurgeDate,c.properties.deletedOn=I.deletedDate,c.recoveryId=I.recoveryId,c.scheduledPurgeDate=I.scheduledPurgeDate,c.deletedOn=I.deletedDate),n&&(n.vaultUrl&&delete c.properties.vaultUrl,n.expires&&delete c.properties.expires,n.created&&delete c.properties.created,n.updated&&delete c.properties.updated),c}function d6(t,e,I){let l;return{async next(){l??(l=t(Object.assign(Object.assign({},e),{maxresults:void 0})));let n=await l.next();return Object.assign(Object.assign({},n),{value:n.value&&I(n.value)})},[Symbol.asyncIterator](){return this},byPage(n){return MN(this,arguments,function*(){var r,s,a,o;let G=t(Object.assign(Object.assign({},e),{maxresults:n?.maxPageSize})).byPage(n);try{for(var i=!0,d=Qy(G),b;b=yield Fn(d.next()),r=b.done,!r;i=!0)o=b.value,i=!1,yield yield Fn(o.map(I))}catch(m){s={error:m}}finally{try{!i&&!r&&(a=d.return)&&(yield Fn(a.call(d)))}finally{if(s)throw s.error}}})}}}var b6="4.10.0";var Do=ER({namespace:"Microsoft.KeyVault",packageName:"@azure/keyvault-secrets",packageVersion:b6});var Vbe=Ms("core-lro");var Rbe=class t extends Error{constructor(e){super(e),this.name="PollerStoppedError",Object.setPrototypeOf(this,t.prototype)}},ybe=class t extends Error{constructor(e){super(e),this.name="PollerCancelledError",Object.setPrototypeOf(this,t.prototype)}},_f=class{constructor(e){this.resolveOnUnsuccessful=!1,this.stopped=!0,this.pollProgressCallbacks=[],this.operation=e,this.promise=new Promise((I,l)=>{this.resolve=I,this.reject=l}),this.promise.catch(()=>{})}async startPolling(e={}){for(this.stopped&&(this.stopped=!1);!this.isStopped()&&!this.isDone();)await this.poll(e),await this.delay()}async pollOnce(e={}){this.isDone()||(this.operation=await this.operation.update({abortSignal:e.abortSignal,fireProgress:this.fireProgress.bind(this)})),this.processUpdatedState()}fireProgress(e){for(let I of this.pollProgressCallbacks)I(e)}async cancelOnce(e={}){this.operation=await this.operation.cancel(e)}poll(e={}){if(!this.pollOncePromise){this.pollOncePromise=this.pollOnce(e);let I=()=>{this.pollOncePromise=void 0};this.pollOncePromise.then(I,I).catch(this.reject)}return this.pollOncePromise}processUpdatedState(){if(this.operation.state.error&&(this.stopped=!0,!this.resolveOnUnsuccessful))throw this.reject(this.operation.state.error),this.operation.state.error;if(this.operation.state.isCancelled&&(this.stopped=!0,!this.resolveOnUnsuccessful)){let e=new ybe("Operation was canceled");throw this.reject(e),e}this.isDone()&&this.resolve&&this.resolve(this.getResult())}async pollUntilDone(e={}){return this.stopped&&this.startPolling(e).catch(this.reject),this.processUpdatedState(),this.promise}onProgress(e){return this.pollProgressCallbacks.push(e),()=>{this.pollProgressCallbacks=this.pollProgressCallbacks.filter(I=>I!==e)}}isDone(){let e=this.operation.state;return!!(e.isCompleted||e.isCancelled||e.error)}stopPolling(){this.stopped||(this.stopped=!0,this.reject&&this.reject(new Rbe("This poller is already stopped")))}isStopped(){return this.stopped}cancelOperation(e={}){if(!this.cancelPromise)this.cancelPromise=this.cancelOnce(e);else if(e.abortSignal)throw new Error("A cancel request is currently pending");return this.cancelPromise}getOperationState(){return this.operation.state}getResult(){return this.operation.state.result}toString(){return this.operation.toString()}};var UX=class extends _f{constructor(){super(...arguments),this.intervalInMs=2e3}async delay(){return UN(this.intervalInMs)}},SX=class{constructor(e,I={}){this.state=e,this.cancelMessage="",I.cancelMessage&&(this.cancelMessage=I.cancelMessage)}async update(){throw new Error("Operation not supported.")}async cancel(){throw new Error(this.cancelMessage)}toString(){return JSON.stringify({state:this.state})}};var m6=class extends SX{constructor(e,I,l={}){super(e,{cancelMessage:"Canceling the deletion of a secret is not supported."}),this.state=e,this.client=I,this.operationOptions=l}deleteSecret(e,I={}){return Do.withSpan("DeleteSecretPoller.deleteSecret",I,async l=>{let n=await this.client.deleteSecret(e,l);return za(n)})}getDeletedSecret(e,I={}){return Do.withSpan("DeleteSecretPoller.getDeletedSecret",I,async l=>{let n=await this.client.getDeletedSecret(e,l);return za(n)})}async update(e={}){let I=this.state,{name:l}=I;if(e.abortSignal&&(this.operationOptions.abortSignal=e.abortSignal),!I.isStarted){let n=await this.deleteSecret(l,this.operationOptions);I.isStarted=!0,I.result=n,n.properties.recoveryId||(I.isCompleted=!0)}if(!I.isCompleted)try{I.result=await this.getDeletedSecret(l,this.operationOptions),I.isCompleted=!0}catch(n){if(n.statusCode===403)I.isCompleted=!0;else if(n.statusCode!==404)throw I.error=n,I.isCompleted=!0,n}return this}};var h6=class extends UX{constructor(e){let{client:I,name:l,operationOptions:n,intervalInMs:c=2e3,resumeFrom:r}=e,s;r&&(s=JSON.parse(r).state);let a=new m6(Object.assign(Object.assign({},s),{name:l}),I,n);super(a),this.intervalInMs=c}};var p6=class extends SX{constructor(e,I,l={}){super(e,{cancelMessage:"Canceling the recovery of a deleted secret is not supported."}),this.state=e,this.client=I,this.options=l}getSecret(e,I={}){return Do.withSpan("RecoverDeletedSecretPoller.getSecret",I,async l=>{let n=await this.client.getSecret(e,I&&I.version?I.version:"",l);return za(n)})}recoverDeletedSecret(e,I={}){return Do.withSpan("RecoverDeletedSecretPoller.recoverDeletedSecret",I,async l=>{let n=await this.client.recoverDeletedSecret(e,l);return za(n)})}async update(e={}){let I=this.state,{name:l}=I;if(e.abortSignal&&(this.options.abortSignal=e.abortSignal),!I.isStarted){try{I.result=(await this.getSecret(l,this.options)).properties,I.isCompleted=!0}catch{}I.isCompleted||(I.result=(await this.recoverDeletedSecret(l,this.options)).properties,I.isStarted=!0)}if(!I.isCompleted)try{I.result=(await this.getSecret(l,this.options)).properties,I.isCompleted=!0}catch(n){if(n.statusCode===403)I.isCompleted=!0;else if(n.statusCode!==404)throw I.error=n,I.isCompleted=!0,n}return this}};var u6=class extends UX{constructor(e){let{client:I,name:l,operationOptions:n,intervalInMs:c=2e3,resumeFrom:r}=e,s;r&&(s=JSON.parse(r).state);let a=new p6(Object.assign(Object.assign({},s),{name:l}),I,n);super(a),this.intervalInMs=c}};var Z6=class{constructor(e,I,l={}){var n,c;this.vaultUrl=e;let r=Object.assign(Object.assign({},l),{userAgentOptions:{userAgentPrefix:`${(c=(n=l.userAgentOptions)===null||n===void 0?void 0:n.userAgentPrefix)!==null&&c!==void 0?c:""} azsdk-js-keyvault-secrets/${b6}`},apiVersion:l.serviceVersion||"7.6",loggingOptions:{logger:kze.info,additionalAllowedHeaderNames:["x-ms-keyvault-region","x-ms-keyvault-network-info","x-ms-keyvault-service-version"]}});this.client=new qf(this.vaultUrl,I,r),this.client.pipeline.removePolicy({name:PD}),this.client.pipeline.addPolicy(tUe(I,l),{}),this.client.pipeline.addPolicy({name:"ContentTypePolicy",sendRequest(s,a){var o;return((o=s.headers.get("Content-Type"))!==null&&o!==void 0?o:"").startsWith("application/json")&&s.headers.set("Content-Type","application/json"),a(s)}})}setSecret(e,I,l={}){let{enabled:n,notBefore:c,expiresOn:r,tags:s}=l,a=IL(l,["enabled","notBefore","expiresOn","tags"]);return Do.withSpan("SecretClient.setSecret",a,async o=>{let G=await this.client.setSecret(e,{value:I,secretAttributes:{enabled:n,notBefore:c,expires:r},tags:s},o);return za(G)})}async beginDeleteSecret(e,I={}){let l=new h6(Object.assign(Object.assign({name:e,client:this.client},I),{operationOptions:I}));return await l.poll(),l}async updateSecretProperties(e,I,l={}){let{enabled:n,notBefore:c,expiresOn:r,tags:s}=l,a=IL(l,["enabled","notBefore","expiresOn","tags"]);return Do.withSpan("SecretClient.updateSecretProperties",a,async o=>{let G=await this.client.updateSecret(e,I,{secretAttributes:{enabled:n,notBefore:c,expires:r},tags:s},o);return za(G).properties})}getSecret(e,I={}){return Do.withSpan("SecretClient.getSecret",I,async l=>{let n=await this.client.getSecret(e,I&&I.version?I.version:"",l);return za(n)})}getDeletedSecret(e,I={}){return Do.withSpan("SecretClient.getDeletedSecret",I,async l=>{let n=await this.client.getDeletedSecret(e,l);return za(n)})}purgeDeletedSecret(e,I={}){return Do.withSpan("SecretClient.purgeDeletedSecret",I,async l=>{await this.client.purgeDeletedSecret(e,l)})}async beginRecoverDeletedSecret(e,I={}){let l=new u6(Object.assign(Object.assign({name:e,client:this.client},I),{operationOptions:I}));return await l.poll(),l}backupSecret(e,I={}){return Do.withSpan("SecretClient.backupSecret",I,async l=>(await this.client.backupSecret(e,l)).value)}restoreSecretBackup(e,I={}){return Do.withSpan("SecretClient.restoreSecretBackup",I,async l=>{let n=await this.client.restoreSecret({secretBundleBackup:e},l);return za(n).properties})}listPropertiesOfSecretVersions(e,I={}){return d6(l=>this.client.getSecretVersions(e,l),I,l=>za(l).properties)}listPropertiesOfSecrets(e={}){return d6(this.client.getSecrets.bind(this.client),e,I=>za(I).properties)}listDeletedSecrets(e={}){return d6(this.client.getDeletedSecrets.bind(this.client),e,za)}};var gbe=class{client;logger;constructor(e,I){if(this.logger=I,e){this.logger.debug(`Using Azure Key Vault at ${e}`);let l=new ch;this.client=new Z6(e,l)}else this.logger.debug("No Azure Key Vault URI provided, secret provider disabled")}async getSecret(e){if(this.client)try{return(await this.client.getSecret(e)).value}catch(I){if(this.logger.warning(`Error fetching secret ${e}: ${I}`),I?.code==="SecretNotFound")return;throw I}}};function nUe(t,e){let I=t.api?.copilot?.azureKeyVaultUri;return Fbe(I,e)}function Fbe(t,e){return new gbe(t,e)}import{createHmac as lkI}from"crypto";var W6=class t{static encode(e){let I=t.hmacGetBytes(e),r=(Math.floor(Date.now()/1e3)+30).toString(),s=Buffer.from(r,"ascii"),G=lkI("sha256",I).update(s).digest().toString("hex").toUpperCase();return`${r}.${G}`}static hmacGetBytes(e){return Buffer.from(e,"ascii")}};var nkI="X-GitHub-Api-Version",ckI="2025-05-01",N6=class t extends JI{constructor(I,l,n,c){super({baseURL:I,apiKey:"",logLevel:_v()?"debug":"info"});this.headers=l;this.runnerLogger=n;this.hmacKey=c}static baseHeaders={"Content-Type":"application/json",Accept:"application/json","X-Interaction-Type":"conversation-agent","Openai-Intent":"conversation-agent","X-Initiator":"user",[nkI]:ckI};hmacKey;additionalHeaders={};static createWithOAuthToken(I,l,n,c,r,s){let a={...this.defaultHeaders(n,r),Authorization:`Bearer ${c}`,...s??{}};return I.debug(`Creating copilot-client for integration ID ${n} with token authentication. User-agent: ${a["User-Agent"]}`),new t(l,a,I)}static createWithHmac(I,l,n,c,r,s,a){let o={...this.defaultHeaders(n,r),Authorization:"",...a??{}};return s&&(o["X-GitHub-User"]=s),I.debug(`Creating copilot-client for integration ID ${n} with key authentication. User-agent: ${o["User-Agent"]}`),new t(l,o,I,c)}static defaultHeaders(I,l){let n=Ibe();return{...t.baseHeaders,"Copilot-Integration-Id":I,"User-Agent":`${n.nameNoScope}/${n.version} (${process.platform} ${process.version}) OpenAI/${Yh}`,"X-Interaction-Id":l}}async prepareOptions(I){this.hmacKey&&(this.headers["Request-HMAC"]=W6.encode(this.hmacKey)),I.headers={...this.headers,...this.additionalHeaders,...I.headers},await super.prepareOptions(I)}setInitiatorHeader(I){this.headers["X-Initiator"]=I}setAdditionalHeaders(I){this.additionalHeaders=I}async listModels(){let I={method:"get",path:""};await this.prepareOptions(I);let l={};if(I.headers)for(let[s,a]of Object.entries(I.headers))typeof a=="string"&&(l[s]=a);let n=`${this.baseURL}/models`,c=await fetch(n,{method:I.method,headers:l});if(!c.ok)return this.runnerLogger.error(`Failed to list models: ${c.status} ${c.statusText}: ${await c.text()}`),c.status===421&&this.runnerLogger.error(`Verify the authenticated user against subscription-based Copilot API endpoint used: ${this.baseURL}`),[];let r=await c.json();return this.runnerLogger.debug(`Successfully listed ${r.data.length} models`),r.data}},OX=class{async createClient(e,I,l){I.startGroup("configured settings:",8),I.debug(JSON.stringify(e,null,2)),I.endGroup(8);let n=e.api?.copilot?.token,c=e.api?.copilot?.hmacKey,r=!!(c||n);if(!r){I.debug("No Copilot HMAC key or GitHub OAuth token provided, trying secret provider");let i=nUe(e,I);try{c=await i.getSecret("capi-hmac-key")}catch(d){I.debug(`Failed to get Copilot HMAC key from secret provider:
|
|
607
607
|
${d}`)}try{n=await i.getSecret("capi-token")}catch(d){I.debug(`Failed to get Copilot GitHub OAuth token from secret provider:
|
|
608
608
|
${d}`)}r=!!(c||n)}let s,a=x2e(e),o=$v(e),G=e.api?.copilot?.sessionId??Dp(e);if(I.debug(`Using Copilot API at ${a} with integration ID ${o}`),n&&(I.debug("Using GitHub OAuth token for Copilot API"),s=N6.createWithOAuthToken(I,a,o,n,G,l?.requestHeaders)),c){I.debug("Using Copilot HMAC key for Copilot API");let i=process.env.GITHUB_USER_ID;i?I.debug(`Using user ID ${i} for Copilot HMAC key`):I.debug("No user ID provided for Copilot HMAC key"),s=N6.createWithHmac(I,a,o,c,G,i,l?.requestHeaders)}if(s===void 0)throw new Error("No GitHub OAuth token or Copilot HMAC key provided");return s}},MX=class t extends dc{request_id;constructor(e){super(e.status,e.error,e.message,e.headers),this.name="CAPIError",this.cause=e.cause,this.ghRequestId=e.headers?.get("x-github-request-id")||this.requestID,this.request_id=this.requestID}ghRequestId;static fromAPIError(e){if(!(!e||!(e instanceof dc)))return new t(e)}};var Abe={type:"ephemeral"},CY=class t{constructor(e,I,l,n){this.settings=I;this.logger=l;this.clientOptions=t.initDefaultOptions(n),l.info(" "),l.debug(`Using model: ${this.model}`),this.clientPromise=e.createClient(I,l,n),this.modelPromise=this.clientPromise.then(async()=>{let c=await this.getModel();return l.debug(`Got model info: ${JSON.stringify(c,null,2)}`),c})}clientOptions;clientPromise;modelPromise;get model(){return this.clientOptions.model}static initDefaultOptions(e){return{model:e?.model||kde.model,toolTokenBudgetProportion:e?.toolTokenBudgetProportion??.25,retryPolicy:{maxRetries:e?.retryPolicy?.maxRetries??5,errorCodesToRetry:e?.retryPolicy?.errorCodesToRetry??[],rateLimitRetryPolicy:{defaultRetryAfterSeconds:e?.retryPolicy?.rateLimitRetryPolicy?.defaultRetryAfterSeconds??5,initialRetryBackoffExtraSeconds:e?.retryPolicy?.rateLimitRetryPolicy?.initialRetryBackoffExtraSeconds??1,retryBackoffExtraGrowth:e?.retryPolicy?.rateLimitRetryPolicy?.retryBackoffExtraGrowth??2,maxRetryAfterSeconds:e?.retryPolicy?.rateLimitRetryPolicy?.maxRetryAfterSeconds??180}},thinkingMode:e?.thinkingMode??!1,requestHeaders:e?.requestHeaders??{}}}getCompletionOptions(e,I){let l={snippy:{enabled:!1}};return{temperature:0,top_p:.95,frequency_penalty:0,presence_penalty:0,tool_choice:I?.toolChoice,...l}}makeRequest(e,I,l,n,c,r,s){return e.chat.completions.create({model:I,messages:[...l],...n,tools:c},{maxRetries:r,headers:s?.requestHeaders,signal:s?.abortSignal}).withResponse()}makeRequestStreaming(e,I,l,n,c,r,s){return e.chat.completions.create({model:I,messages:[...l],...n,tools:c,stream:!0,stream_options:{include_usage:!0}},{maxRetries:r,headers:s?.requestHeaders,signal:s?.abortSignal}).withResponse()}async*getCompletionWithTools(e,I,l,n){let c=this.model,r=await this.clientPromise,s=await this.modelPromise,a=ZN(l),o=[{role:"system",content:e,copilot_cache_control:Abe},...I.map(h=>zf(h))],G=l.map((h,u)=>({type:"function",function:{name:h.name,description:h.description,parameters:h.input_schema},copilot_cache_control:u===l.length-1?Abe:void 0}));this.logger.startGroup("Completion request configuration: ",8),this.logger.debug("Client options: "),this.logger.debug(JSON.stringify(this.clientOptions,null,2)),this.logger.debug("Request options: "),this.logger.debug(JSON.stringify(n??{},null,2)),this.logger.debug("Tools: "),this.logger.debug(JSON.stringify(G,null,2)),this.logger.endGroup(8);let i=this.getCompletionOptions(l,n),d=n?.initialTurnCount!==void 0?n.initialTurnCount+1:0,b=!1,m=!1;for(;!b&&!m;){let h=Date.now();yield{kind:"turn_started",model:c,modelInfo:s,turn:d,timestampMs:h};let u=0,Z=0,N=0,g=[429,503,500,400],y=this.clientOptions.retryPolicy.maxRetries,F=this.clientOptions.retryPolicy.rateLimitRetryPolicy.initialRetryBackoffExtraSeconds,f=0,v=this.clientOptions.retryPolicy.rateLimitRetryPolicy.maxRetryAfterSeconds,X,C;try{let L=[],U;do{N>0&&(yield{kind:"turn_retry",model:c,modelInfo:s,turn:d,timestampMs:Date.now()});try{let Ie={};for(let Ae of n?.processors?.preRequest||[]){let pe=Ae.preRequest({turn:d,retry:N,messages:o,toolDefinitions:G,modelInfo:s,additionalRequestHeaders:Ie,getCompletionWithToolsOptions:n});for await(let Fe of pe)yield Fe}if(this.logger.startGroup("Sending request to the AI model",8),hl(this.settings,"copilot_swe_agent_request_logging")){let Ae=JSON.stringify(o,null,2),pe=JSON.stringify(i,null,2);this.logger.debug(`Request messages: ${Ae}`),this.logger.debug(`Request options: ${pe}`)}L=o.map((Ae,pe)=>pe===o.length-1?{...Ae,copilot_cache_control:Abe}:Ae),u=Date.now(),r.setAdditionalHeaders(Ie);let Ge;if(n?.stream){let Ae=await this.makeRequestStreaming(r,c,L,i,G,y,n);Ge=await skI(Ae,r,n)}else Ge=await this.makeRequest(r,c,L,i,G,y,n);Z=Date.now()-u,X=Ge.data,U={model:c,api_id:X.id,request_id:Ge.response.headers.get("x-github-request-id")||void 0,initiator:n?.requestHeaders?.["X-Initiator"]||Ie["X-Initiator"]};let Qe={};Ge.response.headers.forEach((Ae,pe)=>{if(pe.toLowerCase().startsWith(xde)){let Fe=cze(Ae);Fe&&(Qe[pe.replace(xde,"")]=Fe)}}),yield{kind:"model_call_success",turn:d,callId:n?.callId,modelCallDurationMs:Z,modelCall:U,responseChunk:tze(X),responseUsage:X.usage,requestMessages:JSON.stringify(L),quotaSnapshots:Qe},this.logger.debug(`response (Request-ID ${Ge.request_id}):`),this.logger.debug("data:"),this.logger.debug(JSON.stringify(Ge.data,null,2))}catch(Ie){Z=Date.now()-u;let Ge=MX.fromAPIError(Ie),Qe=Ge?.error;if(Ge){yield{kind:"model_call_failure",turn:d,callId:n?.callId,modelCallDurationMs:Z,requestMessages:JSON.stringify(L),modelCall:{model:c,status:Ge.status,error:JSON.stringify(Ge?.error||Ge?.message||"unknown error"),api_id:Ge.requestID||void 0,request_id:Ge.headers?.get("x-github-request-id")||""}},C=Ge;let pe=Ge.ghRequestId||Ge.headers?.get("x-github-request-id")||Ge.requestID;this.logger.error(`error (Request-ID ${pe})`),this.logger.error(JSON.stringify(Ge,Object.getOwnPropertyNames(Ge),2)),this.logger.debug(`Failed to get response from the AI model: ${Ge}`),Qe&&this.logger.debug(`Inner error: ${JSON.stringify(Qe,null,2)}`);let Fe;for(let _e of n?.processors?.onRequestError||[])Fe=await _e.onRequestError({turn:d,retry:N,maxRetries:y,error:Qe,modelInfo:s,getCompletionWithToolsOptions:n})||Fe;let me=Ge.status,uI=me?this.clientOptions.retryPolicy.errorCodesToRetry.some(_e=>Array.isArray(_e)?me>=_e[0]&&(_e[1]===void 0||me<=_e[1]):me===_e):!1,ve;if(Fe)ve=Fe.retryAfter;else if(Ge.status!==402){if(Ge.status===413){this.logger.debug("Request is too large, trying to remove images from the request");let _e=0;for(let Nl=o.length-1;Nl>=0;Nl--)l0(o[Nl])&&(o.splice(Nl,1),_e++,yield{kind:"images_removed",turn:d,imagesRemoved:1,largeImagesRemoved:1});_e>0?(this.logger.info(`Images have been removed from the request due to size constraints. Please resize images to be smaller than ${Um(s.capabilities.limits.vision?.max_prompt_image_size||0)}.`),this.logger.debug(`Removed ${_e} image messages from the request`),ve=1):this.logger.debug("No image messages found in the request - unsure why the request is too large - will fail")}else if((typeof Ge.status=="number"&&g.includes(Ge.status)||uI)&&(ve=parseInt(Ge.headers?.get("retry-after")||`${this.clientOptions.retryPolicy.rateLimitRetryPolicy.defaultRetryAfterSeconds}`,10)+F,F*=this.clientOptions.retryPolicy.rateLimitRetryPolicy.retryBackoffExtraGrowth,N==y-1))for(let _e=o.length-1;_e>=0;_e--)l0(o[_e])&&(this.logger.debug(`Removing image message at index ${_e} to avoid failure`),o.splice(_e,1),yield{kind:"images_removed",turn:d,imagesRemoved:1})}if(ve!==void 0&&ve<=v){let _e=.8+Math.random()*.4,Nl=ve*_e;this.logger.debug(`Retrying after ${Nl} seconds...`),await new Promise(xI=>setTimeout(xI,Nl*1e3)),f+=Nl,this.logger.debug(`Retrying after ${ve} seconds... Will try again now!`);continue}else ve?this.logger.error(`Retry after ${ve} seconds is too long. Giving up.`):this.logger.error("Retry after is not set. Giving up.")}let Ae=Ge||Ie;for(let pe of n?.processors?.onRequestError||[])await pe.preErrorThrow(Ie);throw this.logger.error("error"),this.logger.error(JSON.stringify(Ae,null,2)),Ae}finally{r.setAdditionalHeaders({}),this.logger.endGroup(8)}}while(!X&&N++<y);if(!X){this.logger.debug("Recent messages prior to failure:");for(let Ge=Math.max(0,o.length-6);Ge<o.length;Ge++)this.logger.debug(`${Ge}: ${JSON.stringify(o[Ge],null,2)}`);let Ie=new Error(`Failed to get response from the AI model; retried ${N-1} times (total retry wait time: ${f} seconds)`,{cause:C});throw this.isRateLimitExceededError(Ie)&&(this.logger.info(`Rate limit exceeded after ${N-1} retries, will fail job but skip Sentry reporting`),Ie.skipReport=!0),Ie}for(let Ie of X.choices.map(Ge=>Ge.message))rkI(Ie.tool_calls||[]),o.push(Ie),yield{kind:"message",turn:d,callId:n?.callId,modelCall:U,message:zf(mX(Ie))};if(this.isToolCallResponse(X)){let Ge=(s.capabilities.limits.max_prompt_tokens||s.capabilities.limits.max_context_window_tokens)*this.clientOptions.toolTokenBudgetProportion,Qe=dve(c,Ge,this,this.settings),pe=X.choices.filter(ve=>ve.message.tool_calls!==void 0).flatMap(ve=>ve.message.tool_calls||[]).filter(AG),Fe=new Map;for(let ve of n?.processors?.preToolsExecution||[]){let _e=await ve.preToolsExecution({turn:d,toolCalls:pe,modelInfo:s});if(_e)for(let[Nl,xI]of _e)Fe.set(Nl,xI)}let me=pe.filter(ve=>!Fe.has(ve.id)),uI=this.mergeToolResults(Fe,pe,me,a,Qe,n?.executeToolsInParallel);for await(let ve of uI){ve.toolResult.resultType==="rejected"&&(m=!0);let _e={role:"tool",tool_call_id:ve.originalCall.id,content:ve.toolResult.textResultForLlm};o.push(_e),yield{kind:"message",turn:d,callId:n?.callId,modelCall:U,message:zf(_e)},yield{kind:"tool_execution",turn:d,callId:n?.callId,toolCallId:ve.originalCall.id,toolResult:ve.toolResult,durationMs:ve.durationMs};for(let Nl of n?.processors?.postToolExecution||[])await Nl.postToolExecution({toolCall:ve.originalCall,toolResult:ve.toolResult,turn:d,modelInfo:s})}}else for(let Ie of X.choices.map(Ge=>Ge.message))yield{kind:"response",turn:d,callId:n?.callId,modelCall:{model:c,api_id:X.id},response:zf(mX(Ie))},b=!0}catch(L){let U;throw L instanceof Error&&L.cause&&L.cause instanceof MX?U=`${L} (Cause: ${L.cause})`:U=`${L}`,yield{kind:"turn_failed",model:c,modelInfo:s,turn:d,error:U,timestampMs:Date.now()},L}finally{let L=Date.now();yield{kind:"turn_ended",model:c,modelInfo:s,turn:d,timestampMs:L},d++}}}async*mergeToolResults(e,I,l,n,c,r=!1){for(let[s,a]of e){let o=I.find(G=>G.id===s);o&&(yield{durationMs:0,originalCall:o,toolResult:a})}l.length>0&&(yield*this.callTools(l,n,c,r))}async*callTools(e,I,l,n=!1){if(e.length===0)throw new Error("Tool call is missing");this.logger.debug(`Tool calls count: ${e.length}`);let c=e.some(s=>{let a=I[s.function.name];return dX(a)}),r=n&&!c;if(c&&n&&this.logger.debug("Custom agent detected in tool calls, forcing sequential execution"),r)this.logger.debug("Running tool calls in parallel"),yield*rve(e.map(s=>()=>this.callTool(s,I,l)));else{this.logger.debug("Running tool calls sequentially");for(let s of e)yield await this.callTool(s,I,l)}}async callTool(e,I,l){let n=0,c=e?.function.name;if(!c)throw new Error("Tool name is missing");let r=e?.function.arguments;if(r==null)throw new Error("Tool call arguments are missing");let s=e?.id;if(!s)throw new Error("Tool call id is missing");let a,o=I[c];try{let G=bX(r);if(!o||!o.callback)a={textResultForLlm:`Tool '${c}' does not exist. Available tools that can be called are ${Object.keys(I).join(", ")}.`,resultType:"failure",error:`Tool '${c}' does not exist.`,sessionLog:`<error>Tool '${c}' does not exist.</error>`,toolTelemetry:{}};else{let i=o.callback,d=Date.now(),b={...l,toolCallId:s,toolOptions:this.settings.service?.tools?.[c]},m=await i({...G},b);n=Date.now()-d,a=typeof m=="string"?{textResultForLlm:m,resultType:"success",toolTelemetry:{}}:m}}catch(G){G instanceof SyntaxError?(a={textResultForLlm:`The arguments for the tool call '${c}' were not valid JSON. The arguments have been cleared. Arguments: ${r}. JSON parse error: ${G.message}`,resultType:"failure",error:`${G.message}`,sessionLog:`<error>Failed to execute \`${c}\` tool with arguments: ${r} due to syntax error: ${G.message}</error>`,toolTelemetry:{properties:{wasSyntaxError:"true"}}},e.function.arguments="{}"):a={textResultForLlm:`Failed to execute \`${c}\` tool with arguments: ${r} due to error: ${G}`,resultType:"failure",error:G instanceof Error?G.message:`${G}`,sessionLog:`<error>Failed to execute \`${c}\` tool with arguments: ${r}</error>`,toolTelemetry:{}}}return{durationMs:n,originalCall:e,toolResult:a}}isToolCallResponse(e){return e.choices.find(I=>I.message.tool_calls!==void 0)!==void 0}isRateLimitExceededError(e){if(e instanceof Error){if(e.message?.includes("exceeded maximum number of retries")&&e.message?.includes("rate-limited requests"))return!0;if(e.message?.includes("Failed to get response from the AI model")&&e.cause instanceof MX)return e.cause.status===429}return!1}async getModel(){let e=this.clientOptions.model,I={id:e,name:e,capabilities:{supports:{vision:!1},limits:{max_prompt_tokens:9e4,max_context_window_tokens:128e3,vision:{max_prompt_image_size:3145728,max_prompt_images:1,supported_media_types:["image/jpeg","image/png","image/webp"]}}}};return(await(await this.clientPromise).listModels()).filter(r=>r.id===e).at(0)||I}};function rkI(t){for(let e of t)e.function.name=e.function.name.replace(/[^a-zA-Z0-9_-]+/g,"_")}async function skI(t,e,I){let l=akI(t.data,e).toReadableStream(),n=iZ.fromReadableStream(l),c=I?.processors?.onStreamingChunk;if(c?.length)for await(let r of n){I?.abortSignal?.throwIfAborted();let s={chunk:r};for(let a of c)a.onStreamingChunk(s)}return{data:await n.finalChatCompletion(),response:t.response,request_id:t.request_id}}function akI(t,e){let I=new Map;return new dd(async function*(){for await(let l of t)l.choices?.forEach(n=>{if(n.delta.role??="assistant",!!n.delta?.tool_calls?.length){n.finish_reason??="tool_calls";let r=I.get(n.index);r||(r={nextSequenceNumber:0,mappings:new Map},I.set(n.index,r)),n.delta.tool_calls?.forEach(s=>{let a=r.mappings.get(s.index);if(a!==void 0)s.id&&a.callId!==s.id&&(a.sequenceNumber=r.nextSequenceNumber++,a.callId=s.id),s.index=a.sequenceNumber;else{let o={callId:s.id,sequenceNumber:r.nextSequenceNumber++};r.mappings.set(s.index,o),s.index=o.sequenceNumber}})}}),yield l},t.controller,e)}var Y6=class extends CY{constructor(e,I,l){let n=new OX;super(n,e,I,l)}};var V6=class t{constructor(e,I,l,n){this.settings=I;this.logger=l;this.clientOptions=t.initDefaultOptions(n),this.logger.info(`Using responses with model: ${this.model}`),this.clientPromise=e.createClient(I,l,this.clientOptions)}clientOptions;clientPromise;get model(){return this.clientOptions.model}static initDefaultOptions(e){return{model:e?.model||"o4-mini",toolTokenBudgetProportion:e?.toolTokenBudgetProportion??.25,retryPolicy:{maxRetries:e?.retryPolicy?.maxRetries??5,errorCodesToRetry:e?.retryPolicy?.errorCodesToRetry??[],rateLimitRetryPolicy:{defaultRetryAfterSeconds:e?.retryPolicy?.rateLimitRetryPolicy?.defaultRetryAfterSeconds??5,initialRetryBackoffExtraSeconds:e?.retryPolicy?.rateLimitRetryPolicy?.initialRetryBackoffExtraSeconds??1,retryBackoffExtraGrowth:e?.retryPolicy?.rateLimitRetryPolicy?.retryBackoffExtraGrowth??2,maxRetryAfterSeconds:e?.retryPolicy?.rateLimitRetryPolicy?.maxRetryAfterSeconds??60}},thinkingMode:e?.thinkingMode??!0,requestHeaders:e?.requestHeaders??{}}}makeRequest(e,I,l,n,c,r,s,a){return e.responses.create({model:I,previous_response_id:r,instructions:l,input:n,parallel_tool_calls:c.length>0?!0:void 0,tools:c,reasoning:{summary:"auto",effort:"medium"},store:!1,include:["reasoning.encrypted_content"]},{maxRetries:s||this.clientOptions.retryPolicy.maxRetries,headers:a?.requestHeaders,signal:a?.abortSignal}).withResponse()}async*getCompletionWithTools(e,I,l,n){let c=await this.clientPromise,r=ZN(l),s=l.map(u=>({name:u.name,description:u.description,parameters:u.input_schema,strict:!1,type:"function"})),a=0,o=this.clientOptions.retryPolicy.maxRetries,G=this.clientOptions.retryPolicy.rateLimitRetryPolicy.initialRetryBackoffExtraSeconds,i=0,d=this.clientOptions.retryPolicy.rateLimitRetryPolicy.maxRetryAfterSeconds,b=I.flatMap(wbe),m,h=!1;for(;!h;){let u;do{u=void 0;try{let Z=await this.makeRequest(c,this.model,e,b,s,void 0,o,n);m=Z.data,b.push(...m.output),this.logger.debug(`response (Request-ID ${Z.request_id}):`),this.logger.debug("data:"),this.logger.debug(JSON.stringify(Z.data,null,2))}catch(Z){let N=Z,g=N.error;if(N){u=N,this.logger.error(`error (Request-ID ${N.requestID})`),this.logger.error(JSON.stringify(N,null,2)),this.logger.debug(`Failed to get response from the AI model: ${N}`),g&&this.logger.debug(`Inner error: ${JSON.stringify(g,null,2)}`);let y=N.status,F=y?this.clientOptions.retryPolicy.errorCodesToRetry.some(v=>Array.isArray(v)?y>=v[0]&&(v[1]===void 0||y<=v[1]):y===v):!1,f;if((N.status===429||F)&&(f=parseInt(N.headers?.get("retry-after")||`${this.clientOptions.retryPolicy.rateLimitRetryPolicy.defaultRetryAfterSeconds}`,10)+G,G*=this.clientOptions.retryPolicy.rateLimitRetryPolicy.retryBackoffExtraGrowth),f!==void 0&&f<=d){this.logger.debug(`Retrying after ${f} seconds...`),await new Promise(v=>setTimeout(v,f*1e3)),i+=f,this.logger.debug(`Retrying after ${f} seconds... Will try again now!`);continue}else f?this.logger.error(`Retry after ${f} seconds is too long. Giving up.`):this.logger.error("Retry after is not set. Giving up.")}throw this.logger.error("error"),this.logger.error(JSON.stringify(Z,null,2)),Z}finally{this.logger.endGroup(8)}}while(u&&a++<o);if(!m||u){this.logger.debug("Recent messages prior to failure:");for(let Z=Math.max(0,b.length-6);Z<b.length;Z++)this.logger.debug(`${Z}: ${JSON.stringify(b[Z],null,2)}`);throw new Error(`Failed to get response from the AI model; retried ${a-1} times (total retry wait time: ${i} seconds)`,{cause:u})}for(let Z of m.output)yield{kind:"message",message:Qbe(Z)};if(this.requiresToolOutput(m)){let N=(await this.runTool(m,r)).map(g=>({type:"function_call_output",call_id:g.toolCallId,output:g.textResultForLlm}));b.push(...N);for(let g of N)yield{kind:"message",message:Qbe(g)}}else yield{kind:"response",response:{content:m.output_text,refusal:null,role:"assistant"}},h=!0}}async runTool(e,I,l){let n=e.output.filter(r=>r.type==="function_call");if(!n||n.length===0)throw new Error("Tool calls in response are missing");let c=[];for(let r of n){let s=r.name;if(!s)throw new Error("Tool name is missing");let a=r.arguments;if(!a)throw new Error("Tool call arguments are missing");let o=r.call_id;if(!o)throw new Error("Tool call id is missing");let G,i=I[s];try{let d=bX(a);if(!i||!i.callback)G={textResultForLlm:`Tool '${s}' does not exist. Available tools that can be called are ${Object.keys(I).join(", ")}.`,resultType:"failure",error:`Tool '${s}' does not exist.`,sessionLog:`<error>Tool '${s}' does not exist.</error>`,toolTelemetry:{}};else{let b=i.callback,m={...l,toolCallId:o,toolOptions:this.settings.service?.tools?.[s],settings:this.settings},h=await b({...d},m);G=typeof h=="string"?{textResultForLlm:h,resultType:"success",toolTelemetry:{}}:h}}catch(d){G={textResultForLlm:`Failed to execute \`${s}\` tool with arguments: ${a} due to error: ${d}`,resultType:"failure",error:d instanceof Error?d.message:`${d}`,sessionLog:`<error>Failed to execute \`${s}\` tool with arguments: ${a}</error>`,toolTelemetry:{properties:{wasSyntaxError:d instanceof SyntaxError?"true":"false"}}}}c.push({toolCallId:o,textResultForLlm:G.textResultForLlm,sessionLog:G.resultType=="success"?G.sessionLog:G.error?`<error>${G.error}</error>`:void 0})}return c}requiresToolOutput(e){return e.output.filter(I=>I.type==="function_call").length>0}};function wbe(t){if(t.role==="function")throw new Error("Function role is not supported");let e=[];if(t.reasoning_opaque&&e.push({id:t.reasoning_opaque,type:"reasoning",summary:t.reasoning_text?[{text:t.reasoning_text,type:"summary_text"}]:[],encrypted_content:t.encrypted_content}),t.role==="assistant"&&t.tool_calls&&t.tool_calls.length>0&&AG(t.tool_calls[0])){let I=t.tool_calls[0];return[...e,{type:"function_call",id:t.id,name:I.function.name,arguments:I.function.arguments,call_id:I.id}]}if(t.role==="tool")return[...e,{type:"function_call_output",id:`fc_${t.tool_call_id}`,call_id:t.tool_call_id,output:typeof t.content=="string"?t.content:t.content.map(I=>I.text).join(" ")??""}];if(!t.content)return e;if(t.role==="assistant"){let I=t.id||crypto.randomUUID();return I.startsWith("msg_")||(I=`msg_${I}`),[...e,{type:"message",id:I,role:t.role,content:[{annotations:[],type:"output_text",text:typeof t.content=="string"?t.content:t.content?.map(l=>l.type==="text"?l.text:"").join(" ")??""}],status:"completed"}]}return[...e,{role:t.role,content:typeof t.content=="string"?[{type:"input_text",text:t.content}]:t.content.map(I=>{if(I.type==="text")return{type:"input_text",text:I.text};if(I.type==="image_url")return{type:"input_image",detail:I.image_url.detail||"auto",image_url:I.image_url.url}}).filter(I=>I!==void 0),type:"message"}]}function Qbe(t){if(t.type==="reasoning")return{role:"assistant",reasoning_opaque:t.id,reasoning_text:t.summary?t.summary.map(e=>e.text).join(" "):void 0,content:"",encrypted_content:t.encrypted_content};if(t.type==="function_call")return{role:"assistant",id:t.id,tool_calls:[{id:t.call_id,type:"function",function:{name:t.name,arguments:t.arguments}}],content:""};if(t.type==="function_call_output")return{role:"tool",content:t.output,tool_call_id:t.call_id};if(t.type==="message")return{id:"id"in t?t.id:void 0,role:t.role,content:typeof t.content=="string"?t.content:t.content?.map(e=>e.type==="input_text"||e.type==="output_text"?e.text:"").join(" ")??""};throw new Error(`Unknown item type: ${t.type}`)}function okI(t){let e;t.incomplete_details?.reason==="content_filter"?e="content_filter":t.incomplete_details?.reason==="max_output_tokens"?e="length":e=t.output.some(n=>n.type==="function_call")?"tool_calls":"stop";let l=t.output.filter(n=>n.type==="message"||n.type==="reasoning"||n.type==="function_call").map(n=>Qbe(n)).filter(n=>n.role==="assistant").map((n,c)=>({message:{content:Array.isArray(n.content)?n.content.map(r=>typeof r=="string"?r:"text"in r?r.text:"").join(" "):n.content||null,refusal:n.refusal||null,role:n.role||null,tool_calls:n.tool_calls?.filter(r=>r.type==="function"),reasoning_opaque:n.reasoning_opaque,reasoning_text:n.reasoning_text,encrypted_content:n.encrypted_content},index:c,finish_reason:e,logprobs:null}));return{id:t.id,choices:l,created:t.created_at,model:t.model,object:"chat.completion",usage:{completion_tokens:t.usage?.output_tokens||0,prompt_tokens:t.usage?.input_tokens||0,total_tokens:t.usage?.total_tokens||0}}}function cUe(t){return{request_id:t.request_id,data:okI(t.data),response:t.response}}var R6=class extends CY{makeResponsesRequest(e,I,l,n,c,r,s){let a=l.find(b=>b.role==="system")?.content||"",o=Array.isArray(a)?a.join(`
|
|
609
|
-
`):a,i=l.filter(b=>b.role!=="system").flatMap(wbe),d=c.filter(b=>b.type==="function").map(b=>({name:b.function.name,description:b.function.description,parameters:b.function.parameters||null,strict:!1,type:"function"}));return this.logger.debug(`Making responses request with input: ${JSON.stringify(i,null,2)}`),e.responses.create({model:I,previous_response_id:void 0,instructions:o,input:i,parallel_tool_calls:c.length>0?!0:void 0,tools:d,reasoning:{summary:"auto",effort:"medium"},store:!1,include:["reasoning.encrypted_content"]},{maxRetries:r||this.clientOptions.retryPolicy.maxRetries,headers:s?.requestHeaders,signal:s?.abortSignal}).withResponse()}makeRequest(e,I,l,n,c,r,s){return this.makeResponsesRequest(e,I,l,n,c,r,s).then(cUe)}};var y6=class extends R6{constructor(e,I,l){let n=new OX;super(n,e,I,l)}};var $f=class{constructor(e,I,l){this.settings=e;this.logger=I;this.clientOptions=l;this.chatClient=new Y6(e,I,l)}chatClient;get model(){return this.chatClient.model}async*getCompletionWithTools(e,I,l,n){let c=await this.chatClient.modelPromise;(this.clientOptions?.thinkingMode||hl(this.settings,"copilot_swe_agent_enable_responses_api"))&&c&&c.supported_endpoints?.includes("/responses")?yield*new y6(this.settings,this.logger,{model:this.chatClient.model,...this.clientOptions}).getCompletionWithTools(e,I,l,n):yield*this.chatClient.getCompletionWithTools(e,I,l,n)}};var g6=class extends CY{constructor(e,I,l,n){super(e,I,l,n)}getCompletionOptions(e,I){return{...this.model.startsWith("gpt-4")?{temperature:0,top_p:.95,frequency_penalty:0,presence_penalty:0,parallel_tool_calls:e?!1:void 0}:{},tool_choice:I?.toolChoice}}async*getCompletionWithTools(e,I,l,n){let c=await super.getCompletionWithTools(e,I,l,n);for await(let r of c)r.kind==="message"?yield{...r,message:mX({...r.message,reasoning_text:r.message?.cot_summary})}:yield r}};var F6=class extends V6{constructor(e,I,l,n){super(e,I,l,n)}};var Xbe=class extends Tf{constructor(e){super(e)}setInitiatorHeader(e){}setAdditionalHeaders(e){}listModels(){return Promise.resolve([])}},A6=class{async createClient(e,I,l){I.startGroup("configured settings:",8),I.debug(JSON.stringify(e,null,2)),I.endGroup(8);let n=e.api?.openai?.apiKey,c=e.api?.openai?.azureKeyVaultUri,r=e.api?.openai?.azureSecretName;if(!n&&c){I.debug("No API_KEY provided, trying secret provider");let G=Fbe(c,I);try{n=await G.getSecret(r||"azure-openai-api-key")}catch(i){I.debug(`Failed to get API Key from secret provider:
|
|
609
|
+
`):a,i=l.filter(b=>b.role!=="system").flatMap(wbe),d=c.filter(b=>b.type==="function").map(b=>({name:b.function.name,description:b.function.description,parameters:b.function.parameters||null,strict:!1,type:"function"}));return this.logger.debug(`Making responses request with input: ${JSON.stringify(i,null,2)}`),e.responses.create({model:I,previous_response_id:void 0,instructions:o,input:i,parallel_tool_calls:c.length>0?!0:void 0,tools:d,reasoning:{summary:"auto",effort:"medium"},store:!1,include:["reasoning.encrypted_content"]},{maxRetries:r||this.clientOptions.retryPolicy.maxRetries,headers:s?.requestHeaders,signal:s?.abortSignal}).withResponse()}makeRequest(e,I,l,n,c,r,s){return this.makeResponsesRequest(e,I,l,n,c,r,s).then(cUe)}async*getCompletionWithTools(e,I,l,n){yield*super.getCompletionWithTools(e,I,l,{...n,stream:!1})}};var y6=class extends R6{constructor(e,I,l){let n=new OX;super(n,e,I,l)}};var $f=class{constructor(e,I,l){this.settings=e;this.logger=I;this.clientOptions=l;this.chatClient=new Y6(e,I,l)}chatClient;get model(){return this.chatClient.model}async*getCompletionWithTools(e,I,l,n){let c=await this.chatClient.modelPromise;(this.clientOptions?.thinkingMode||hl(this.settings,"copilot_swe_agent_enable_responses_api"))&&c&&c.supported_endpoints?.includes("/responses")?yield*new y6(this.settings,this.logger,{model:this.chatClient.model,...this.clientOptions}).getCompletionWithTools(e,I,l,n):yield*this.chatClient.getCompletionWithTools(e,I,l,n)}};var g6=class extends CY{constructor(e,I,l,n){super(e,I,l,n)}getCompletionOptions(e,I){return{...this.model.startsWith("gpt-4")?{temperature:0,top_p:.95,frequency_penalty:0,presence_penalty:0,parallel_tool_calls:e?!1:void 0}:{},tool_choice:I?.toolChoice}}async*getCompletionWithTools(e,I,l,n){let c=await super.getCompletionWithTools(e,I,l,n);for await(let r of c)r.kind==="message"?yield{...r,message:mX({...r.message,reasoning_text:r.message?.cot_summary})}:yield r}};var F6=class extends V6{constructor(e,I,l,n){super(e,I,l,n)}};var Xbe=class extends Tf{constructor(e){super(e)}setInitiatorHeader(e){}setAdditionalHeaders(e){}listModels(){return Promise.resolve([])}},A6=class{async createClient(e,I,l){I.startGroup("configured settings:",8),I.debug(JSON.stringify(e,null,2)),I.endGroup(8);let n=e.api?.openai?.apiKey,c=e.api?.openai?.azureKeyVaultUri,r=e.api?.openai?.azureSecretName;if(!n&&c){I.debug("No API_KEY provided, trying secret provider");let G=Fbe(c,I);try{n=await G.getSecret(r||"azure-openai-api-key")}catch(i){I.debug(`Failed to get API Key from secret provider:
|
|
610
610
|
${i}`)}}let s=k2e(e);I.debug(`Using Azure Open API at ${s}`);let o={baseURL:`${new URL(s).origin}/openai`,apiVersion:e.api?.openai?.azure?.apiVersion||"2024-10-21",deployment:l?.model,defaultHeaders:l?.requestHeaders};if(n)o={...o,apiKey:n},I.debug("Using Azure OpenAI API Key");else{let G=new ch,d=EGe(G,"https://cognitiveservices.azure.com/.default");o={...o,azureADTokenProvider:d},I.debug("Using Azure Managed Identity")}return new Xbe(o)}};var Ebe=class extends JI{constructor(e){super(e)}setInitiatorHeader(e){}setAdditionalHeaders(e){}listModels(){return Promise.resolve([])}},Q6=class{async createClient(e,I,l){I.startGroup("configured settings:",8),I.debug(JSON.stringify(e,null,2)),I.endGroup(8);let n=f2e(e),c=e.api?.openai?.baseUrl,r=l?.requestHeaders;return new Ebe({baseURL:c,apiKey:n,defaultHeaders:r})}};function Hbe(t,e,I,l){switch(I){case"sweagent-aip":return new oK(t,e,l);case"sweagent-anthropic":return new EP(t,e,l);case"sweagent-capi":return new $f(t,e,l);case"sweagent-openai":return l?.thinkingMode?new F6(rUe(t),t,e,l):new g6(rUe(t),t,e,l);default:return new $f(t,e,l)}}function rUe(t){return t.api?.openai?.azure?.url?new A6:new Q6}import{randomUUID as l9I}from"crypto";import{tmpdir as n9I}from"os";import c9I from"path";var YUe=Ll(ZUe(),1);import{exec as _kI,spawn as $kI}from"child_process";function Bbe({onlyFirst:t=!1}={}){let I=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");return new RegExp(I,t?void 0:"g")}var qkI=Bbe();function zbe(t){if(typeof t!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof t}\``);return t.replace(qkI,"")}import{promisify as e9I}from"util";var Rb="___BEGIN___COMMAND_OUTPUT_MARKER___",WUe=`
|
|
611
611
|
${Rb}`,V0="___BEGIN___COMMAND_DONE_MARKER___",I9I=new RegExp(`${V0}(\\d+)`),NUe=5e3,l3=100*1024,qX=class t{constructor(e,I,l={}){this.config=e;this.createdAtMs=Date.now(),this.lastUsedAtMs=Date.now();let n=this.config.shellType==="powershell",c=n?"pwsh.exe":"bash",r=n?["-nop","-nol"]:["--norc","--noprofile"],s=n?!1:void 0;this.process=(0,YUe.spawn)(c,r,{name:"xterm-color",cols:120,rows:80,cwd:I,env:l,useConpty:s}),this.process.onData(a=>{let G=zbe(a).replaceAll("\r","");if(this.outputBuffer.length+G.length>l3){this.wasTruncated=!0;let i=this.outputBuffer.lastIndexOf(Rb);if(i!==-1){let d=this.outputBuffer.substring(0,i+Rb.length),b=this.outputBuffer.substring(i+Rb.length),m=l3-G.length-d.length;if(m>0){let h=Dn(b,"output",m,"start");this.outputBuffer=d+h}else{this.outputBuffer=d+Dn(G,"output",l3-d.length,"start");return}}else{let d=l3-G.length;if(d>0)this.outputBuffer=Dn(this.outputBuffer,"output",d,"start");else{this.outputBuffer=Dn(G,"output",l3,"start");return}}}this.outputBuffer+=G}),this.process.onExit(a=>this.shutdown())}process;outputBuffer="";isCommandInProgress=!1;wasTruncated=!1;createdAtMs;lastUsedAtMs;onPartialOutputChanged;static shellIsSupportedCache=new Map;writeDelay=Promise.resolve();static async create(e,I,l={}){await t.ensureShellIsSupported(e.shellType);let n=new t(e,I,l);return await n.initializeShellEnvironment(),n}setPartialOutputChangedCallback(e){this.onPartialOutputChanged=e}async executeCommand(e,I){if(this.updateLastUsedTime(),!this.process)throw new Error(`Failed to start ${this.config.shellType} process`);if(this.tryStartCommand(e))return await(I?this.waitForCommandCompletionOrTimeout(I):this.waitForCommandCompletion())}async cwd(){try{let e=this.config.shellType==="powershell"?"(pwd).Path":"pwd",I=await this.executeCommand(e,NUe);return I?.exitCode===0?I.output:void 0}catch{return}}async tryExecuteAsyncCommand(e){return this.updateLastUsedTime(),this.tryStartCommand(e)?(this.waitForCommandCompletion().catch(I=>{}),this.config.shellType==="powershell"&&await new Promise(I=>setTimeout(I,250)),!0):!1}async tryExecuteDetachedCommand(e,I){return this.updateLastUsedTime(),this.isCommandInProgress?!1:process.platform==="win32"?this.tryExecuteDetachedCommandWindows(e,I):this.tryExecuteDetachedCommandUnix(e,I)}async tryExecuteDetachedCommandWindows(e,I){if(!(this.config.shellType==="powershell"))throw new Error("Only PowerShell is supported for detached commands on Windows");try{let n=e.replace(/"/g,'""'),c=I.replace(/\\/g,"\\\\"),r=`Start-Process -FilePath "pwsh.exe" -ArgumentList "-NoProfile","-Command","${n} *>> '${c}' 2>&1" -WindowStyle Hidden`;return $kI("pwsh.exe",["-NoProfile","-Command",r],{stdio:"ignore",cwd:await this.cwd(),windowsHide:!0}).unref(),this.isCommandInProgress=!0,this.outputBuffer=`${Rb}
|
|
612
612
|
<command detached, output redirected to ${I}>
|