@github/copilot 0.0.368-4 → 0.0.368
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 +629 -629
- package/package.json +2 -2
- package/sdk/index.js +2 -2
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.368
|
|
4
|
+
"version": "0.0.368",
|
|
5
5
|
"license": "SEE LICENSE IN LICENSE.md",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"repository": {
|
|
@@ -39,6 +39,6 @@
|
|
|
39
39
|
"ripgrep/**/*"
|
|
40
40
|
],
|
|
41
41
|
"buildMetadata": {
|
|
42
|
-
"gitCommit": "
|
|
42
|
+
"gitCommit": "baffc7e"
|
|
43
43
|
}
|
|
44
44
|
}
|
package/sdk/index.js
CHANGED
|
@@ -1717,7 +1717,7 @@ new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
|
1717
1717
|
|
|
1718
1718
|
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
1719
1719
|
`);this.baseURL=s.baseURL,this.timeout=s.timeout??$Ue.DEFAULT_TIMEOUT,this.logger=s.logger??console;let c="warn";this.logLevel=c,this.logLevel=Yze(s.logLevel,"ClientOptions.logLevel",this)??Yze(_Z("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??c,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??Fzt(),qt(this,Npe,Qzt,"f"),this._options=s,this.apiKey=typeof I=="string"?I:"Missing Key",this.organization=l,this.project=n,this.webhookSecret=r}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:I}){}async authHeaders(e){return ht([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Wze(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${DF}`}defaultIdempotencyKey(){return`stainless-node-retry-${aze()}`}makeStatusError(e,I,l,n){return Rs.generate(e,I,l,n)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!="function")return!1;let I;try{I=await e()}catch(l){throw l instanceof ut?l:new ut(`Failed to get token from 'apiKey' function: ${l.message}`,{cause:l})}if(typeof I!="string"||!I)throw new ut(`Expected 'apiKey' function argument to return a string but it returned ${I}`);return this.apiKey=I,!0}buildURL(e,I,l){let n=!ne(this,_Ue,"m",QUt).call(this)&&l||this.baseURL,r=pzt(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();return Zzt(a)||(I={...a,...I}),typeof I=="object"&&I&&!Array.isArray(I)&&(r.search=this.stringifyQuery(I)),r.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:I,options:l}){}get(e,I){return this.methodRequest("get",e,I)}post(e,I){return this.methodRequest("post",e,I)}patch(e,I){return this.methodRequest("patch",e,I)}put(e,I){return this.methodRequest("put",e,I)}delete(e,I){return this.methodRequest("delete",e,I)}methodRequest(e,I,l){return this.request(Promise.resolve(l).then(n=>({method:e,path:I,...n})))}request(e,I=null){return new $X(this,this.makeRequest(e,I,void 0))}async makeRequest(e,I,l){let n=await e,r=n.maxRetries??this.maxRetries;I==null&&(I=r),await this.prepareOptions(n);let{req:a,url:s,timeout:c}=await this.buildRequest(n,{retryCount:r-I});await this.prepareRequest(a,{url:s,options:n});let o="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),i=l===void 0?"":`, retryOf: ${l}`,d=Date.now();if(Ps(this).debug(`[${o}] sending request`,ug({retryOfRequestLogID:l,method:n.method,url:s,options:n,headers:a.headers})),n.signal?.aborted)throw new Rc;let G=new AbortController,b=await this.fetchWithTimeout(s,a,c,G).catch(A8),u=Date.now();if(b instanceof globalThis.Error){let W=`retrying, ${I} attempts remaining`;if(n.signal?.aborted)throw new Rc;let N=R8(b)||/timed? ?out/i.test(String(b)+("cause"in b?String(b.cause):""));if(I)return Ps(this).info(`[${o}] connection ${N?"timed out":"failed"} - ${W}`),Ps(this).debug(`[${o}] connection ${N?"timed out":"failed"} (${W})`,ug({retryOfRequestLogID:l,url:s,durationMs:u-d,message:b.message})),this.retryRequest(n,I,l??o);throw Ps(this).info(`[${o}] connection ${N?"timed out":"failed"} - error; no more retries left`),Ps(this).debug(`[${o}] connection ${N?"timed out":"failed"} (error; no more retries left)`,ug({retryOfRequestLogID:l,url:s,durationMs:u-d,message:b.message})),N?new jF:new TF({cause:b})}let h=[...b.headers.entries()].filter(([W])=>W==="x-request-id").map(([W,N])=>", "+W+": "+JSON.stringify(N)).join(""),p=`[${o}${i}${h}] ${a.method} ${s} ${b.ok?"succeeded":"failed"} with status ${b.status} in ${u-d}ms`;if(!b.ok){let W=await this.shouldRetry(b);if(I&&W){let v=`retrying, ${I} attempts remaining`;return await wzt(b.body),Ps(this).info(`${p} - ${v}`),Ps(this).debug(`[${o}] response error (${v})`,ug({retryOfRequestLogID:l,url:b.url,status:b.status,headers:b.headers,durationMs:u-d})),this.retryRequest(n,I,l??o,b.headers)}let N=W?"error; no more retries left":"error; not retryable";Ps(this).info(`${p} - ${N}`);let y=await b.text().catch(v=>A8(v).message),g=Yzt(y),Q=g?void 0:y;throw Ps(this).debug(`[${o}] response error (${N})`,ug({retryOfRequestLogID:l,url:b.url,status:b.status,headers:b.headers,message:Q,durationMs:Date.now()-d})),this.makeStatusError(b.status,g,Q,b.headers)}return Ps(this).info(p),Ps(this).debug(`[${o}] response start`,ug({retryOfRequestLogID:l,url:b.url,status:b.status,headers:b.headers,durationMs:u-d})),{response:b,options:n,controller:G,requestLogID:o,retryOfRequestLogID:l,startTime:d}}getAPIList(e,I,l){return this.requestAPIList(I,{method:"get",path:e,...l})}requestAPIList(e,I){let l=this.makeRequest(I,null,void 0);return new H8(this,l,e)}async fetchWithTimeout(e,I,l,n){let{signal:r,method:a,...s}=I||{};r&&r.addEventListener("abort",()=>n.abort());let c=setTimeout(()=>n.abort(),l),o=globalThis.ReadableStream&&s.body instanceof globalThis.ReadableStream||typeof s.body=="object"&&s.body!==null&&Symbol.asyncIterator in s.body,i={signal:n.signal,...o?{duplex:"half"}:{},method:"GET",...s};a&&(i.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,i)}finally{clearTimeout(c)}}async shouldRetry(e){let I=e.headers.get("x-should-retry");return I==="true"?!0:I==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,I,l,n){let r,a=n?.get("retry-after-ms");if(a){let c=parseFloat(a);Number.isNaN(c)||(r=c)}let s=n?.get("retry-after");if(s&&!r){let c=parseFloat(s);Number.isNaN(c)?r=Date.parse(s)-Date.now():r=c*1e3}if(!(r&&0<=r&&r<60*1e3)){let c=e.maxRetries??this.maxRetries;r=this.calculateDefaultRetryTimeoutMillis(I,c)}return await D0(r),this.makeRequest(e,I-1,l)}calculateDefaultRetryTimeoutMillis(e,I){let r=I-e,a=Math.min(.5*Math.pow(2,r),8),s=1-Math.random()*.25;return a*s*1e3}async buildRequest(e,{retryCount:I=0}={}){let l={...e},{method:n,path:r,query:a,defaultBaseURL:s}=l,c=this.buildURL(r,a,s);"timeout"in l&&Nzt("timeout",l.timeout),l.timeout=l.timeout??this.timeout;let{bodyHeaders:o,body:i}=this.buildBody({options:l}),d=await this.buildHeaders({options:e,method:n,bodyHeaders:o,retryCount:I});return{req:{method:n,headers:d,...l.signal&&{signal:l.signal},...globalThis.ReadableStream&&i instanceof globalThis.ReadableStream&&{duplex:"half"},...i&&{body:i},...this.fetchOptions??{},...l.fetchOptions??{}},url:c,timeout:l.timeout}}async buildHeaders({options:e,method:I,bodyHeaders:l,retryCount:n}){let r={};this.idempotencyHeader&&I!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),r[this.idempotencyHeader]=e.idempotencyKey);let a=ht([r,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(n),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Azt(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,l,e.headers]);return this.validateHeaders(a),a.values}buildBody({options:{body:e,headers:I}}){if(!e)return{bodyHeaders:void 0,body:void 0};let l=ht([I]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&l.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:xhe(e)}:ne(this,Npe,"f").call(this,{body:e,headers:l})}};$Ue=ZI,Npe=new WeakMap,_Ue=new WeakSet,QUt=function(){return this.baseURL!=="https://api.openai.com/v1"};ZI.OpenAI=$Ue;ZI.DEFAULT_TIMEOUT=6e5;ZI.OpenAIError=ut;ZI.APIError=Rs;ZI.APIConnectionError=TF;ZI.APIConnectionTimeoutError=jF;ZI.APIUserAbortError=Rc;ZI.NotFoundError=Qx;ZI.ConflictError=Ex;ZI.RateLimitError=Xx;ZI.BadRequestError=Ax;ZI.AuthenticationError=Fx;ZI.InternalServerError=Hx;ZI.PermissionDeniedError=wx;ZI.UnprocessableEntityError=vx;ZI.InvalidWebhookSignatureError=T0;ZI.toFile=qhe;ZI.Completions=sH;ZI.Chat=qF;ZI.Embeddings=oH;ZI.Files=dH;ZI.Images=uH;ZI.Audio=q0;ZI.Moderations=pH;ZI.Models=hH;ZI.FineTuning=eW;ZI.Graders=lw;ZI.VectorStores=yg;ZI.Webhooks=ZH;ZI.Beta=$0;ZI.Batches=IH;ZI.Uploads=sw;ZI.Responses=aw;ZI.Realtime=nw;ZI.Conversations=tw;ZI.Evals=Iw;ZI.Containers=ew});var P8,Gll,EUt=m(()=>{Ac();qZ();T8();Ype();P8=class extends ZI{constructor({baseURL:e=_Z("OPENAI_BASE_URL"),apiKey:I=_Z("AZURE_OPENAI_API_KEY"),apiVersion:l=_Z("OPENAI_API_VERSION"),endpoint:n,deployment:r,azureADTokenProvider:a,dangerouslyAllowBrowser:s,...c}={}){if(!l)throw new ut("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).");if(typeof a=="function"&&(s=!0),!a&&!I)throw new ut("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(a&&I)throw new ut("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(c.defaultQuery={...c.defaultQuery,"api-version":l},e){if(n)throw new ut("baseURL and endpoint are mutually exclusive")}else{if(n||(n=process.env.AZURE_OPENAI_ENDPOINT),!n)throw new ut("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");e=`${n}/openai`}super({apiKey:a??I,baseURL:e,...c,...s!==void 0?{dangerouslyAllowBrowser:s}:{}}),this.apiVersion="",this.apiVersion=l,this.deploymentName=r}async buildRequest(e,I={}){if(Gll.has(e.path)&&e.method==="post"&&e.body!==void 0){if(!Jx(e.body))throw new Error("Expected request body to be an object");let l=this.deploymentName||e.body.model||e.__metadata?.model;l!==void 0&&!this.baseURL.includes("/deployments")&&(e.path=`/deployments/${l}${e.path}`)}return super.buildRequest(e,I)}async authHeaders(e){return typeof this._options.apiKey=="string"?ht([{"api-key":this.apiKey}]):super.authHeaders(e)}},Gll=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"])});var q8=m(()=>{Ype();Eze();Dhe();Ype();Ya();j0();EUt()});var vUt=m(()=>{_ze()});var bll,XUt,HUt=m(()=>{bll=[Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError,globalThis.DOMException,globalThis.AssertionError,globalThis.SystemError].filter(Boolean).map(t=>[t.name,t]),XUt=new Map(bll)});function _8(t,e={}){let{maxDepth:I=Number.POSITIVE_INFINITY,useToJSON:l=!0}=e;return typeof t=="object"&&t!==null?fUt({from:t,seen:[],forceEnumerable:!0,maxDepth:I,depth:0,useToJSON:l,serialize:!0}):typeof t=="function"?`[Function: ${t.name||"anonymous"}]`:t}function CUt(t){return!!t&&typeof t=="object"&&typeof t.name=="string"&&typeof t.message=="string"&&typeof t.stack=="string"}var mll,eOe,ull,hll,fUt,JUt=m(()=>{HUt();mll=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1},{property:"errors",enumerable:!1}],eOe=new WeakSet,ull=t=>{eOe.add(t);let e=t.toJSON();return eOe.delete(t),e},hll=t=>{let e=XUt.get(t)??Error;return e===AggregateError?new e([]):new e},fUt=({from:t,seen:e,to:I,forceEnumerable:l,maxDepth:n,depth:r,useToJSON:a,serialize:s})=>{if(I||(Array.isArray(t)?I=[]:!s&&CUt(t)?I=hll(t.name):I={}),e.push(t),r>=n)return I;if(a&&typeof t.toJSON=="function"&&!eOe.has(t))return ull(t);let c=o=>fUt({from:o,seen:[...e],forceEnumerable:l,maxDepth:n,depth:r,useToJSON:a,serialize:s});for(let[o,i]of Object.entries(t)){if(i&&i instanceof Uint8Array&&i.constructor.name==="Buffer"){I[o]="[object Buffer]";continue}if(i!==null&&typeof i=="object"&&typeof i.pipe=="function"){I[o]="[object Stream]";continue}if(typeof i!="function"){if(!i||typeof i!="object"){try{I[o]=i}catch{}continue}if(!e.includes(t[o])){r++,I[o]=c(t[o]);continue}I[o]="[Circular]"}}if(s||I instanceof Error)for(let{property:o,enumerable:i}of mll)t[o]!==void 0&&t[o]!==null&&Object.defineProperty(I,o,{value:CUt(t[o])||Array.isArray(t[o])?c(t[o]):t[o],enumerable:l?!0:i,configurable:!0,writable:!0});return I}});function cw(t){return t?.description?.startsWith(tOe)??!1}var tOe,$8=m(()=>{"use strict";tOe="Custom agent:"});function kUt(t){return{agent:t,model:gpe[t]}}var gpe,ype,LUt,IOe=m(()=>{"use strict";gpe={"sweagent-capi":"claude-sonnet-4.5","sweagent-aip":"swe-mini2-genai-v2","sweagent-anthropic":"claude-sonnet-4-5-20250929","sweagent-openai":"gpt-5"},ype="sweagent-capi",LUt={agent:ype,model:gpe[ype]}});function xUt(t){if(t)try{let e=new URLSearchParams(t),I=parseInt(e.get("ent")||"0",10),l=parseFloat(e.get("ov")||"0.0"),n=e.get("ovPerm")==="true",r=parseFloat(e.get("rem")||"0.0"),a=e.get("rst"),s;a?s=new Date(a):(s=new Date,s.setMonth(s.getMonth()+1));let c=Math.round(Math.max(0,I*(1-r/100)));return isNaN(I)||isNaN(l)||isNaN(r)?void 0:{isUnlimitedEntitlement:I===-1,entitlementRequests:I,usedRequests:c,usageAllowedWithExhaustedQuota:n,overage:l,overageAllowedWithExhaustedQuota:n,remainingPercentage:r,resetDate:s}}catch{return}}var lOe,BUt=m(()=>{"use strict";lOe="x-quota-snapshot-"});var SUt,zUt=m(()=>{JZ();SUt=Gd("keyvault-secrets")});var UUt,OUt=m(()=>{JZ();UUt=Gd("keyvault-secrets")});function gd(t,e){return typeof t=="string"?kme(t,e):kme(t)}var MUt=m(()=>{zy()});var TUt=m(()=>{});function nOe(t){return FP(t,["key"])&&typeof t.key=="string"}var jUt=m(()=>{md()});var DUt=m(()=>{md()});var KUt=m(()=>{md()});function e7(t){let e=t;return e&&typeof e.getToken=="function"&&(e.signRequest===void 0||e.getToken.length>0)}var PUt=m(()=>{});var rOe=m(()=>{TUt();jUt();DUt();KUt();PUt()});function qUt(t){return{name:pll,sendRequest:(e,I)=>{let l=new URL(e.url);return!l.searchParams.get("api-version")&&t.apiVersion&&(e.url=`${e.url}${Array.from(l.searchParams.keys()).length>0?"&":"?"}api-version=${t.apiVersion}`),I(e)}}}var pll,_Ut=m(()=>{pll="ApiVersionPolicy"});function $Ut(t,e){return{name:Zll,async sendRequest(I,l){return I.headers.set(e,t.key),l(I)}}}var Zll,eOt=m(()=>{Zll="keyCredentialAuthenticationPolicy"});function tOt(t,e,I={}){var l,n,r,a;let{credential:s,clientOptions:c}=I;if(s){if(e7(s)){let o=wX({credential:s,scopes:(n=(l=c?.credentials)===null||l===void 0?void 0:l.scopes)!==null&&n!==void 0?n:`${e}/.default`});t.addPolicy(o)}else if(Wll(s)){if(!(!((r=c?.credentials)===null||r===void 0)&&r.apiKeyHeaderName))throw new Error("Missing API Key Header Name");let o=$Ut(s,(a=c?.credentials)===null||a===void 0?void 0:a.apiKeyHeaderName);t.addPolicy(o)}}}function IOt(t,e,I={}){let l=Iq(I);return l.addPolicy(qUt(I)),tOt(l,t,{credential:e,clientOptions:I}),l}function Wll(t){return t.key!==void 0}var aOe=m(()=>{su();rOe();_Ut();eOt()});function em(t){return fxe(t)}var lOt=m(()=>{zy()});function ow(t){return t.onResponse?Object.assign(Object.assign({},t),{onResponse(e,I){var l;(l=t.onResponse)===null||l===void 0||l.call(t,e,I,I)}}):t}function nOt(t,e,I={}){let l;e&&(Nll(e)?l=e:I=e??{});let n=IOt(t,l,I),r=Cxe(t,Object.assign(Object.assign({},I),{pipeline:n})),a=(s,...c)=>({get:(o={})=>r.path(s,...c).get(ow(o)),post:(o={})=>r.path(s,...c).post(ow(o)),put:(o={})=>r.path(s,...c).put(ow(o)),patch:(o={})=>r.path(s,...c).patch(ow(o)),delete:(o={})=>r.path(s,...c).delete(ow(o)),head:(o={})=>r.path(s,...c).head(ow(o)),options:(o={})=>r.path(s,...c).options(ow(o)),trace:(o={})=>r.path(s,...c).trace(ow(o))});return{path:a,pathUnchecked:a,pipeline:r.pipeline}}function Nll(t){return nOe(t)||e7(t)}var rOt=m(()=>{rOe();aOe();zy()});var aOt=m(()=>{});var Vpe=m(()=>{MUt();aOe();lOt();rOt();aOt()});function sOe(t,e,I={}){var l,n,r,a,s,c,o,i;let d=(n=(l=I.endpoint)!==null&&l!==void 0?l:I.baseUrl)!==null&&n!==void 0?n:String(t),G=(r=I?.userAgentOptions)===null||r===void 0?void 0:r.userAgentPrefix,b="azsdk-js-keyvault-secrets/1.0.0-beta.1",u=G?`${G} azsdk-js-api ${b}`:`azsdk-js-api ${b}`,h=Object.assign(Object.assign({},I),{userAgentOptions:{userAgentPrefix:u},loggingOptions:{logger:(s=(a=I.loggingOptions)===null||a===void 0?void 0:a.logger)!==null&&s!==void 0?s:UUt.info},credentials:{scopes:(o=(c=I.credentials)===null||c===void 0?void 0:c.scopes)!==null&&o!==void 0?o:["https://vault.azure.net/.default"]}}),{apiVersion:p}=h,W=PP(h,["apiVersion"]),N=nOt(d,e,W);N.pipeline.removePolicy({name:"ApiVersionPolicy"});let y=(i=I.apiVersion)!==null&&i!==void 0?i:"7.6";return N.pipeline.addPolicy({name:"ClientApiVersionPolicy",sendRequest:(g,Q)=>{let f=new URL(g.url);return f.searchParams.get("api-version")||(g.url=`${g.url}${Array.from(f.searchParams.keys()).length>0?"&":"?"}api-version=${y}`),Q(g)}}),Object.assign(Object.assign({},N),{apiVersion:y})}var sOt=m(()=>{Kk();OUt();Vpe()});function cOt(t){return{value:t.value,tags:t.tags,contentType:t.contentType,attributes:t.secretAttributes?oOt(t.secretAttributes):t.secretAttributes}}function oOt(t){return{enabled:t.enabled,nbf:t.notBefore?t.notBefore.getTime()/1e3|0:t.notBefore,exp:t.expires?t.expires.getTime()/1e3|0:t.expires}}function Ape(t){return{enabled:t.enabled,notBefore:t.nbf?new Date(t.nbf*1e3):t.nbf,expires:t.exp?new Date(t.exp*1e3):t.exp,created:t.created?new Date(t.created*1e3):t.created,updated:t.updated?new Date(t.updated*1e3):t.updated,recoverableDays:t.recoverableDays,recoveryLevel:t.recoveryLevel}}function m9(t){return{value:t.value,id:t.id,contentType:t.contentType,attributes:t.attributes?Ape(t.attributes):t.attributes,tags:t.tags,kid:t.kid,managed:t.managed}}function Zu(t){return{error:t.error?iOt(t.error):t.error}}function iOt(t){return{code:t.code,message:t.message,innerError:t.innererror?iOt(t.innererror):t.innererror}}function cOe(t){return{value:t.value,id:t.id,contentType:t.contentType,attributes:t.attributes?Ape(t.attributes):t.attributes,tags:t.tags,kid:t.kid,managed:t.managed,recoveryId:t.recoveryId,scheduledPurgeDate:t.scheduledPurgeDate?new Date(t.scheduledPurgeDate*1e3):t.scheduledPurgeDate,deletedDate:t.deletedDate?new Date(t.deletedDate*1e3):t.deletedDate}}function dOt(t){return{contentType:t.contentType,attributes:t.secretAttributes?oOt(t.secretAttributes):t.secretAttributes,tags:t.tags}}function oOe(t){return{value:t.value?Yll(t.value):t.value,nextLink:t.nextLink}}function Yll(t){return t.map(e=>yll(e))}function yll(t){return{id:t.id,attributes:t.attributes?Ape(t.attributes):t.attributes,tags:t.tags,contentType:t.contentType,managed:t.managed}}function GOt(t){return{value:t.value?gll(t.value):t.value,nextLink:t.nextLink}}function gll(t){return t.map(e=>Vll(e))}function Vll(t){return{id:t.id,attributes:t.attributes?Ape(t.attributes):t.attributes,tags:t.tags,contentType:t.contentType,managed:t.managed,recoveryId:t.recoveryId,scheduledPurgeDate:t.scheduledPurgeDate?new Date(t.scheduledPurgeDate*1e3):t.scheduledPurgeDate,deletedDate:t.deletedDate?new Date(t.deletedDate*1e3):t.deletedDate}}function bOt(t){return{value:t.value&&typeof t.value=="string"?E4t(t.value,"base64url"):t.value}}function mOt(t){return{value:Q4t(t.secretBundleBackup,"base64url")}}var t7,Rpe,iOe=m(()=>{md();(function(t){t.Purgeable="Purgeable",t.RecoverablePurgeable="Recoverable+Purgeable",t.Recoverable="Recoverable",t.RecoverableProtectedSubscription="Recoverable+ProtectedSubscription",t.CustomizedRecoverablePurgeable="CustomizedRecoverable+Purgeable",t.CustomizedRecoverable="CustomizedRecoverable",t.CustomizedRecoverableProtectedSubscription="CustomizedRecoverable+ProtectedSubscription"})(t7||(t7={}));(function(t){t.V75="7.5",t.V76Preview2="7.6-preview.2",t.V76="7.6"})(Rpe||(Rpe={}))});function Fpe(t,e,I,l,n={}){var r,a;let s=(r=n.itemName)!==null&&r!==void 0?r:"value",c=(a=n.nextLinkName)!==null&&a!==void 0?a:"nextLink",o={getPage:async i=>{let d=i===void 0?await e():await t.pathUnchecked(i).get();Qll(d,l);let G=await I(d),b=Fll(G,c);return{page:wll(G,s),nextPageLink:b}},byPage:i=>{let{continuationToken:d}=i??{};return dOe(o,{pageLink:d})}};return Rll(o)}function Rll(t){var e;let I=All(t);return{next(){return I.next()},[Symbol.asyncIterator](){return this},byPage:(e=t?.byPage)!==null&&e!==void 0?e:(l=>{let{continuationToken:n}=l??{};return dOe(t,{pageLink:n})})}}function All(t){return ZF(this,arguments,function*(){var I,l,n,r;let a=dOe(t);try{for(var s=!0,c=FX(a),o;o=yield Wa(c.next()),I=o.done,!I;s=!0)r=o.value,s=!1,yield Wa(yield*Q3t(FX(r)))}catch(i){l={error:i}}finally{try{!s&&!I&&(n=c.return)&&(yield Wa(n.call(c)))}finally{if(l)throw l.error}}})}function dOe(t){return ZF(this,arguments,function*(I,l={}){let{pageLink:n}=l,r=yield Wa(I.getPage(n??I.firstPageLink));if(!r)return yield Wa(void 0);let a=r.page;for(a.continuationToken=r.nextPageLink,yield yield Wa(a);r.nextPageLink;){if(r=yield Wa(I.getPage(r.nextPageLink)),!r)return yield Wa(void 0);a=r.page,a.continuationToken=r.nextPageLink,yield yield Wa(a)}})}function Fll(t,e){if(!e)return;let I=t[e];if(typeof I!="string"&&typeof I<"u"&&I!==null)throw new Uy(`Body Property ${e} should be a string or undefined or null but got ${typeof I}`);if(I!==null)return I}function wll(t,e){let I=t[e];if(!Array.isArray(I))throw new Uy(`Couldn't paginate response
|
|
1720
|
-
Body doesn't contain an array property with name: ${e}`);return I??[]}function Qll(t,e){if(!e.includes(t.status))throw gd(`Pagination failed with unexpected statusCode ${t.status}`,t)}var uOt=m(()=>{Kk();Vpe();su()});function u9(t,e,I){return(e??I==="+")||I==="#"?hOt(t):pOt(t)}function hOt(t){return t.split(/(%[0-9A-Fa-f]{2})/g).map(e=>/%[0-9A-Fa-f]/.test(e)?e:encodeURI(e)).join("")}function pOt(t){return encodeURIComponent(t).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function I7(t){return t!=null}function GOe(t){return[!!t&&[";","?","&"].includes(t),t&&["?","&"].includes(t)?"=":""]}function wpe(t,e=!1){return e?!t||t==="+"?"":t:!t||t==="+"||t==="#"?",":t==="?"?"&":t}function Ell(t){let e=t.isFirst,{op:I,varName:l,varValue:n,reserved:r}=t,a=[],[s,c]=GOe(I);if(Array.isArray(n))for(let o of n.filter(I7))a.push(`${wpe(I,e)}`),s&&l&&(a.push(`${encodeURIComponent(l)}`),o===""?a.push(c):a.push("=")),a.push(u9(o,r,I)),e=!1;else if(typeof n=="object")for(let o of Object.keys(n)){let i=n[o];I7(i)&&(a.push(`${wpe(I,e)}`),o&&(a.push(`${encodeURIComponent(o)}`),s&&i===""?a.push(c):a.push("=")),a.push(u9(i,r,I)),e=!1)}return a.join("")}function vll(t){let{op:e,varName:I,varValue:l,isFirst:n,reserved:r}=t,a=[],s=wpe(e,n),[c,o]=GOe(e);if(c&&I){if(a.push(u9(I,r,e)),l==="")return o||a.push(o),a.join("")?`${s}${a.join("")}`:void 0;a.push("=")}let i=[];if(Array.isArray(l))for(let d of l.filter(I7))i.push(u9(d,r,e));else if(typeof l=="object")for(let d of Object.keys(l))I7(l[d])&&(i.push(pOt(d)),i.push(u9(l[d],r,e)));return a.push(i.join(",")),a.join(",")?`${s}${a.join("")}`:void 0}function Xll(t){let{op:e,varName:I,modifier:l,isFirst:n,reserved:r,varValue:a}=t;if(I7(a))if(["string","number","boolean"].includes(typeof a)){let s=a.toString(),[c,o]=GOe(e),i=[wpe(e,n)];return c&&I&&(i.push(I),s===""?i.push(o):i.push("=")),l&&l!=="*"&&(s=s.substring(0,parseInt(l,10))),i.push(u9(s,r,e)),i.join("")}else return l==="*"?Ell(t):vll(t);else return}function Wu(t,e,I){return t.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g,(l,n,r)=>{if(!n)return hOt(r);let a;["+","#",".","/",";","?","&"].includes(n[0])&&(a=n[0],n=n.slice(1));let s=n.split(/,/g),c=[];for(let o of s){let i=/([^:\*]*)(?::(\d+)|(\*))?/.exec(o);if(!i||!i[1])continue;let d=Xll({isFirst:c.length===0,op:a,varValue:e[i[1]],varName:i[1],modifier:i[2]||i[3],reserved:I?.allowReserved});d&&c.push(d)}return c.join("")})}var ZOt=m(()=>{});function Hll(t,e,I={requestOptions:{}}){var l,n;let r=Wu("/secrets/restore{?api%2Dversion}",{"api%2Dversion":t.apiVersion},{allowReserved:(l=I?.requestOptions)===null||l===void 0?void 0:l.skipUrlEncoding});return t.path(r).post(Object.assign(Object.assign({},em(I)),{contentType:"application/json",headers:Object.assign({accept:"application/json"},(n=I.requestOptions)===null||n===void 0?void 0:n.headers),body:mOt(e)}))}async function Cll(t){if(!["200"].includes(t.status)){let I=gd(t);throw I.details=Zu(t.body),I}return m9(t.body)}async function bOe(t,e,I={requestOptions:{}}){let l=await Hll(t,e,I);return Cll(l)}function fll(t,e,I={requestOptions:{}}){var l,n;let r=Wu("/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(r).post(Object.assign(Object.assign({},em(I)),{headers:Object.assign({accept:"application/json"},(n=I.requestOptions)===null||n===void 0?void 0:n.headers)}))}async function Jll(t){if(!["200"].includes(t.status)){let I=gd(t);throw I.details=Zu(t.body),I}return bOt(t.body)}async function mOe(t,e,I={requestOptions:{}}){let l=await fll(t,e,I);return Jll(l)}function Lll(t,e,I={requestOptions:{}}){var l,n;let r=Wu("/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(r).post(Object.assign(Object.assign({},em(I)),{headers:Object.assign({accept:"application/json"},(n=I.requestOptions)===null||n===void 0?void 0:n.headers)}))}async function kll(t){if(!["200"].includes(t.status)){let I=gd(t);throw I.details=Zu(t.body),I}return m9(t.body)}async function uOe(t,e,I={requestOptions:{}}){let l=await Lll(t,e,I);return kll(l)}function xll(t,e,I={requestOptions:{}}){var l,n;let r=Wu("/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(r).delete(Object.assign(Object.assign({},em(I)),{headers:Object.assign({accept:"application/json"},(n=I.requestOptions)===null||n===void 0?void 0:n.headers)}))}async function Bll(t){if(!["204"].includes(t.status)){let I=gd(t);throw I.details=Zu(t.body),I}}async function hOe(t,e,I={requestOptions:{}}){let l=await xll(t,e,I);return Bll(l)}function Sll(t,e,I={requestOptions:{}}){var l,n;let r=Wu("/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(r).get(Object.assign(Object.assign({},em(I)),{headers:Object.assign({accept:"application/json"},(n=I.requestOptions)===null||n===void 0?void 0:n.headers)}))}async function zll(t){if(!["200"].includes(t.status)){let I=gd(t);throw I.details=Zu(t.body),I}return cOe(t.body)}async function pOe(t,e,I={requestOptions:{}}){let l=await Sll(t,e,I);return zll(l)}function Ull(t,e={requestOptions:{}}){var I,l;let n=Wu("/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({},em(e)),{headers:Object.assign({accept:"application/json"},(l=e.requestOptions)===null||l===void 0?void 0:l.headers)}))}async function Oll(t){if(!["200"].includes(t.status)){let I=gd(t);throw I.details=Zu(t.body),I}return GOt(t.body)}function ZOe(t,e={requestOptions:{}}){return Fpe(t,()=>Ull(t,e),Oll,["200"],{itemName:"value",nextLinkName:"nextLink"})}function Mll(t,e,I={requestOptions:{}}){var l,n;let r=Wu("/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(r).get(Object.assign(Object.assign({},em(I)),{headers:Object.assign({accept:"application/json"},(n=I.requestOptions)===null||n===void 0?void 0:n.headers)}))}async function Tll(t){if(!["200"].includes(t.status)){let I=gd(t);throw I.details=Zu(t.body),I}return oOe(t.body)}function WOe(t,e,I={requestOptions:{}}){return Fpe(t,()=>Mll(t,e,I),Tll,["200"],{itemName:"value",nextLinkName:"nextLink"})}function jll(t,e={requestOptions:{}}){var I,l;let n=Wu("/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({},em(e)),{headers:Object.assign({accept:"application/json"},(l=e.requestOptions)===null||l===void 0?void 0:l.headers)}))}async function Dll(t){if(!["200"].includes(t.status)){let I=gd(t);throw I.details=Zu(t.body),I}return oOe(t.body)}function NOe(t,e={requestOptions:{}}){return Fpe(t,()=>jll(t,e),Dll,["200"],{itemName:"value",nextLinkName:"nextLink"})}function Kll(t,e,I,l={requestOptions:{}}){var n,r;let a=Wu("/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(a).get(Object.assign(Object.assign({},em(l)),{headers:Object.assign({accept:"application/json"},(r=l.requestOptions)===null||r===void 0?void 0:r.headers)}))}async function Pll(t){if(!["200"].includes(t.status)){let I=gd(t);throw I.details=Zu(t.body),I}return m9(t.body)}async function YOe(t,e,I,l={requestOptions:{}}){let n=await Kll(t,e,I,l);return Pll(n)}function qll(t,e,I,l,n={requestOptions:{}}){var r,a;let s=Wu("/secrets/{secret-name}/{secret-version}{?api%2Dversion}",{"secret-name":e,"secret-version":I,"api%2Dversion":t.apiVersion},{allowReserved:(r=n?.requestOptions)===null||r===void 0?void 0:r.skipUrlEncoding});return t.path(s).patch(Object.assign(Object.assign({},em(n)),{contentType:"application/json",headers:Object.assign({accept:"application/json"},(a=n.requestOptions)===null||a===void 0?void 0:a.headers),body:dOt(l)}))}async function _ll(t){if(!["200"].includes(t.status)){let I=gd(t);throw I.details=Zu(t.body),I}return m9(t.body)}async function yOe(t,e,I,l,n={requestOptions:{}}){let r=await qll(t,e,I,l,n);return _ll(r)}function $ll(t,e,I={requestOptions:{}}){var l,n;let r=Wu("/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(r).delete(Object.assign(Object.assign({},em(I)),{headers:Object.assign({accept:"application/json"},(n=I.requestOptions)===null||n===void 0?void 0:n.headers)}))}async function enl(t){if(!["200"].includes(t.status)){let I=gd(t);throw I.details=Zu(t.body),I}return cOe(t.body)}async function gOe(t,e,I={requestOptions:{}}){let l=await $ll(t,e,I);return enl(l)}function tnl(t,e,I,l={requestOptions:{}}){var n,r;let a=Wu("/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).put(Object.assign(Object.assign({},em(l)),{contentType:"application/json",headers:Object.assign({accept:"application/json"},(r=l.requestOptions)===null||r===void 0?void 0:r.headers),body:cOt(I)}))}async function Inl(t){if(!["200"].includes(t.status)){let I=gd(t);throw I.details=Zu(t.body),I}return m9(t.body)}async function VOe(t,e,I,l={requestOptions:{}}){let n=await tnl(t,e,I,l);return Inl(n)}var ROe=m(()=>{iOe();uOt();ZOt();Vpe()});var WOt=m(()=>{sOt();ROe()});var l7,AOe=m(()=>{WOt();ROe();l7=class{constructor(e,I,l={}){var n;let r=(n=l?.userAgentOptions)===null||n===void 0?void 0:n.userAgentPrefix,a=r?`${r} azsdk-js-client`:"azsdk-js-client";this._client=sOe(e,I,Object.assign(Object.assign({},l),{userAgentOptions:{userAgentPrefix:a}})),this.pipeline=this._client.pipeline}restoreSecret(e,I={requestOptions:{}}){return bOe(this._client,e,I)}backupSecret(e,I={requestOptions:{}}){return mOe(this._client,e,I)}recoverDeletedSecret(e,I={requestOptions:{}}){return uOe(this._client,e,I)}purgeDeletedSecret(e,I={requestOptions:{}}){return hOe(this._client,e,I)}getDeletedSecret(e,I={requestOptions:{}}){return pOe(this._client,e,I)}getDeletedSecrets(e={requestOptions:{}}){return ZOe(this._client,e)}getSecretVersions(e,I={requestOptions:{}}){return WOe(this._client,e,I)}getSecrets(e={requestOptions:{}}){return NOe(this._client,e)}getSecret(e,I,l={requestOptions:{}}){return YOe(this._client,e,I,l)}updateSecret(e,I,l,n={requestOptions:{}}){return yOe(this._client,e,I,l,n)}deleteSecret(e,I={requestOptions:{}}){return gOe(this._client,e,I)}setSecret(e,I,l={requestOptions:{}}){return VOe(this._client,e,I,l)}}});function FOe(t){let e=/,? +/,I=t.split(e).reduce((l,n)=>{if(n.match(/\w="/)){let[r,...a]=n.split("=");if(lnl.includes(r))return Object.assign(Object.assign({},l),{[r]:a.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 lnl,NOt=m(()=>{lnl=["authorization","authorization_url","resource","scope","tenantId","claims","error"]});async function rnl(t,e,I){async function l(){if(Date.now()<I)try{return await t()}catch{return null}else{let r=await t();if(r===null)throw new Error("Failed to refresh access token.");return r}}let n=await l();for(;n===null;)await uF(e),n=await l();return n}function YOt(t,e){let I=null,l=null,n,r=Object.assign(Object.assign({},nnl),e),a={get isRefreshing(){return I!==null},get shouldRefresh(){var c;return a.isRefreshing?!1:l?.refreshAfterTimestamp&&l.refreshAfterTimestamp<Date.now()?!0:((c=l?.expiresOnTimestamp)!==null&&c!==void 0?c:0)-r.refreshWindowInMs<Date.now()},get mustRefresh(){return l===null||l.expiresOnTimestamp-r.forcedRefreshWindowInMs<Date.now()}};function s(c,o){var i;return a.isRefreshing||(I=rnl(()=>t.getToken(c,o),r.retryIntervalInMs,(i=l?.expiresOnTimestamp)!==null&&i!==void 0?i:Date.now()).then(G=>(I=null,l=G,n=o.tenantId,l)).catch(G=>{throw I=null,l=null,n=void 0,G})),I}return async(c,o)=>{let i=!!o.claims,d=n!==o.tenantId;return i&&(l=null),d||i||a.mustRefresh?s(c,o):(a.shouldRefresh&&s(c,o),l)}}var nnl,yOt=m(()=>{md();nnl={forcedRefreshWindowInMs:1e3,retryIntervalInMs:3e3,refreshWindowInMs:1e3*60*2}});var gOt,VOt=m(()=>{JZ();gOt=Gd("keyvault-common")});function anl(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.`)}function ROt(t,e={}){let{disableChallengeResourceVerification:I}=e,l={status:"none"},n=YOt(t);function r(i){return{abortSignal:i.abortSignal,requestOptions:{timeout:i.timeout>0?i.timeout:void 0},tracingOptions:i.tracingOptions}}async function a(i){let d=r(i);switch(l.status){case"none":l={status:"started",originalBody:i.body},i.body=null;break;case"started":break;case"complete":{let G=await n(l.scopes,Object.assign(Object.assign({},d),{enableCae:!0,tenantId:l.tenantId}));G&&i.headers.set("authorization",`Bearer ${G.token}`);break}}}async function s(i,d,G){if(d.status!==401)return d;i.body===null&&l.status==="started"&&(i.body=l.originalBody);let b=r(i),u=d.headers.get("WWW-Authenticate");if(!u)return gOt.warning("keyVaultAuthentication policy encountered a 401 response without a corresponding WWW-Authenticate header. This is unexpected. Not handling the 401 response."),d;let h=FOe(u),p=h.resource?h.resource+"/.default":h.scope;if(!p)return d;I||anl(p,i);let W=await n([p],Object.assign(Object.assign({},b),{enableCae:!0,tenantId:h.tenantId}));return W?(i.headers.set("Authorization",`Bearer ${W.token}`),l={status:"complete",scopes:[p],tenantId:h.tenantId},G(i)):d}async function c(i,d,G){if(l.status!=="complete"||d.status!==401)return d;let b=r(i),u=d.headers.get("WWW-Authenticate");if(!u)return d;let{claims:h,error:p}=FOe(u);if(p!=="insufficient_claims"||h===void 0)return d;let W=atob(h),N=await n(l.scopes,Object.assign(Object.assign({},b),{enableCae:!0,tenantId:l.tenantId,claims:W}));return i.headers.set("Authorization",`Bearer ${N.token}`),G(i)}async function o(i,d){await a(i);let G=await d(i);return G=await s(i,G,d),G=await c(i,G,d),G}return{name:snl,sendRequest:o}}var snl,AOt=m(()=>{NOt();yOt();VOt();snl="keyVaultAuthenticationPolicy"});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 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}`,r=l[2],a=l.length===4?l[3]:void 0;return{vaultUrl:n,name:r,version:a}}var wOt=m(()=>{});var wOe=m(()=>{AOt();wOt()});var QOt=m(()=>{});var EOt=m(()=>{iOe()});var vOt=m(()=>{AOe();EOt()});function QOe(t){let I=t.split("/")[3];return Object.assign({sourceId:t},FOt(I,t))}var EOe=m(()=>{wOe()});function BG(t){let e=t,I=t,l=QOe(e.id),n=e.attributes;delete e.attributes;let r={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&&(r.properties.recoveryId=I.recoveryId,r.properties.scheduledPurgeDate=I.scheduledPurgeDate,r.properties.deletedOn=I.deletedDate,r.recoveryId=I.recoveryId,r.scheduledPurgeDate=I.scheduledPurgeDate,r.deletedOn=I.deletedDate),n&&(n.vaultUrl&&delete r.properties.vaultUrl,n.expires&&delete r.properties.expires,n.created&&delete r.properties.created,n.updated&&delete r.properties.updated),r}function Qpe(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 ZF(this,arguments,function*(){var a,s,c,o;let i=t(Object.assign(Object.assign({},e),{maxresults:n?.maxPageSize})).byPage(n);try{for(var d=!0,G=FX(i),b;b=yield Wa(G.next()),a=b.done,!a;d=!0)o=b.value,d=!1,yield yield Wa(o.map(I))}catch(u){s={error:u}}finally{try{!d&&!a&&(c=G.return)&&(yield Wa(c.call(G)))}finally{if(s)throw s.error}}})}}}var Epe=m(()=>{Kk();EOe()});var vpe,vOe=m(()=>{vpe="4.10.0"});var tm,Xpe=m(()=>{XGe();vOe();tm=Rv({namespace:"Microsoft.KeyVault",packageName:"@azure/keyvault-secrets",packageVersion:vpe})});var XOe,Hpe=m(()=>{JZ();XOe=Gd("core-lro")});var Cpe=m(()=>{});var fpe=m(()=>{Hpe();Cpe()});var HOe=m(()=>{fpe();Hpe()});var XOt=m(()=>{fpe();Cpe();md()});var HOt=m(()=>{HOe();XOt()});var COt=m(()=>{HOe();Hpe()});var COe,fOe,n7,JOe=m(()=>{COe=class t extends Error{constructor(e){super(e),this.name="PollerStoppedError",Object.setPrototypeOf(this,t.prototype)}},fOe=class t extends Error{constructor(e){super(e),this.name="PollerCancelledError",Object.setPrototypeOf(this,t.prototype)}},n7=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 fOe("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 COe("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 fOt=m(()=>{COt();Cpe();JOe();fpe()});var JOt=m(()=>{fOt()});var LOt=m(()=>{});var kOt=m(()=>{HOt();JOt();JOe();LOt()});var h9,p9,r7=m(()=>{kOt();md();h9=class extends n7{constructor(){super(...arguments),this.intervalInMs=2e3}async delay(){return uF(this.intervalInMs)}},p9=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 Jpe,xOt=m(()=>{r7();Epe();Xpe();Jpe=class extends p9{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 tm.withSpan("DeleteSecretPoller.deleteSecret",I,async l=>{let n=await this.client.deleteSecret(e,l);return BG(n)})}getDeletedSecret(e,I={}){return tm.withSpan("DeleteSecretPoller.getDeletedSecret",I,async l=>{let n=await this.client.getDeletedSecret(e,l);return BG(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 Lpe,BOt=m(()=>{xOt();r7();Lpe=class extends h9{constructor(e){let{client:I,name:l,operationOptions:n,intervalInMs:r=2e3,resumeFrom:a}=e,s;a&&(s=JSON.parse(a).state);let c=new Jpe(Object.assign(Object.assign({},s),{name:l}),I,n);super(c),this.intervalInMs=r}}});var kpe,SOt=m(()=>{r7();Epe();Xpe();kpe=class extends p9{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 tm.withSpan("RecoverDeletedSecretPoller.getSecret",I,async l=>{let n=await this.client.getSecret(e,I&&I.version?I.version:"",l);return BG(n)})}recoverDeletedSecret(e,I={}){return tm.withSpan("RecoverDeletedSecretPoller.recoverDeletedSecret",I,async l=>{let n=await this.client.recoverDeletedSecret(e,l);return BG(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 xpe,zOt=m(()=>{SOt();r7();xpe=class extends h9{constructor(e){let{client:I,name:l,operationOptions:n,intervalInMs:r=2e3,resumeFrom:a}=e,s;a&&(s=JSON.parse(a).state);let c=new kpe(Object.assign(Object.assign({},s),{name:l}),I,n);super(c),this.intervalInMs=r}}});var Bpe,UOt=m(()=>{Kk();zUt();AOe();wOe();QOt();vOt();EOe();Epe();Xpe();su();vOe();BOt();zOt();Bpe=class{constructor(e,I,l={}){var n,r;this.vaultUrl=e;let a=Object.assign(Object.assign({},l),{userAgentOptions:{userAgentPrefix:`${(r=(n=l.userAgentOptions)===null||n===void 0?void 0:n.userAgentPrefix)!==null&&r!==void 0?r:""} azsdk-js-keyvault-secrets/${vpe}`},apiVersion:l.serviceVersion||"7.6",loggingOptions:{logger:SUt.info,additionalAllowedHeaderNames:["x-ms-keyvault-region","x-ms-keyvault-network-info","x-ms-keyvault-service-version"]}});this.client=new l7(this.vaultUrl,I,a),this.client.pipeline.removePolicy({name:Dme}),this.client.pipeline.addPolicy(ROt(I,l),{}),this.client.pipeline.addPolicy({name:"ContentTypePolicy",sendRequest(s,c){var o;return((o=s.headers.get("Content-Type"))!==null&&o!==void 0?o:"").startsWith("application/json")&&s.headers.set("Content-Type","application/json"),c(s)}})}setSecret(e,I,l={}){let{enabled:n,notBefore:r,expiresOn:a,tags:s}=l,c=PP(l,["enabled","notBefore","expiresOn","tags"]);return tm.withSpan("SecretClient.setSecret",c,async o=>{let i=await this.client.setSecret(e,{value:I,secretAttributes:{enabled:n,notBefore:r,expires:a},tags:s},o);return BG(i)})}async beginDeleteSecret(e,I={}){let l=new Lpe(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:r,expiresOn:a,tags:s}=l,c=PP(l,["enabled","notBefore","expiresOn","tags"]);return tm.withSpan("SecretClient.updateSecretProperties",c,async o=>{let i=await this.client.updateSecret(e,I,{secretAttributes:{enabled:n,notBefore:r,expires:a},tags:s},o);return BG(i).properties})}getSecret(e,I={}){return tm.withSpan("SecretClient.getSecret",I,async l=>{let n=await this.client.getSecret(e,I&&I.version?I.version:"",l);return BG(n)})}getDeletedSecret(e,I={}){return tm.withSpan("SecretClient.getDeletedSecret",I,async l=>{let n=await this.client.getDeletedSecret(e,l);return BG(n)})}purgeDeletedSecret(e,I={}){return tm.withSpan("SecretClient.purgeDeletedSecret",I,async l=>{await this.client.purgeDeletedSecret(e,l)})}async beginRecoverDeletedSecret(e,I={}){let l=new xpe(Object.assign(Object.assign({name:e,client:this.client},I),{operationOptions:I}));return await l.poll(),l}backupSecret(e,I={}){return tm.withSpan("SecretClient.backupSecret",I,async l=>(await this.client.backupSecret(e,l)).value)}restoreSecretBackup(e,I={}){return tm.withSpan("SecretClient.restoreSecretBackup",I,async l=>{let n=await this.client.restoreSecret({secretBundleBackup:e},l);return BG(n).properties})}listPropertiesOfSecretVersions(e,I={}){return Qpe(l=>this.client.getSecretVersions(e,l),I,l=>BG(l).properties)}listPropertiesOfSecrets(e={}){return Qpe(this.client.getSecrets.bind(this.client),e,I=>BG(I).properties)}listDeletedSecrets(e={}){return Qpe(this.client.getDeletedSecrets.bind(this.client),e,BG)}}});function OOt(t,e){let I=t.api?.copilot?.azureKeyVaultUri;return kOe(I,e)}function kOe(t,e){return new LOe(t,e)}var LOe,xOe=m(()=>{"use strict";due();UOt();LOe=class{client;logger;constructor(e,I){if(this.logger=I,e){this.logger.debug(`Using Azure Key Vault at ${e}`);let l=new H0;this.client=new Bpe(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}}}});import{readFileSync as bnl}from"fs";import{dirname as mnl,join as BOe}from"path";import{fileURLToPath as unl}from"url";function SOe(){return MOt().version}function MOt(){if(a7!==null)return a7;try{let t=unl(import.meta.url),e=mnl(t),I=[BOe(e,"package.json"),BOe(e,"../package.json"),BOe(e,"../../package.json")];for(let n of I)try{let r=JSON.parse(bnl(n,"utf8")),a={name:r.name||"unknown",version:r.version||"unknown",buildMetadata:r.buildMetadata};return a7=a,a}catch{continue}let l={name:"unknown",version:"unknown"};return a7=l,l}catch{let e={name:"unknown",version:"unknown"};return a7=e,e}}function hnl(t){return t.replace(/^@.*\//,"")}function Spe(t){let e=MOt(),I=hnl(e.name),l=t?.clientName?`client/${t.clientName} `:"",n=process.env.TERM_PROGRAM??"unknown";return`${I}/${e.version} (${l}${process.platform} ${process.version}) term/${n}`}var a7,zpe=m(()=>{"use strict";a7=null});import{spawnSync as pnl}from"child_process";import{createHmac as Znl}from"crypto";var TOt,Upe,jOt=m(()=>{"use strict";TOt="askpass:",Upe=class t{static encode(e){if(e.startsWith(TOt)){let I=e.slice(TOt.length);return t.executeAskpassCommand(I)}return t.encodeWithKey(e)}static executeAskpassCommand(e){let I=e.split(" ").filter(s=>s.length>0),l=I[0],n=I.slice(1),r=pnl(l,n,{encoding:"utf8",timeout:1e4,maxBuffer:1024*1024});if(r.error)throw new Error(`Failed to execute HMAC askpass command: ${r.error.message}`);if(r.status!==0){let s=r.stderr?.trim()||"";throw new Error(`HMAC askpass command exited with code ${r.status}${s?`: ${s}`:""}`)}let a=r.stdout?.trim();if(!a)throw new Error("HMAC askpass command returned empty token");return a}static encodeWithKey(e){let I=t.hmacGetBytes(e),a=(Math.floor(Date.now()/1e3)+30).toString(),s=Buffer.from(a,"ascii"),i=Znl("sha256",I).update(s).digest().toString("hex").toUpperCase();return`${a}.${i}`}static hmacGetBytes(e){return Buffer.from(e,"ascii")}}});var Wnl,Nnl,DOt,WH,Z9,W9,s7=m(()=>{"use strict";q8();xOe();_i();eV();DG();KI();zpe();jOt();Wnl="X-GitHub-Api-Version",Nnl="2025-05-01",DOt=["https://api.enterprise.githubcopilot.com","https://api.business.githubcopilot.com","https://api.individual.githubcopilot.com"],WH=class t extends ZI{constructor(I,l,n,r,a){let s=a?void 0:_B()?"debug":"info";super({baseURL:I,apiKey:"",logLevel:s});this.headers=l;this.runnerLogger=n;this.hmacKey=r}static baseHeaders={"Content-Type":"application/json",Accept:"application/json","X-Interaction-Type":"conversation-agent","Openai-Intent":"conversation-agent","X-Initiator":"user",[Wnl]:Nnl};hmacKey;additionalHeaders={};static createWithOAuthToken(I,l,n,r,a,s,c,o){let i={...this.defaultHeaders(n,a,o),Authorization:`Bearer ${r}`,...s??{}};return I.debug(`Creating copilot-client for integration ID ${n} with token authentication. User-agent: ${i["User-Agent"]}`),new t(l,i,I,void 0,c)}static createWithHmac(I,l,n,r,a,s,c,o,i){let d={...this.defaultHeaders(n,a,i),Authorization:"",...c??{}};return s&&(d["X-GitHub-User"]=s),I.debug(`Creating copilot-client for integration ID ${n} with HMAC key authentication. User-agent: ${d["User-Agent"]}`),new t(l,d,I,r,o)}static defaultHeaders(I,l,n){return{...t.baseHeaders,"Copilot-Integration-Id":I,"X-Interaction-Id":l,"User-Agent":Spe(n)}}async prepareOptions(I){this.hmacKey&&(this.headers["Request-HMAC"]=Upe.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[r,a]of Object.entries(I.headers))typeof a=="string"&&(l[r]=a);let n=[this.baseURL];if(DOt.includes(this.baseURL))for(let r of DOt)r!==this.baseURL&&n.push(r);for(let r of n){let a=`${r}/models`,s=await fetch(a,{method:I.method,headers:l});if(s.ok){let c=await s.json();return this.runnerLogger.debug(`Successfully listed ${c.data.length} models`),c.data}if(s.status===421){this.runnerLogger.debug(`Failed to list models due to subscription-based route ${r}: ${s.status} ${s.statusText}: ${await s.text()}`);continue}return this.runnerLogger.error(`Failed to list models due to non-retryable error: ${s.status} ${s.statusText}: ${await s.text()}`),[]}return this.runnerLogger.error("Failed to list models"),[]}},Z9=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,r=e.api?.copilot?.hmacKey,a=!!(r||n);if(!a){I.debug("No Copilot HMAC key or GitHub OAuth token provided, trying secret provider");let d=OOt(e,I);try{r=await d.getSecret("dev-CapiHmacKey")}catch(G){I.debug(`Failed to get Copilot HMAC key from secret provider:
|
|
1720
|
+
Body doesn't contain an array property with name: ${e}`);return I??[]}function Qll(t,e){if(!e.includes(t.status))throw gd(`Pagination failed with unexpected statusCode ${t.status}`,t)}var uOt=m(()=>{Kk();Vpe();su()});function u9(t,e,I){return(e??I==="+")||I==="#"?hOt(t):pOt(t)}function hOt(t){return t.split(/(%[0-9A-Fa-f]{2})/g).map(e=>/%[0-9A-Fa-f]/.test(e)?e:encodeURI(e)).join("")}function pOt(t){return encodeURIComponent(t).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function I7(t){return t!=null}function GOe(t){return[!!t&&[";","?","&"].includes(t),t&&["?","&"].includes(t)?"=":""]}function wpe(t,e=!1){return e?!t||t==="+"?"":t:!t||t==="+"||t==="#"?",":t==="?"?"&":t}function Ell(t){let e=t.isFirst,{op:I,varName:l,varValue:n,reserved:r}=t,a=[],[s,c]=GOe(I);if(Array.isArray(n))for(let o of n.filter(I7))a.push(`${wpe(I,e)}`),s&&l&&(a.push(`${encodeURIComponent(l)}`),o===""?a.push(c):a.push("=")),a.push(u9(o,r,I)),e=!1;else if(typeof n=="object")for(let o of Object.keys(n)){let i=n[o];I7(i)&&(a.push(`${wpe(I,e)}`),o&&(a.push(`${encodeURIComponent(o)}`),s&&i===""?a.push(c):a.push("=")),a.push(u9(i,r,I)),e=!1)}return a.join("")}function vll(t){let{op:e,varName:I,varValue:l,isFirst:n,reserved:r}=t,a=[],s=wpe(e,n),[c,o]=GOe(e);if(c&&I){if(a.push(u9(I,r,e)),l==="")return o||a.push(o),a.join("")?`${s}${a.join("")}`:void 0;a.push("=")}let i=[];if(Array.isArray(l))for(let d of l.filter(I7))i.push(u9(d,r,e));else if(typeof l=="object")for(let d of Object.keys(l))I7(l[d])&&(i.push(pOt(d)),i.push(u9(l[d],r,e)));return a.push(i.join(",")),a.join(",")?`${s}${a.join("")}`:void 0}function Xll(t){let{op:e,varName:I,modifier:l,isFirst:n,reserved:r,varValue:a}=t;if(I7(a))if(["string","number","boolean"].includes(typeof a)){let s=a.toString(),[c,o]=GOe(e),i=[wpe(e,n)];return c&&I&&(i.push(I),s===""?i.push(o):i.push("=")),l&&l!=="*"&&(s=s.substring(0,parseInt(l,10))),i.push(u9(s,r,e)),i.join("")}else return l==="*"?Ell(t):vll(t);else return}function Wu(t,e,I){return t.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g,(l,n,r)=>{if(!n)return hOt(r);let a;["+","#",".","/",";","?","&"].includes(n[0])&&(a=n[0],n=n.slice(1));let s=n.split(/,/g),c=[];for(let o of s){let i=/([^:\*]*)(?::(\d+)|(\*))?/.exec(o);if(!i||!i[1])continue;let d=Xll({isFirst:c.length===0,op:a,varValue:e[i[1]],varName:i[1],modifier:i[2]||i[3],reserved:I?.allowReserved});d&&c.push(d)}return c.join("")})}var ZOt=m(()=>{});function Hll(t,e,I={requestOptions:{}}){var l,n;let r=Wu("/secrets/restore{?api%2Dversion}",{"api%2Dversion":t.apiVersion},{allowReserved:(l=I?.requestOptions)===null||l===void 0?void 0:l.skipUrlEncoding});return t.path(r).post(Object.assign(Object.assign({},em(I)),{contentType:"application/json",headers:Object.assign({accept:"application/json"},(n=I.requestOptions)===null||n===void 0?void 0:n.headers),body:mOt(e)}))}async function Cll(t){if(!["200"].includes(t.status)){let I=gd(t);throw I.details=Zu(t.body),I}return m9(t.body)}async function bOe(t,e,I={requestOptions:{}}){let l=await Hll(t,e,I);return Cll(l)}function fll(t,e,I={requestOptions:{}}){var l,n;let r=Wu("/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(r).post(Object.assign(Object.assign({},em(I)),{headers:Object.assign({accept:"application/json"},(n=I.requestOptions)===null||n===void 0?void 0:n.headers)}))}async function Jll(t){if(!["200"].includes(t.status)){let I=gd(t);throw I.details=Zu(t.body),I}return bOt(t.body)}async function mOe(t,e,I={requestOptions:{}}){let l=await fll(t,e,I);return Jll(l)}function Lll(t,e,I={requestOptions:{}}){var l,n;let r=Wu("/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(r).post(Object.assign(Object.assign({},em(I)),{headers:Object.assign({accept:"application/json"},(n=I.requestOptions)===null||n===void 0?void 0:n.headers)}))}async function kll(t){if(!["200"].includes(t.status)){let I=gd(t);throw I.details=Zu(t.body),I}return m9(t.body)}async function uOe(t,e,I={requestOptions:{}}){let l=await Lll(t,e,I);return kll(l)}function xll(t,e,I={requestOptions:{}}){var l,n;let r=Wu("/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(r).delete(Object.assign(Object.assign({},em(I)),{headers:Object.assign({accept:"application/json"},(n=I.requestOptions)===null||n===void 0?void 0:n.headers)}))}async function Bll(t){if(!["204"].includes(t.status)){let I=gd(t);throw I.details=Zu(t.body),I}}async function hOe(t,e,I={requestOptions:{}}){let l=await xll(t,e,I);return Bll(l)}function Sll(t,e,I={requestOptions:{}}){var l,n;let r=Wu("/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(r).get(Object.assign(Object.assign({},em(I)),{headers:Object.assign({accept:"application/json"},(n=I.requestOptions)===null||n===void 0?void 0:n.headers)}))}async function zll(t){if(!["200"].includes(t.status)){let I=gd(t);throw I.details=Zu(t.body),I}return cOe(t.body)}async function pOe(t,e,I={requestOptions:{}}){let l=await Sll(t,e,I);return zll(l)}function Ull(t,e={requestOptions:{}}){var I,l;let n=Wu("/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({},em(e)),{headers:Object.assign({accept:"application/json"},(l=e.requestOptions)===null||l===void 0?void 0:l.headers)}))}async function Oll(t){if(!["200"].includes(t.status)){let I=gd(t);throw I.details=Zu(t.body),I}return GOt(t.body)}function ZOe(t,e={requestOptions:{}}){return Fpe(t,()=>Ull(t,e),Oll,["200"],{itemName:"value",nextLinkName:"nextLink"})}function Mll(t,e,I={requestOptions:{}}){var l,n;let r=Wu("/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(r).get(Object.assign(Object.assign({},em(I)),{headers:Object.assign({accept:"application/json"},(n=I.requestOptions)===null||n===void 0?void 0:n.headers)}))}async function Tll(t){if(!["200"].includes(t.status)){let I=gd(t);throw I.details=Zu(t.body),I}return oOe(t.body)}function WOe(t,e,I={requestOptions:{}}){return Fpe(t,()=>Mll(t,e,I),Tll,["200"],{itemName:"value",nextLinkName:"nextLink"})}function jll(t,e={requestOptions:{}}){var I,l;let n=Wu("/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({},em(e)),{headers:Object.assign({accept:"application/json"},(l=e.requestOptions)===null||l===void 0?void 0:l.headers)}))}async function Dll(t){if(!["200"].includes(t.status)){let I=gd(t);throw I.details=Zu(t.body),I}return oOe(t.body)}function NOe(t,e={requestOptions:{}}){return Fpe(t,()=>jll(t,e),Dll,["200"],{itemName:"value",nextLinkName:"nextLink"})}function Kll(t,e,I,l={requestOptions:{}}){var n,r;let a=Wu("/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(a).get(Object.assign(Object.assign({},em(l)),{headers:Object.assign({accept:"application/json"},(r=l.requestOptions)===null||r===void 0?void 0:r.headers)}))}async function Pll(t){if(!["200"].includes(t.status)){let I=gd(t);throw I.details=Zu(t.body),I}return m9(t.body)}async function YOe(t,e,I,l={requestOptions:{}}){let n=await Kll(t,e,I,l);return Pll(n)}function qll(t,e,I,l,n={requestOptions:{}}){var r,a;let s=Wu("/secrets/{secret-name}/{secret-version}{?api%2Dversion}",{"secret-name":e,"secret-version":I,"api%2Dversion":t.apiVersion},{allowReserved:(r=n?.requestOptions)===null||r===void 0?void 0:r.skipUrlEncoding});return t.path(s).patch(Object.assign(Object.assign({},em(n)),{contentType:"application/json",headers:Object.assign({accept:"application/json"},(a=n.requestOptions)===null||a===void 0?void 0:a.headers),body:dOt(l)}))}async function _ll(t){if(!["200"].includes(t.status)){let I=gd(t);throw I.details=Zu(t.body),I}return m9(t.body)}async function yOe(t,e,I,l,n={requestOptions:{}}){let r=await qll(t,e,I,l,n);return _ll(r)}function $ll(t,e,I={requestOptions:{}}){var l,n;let r=Wu("/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(r).delete(Object.assign(Object.assign({},em(I)),{headers:Object.assign({accept:"application/json"},(n=I.requestOptions)===null||n===void 0?void 0:n.headers)}))}async function enl(t){if(!["200"].includes(t.status)){let I=gd(t);throw I.details=Zu(t.body),I}return cOe(t.body)}async function gOe(t,e,I={requestOptions:{}}){let l=await $ll(t,e,I);return enl(l)}function tnl(t,e,I,l={requestOptions:{}}){var n,r;let a=Wu("/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).put(Object.assign(Object.assign({},em(l)),{contentType:"application/json",headers:Object.assign({accept:"application/json"},(r=l.requestOptions)===null||r===void 0?void 0:r.headers),body:cOt(I)}))}async function Inl(t){if(!["200"].includes(t.status)){let I=gd(t);throw I.details=Zu(t.body),I}return m9(t.body)}async function VOe(t,e,I,l={requestOptions:{}}){let n=await tnl(t,e,I,l);return Inl(n)}var ROe=m(()=>{iOe();uOt();ZOt();Vpe()});var WOt=m(()=>{sOt();ROe()});var l7,AOe=m(()=>{WOt();ROe();l7=class{constructor(e,I,l={}){var n;let r=(n=l?.userAgentOptions)===null||n===void 0?void 0:n.userAgentPrefix,a=r?`${r} azsdk-js-client`:"azsdk-js-client";this._client=sOe(e,I,Object.assign(Object.assign({},l),{userAgentOptions:{userAgentPrefix:a}})),this.pipeline=this._client.pipeline}restoreSecret(e,I={requestOptions:{}}){return bOe(this._client,e,I)}backupSecret(e,I={requestOptions:{}}){return mOe(this._client,e,I)}recoverDeletedSecret(e,I={requestOptions:{}}){return uOe(this._client,e,I)}purgeDeletedSecret(e,I={requestOptions:{}}){return hOe(this._client,e,I)}getDeletedSecret(e,I={requestOptions:{}}){return pOe(this._client,e,I)}getDeletedSecrets(e={requestOptions:{}}){return ZOe(this._client,e)}getSecretVersions(e,I={requestOptions:{}}){return WOe(this._client,e,I)}getSecrets(e={requestOptions:{}}){return NOe(this._client,e)}getSecret(e,I,l={requestOptions:{}}){return YOe(this._client,e,I,l)}updateSecret(e,I,l,n={requestOptions:{}}){return yOe(this._client,e,I,l,n)}deleteSecret(e,I={requestOptions:{}}){return gOe(this._client,e,I)}setSecret(e,I,l={requestOptions:{}}){return VOe(this._client,e,I,l)}}});function FOe(t){let e=/,? +/,I=t.split(e).reduce((l,n)=>{if(n.match(/\w="/)){let[r,...a]=n.split("=");if(lnl.includes(r))return Object.assign(Object.assign({},l),{[r]:a.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 lnl,NOt=m(()=>{lnl=["authorization","authorization_url","resource","scope","tenantId","claims","error"]});async function rnl(t,e,I){async function l(){if(Date.now()<I)try{return await t()}catch{return null}else{let r=await t();if(r===null)throw new Error("Failed to refresh access token.");return r}}let n=await l();for(;n===null;)await uF(e),n=await l();return n}function YOt(t,e){let I=null,l=null,n,r=Object.assign(Object.assign({},nnl),e),a={get isRefreshing(){return I!==null},get shouldRefresh(){var c;return a.isRefreshing?!1:l?.refreshAfterTimestamp&&l.refreshAfterTimestamp<Date.now()?!0:((c=l?.expiresOnTimestamp)!==null&&c!==void 0?c:0)-r.refreshWindowInMs<Date.now()},get mustRefresh(){return l===null||l.expiresOnTimestamp-r.forcedRefreshWindowInMs<Date.now()}};function s(c,o){var i;return a.isRefreshing||(I=rnl(()=>t.getToken(c,o),r.retryIntervalInMs,(i=l?.expiresOnTimestamp)!==null&&i!==void 0?i:Date.now()).then(G=>(I=null,l=G,n=o.tenantId,l)).catch(G=>{throw I=null,l=null,n=void 0,G})),I}return async(c,o)=>{let i=!!o.claims,d=n!==o.tenantId;return i&&(l=null),d||i||a.mustRefresh?s(c,o):(a.shouldRefresh&&s(c,o),l)}}var nnl,yOt=m(()=>{md();nnl={forcedRefreshWindowInMs:1e3,retryIntervalInMs:3e3,refreshWindowInMs:1e3*60*2}});var gOt,VOt=m(()=>{JZ();gOt=Gd("keyvault-common")});function anl(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.`)}function ROt(t,e={}){let{disableChallengeResourceVerification:I}=e,l={status:"none"},n=YOt(t);function r(i){return{abortSignal:i.abortSignal,requestOptions:{timeout:i.timeout>0?i.timeout:void 0},tracingOptions:i.tracingOptions}}async function a(i){let d=r(i);switch(l.status){case"none":l={status:"started",originalBody:i.body},i.body=null;break;case"started":break;case"complete":{let G=await n(l.scopes,Object.assign(Object.assign({},d),{enableCae:!0,tenantId:l.tenantId}));G&&i.headers.set("authorization",`Bearer ${G.token}`);break}}}async function s(i,d,G){if(d.status!==401)return d;i.body===null&&l.status==="started"&&(i.body=l.originalBody);let b=r(i),u=d.headers.get("WWW-Authenticate");if(!u)return gOt.warning("keyVaultAuthentication policy encountered a 401 response without a corresponding WWW-Authenticate header. This is unexpected. Not handling the 401 response."),d;let h=FOe(u),p=h.resource?h.resource+"/.default":h.scope;if(!p)return d;I||anl(p,i);let W=await n([p],Object.assign(Object.assign({},b),{enableCae:!0,tenantId:h.tenantId}));return W?(i.headers.set("Authorization",`Bearer ${W.token}`),l={status:"complete",scopes:[p],tenantId:h.tenantId},G(i)):d}async function c(i,d,G){if(l.status!=="complete"||d.status!==401)return d;let b=r(i),u=d.headers.get("WWW-Authenticate");if(!u)return d;let{claims:h,error:p}=FOe(u);if(p!=="insufficient_claims"||h===void 0)return d;let W=atob(h),N=await n(l.scopes,Object.assign(Object.assign({},b),{enableCae:!0,tenantId:l.tenantId,claims:W}));return i.headers.set("Authorization",`Bearer ${N.token}`),G(i)}async function o(i,d){await a(i);let G=await d(i);return G=await s(i,G,d),G=await c(i,G,d),G}return{name:snl,sendRequest:o}}var snl,AOt=m(()=>{NOt();yOt();VOt();snl="keyVaultAuthenticationPolicy"});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 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}`,r=l[2],a=l.length===4?l[3]:void 0;return{vaultUrl:n,name:r,version:a}}var wOt=m(()=>{});var wOe=m(()=>{AOt();wOt()});var QOt=m(()=>{});var EOt=m(()=>{iOe()});var vOt=m(()=>{AOe();EOt()});function QOe(t){let I=t.split("/")[3];return Object.assign({sourceId:t},FOt(I,t))}var EOe=m(()=>{wOe()});function BG(t){let e=t,I=t,l=QOe(e.id),n=e.attributes;delete e.attributes;let r={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&&(r.properties.recoveryId=I.recoveryId,r.properties.scheduledPurgeDate=I.scheduledPurgeDate,r.properties.deletedOn=I.deletedDate,r.recoveryId=I.recoveryId,r.scheduledPurgeDate=I.scheduledPurgeDate,r.deletedOn=I.deletedDate),n&&(n.vaultUrl&&delete r.properties.vaultUrl,n.expires&&delete r.properties.expires,n.created&&delete r.properties.created,n.updated&&delete r.properties.updated),r}function Qpe(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 ZF(this,arguments,function*(){var a,s,c,o;let i=t(Object.assign(Object.assign({},e),{maxresults:n?.maxPageSize})).byPage(n);try{for(var d=!0,G=FX(i),b;b=yield Wa(G.next()),a=b.done,!a;d=!0)o=b.value,d=!1,yield yield Wa(o.map(I))}catch(u){s={error:u}}finally{try{!d&&!a&&(c=G.return)&&(yield Wa(c.call(G)))}finally{if(s)throw s.error}}})}}}var Epe=m(()=>{Kk();EOe()});var vpe,vOe=m(()=>{vpe="4.10.0"});var tm,Xpe=m(()=>{XGe();vOe();tm=Rv({namespace:"Microsoft.KeyVault",packageName:"@azure/keyvault-secrets",packageVersion:vpe})});var XOe,Hpe=m(()=>{JZ();XOe=Gd("core-lro")});var Cpe=m(()=>{});var fpe=m(()=>{Hpe();Cpe()});var HOe=m(()=>{fpe();Hpe()});var XOt=m(()=>{fpe();Cpe();md()});var HOt=m(()=>{HOe();XOt()});var COt=m(()=>{HOe();Hpe()});var COe,fOe,n7,JOe=m(()=>{COe=class t extends Error{constructor(e){super(e),this.name="PollerStoppedError",Object.setPrototypeOf(this,t.prototype)}},fOe=class t extends Error{constructor(e){super(e),this.name="PollerCancelledError",Object.setPrototypeOf(this,t.prototype)}},n7=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 fOe("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 COe("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 fOt=m(()=>{COt();Cpe();JOe();fpe()});var JOt=m(()=>{fOt()});var LOt=m(()=>{});var kOt=m(()=>{HOt();JOt();JOe();LOt()});var h9,p9,r7=m(()=>{kOt();md();h9=class extends n7{constructor(){super(...arguments),this.intervalInMs=2e3}async delay(){return uF(this.intervalInMs)}},p9=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 Jpe,xOt=m(()=>{r7();Epe();Xpe();Jpe=class extends p9{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 tm.withSpan("DeleteSecretPoller.deleteSecret",I,async l=>{let n=await this.client.deleteSecret(e,l);return BG(n)})}getDeletedSecret(e,I={}){return tm.withSpan("DeleteSecretPoller.getDeletedSecret",I,async l=>{let n=await this.client.getDeletedSecret(e,l);return BG(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 Lpe,BOt=m(()=>{xOt();r7();Lpe=class extends h9{constructor(e){let{client:I,name:l,operationOptions:n,intervalInMs:r=2e3,resumeFrom:a}=e,s;a&&(s=JSON.parse(a).state);let c=new Jpe(Object.assign(Object.assign({},s),{name:l}),I,n);super(c),this.intervalInMs=r}}});var kpe,SOt=m(()=>{r7();Epe();Xpe();kpe=class extends p9{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 tm.withSpan("RecoverDeletedSecretPoller.getSecret",I,async l=>{let n=await this.client.getSecret(e,I&&I.version?I.version:"",l);return BG(n)})}recoverDeletedSecret(e,I={}){return tm.withSpan("RecoverDeletedSecretPoller.recoverDeletedSecret",I,async l=>{let n=await this.client.recoverDeletedSecret(e,l);return BG(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 xpe,zOt=m(()=>{SOt();r7();xpe=class extends h9{constructor(e){let{client:I,name:l,operationOptions:n,intervalInMs:r=2e3,resumeFrom:a}=e,s;a&&(s=JSON.parse(a).state);let c=new kpe(Object.assign(Object.assign({},s),{name:l}),I,n);super(c),this.intervalInMs=r}}});var Bpe,UOt=m(()=>{Kk();zUt();AOe();wOe();QOt();vOt();EOe();Epe();Xpe();su();vOe();BOt();zOt();Bpe=class{constructor(e,I,l={}){var n,r;this.vaultUrl=e;let a=Object.assign(Object.assign({},l),{userAgentOptions:{userAgentPrefix:`${(r=(n=l.userAgentOptions)===null||n===void 0?void 0:n.userAgentPrefix)!==null&&r!==void 0?r:""} azsdk-js-keyvault-secrets/${vpe}`},apiVersion:l.serviceVersion||"7.6",loggingOptions:{logger:SUt.info,additionalAllowedHeaderNames:["x-ms-keyvault-region","x-ms-keyvault-network-info","x-ms-keyvault-service-version"]}});this.client=new l7(this.vaultUrl,I,a),this.client.pipeline.removePolicy({name:Dme}),this.client.pipeline.addPolicy(ROt(I,l),{}),this.client.pipeline.addPolicy({name:"ContentTypePolicy",sendRequest(s,c){var o;return((o=s.headers.get("Content-Type"))!==null&&o!==void 0?o:"").startsWith("application/json")&&s.headers.set("Content-Type","application/json"),c(s)}})}setSecret(e,I,l={}){let{enabled:n,notBefore:r,expiresOn:a,tags:s}=l,c=PP(l,["enabled","notBefore","expiresOn","tags"]);return tm.withSpan("SecretClient.setSecret",c,async o=>{let i=await this.client.setSecret(e,{value:I,secretAttributes:{enabled:n,notBefore:r,expires:a},tags:s},o);return BG(i)})}async beginDeleteSecret(e,I={}){let l=new Lpe(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:r,expiresOn:a,tags:s}=l,c=PP(l,["enabled","notBefore","expiresOn","tags"]);return tm.withSpan("SecretClient.updateSecretProperties",c,async o=>{let i=await this.client.updateSecret(e,I,{secretAttributes:{enabled:n,notBefore:r,expires:a},tags:s},o);return BG(i).properties})}getSecret(e,I={}){return tm.withSpan("SecretClient.getSecret",I,async l=>{let n=await this.client.getSecret(e,I&&I.version?I.version:"",l);return BG(n)})}getDeletedSecret(e,I={}){return tm.withSpan("SecretClient.getDeletedSecret",I,async l=>{let n=await this.client.getDeletedSecret(e,l);return BG(n)})}purgeDeletedSecret(e,I={}){return tm.withSpan("SecretClient.purgeDeletedSecret",I,async l=>{await this.client.purgeDeletedSecret(e,l)})}async beginRecoverDeletedSecret(e,I={}){let l=new xpe(Object.assign(Object.assign({name:e,client:this.client},I),{operationOptions:I}));return await l.poll(),l}backupSecret(e,I={}){return tm.withSpan("SecretClient.backupSecret",I,async l=>(await this.client.backupSecret(e,l)).value)}restoreSecretBackup(e,I={}){return tm.withSpan("SecretClient.restoreSecretBackup",I,async l=>{let n=await this.client.restoreSecret({secretBundleBackup:e},l);return BG(n).properties})}listPropertiesOfSecretVersions(e,I={}){return Qpe(l=>this.client.getSecretVersions(e,l),I,l=>BG(l).properties)}listPropertiesOfSecrets(e={}){return Qpe(this.client.getSecrets.bind(this.client),e,I=>BG(I).properties)}listDeletedSecrets(e={}){return Qpe(this.client.getDeletedSecrets.bind(this.client),e,BG)}}});function OOt(t,e){let I=t.api?.copilot?.azureKeyVaultUri;return kOe(I,e)}function kOe(t,e){return new LOe(t,e)}var LOe,xOe=m(()=>{"use strict";due();UOt();LOe=class{client;logger;constructor(e,I){if(this.logger=I,e){this.logger.debug(`Using Azure Key Vault at ${e}`);let l=new H0;this.client=new Bpe(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}}}});import{readFileSync as bnl}from"fs";import{dirname as mnl,join as BOe}from"path";import{fileURLToPath as unl}from"url";function SOe(){return MOt().version}function MOt(){if(a7!==null)return a7;try{let t=unl(import.meta.url),e=mnl(t),I=[BOe(e,"package.json"),BOe(e,"../package.json"),BOe(e,"../../package.json")];for(let n of I)try{let r=JSON.parse(bnl(n,"utf8")),a={name:r.name||"unknown",version:r.version||"unknown",buildMetadata:r.buildMetadata};return a7=a,a}catch{continue}let l={name:"unknown",version:"unknown"};return a7=l,l}catch{let e={name:"unknown",version:"unknown"};return a7=e,e}}function hnl(t){return t.replace(/^@.*\//,"")}function Spe(t){let e=MOt(),I=hnl(e.name),l=t?.clientName?`client/${t.clientName} `:"",n=process.env.TERM_PROGRAM??"unknown";return`${I}/${e.version} (${l}${process.platform} ${process.version}) term/${n}`}var a7,zpe=m(()=>{"use strict";a7=null});import{spawnSync as pnl}from"child_process";import{createHmac as Znl}from"crypto";var TOt,Upe,jOt=m(()=>{"use strict";TOt="askpass:",Upe=class t{static encode(e,I){if(e.startsWith(TOt)){let l=e.slice(TOt.length);I?.debug("[HMACEncoder] Detected askpass command mode, executing command");let n=t.executeAskpassCommand(l,I);return I?.debug(`[HMACEncoder] Askpass command returned token (length: ${n.length}, format: ${t.describeTokenFormat(n)})`),n}return I?.debug("[HMACEncoder] Using standard HMAC key encoding"),t.encodeWithKey(e)}static describeTokenFormat(e){if(!e)return"empty";let I=e.split(".");if(I.length===2){let[n,r]=I,a=/^\d+$/.test(n),s=/^[A-Fa-f0-9]+$/.test(r);if(a&&s)return`valid HMAC format (timestamp.signature, signature length: ${r.length})`}let l=/[^A-Za-z0-9]/.test(e);return`unknown format (length: ${e.length}, has special chars: ${l})`}static executeAskpassCommand(e,I){let l=e.split(" ").filter(c=>c.length>0),n=l[0],r=l.slice(1);I?.debug(`[HMACEncoder] Executing askpass command: ${n} with ${r.length} argument(s)`);let a=pnl(n,r,{encoding:"utf8",timeout:1e4,maxBuffer:1024*1024});if(a.error)throw I?.debug(`[HMACEncoder] Askpass command spawn error: ${a.error.message}`),new Error(`Failed to execute HMAC askpass command: ${a.error.message}`);if(I?.debug(`[HMACEncoder] Askpass command completed with exit code: ${a.status}`),a.status!==0){let c=a.stderr?.trim()||"";throw I?.debug(`[HMACEncoder] Askpass command failed with stderr: ${c||"(empty)"}`),new Error(`HMAC askpass command exited with code ${a.status}${c?`: ${c}`:""}`)}let s=a.stdout?.trim();if(!s)throw I?.debug("[HMACEncoder] Askpass command returned empty stdout"),new Error("HMAC askpass command returned empty token");return I?.debug(`[HMACEncoder] Askpass command stdout length: ${s.length} characters`),s}static encodeWithKey(e){let I=t.hmacGetBytes(e),a=(Math.floor(Date.now()/1e3)+30).toString(),s=Buffer.from(a,"ascii"),i=Znl("sha256",I).update(s).digest().toString("hex").toUpperCase();return`${a}.${i}`}static hmacGetBytes(e){return Buffer.from(e,"ascii")}}});var Wnl,Nnl,DOt,WH,Z9,W9,s7=m(()=>{"use strict";q8();xOe();_i();eV();DG();KI();zpe();jOt();Wnl="X-GitHub-Api-Version",Nnl="2025-05-01",DOt=["https://api.enterprise.githubcopilot.com","https://api.business.githubcopilot.com","https://api.individual.githubcopilot.com"],WH=class t extends ZI{constructor(I,l,n,r,a){let s=a?void 0:_B()?"debug":"info";super({baseURL:I,apiKey:"",logLevel:s});this.headers=l;this.runnerLogger=n;this.hmacKey=r}static baseHeaders={"Content-Type":"application/json",Accept:"application/json","X-Interaction-Type":"conversation-agent","Openai-Intent":"conversation-agent","X-Initiator":"user",[Wnl]:Nnl};hmacKey;additionalHeaders={};static createWithOAuthToken(I,l,n,r,a,s,c,o){let i={...this.defaultHeaders(n,a,o),Authorization:`Bearer ${r}`,...s??{}};return I.debug(`Creating copilot-client for integration ID ${n} with token authentication. User-agent: ${i["User-Agent"]}`),new t(l,i,I,void 0,c)}static createWithHmac(I,l,n,r,a,s,c,o,i){let d={...this.defaultHeaders(n,a,i),Authorization:"",...c??{}};return s&&(d["X-GitHub-User"]=s),I.debug(`Creating copilot-client for integration ID ${n} with HMAC key authentication. User-agent: ${d["User-Agent"]}`),new t(l,d,I,r,o)}static defaultHeaders(I,l,n){return{...t.baseHeaders,"Copilot-Integration-Id":I,"X-Interaction-Id":l,"User-Agent":Spe(n)}}async prepareOptions(I){this.hmacKey&&(this.headers["Request-HMAC"]=Upe.encode(this.hmacKey,this.runnerLogger)),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[r,a]of Object.entries(I.headers))typeof a=="string"&&(l[r]=a);let n=[this.baseURL];if(DOt.includes(this.baseURL))for(let r of DOt)r!==this.baseURL&&n.push(r);for(let r of n){let a=`${r}/models`,s=await fetch(a,{method:I.method,headers:l});if(s.ok){let c=await s.json();return this.runnerLogger.debug(`Successfully listed ${c.data.length} models`),c.data}if(s.status===421){this.runnerLogger.debug(`Failed to list models due to subscription-based route ${r}: ${s.status} ${s.statusText}: ${await s.text()}`);continue}return this.runnerLogger.error(`Failed to list models due to non-retryable error: ${s.status} ${s.statusText}: ${await s.text()}`),[]}return this.runnerLogger.error("Failed to list models"),[]}},Z9=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,r=e.api?.copilot?.hmacKey,a=!!(r||n);if(!a){I.debug("No Copilot HMAC key or GitHub OAuth token provided, trying secret provider");let d=OOt(e,I);try{r=await d.getSecret("dev-CapiHmacKey")}catch(G){I.debug(`Failed to get Copilot HMAC key from secret provider:
|
|
1721
1721
|
${Fe(G)}`)}try{n=await d.getSecret("capi-token")}catch(G){I.debug(`Failed to get Copilot GitHub OAuth token from secret provider:
|
|
1722
1722
|
${Fe(G)}`)}a=!!(r||n)}let s,c=lqe(e),o=jB(e),i=e.api?.copilot?.sessionId??p2(e);if(I.debug(`Using Copilot API at ${c} with integration ID ${o}`),n&&(I.debug("Using GitHub OAuth token for Copilot API"),s=WH.createWithOAuthToken(I,c,o,n,i,l?.requestHeaders,l?.disableHttpLogging,e)),r){I.debug("Using Copilot HMAC key for Copilot API");let d=process.env.GITHUB_USER_ID;d?I.debug(`Using user ID ${d} for Copilot HMAC key`):I.debug("No user ID provided for Copilot HMAC key"),s=WH.createWithHmac(I,c,o,r,i,d,l?.requestHeaders,l?.disableHttpLogging,e)}if(s===void 0)throw new Error("No GitHub OAuth token or Copilot HMAC key provided");return s}},W9=class t extends Rs{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 Rs)))return new t(e)}}});function ynl(t){let e=t,I=!1;for(;e;){if(typeof e=="object"&&e!==null&&"message"in e&&typeof e.message=="string"&&(e instanceof TypeError&&e.message.includes("terminated")&&(I=!0),"name"in e&&e.name==="TypeError"&&e.message.includes("terminated")&&(I=!0),e.message.includes("GOAWAY")||e.message.includes("UND_ERR_SOCKET")))return!0;e=typeof e=="object"&&e!==null&&"cause"in e?e.cause:void 0}return I}function gnl(t){let e=new ZI.APIError(503,{error:{message:"HTTP/2 GOAWAY connection terminated",type:"connection_error"}},"HTTP/2 GOAWAY connection terminated",new Headers);return e.cause=t,e}function Vnl(t){let e=0;return t.choices?.forEach(I=>{e+=new TextEncoder().encode(I.delta?.content??"").length,I.delta?.tool_calls?.forEach(l=>{l.function&&(e+=new TextEncoder().encode(l.function.name).length,e+=new TextEncoder().encode(l.function.arguments??"").length)})}),e}function Rnl(t,e,I){let l=new Map,n=new Set;return new _h(async function*(){for await(let r of t)r.choices?.forEach(a=>{if(a.delta){let c=!!(a.delta.content||a.delta.tool_calls?.length||a.delta.refusal),o=!n.has(a.index);!a.delta.role&&(c||o)&&(a.delta.role="assistant",n.add(a.index))}if(!!a.delta?.tool_calls?.length){a.delta&&!a.delta.role&&(a.delta.role="assistant",n.add(a.index)),a.finish_reason??="tool_calls";let c=l.get(a.index);c||(c={nextSequenceNumber:0,mappings:new Map},l.set(a.index,c)),a.delta.tool_calls?.forEach(o=>{let i=c.mappings.get(o.index);if(i!==void 0)o.id&&i.callId!==o.id&&(i.sequenceNumber=c.nextSequenceNumber++,i.callId=o.id),o.index=i.sequenceNumber;else{let d={callId:o.id,sequenceNumber:c.nextSequenceNumber++};c.mappings.set(o.index,d),o.index=d.sequenceNumber}})}}),r.choices?.some(a=>!a.finish_reason)&&I.debug(`Chunk received with choices missing finish_reason: ${JSON.stringify(r,null,2)}`),yield r},t.controller,e)}function Anl(t,e){t.forEach(I=>{if(Mn(I)){I.function.name=I.function.name.replace(/[^a-zA-Z0-9_-]+/g,"_");try{MF(I.function.arguments)}catch(l){if(l instanceof SyntaxError){let n=I.function.name,r=I.function.arguments;e.set(I.id,{textResultForLlm:`The arguments for the tool call '${n}' were not valid JSON. The arguments have been cleared. Arguments: ${r}. JSON parse error: ${l.message}`,resultType:"failure",error:`${l.message}`,sessionLog:`<error>Failed to execute \`${n}\` tool with arguments: ${r} due to syntax error: ${l.message}</error>`,toolTelemetry:{properties:{wasSyntaxError:"true"}}}),I.function.arguments="{}"}}}else pN(I)&&(I.custom.name=I.custom.name.replace(/[^a-zA-Z0-9_-]+/g,"_"))})}var Ynl,iw,Ope=m(()=>{"use strict";q8();vUt();ape();JUt();$g();$8();KI();V8();ty();Nj();_i();Ji();zc();Zj();IOe();BUt();s7();pJ();Fm();Ynl={type:"ephemeral"};iw=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 r=await this.getModel();return l.debug(`Got model info: ${JSON.stringify(r,null,2)}`),r})}clientOptions;clientPromise;modelPromise;get model(){return this.clientOptions.model}static initDefaultOptions(e){return{model:e?.model||gpe["sweagent-capi"],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??{},disableHttpLogging:e?.disableHttpLogging??!1,enableCacheControl:e?.enableCacheControl??!1}}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,r,a,s){return e.chat.completions.create({model:I,messages:[...l],...n,tools:r},{maxRetries:a,headers:s?.requestHeaders,signal:s?.abortSignal}).withResponse()}async makeRequestStreaming(e,I,l,n,r,a,s){let c=Date.now(),o=await e.chat.completions.create({model:I,messages:[...l],...n,tools:r,stream:!0,stream_options:{include_usage:!0}},{maxRetries:a,headers:s?.requestHeaders,signal:s?.abortSignal}).withResponse(),i=Rnl(o.data,e,this.logger).toReadableStream(),d=Wg.fromReadableStream(i),G=s?.processors?.onStreamingChunk,b,u,h,p=0,W=0;if(G?.length){let N=ro();for await(let y of d){s?.abortSignal?.throwIfAborted();let g=Date.now();if(b===void 0)b=g-c;else if(h!==void 0){let v=g-h;W+=v,p++}h=g;let Q=y.choices?.[0],f={content:Q?.delta?.content??void 0,reportIntentArguments:void 0,size:Vnl(y),streamingId:N};if(Q?.delta?.tool_calls){for(let v of Q.delta.tool_calls)if(v.function?.name===UN&&v.function?.arguments){f.reportIntentArguments=v.function.arguments;break}}if(f.content||f.reportIntentArguments||f.size>0)for(let v of G)v.onStreamingChunk(f)}}return p>0&&(u=W/p),{data:await d.finalChatCompletion(),response:o.response,request_id:o.request_id,ttftMs:b,interTokenLatencyMs:u}}async*getCompletionWithTools(e,I,l,n){let r=this.model,a=await this.clientPromise,s=await this.modelPromise,c=M3(l),o=this.clientOptions.enableCacheControl?Ynl:void 0,i=[{role:"system",content:e,copilot_cache_control:o},...I.map(p=>Q3(p))],d=l.map((p,W)=>{let N=W===l.length-1?o:void 0;return p.type==="custom"?{type:"custom",custom:{name:p.name,description:p.description,format:p.format?{type:"grammar",grammar:{syntax:p.format.syntax,definition:p.format.definition}}:void 0},copilot_cache_control:N}:{type:"function",function:{name:p.name,description:p.description,parameters:p.input_schema},copilot_cache_control:N}});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(d,null,2)),this.logger.endGroup(8);let G=this.getCompletionOptions(l,n),b=n?.initialTurnCount!==void 0?n.initialTurnCount+1:0,u=!1,h=!1;for(;!u&&!h;){let p=Date.now();yield{kind:"turn_started",model:r,modelInfo:s,turn:b,timestampMs:p};let W=0,N=0,y=0,g=[429,503,500,400],Q=this.clientOptions.retryPolicy.maxRetries,f=this.clientOptions.retryPolicy.rateLimitRetryPolicy.initialRetryBackoffExtraSeconds,v=0,X=this.clientOptions.retryPolicy.rateLimitRetryPolicy.maxRetryAfterSeconds,J,B;try{let H=[],te;do{y>0&&(yield{kind:"turn_retry",model:r,modelInfo:s,turn:b,timestampMs:Date.now()});try{let ee={};for(let me of n?.processors?.preRequest||[]){let Je=me.preRequest({turn:b,retry:y,messages:i,toolDefinitions:d,modelInfo:s,additionalRequestHeaders:ee,getCompletionWithToolsOptions:n});for await(let Rt of Je)yield Rt}if(this.logger.startGroup("Sending request to the AI model",8),_n(this.settings,"copilot_swe_agent_request_logging")){let me=JSON.stringify(i,null,2),Je=JSON.stringify(G,null,2);this.logger.debug(`Request messages: ${me}`),this.logger.debug(`Request options: ${Je}`)}H=i.map((me,Je)=>Je===i.length-1?{...me,copilot_cache_control:o}:me),W=Date.now(),a.setAdditionalHeaders(ee);let ve;n?.stream?ve=await this.makeRequestStreaming(a,r,H,G,d,Q,n):ve=await this.makeRequest(a,r,H,G,d,Q,n),N=Date.now()-W,J=ve.data,te={model:r,api_id:J.id,request_id:ve.response.headers.get("x-github-request-id")||void 0,initiator:n?.requestHeaders?.["X-Initiator"]||ee["X-Initiator"]};let fe={};ve.response.headers.forEach((me,Je)=>{if(Je.toLowerCase().startsWith(lOe)){let Rt=xUt(me);Rt&&(fe[Je.replace(lOe,"")]=Rt)}}),yield{kind:"model_call_success",turn:b,callId:n?.callId,modelCallDurationMs:N,ttftMs:ve.ttftMs,interTokenLatencyMs:ve.interTokenLatencyMs,modelCall:te,responseChunk:Mse(J),responseUsage:J.usage,requestMessages:JSON.stringify(H),quotaSnapshots:fe},this.logger.debug(`response (Request-ID ${ve.request_id}):`),this.logger.debug("data:"),this.logger.debug(JSON.stringify(ve.data,null,2))}catch(ee){N=Date.now()-W;let ve=ee;ynl(ee)&&(ve=gnl(ee));let me=W9.fromAPIError(ve),Je=me?.error;if(me){yield{kind:"model_call_failure",turn:b,callId:n?.callId,modelCallDurationMs:N,requestMessages:JSON.stringify(H),modelCall:{model:r,status:me.status,error:JSON.stringify(me?.error||me?.message||"unknown error"),api_id:me.requestID||void 0,request_id:me.headers?.get("x-github-request-id")||""}},B=me;let ze=me.ghRequestId||me.headers?.get("x-github-request-id")||me.requestID;this.logger.error(`error (Request-ID ${ze})`),this.logger.error(JSON.stringify(_8(me),null,2)),this.logger.debug(`Failed to get response from the AI model: ${Fe(me)}`),Je&&this.logger.debug(`Inner error: ${JSON.stringify(_8(Je),null,2)}`);let Ut;for(let lI of n?.processors?.onRequestError||[])Ut=await lI.onRequestError({turn:b,retry:y,maxRetries:Q,error:Je,modelInfo:s,getCompletionWithToolsOptions:n})||Ut;let bt=me.status,ue=bt?this.clientOptions.retryPolicy.errorCodesToRetry.some(lI=>Array.isArray(lI)?bt>=lI[0]&&(lI[1]===void 0||bt<=lI[1]):bt===lI):!1,tt;if(Ut)tt=Ut.retryAfter;else if(me.status!==402){if(me.status===413){this.logger.debug("Request is too large, trying to remove images from the request");let lI=0;for(let cn=i.length-1;cn>=0;cn--)jN(i[cn])&&(i.splice(cn,1),lI++,yield{kind:"images_removed",turn:b,imagesRemoved:1,largeImagesRemoved:1});lI>0?(this.logger.info(`Images have been removed from the request due to size constraints. Please resize images to be smaller than ${$Y(s.capabilities.limits.vision?.max_prompt_image_size||0)}.`),this.logger.debug(`Removed ${lI} image messages from the request`),tt=1):this.logger.debug("No image messages found in the request - unsure why the request is too large - will fail")}else if((typeof me.status=="number"&&g.includes(me.status)||ue)&&(tt=parseInt(me.headers?.get("retry-after")||`${this.clientOptions.retryPolicy.rateLimitRetryPolicy.defaultRetryAfterSeconds}`,10)+f,f*=this.clientOptions.retryPolicy.rateLimitRetryPolicy.retryBackoffExtraGrowth,y==Q-1))for(let lI=i.length-1;lI>=0;lI--)jN(i[lI])&&(this.logger.debug(`Removing image message at index ${lI} to avoid failure`),i.splice(lI,1),yield{kind:"images_removed",turn:b,imagesRemoved:1})}if(tt!==void 0&&tt<=X){let lI=.8+Math.random()*.4,cn=tt*lI;this.logger.debug(`Retrying after ${cn} seconds...`),await new Promise(de=>setTimeout(de,cn*1e3)),v+=cn,this.logger.debug(`Retrying after ${tt} seconds... Will try again now!`);continue}else tt?this.logger.error(`Retry after ${tt} seconds is too long. Giving up.`):this.logger.error("Retry after is not set. Giving up.")}let Rt=me||ee;for(let ze of n?.processors?.onRequestError||[])await ze.preErrorThrow(ee);throw this.logger.error("error"),this.logger.error(JSON.stringify(_8(Rt),null,2)),Rt}finally{a.setAdditionalHeaders({}),this.logger.endGroup(8)}}while(!J&&y++<Q);if(!J){this.logger.debug("Recent messages prior to failure:");for(let ve=Math.max(0,i.length-6);ve<i.length;ve++)this.logger.debug(`${ve}: ${JSON.stringify(i[ve],null,2)}`);let ee=new Error(`Failed to get response from the AI model; retried ${y-1} times (total retry wait time: ${v} seconds)`,{cause:B});throw this.isRateLimitExceededError(ee)&&(this.logger.info(`Rate limit exceeded after ${y-1} retries, will fail job but skip Sentry reporting`),ee.skipReport=!0),ee}let Qe=new Map,C=J.choices||[];if(C.length===0){let ee={role:"assistant",content:null,refusal:null};i.push(ee),yield{kind:"message",turn:b,callId:n?.callId,modelCall:te,message:Q3(vE(ee))}}else for(let ee of C.map(ve=>ve.message))ee.tool_calls&&Anl(ee.tool_calls,Qe),i.push(ee),yield{kind:"message",turn:b,callId:n?.callId,modelCall:te,message:Q3(vE(ee))};if(this.isToolCallResponse(J)){let ve=(s.capabilities.limits.max_prompt_tokens||s.capabilities.limits.max_context_window_tokens)*this.clientOptions.toolTokenBudgetProportion,fe=O2t(r,ve,this,this.settings,n?.abortSignal),Je=J.choices.filter(Ut=>Ut.message.tool_calls!==void 0).flatMap(Ut=>Ut.message.tool_calls||[]).filter(Ale);for(let Ut of n?.processors?.preToolsExecution||[]){let bt=await Ut.preToolsExecution({turn:b,toolCalls:Je,modelInfo:s});if(bt)for(let[ue,tt]of bt)Qe.set(ue,tt)}let Rt=Je.filter(Ut=>!Qe.has(Ut.id)),ze=this.mergeToolResults(Qe,Je,Rt,c,fe,n?.executeToolsInParallel,n?.abortSignal);for await(let Ut of ze){Ut.toolResult.resultType==="rejected"&&(h=!0);let bt={role:"tool",tool_call_id:Ut.originalCall.id,content:Ut.toolResult.textResultForLlm};i.push(bt),yield{kind:"message",turn:b,callId:n?.callId,modelCall:te,message:Q3(bt)},yield{kind:"tool_execution",turn:b,callId:n?.callId,toolCallId:Ut.originalCall.id,toolResult:Ut.toolResult,durationMs:Ut.durationMs};for(let ue of n?.processors?.postToolExecution||[])await ue.postToolExecution({toolCall:Ut.originalCall,toolResult:Ut.toolResult,turn:b,modelInfo:s})}}else for(let ee of J.choices.map(ve=>ve.message))yield{kind:"response",turn:b,callId:n?.callId,modelCall:{model:r,api_id:J.id},response:Q3(vE(ee))},u=!0}catch(H){let te;throw H instanceof Error&&H.cause&&H.cause instanceof W9?te=`${Fe(H)} (Cause: ${Fe(H.cause)})`:te=`${Fe(H)}`,H instanceof TypeError&&te.includes("terminated")&&(this.logger.error(`Model call terminated unexpectedly during turn ${b}`),this.logger.error(`Serialized error: ${JSON.stringify(_8(H),null,2)}`)),yield{kind:"turn_failed",model:r,modelInfo:s,turn:b,error:te,timestampMs:Date.now()},H}finally{let H=Date.now();yield{kind:"turn_ended",model:r,modelInfo:s,turn:b,timestampMs:H},b++}}}async*mergeToolResults(e,I,l,n,r,a=!1,s){for(let[c,o]of e){let i=I.find(d=>d.id===c);i&&(yield{durationMs:0,originalCall:i,toolResult:o})}l.length>0&&(yield*this.callTools(l,n,r,a,s))}async*callTools(e,I,l,n=!1,r){if(e.length===0)throw new Error("Tool call is missing");this.logger.debug(`Tool calls count: ${e.length}`);let a=e.some(c=>{let o=Mn(c)?c.function.name:c.custom.name,i=I[o];return cw(i)}),s=n&&!a;if(a&&n&&this.logger.debug("Custom agent detected in tool calls, forcing sequential execution"),s)this.logger.debug("Running tool calls in parallel"),yield*Clt(e.map(c=>()=>this.callTool(c,I,l)),r);else{this.logger.debug("Running tool calls sequentially");for(let c of e)r?.throwIfAborted(),yield await this.callTool(c,I,l)}}async callTool(e,I,l){let n=0,r=Mn(e)?e.function.name:e.custom.name;if(!r)throw new Error("Tool name is missing");let a=e.id;if(!a)throw new Error("Tool call id is missing");let s,c=I[r];try{let o;if(Mn(e)){let i=e.function.arguments;if(i==null)throw new Error("Tool call arguments are missing");o=MF(i)}else o=e.custom.input;if(!c||!c.callback)s={textResultForLlm:`Tool '${r}' does not exist. Available tools that can be called are ${Object.keys(I).join(", ")}.`,resultType:"failure",error:`Tool '${r}' does not exist.`,sessionLog:`<error>Tool '${r}' does not exist.</error>`,toolTelemetry:{}};else{let i=c.callback,d=Date.now(),G={...l,toolCallId:a,toolOptions:this.settings.service?.tools?.[r]},b=await i(o,G);n=Date.now()-d,s=typeof b=="string"?{textResultForLlm:b,resultType:"success",toolTelemetry:{}}:b}}catch(o){let i=Mn(e)?e.function.arguments:e.custom.input;s={textResultForLlm:`Failed to execute \`${r}\` tool with arguments: ${i} due to error: ${Fe(o)}`,resultType:"failure",error:o instanceof Error?o.message:`${Fe(o)}`,sessionLog:`<error>Failed to execute \`${r}\` tool with arguments: ${i}</error>`,toolTelemetry:{}}}return{durationMs:n,originalCall:e,toolResult:s}}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 W9)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(a=>a.id===e).at(0)||I}}});var Mpe,KOt=m(()=>{"use strict";Ope();s7();Mpe=class extends iw{constructor(e,I,l){let n=new Z9;super(n,e,I,l)}}});var N9,zOe=m(()=>{"use strict";$g();ty();Zj();Ope();N9=class extends iw{makeResponsesRequest(e,I,l,n,r,a,s,c){let o=l.find(W=>W.role==="system")?.content||"",i=Array.isArray(o)?o.join(`
|
|
1723
1723
|
`):o,G=l.filter(W=>W.role!=="system").flatMap(hNt),b=r.filter(W=>W.type==="function").map(W=>({name:W.function.name,description:W.function.description,parameters:W.function.parameters||null,strict:!1,type:"function"})),u=r.filter(W=>W.type==="custom").map(W=>({name:W.custom.name,description:W.custom.description,type:"custom",format:W.custom.format?W.custom.format.type==="grammar"?{type:"grammar",syntax:W.custom.format.grammar.syntax,definition:W.custom.format.grammar.definition}:{type:"text"}:void 0})),h=[...b,...u];this.logger.debug(`Making responses request with input: ${JSON.stringify(G,null,2)}`);let p={summary:"auto",effort:"medium"};return e.responses.create({model:I,previous_response_id:void 0,instructions:i,input:G,parallel_tool_calls:r.length>0?!0:void 0,tools:h,reasoning:p,store:!1,...c?{stream:!0}:{},include:["reasoning.encrypted_content"]},{maxRetries:a||this.clientOptions.retryPolicy.maxRetries,headers:s?.requestHeaders,signal:s?.abortSignal}).withResponse()}makeRequest(e,I,l,n,r,a,s){return this.makeResponsesRequest(e,I,l,n,r,a,s).then(c=>VXe(c))}async makeRequestStreaming(e,I,l,n,r,a,s){let c=Date.now(),o=await this.makeResponsesRequest(e,I,l,n,r,a,s,!0),i=null,d,G,b,u=0,h=0,p=new Map,W=0,N=new Set,y="",g=!1,Q=s?.processors?.onStreamingChunk,f=()=>{let v=Date.now();d===void 0?d=v-c:b!==void 0&&(h+=v-b,u++),b=v};try{let v=o.request_id??ro();for await(let X of o.data){if(s?.abortSignal?.throwIfAborted(),X.type==="response.completed"){i=X.response;continue}let J={content:void 0,reportIntentArguments:void 0,size:0,streamingId:v};if(X.type==="response.output_text.delta"&&(f(),J.size+=new TextEncoder().encode(X.delta).length,J.content=X.delta),X.type==="response.reasoning_summary_part.added"&&(g&&y.length>0&&(y+=`
|
|
@@ -1941,7 +1941,7 @@ Focus particularly on:
|
|
|
1941
1941
|
Include all important tool calls and their results as part of the appropriate sections, with special emphasis on the most recent operations.`});var RWe,aPt=m(()=>{"use strict";RWe=class{async exec(){return 0}async execReturn(){return{exitCode:0,stdout:"",stderr:""}}}});var fPt=Y((G_,$9)=>{var xbl=200,hPt="__lodash_hash_undefined__",Bbl=800,Sbl=16,pPt=9007199254740991,ZPt="[object Arguments]",zbl="[object Array]",Ubl="[object AsyncFunction]",Obl="[object Boolean]",Mbl="[object Date]",Tbl="[object Error]",WPt="[object Function]",jbl="[object GeneratorFunction]",Dbl="[object Map]",Kbl="[object Number]",Pbl="[object Null]",NPt="[object Object]",qbl="[object Proxy]",_bl="[object RegExp]",$bl="[object Set]",eml="[object String]",tml="[object Undefined]",Iml="[object WeakMap]",lml="[object ArrayBuffer]",nml="[object DataView]",rml="[object Float32Array]",aml="[object Float64Array]",sml="[object Int8Array]",cml="[object Int16Array]",oml="[object Int32Array]",iml="[object Uint8Array]",dml="[object Uint8ClampedArray]",Gml="[object Uint16Array]",bml="[object Uint32Array]",mml=/[\\^$.*+?()[\]{}|]/g,uml=/^\[object .+?Constructor\]$/,hml=/^(?:0|[1-9]\d*)$/,Va={};Va[rml]=Va[aml]=Va[sml]=Va[cml]=Va[oml]=Va[iml]=Va[dml]=Va[Gml]=Va[bml]=!0;Va[ZPt]=Va[zbl]=Va[lml]=Va[Obl]=Va[nml]=Va[Mbl]=Va[Tbl]=Va[WPt]=Va[Dbl]=Va[Kbl]=Va[NPt]=Va[_bl]=Va[$bl]=Va[eml]=Va[Iml]=!1;var YPt=typeof global=="object"&&global&&global.Object===Object&&global,pml=typeof self=="object"&&self&&self.Object===Object&&self,u_=YPt||pml||Function("return this")(),yPt=typeof G_=="object"&&G_&&!G_.nodeType&&G_,b_=yPt&&typeof $9=="object"&&$9&&!$9.nodeType&&$9,gPt=b_&&b_.exports===yPt,qje=gPt&&YPt.process,sPt=(function(){try{var t=b_&&b_.require&&b_.require("util").types;return t||qje&&qje.binding&&qje.binding("util")}catch{}})(),cPt=sPt&&sPt.isTypedArray;function Zml(t,e,I){switch(I.length){case 0:return t.call(e);case 1:return t.call(e,I[0]);case 2:return t.call(e,I[0],I[1]);case 3:return t.call(e,I[0],I[1],I[2])}return t.apply(e,I)}function Wml(t,e){for(var I=-1,l=Array(t);++I<t;)l[I]=e(I);return l}function Nml(t){return function(e){return t(e)}}function Yml(t,e){return t?.[e]}function yml(t,e){return function(I){return t(e(I))}}var gml=Array.prototype,Vml=Function.prototype,wWe=Object.prototype,_je=u_["__core-js_shared__"],QWe=Vml.toString,vg=wWe.hasOwnProperty,oPt=(function(){var t=/[^.]+$/.exec(_je&&_je.keys&&_je.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""})(),VPt=wWe.toString,Rml=QWe.call(Object),Aml=RegExp("^"+QWe.call(vg).replace(mml,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),AWe=gPt?u_.Buffer:void 0,iPt=u_.Symbol,dPt=u_.Uint8Array,GPt=AWe?AWe.allocUnsafe:void 0,RPt=yml(Object.getPrototypeOf,Object),bPt=Object.create,Fml=wWe.propertyIsEnumerable,wml=gml.splice,kH=iPt?iPt.toStringTag:void 0,FWe=(function(){try{var t=nDe(Object,"defineProperty");return t({},"",{}),t}catch{}})(),Qml=AWe?AWe.isBuffer:void 0,mPt=Math.max,Eml=Date.now,APt=nDe(u_,"Map"),m_=nDe(Object,"create"),vml=(function(){function t(){}return function(e){if(!BH(e))return{};if(bPt)return bPt(e);t.prototype=e;var I=new t;return t.prototype=void 0,I}})();function xH(t){var e=-1,I=t==null?0:t.length;for(this.clear();++e<I;){var l=t[e];this.set(l[0],l[1])}}function Xml(){this.__data__=m_?m_(null):{},this.size=0}function Hml(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}function Cml(t){var e=this.__data__;if(m_){var I=e[t];return I===hPt?void 0:I}return vg.call(e,t)?e[t]:void 0}function fml(t){var e=this.__data__;return m_?e[t]!==void 0:vg.call(e,t)}function Jml(t,e){var I=this.__data__;return this.size+=this.has(t)?0:1,I[t]=m_&&e===void 0?hPt:e,this}xH.prototype.clear=Xml;xH.prototype.delete=Hml;xH.prototype.get=Cml;xH.prototype.has=fml;xH.prototype.set=Jml;function Xg(t){var e=-1,I=t==null?0:t.length;for(this.clear();++e<I;){var l=t[e];this.set(l[0],l[1])}}function Lml(){this.__data__=[],this.size=0}function kml(t){var e=this.__data__,I=EWe(e,t);if(I<0)return!1;var l=e.length-1;return I==l?e.pop():wml.call(e,I,1),--this.size,!0}function xml(t){var e=this.__data__,I=EWe(e,t);return I<0?void 0:e[I][1]}function Bml(t){return EWe(this.__data__,t)>-1}function Sml(t,e){var I=this.__data__,l=EWe(I,t);return l<0?(++this.size,I.push([t,e])):I[l][1]=e,this}Xg.prototype.clear=Lml;Xg.prototype.delete=kml;Xg.prototype.get=xml;Xg.prototype.has=Bml;Xg.prototype.set=Sml;function eB(t){var e=-1,I=t==null?0:t.length;for(this.clear();++e<I;){var l=t[e];this.set(l[0],l[1])}}function zml(){this.size=0,this.__data__={hash:new xH,map:new(APt||Xg),string:new xH}}function Uml(t){var e=XWe(this,t).delete(t);return this.size-=e?1:0,e}function Oml(t){return XWe(this,t).get(t)}function Mml(t){return XWe(this,t).has(t)}function Tml(t,e){var I=XWe(this,t),l=I.size;return I.set(t,e),this.size+=I.size==l?0:1,this}eB.prototype.clear=zml;eB.prototype.delete=Uml;eB.prototype.get=Oml;eB.prototype.has=Mml;eB.prototype.set=Tml;function tB(t){var e=this.__data__=new Xg(t);this.size=e.size}function jml(){this.__data__=new Xg,this.size=0}function Dml(t){var e=this.__data__,I=e.delete(t);return this.size=e.size,I}function Kml(t){return this.__data__.get(t)}function Pml(t){return this.__data__.has(t)}function qml(t,e){var I=this.__data__;if(I instanceof Xg){var l=I.__data__;if(!APt||l.length<xbl-1)return l.push([t,e]),this.size=++I.size,this;I=this.__data__=new eB(l)}return I.set(t,e),this.size=I.size,this}tB.prototype.clear=jml;tB.prototype.delete=Dml;tB.prototype.get=Kml;tB.prototype.has=Pml;tB.prototype.set=qml;function _ml(t,e){var I=IDe(t),l=!I&&tDe(t),n=!I&&!l&&EPt(t),r=!I&&!l&&!n&&XPt(t),a=I||l||n||r,s=a?Wml(t.length,String):[],c=s.length;for(var o in t)(e||vg.call(t,o))&&!(a&&(o=="length"||n&&(o=="offset"||o=="parent")||r&&(o=="buffer"||o=="byteLength"||o=="byteOffset")||wPt(o,c)))&&s.push(o);return s}function $je(t,e,I){(I!==void 0&&!HWe(t[e],I)||I===void 0&&!(e in t))&&lDe(t,e,I)}function $ml(t,e,I){var l=t[e];(!(vg.call(t,e)&&HWe(l,I))||I===void 0&&!(e in t))&&lDe(t,e,I)}function EWe(t,e){for(var I=t.length;I--;)if(HWe(t[I][0],e))return I;return-1}function lDe(t,e,I){e=="__proto__"&&FWe?FWe(t,e,{configurable:!0,enumerable:!0,value:I,writable:!0}):t[e]=I}var eul=bul();function vWe(t){return t==null?t===void 0?tml:Pbl:kH&&kH in Object(t)?mul(t):Nul(t)}function uPt(t){return h_(t)&&vWe(t)==ZPt}function tul(t){if(!BH(t)||Zul(t))return!1;var e=aDe(t)?Aml:uml;return e.test(Vul(t))}function Iul(t){return h_(t)&&vPt(t.length)&&!!Va[vWe(t)]}function lul(t){if(!BH(t))return Wul(t);var e=QPt(t),I=[];for(var l in t)l=="constructor"&&(e||!vg.call(t,l))||I.push(l);return I}function FPt(t,e,I,l,n){t!==e&&eul(e,function(r,a){if(n||(n=new tB),BH(r))nul(t,e,a,I,FPt,l,n);else{var s=l?l(eDe(t,a),r,a+"",t,e,n):void 0;s===void 0&&(s=r),$je(t,a,s)}},HPt)}function nul(t,e,I,l,n,r,a){var s=eDe(t,I),c=eDe(e,I),o=a.get(c);if(o){$je(t,I,o);return}var i=r?r(s,c,I+"",t,e,a):void 0,d=i===void 0;if(d){var G=IDe(c),b=!G&&EPt(c),u=!G&&!b&&XPt(c);i=c,G||b||u?IDe(s)?i=s:Rul(s)?i=iul(s):b?(d=!1,i=sul(c,!0)):u?(d=!1,i=oul(c,!0)):i=[]:Aul(c)||tDe(c)?(i=s,tDe(s)?i=Ful(s):(!BH(s)||aDe(s))&&(i=uul(c))):d=!1}d&&(a.set(c,i),n(i,c,l,r,a),a.delete(c)),$je(t,I,i)}function rul(t,e){return yul(Yul(t,e,CPt),t+"")}var aul=FWe?function(t,e){return FWe(t,"toString",{configurable:!0,enumerable:!1,value:Qul(e),writable:!0})}:CPt;function sul(t,e){if(e)return t.slice();var I=t.length,l=GPt?GPt(I):new t.constructor(I);return t.copy(l),l}function cul(t){var e=new t.constructor(t.byteLength);return new dPt(e).set(new dPt(t)),e}function oul(t,e){var I=e?cul(t.buffer):t.buffer;return new t.constructor(I,t.byteOffset,t.length)}function iul(t,e){var I=-1,l=t.length;for(e||(e=Array(l));++I<l;)e[I]=t[I];return e}function dul(t,e,I,l){var n=!I;I||(I={});for(var r=-1,a=e.length;++r<a;){var s=e[r],c=l?l(I[s],t[s],s,I,t):void 0;c===void 0&&(c=t[s]),n?lDe(I,s,c):$ml(I,s,c)}return I}function Gul(t){return rul(function(e,I){var l=-1,n=I.length,r=n>1?I[n-1]:void 0,a=n>2?I[2]:void 0;for(r=t.length>3&&typeof r=="function"?(n--,r):void 0,a&&hul(I[0],I[1],a)&&(r=n<3?void 0:r,n=1),e=Object(e);++l<n;){var s=I[l];s&&t(e,s,l,r)}return e})}function bul(t){return function(e,I,l){for(var n=-1,r=Object(e),a=l(e),s=a.length;s--;){var c=a[t?s:++n];if(I(r[c],c,r)===!1)break}return e}}function XWe(t,e){var I=t.__data__;return pul(e)?I[typeof e=="string"?"string":"hash"]:I.map}function nDe(t,e){var I=Yml(t,e);return tul(I)?I:void 0}function mul(t){var e=vg.call(t,kH),I=t[kH];try{t[kH]=void 0;var l=!0}catch{}var n=VPt.call(t);return l&&(e?t[kH]=I:delete t[kH]),n}function uul(t){return typeof t.constructor=="function"&&!QPt(t)?vml(RPt(t)):{}}function wPt(t,e){var I=typeof t;return e=e??pPt,!!e&&(I=="number"||I!="symbol"&&hml.test(t))&&t>-1&&t%1==0&&t<e}function hul(t,e,I){if(!BH(I))return!1;var l=typeof e;return(l=="number"?rDe(I)&&wPt(e,I.length):l=="string"&&e in I)?HWe(I[e],t):!1}function pul(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}function Zul(t){return!!oPt&&oPt in t}function QPt(t){var e=t&&t.constructor,I=typeof e=="function"&&e.prototype||wWe;return t===I}function Wul(t){var e=[];if(t!=null)for(var I in Object(t))e.push(I);return e}function Nul(t){return VPt.call(t)}function Yul(t,e,I){return e=mPt(e===void 0?t.length-1:e,0),function(){for(var l=arguments,n=-1,r=mPt(l.length-e,0),a=Array(r);++n<r;)a[n]=l[e+n];n=-1;for(var s=Array(e+1);++n<e;)s[n]=l[n];return s[e]=I(a),Zml(t,this,s)}}function eDe(t,e){if(!(e==="constructor"&&typeof t[e]=="function")&&e!="__proto__")return t[e]}var yul=gul(aul);function gul(t){var e=0,I=0;return function(){var l=Eml(),n=Sbl-(l-I);if(I=l,n>0){if(++e>=Bbl)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}function Vul(t){if(t!=null){try{return QWe.call(t)}catch{}try{return t+""}catch{}}return""}function HWe(t,e){return t===e||t!==t&&e!==e}var tDe=uPt((function(){return arguments})())?uPt:function(t){return h_(t)&&vg.call(t,"callee")&&!Fml.call(t,"callee")},IDe=Array.isArray;function rDe(t){return t!=null&&vPt(t.length)&&!aDe(t)}function Rul(t){return h_(t)&&rDe(t)}var EPt=Qml||Eul;function aDe(t){if(!BH(t))return!1;var e=vWe(t);return e==WPt||e==jbl||e==Ubl||e==qbl}function vPt(t){return typeof t=="number"&&t>-1&&t%1==0&&t<=pPt}function BH(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}function h_(t){return t!=null&&typeof t=="object"}function Aul(t){if(!h_(t)||vWe(t)!=NPt)return!1;var e=RPt(t);if(e===null)return!0;var I=vg.call(e,"constructor")&&e.constructor;return typeof I=="function"&&I instanceof I&&QWe.call(I)==Rml}var XPt=cPt?Nml(cPt):Iul;function Ful(t){return dul(t,HPt(t))}function HPt(t){return rDe(t)?_ml(t,!0):lul(t)}var wul=Gul(function(t,e,I){FPt(t,e,I)});function Qul(t){return function(){return t}}function CPt(t){return t}function Eul(){return!1}$9.exports=wul});async function vul(t={}){let e=await pqe();return cqe((0,JPt.default)({},e,t))}async function sDe(t={}){if(q$())throw new Error("Settings have already been initialized");return vul(t)}var JPt,LPt=m(()=>{"use strict";JPt=pI(fPt(),1);_$();PB()});import{readdir as Xul,stat as Hul}from"fs/promises";async function Cul(t,e){try{let I=await Hul(t);if(I.isDirectory()){let l=await Xul(t);return{path:t,type:"directory",lines:l.length}}else{let l=I.size/1048576;if(I.size>kPt){let r=(kPt/1048576).toFixed(0);return e.debug(`File ${t} is too large (${l.toFixed(1)}MB). Maximum file size is ${r}MB. Skipping line count.`),{path:t,type:"file",sizeMB:l}}let{totalLineCount:n}=await Cle(t,1,void 0);return{path:t,type:"file",lines:n}}}catch(I){return e.debug(`Error getting file info for ${t}: ${Fe(I)}`),{path:t,type:"file",error:Fe(I)}}}async function xPt(t,e){let I=t.filter(r=>!ay(r.path));if(I.length===0)return"";let l=await Promise.all(I.map(r=>Cul(r.path,e))),n=["<tagged_files>"];for(let r of l)r.error?n.push(`* ${r.path} (error: ${r.error})`):r.sizeMB!==void 0?n.push(`* ${r.path} (large file: ${r.sizeMB.toFixed(1)}MB)`):r.type==="directory"?n.push(`* ${r.path} (${r.lines} entries)`):n.push(`* ${r.path} (${r.lines} lines)`);return n.push("</tagged_files>"),n.join(`
|
|
1942
1942
|
`)}async function BPt(t,e){let I=t.filter(n=>n.type==="file"&&ay(n.path));return(await Promise.all(I.map(async n=>{try{let r=await Yce(n.path,e);return r?[{type:"text",text:`Image file at path ${n.path}`},{type:"image_url",image_url:{url:`data:${r.mimeType};base64,${r.base64Data}`}}]:void 0}catch(r){e.error(`Failed to process image ${n.path}: ${r instanceof Error?r.message:String(r)}`);return}}))).filter(n=>n!==void 0).flat()}var kPt,SPt=m(()=>{"use strict";KI();_p();Nce();kPt=10*1024*1024});async function gw(t,e,I){if(!t||t.length===0)return;let l=!1,n={};for(let r of t)try{let a=await r(e);a&&(l=!0,n={...n,...a})}catch(a){I.error(`Hook execution failed: ${Fe(a)}`)}return l?n:void 0}var cDe=m(()=>{"use strict";KI()});async function JZr(t,e,I){return(await oDe(t,e,void 0,I)).filter(r=>u3(r.id)).map(r=>({model:r.id,label:r.name}))}async function oDe(t,e,I,l){if(g9())return[];if(I??=ro(),e??=p_,l??=new qo,t.type==="hmac"){if(sp&&t.type===sp.authInfo.type&&t.hmac===sp.authInfo.hmac)return sp.models;let i=await WH.createWithHmac(l,MB,e,t.hmac,I).listModels();return sp={models:i.filter(G=>SN(G.id,i)),authInfo:t},sp.models}let n=await zN(t);if(!n)throw new Error("Failed to get token for auth info");if(sp&&sp.authInfo.type!=="hmac"&&n===await zN(sp.authInfo))return sp.models;let r=await bC(t.host,n,l),s=await WH.createWithOAuthToken(l,r,e,n,I).listModels();return sp={models:s.filter(o=>SN(o.id,s)),authInfo:t},sp.models}var sp,iDe=m(()=>{"use strict";$g();t1();s3();h3();s7();DG();sZe();IB();sp=null});function ful(t,e){if(t.length===0)return t;let I=[],l=new Set,n=!1;for(let s=t.length-1;s>=0;s--){let c=t[s];if(c.role==="assistant"&&(n=!0),c.role==="assistant"&&"tool_calls"in c&&c.tool_calls&&c.tool_calls.length>0)for(let o of c.tool_calls)l.has(o.id)||I.push(o.id);else{if(n)break;c.role==="tool"&&c.tool_call_id&&l.add(c.tool_call_id)}}if(I.length===0)return t;let r="The execution of this tool, or a previous tool was interrupted.";e.info(`Completing ${I.length} orphaned tool calls.`);let a=I.map(s=>({role:"tool",tool_call_id:s,content:r}));return[...t,...a]}var p_,zPt,dDe,CWe,Hg,fWe,IB=m(()=>{"use strict";lTt();$g();POe();MOe();c3e();TOe();u2e();rTt();GTt();m7();t1();s3();bTt();mTt();qKt();h3();$Kt();tPt();IPt();EQ();KI();V8();ty();zpe();Tje();Wce();gHe();Fm();eZe();Y9();rPt();aPt();l1();mC();_$();LPt();K0e();zc();sMe();GDe();SPt();cDe();iDe();p_=process.env.GITHUB_COPILOT_INTEGRATION_ID||"copilot-developer-cli",zPt=ITt(bC),dDe=class{constructor(e,I){this.logger=e;this.session=I}messageQueue=[];async*preRequest(e){this.logger.debug("ImmediatePromptProcessor: Injecting immediate prompts");let l=(await this.session.getChatMessages()).length;for(;this.messageQueue.length>0;){let a=this.messageQueue.shift();this.session.emit("user.message",{content:a.prompt,attachments:a.attachments})}let r=(await this.session.getChatMessages()).slice(l);for(let a of r)e.messages.push(a),yield{kind:"message",message:a,turn:e.turn,source:"immediate-prompt"}}addMessage(e){this.messageQueue.push(e)}toJSON(){return"ImmediatePromptProcessor"}},CWe=class{sessionId;startTime;modifiedTime;summary;logger;disableHttpLogging;events=[];_chatMessages=[];_selectedModel;eventProcessingQueue=Promise.resolve();eventHandlers={};wildcardEventHandlers=[];integrationId;allowedTools;disabledTools;executeToolsInParallel;shellConfig;requestPermission;mcpServers;hooks;customAgents;selectedCustomAgent;organizationCustomInstructions;skipCustomInstructions;systemMessageConfig;workingDir;featureFlags;trajectoryFile;eventsLogDirectory;authInfo;copilotUrl;onToolsUpdate;enableStreaming=!1;handoffContext;externalToolDefinitions;externalToolDispatcher;clientName;constructor(e={}){this.logger=e.logger||new qo,this.sessionId=e.sessionId||ro(),this.startTime=e.startTime||new Date,this.modifiedTime=e.modifiedTime||this.startTime,this.summary=e.summary,this.integrationId=e.integrationId||p_,this.skipCustomInstructions=e.skipCustomInstructions??!1,this.workingDir=e.workingDirectory||process.cwd(),this.disableHttpLogging=e.disableHttpLogging,this.updateOptions(e)}static async fromEvents(e,I){if(e.length===0)throw new Error("Cannot create session from empty events array");let l=e[0];if(l.type!=="session.start")throw new Error("First event must be session.start");let n=new this({...I,sessionId:l.data.sessionId,startTime:new Date(l.data.startTime)});n._selectedModel=l.data.selectedModel,n.events.push(l);for(let r=1;r<e.length;r++){let a=e[r];n.events.push(a),await n.processEventForState(a)}return n}setAuthInfo(e){this.updateOptions({authInfo:e})}updateOptions(e){e.clientName!==void 0&&(this.clientName=e.clientName),e.model!==void 0&&(this._selectedModel=e.model),e.integrationId!==void 0&&(this.integrationId=e.integrationId),e.allowedTools!==void 0&&(this.allowedTools=e.allowedTools),e.disabledTools!==void 0&&(this.disabledTools=e.disabledTools),e.executeToolsInParallel!==void 0&&(this.executeToolsInParallel=e.executeToolsInParallel),e.shellConfig!==void 0&&(this.shellConfig=e.shellConfig),e.requestPermission!==void 0&&(this.requestPermission=e.requestPermission),e.featureFlags!==void 0&&(this.featureFlags=e.featureFlags),e.mcpServers!==void 0&&(this.mcpServers=e.mcpServers),e.customAgents!==void 0?this.customAgents=e.customAgents:this.loadCustomAgents().catch(I=>this.logger.error(`Failed to load custom agents: ${Fe(I)}`)),e.selectedCustomAgent!==void 0&&(this.selectedCustomAgent=e.selectedCustomAgent),e.organizationCustomInstructions!==void 0&&(this.organizationCustomInstructions=e.organizationCustomInstructions),e.skipCustomInstructions!==void 0&&(this.skipCustomInstructions=e.skipCustomInstructions),e.systemMessage!==void 0&&(this.systemMessageConfig=e.systemMessage),e.hooks!==void 0&&(this.hooks=e.hooks),e.externalToolDefinitions!==void 0&&(this.externalToolDefinitions=e.externalToolDefinitions),e.externalToolDispatcher!==void 0&&(this.externalToolDispatcher=e.externalToolDispatcher),e.logger!==void 0&&(this.logger=e.logger),e.trajectoryFile!==void 0&&(this.trajectoryFile=e.trajectoryFile),e.eventsLogDirectory!==void 0&&(this.eventsLogDirectory=e.eventsLogDirectory),e.disableHttpLogging!==void 0&&(this.disableHttpLogging=e.disableHttpLogging),e.workingDirectory!==void 0&&(this.workingDir=e.workingDirectory),e.authInfo!==void 0&&(this.authInfo=e.authInfo),e.copilotUrl!==void 0&&(this.copilotUrl=e.copilotUrl),e.enableStreaming!==void 0&&(this.enableStreaming=e.enableStreaming)}setOnToolsUpdate(e){this.onToolsUpdate=e}getAvailableCustomAgents(){return this.customAgents||[]}async selectCustomAgent(e){let I=this.customAgents?.find(l=>l.name===e);if(!I)throw new Error(`Custom agent '${e}' not found`);this.selectedCustomAgent=I,this.emit("custom_agent.selected",{agentName:I.name,agentDisplayName:I.displayName,tools:I.tools})}clearCustomAgent(){this.selectedCustomAgent=void 0}on(e,I){return e==="*"?(this.wildcardEventHandlers.push(I),()=>{let l=this.wildcardEventHandlers.indexOf(I);l!==-1&&this.wildcardEventHandlers.splice(l,1)}):(this.eventHandlers[e]||(this.eventHandlers[e]=[]),this.eventHandlers[e].push(I),()=>{let l=this.eventHandlers[e];if(l){let n=l.indexOf(I);n!==-1&&l.splice(n,1)}})}emitInternal(e,I,l=!1){let n=ro(),r=new Date().toISOString(),a=this.getLastEventId(),s={type:e,data:I,id:n,timestamp:r,parentId:a,...l&&{ephemeral:l}};this.events.push(s),this.enqueueEventProcessing(()=>this.processEventForState(s)).catch(c=>{this.logger.error(`Error emitting event: ${c instanceof Error?c.message:String(c)}`)}).catch(c=>{this.logger.error(`Error emitting event ${c instanceof Error?c.message:String(c)}`)}),[...this.eventHandlers[s.type]||[],...this.wildcardEventHandlers].forEach(c=>{try{c(s)}catch(o){this.logger.error(`Error in event handler for event type ${s.type}: ${o instanceof Error?o.message:String(o)}`)}})}emit(e,I){this.emitInternal(e,I)}emitEphemeral(e,I){this.emitInternal(e,I,!0)}getEvents(){return this.events}async getChatMessages(){return this.enqueueEventProcessing(()=>this._chatMessages)}async getChatContextMessages(){return(await this.getChatMessages()).filter(I=>I.role!=="system")}async getSystemContextMessages(){return(await this.getChatMessages()).filter(I=>I.role==="system")}async getSelectedModel(){return this.enqueueEventProcessing(()=>this._selectedModel)}async setSelectedModel(e){let I=await this.getSelectedModel();this.emit("session.model_change",{previousModel:I,newModel:e})}getLastEventId(){return this.events.length===0?null:this.events[this.events.length-1].id}enqueueEventProcessing(e){let I=this.eventProcessingQueue.then(()=>e());return this.eventProcessingQueue=I,I}async processEventForState(e){switch(e.type){case"session.start":e.data.selectedModel&&(this._selectedModel=e.data.selectedModel);break;case"session.model_change":this._selectedModel=e.data.newModel;break;case"user.message":{let I=e.data.content,l=[];if(e.data.attachments&&e.data.attachments.length>0){let n=await BPt(e.data.attachments,this.logger);if(l.push(...n),e.data.attachments&&e.data.attachments.length>0){let r=await xPt(e.data.attachments,this.logger);r&&(I=`${I}
|
|
1943
1943
|
|
|
1944
|
-
${r}`)}}l.length>0?this._chatMessages.push({role:"user",content:[{type:"text",text:I},...l]}):this._chatMessages.push({role:"user",content:I});break}case"assistant.message":{if(e.ephemeral||e.data.parentToolCallId)break;let I={role:"assistant",content:e.data.content||null};e.data.toolRequests&&e.data.toolRequests.length>0&&(I.tool_calls=e.data.toolRequests.map(l=>l.toolCallId.startsWith("custom_")?{id:l.toolCallId,type:"custom",custom:{name:l.name,input:typeof l.arguments=="string"?l.arguments:JSON.stringify(l.arguments)}}:{id:l.toolCallId,type:"function",function:{name:l.name,arguments:typeof l.arguments=="string"?l.arguments:JSON.stringify(l.arguments)}})),this._chatMessages.push(I);break}case"tool.execution_complete":{if(e.data.parentToolCallId)break;e.data.isUserRequested||this._chatMessages.push({role:"tool",tool_call_id:e.data.toolCallId,content:e.data.success?e.data.result?.content||"":e.data.error?.message||"Tool execution failed"});break}case"system.message":this._chatMessages.push({role:e.data.role,content:e.data.content,...e.data.name&&{name:e.data.name}});break;case"session.import_legacy":this._chatMessages=[...e.data.legacySession.chatMessages],e.data.legacySession.selectedModel&&(this._selectedModel=e.data.legacySession.selectedModel);break;case"abort":case"session.resume":this._chatMessages=ful(this._chatMessages,this.logger);break;case"session.handoff":e.data.context&&(this.handoffContext=e.data.context);break;case"assistant.intent":case"session.idle":case"session.error":case"session.info":case"session.truncation":case"assistant.turn_start":case"assistant.turn_end":case"assistant.usage":case"tool.user_requested":case"tool.execution_start":case"tool.execution_partial_result":case"custom_agent.started":case"custom_agent.completed":case"custom_agent.failed":case"custom_agent.selected":case"hook.start":case"hook.end":break;default:{let I=e;this.logger.error(`Unknown event type: ${I.type}`);break}}}async loadCustomAgents(){if(!this.authInfo){this.logger.debug("No auth info available, skipping custom agents load");return}this.customAgents=await UPt(this.authInfo,this.workingDir,this.integrationId,this.logger)}},Hg=class extends CWe{callback=new Fee;isProcessing=!1;messageQueue=[];immediatePromptProcessor;mcpHost;abortController;activeCustomAgents=new Map;mcpHostCache;constructor(e={}){super(e),this.immediatePromptProcessor=new dDe(this.logger,this),this.mcpHostCache=new VWe(this.logger)}updateOptions(e){if(super.updateOptions(e),e.trajectoryFile!==void 0){let I=new dZe(this.logger,e.trajectoryFile);this.callback.addCallback(I)}if(e.eventsLogDirectory!==void 0){let I=new cZe(this.logger,e.eventsLogDirectory);this.callback.addCallback(I)}}getMetadata(){return{sessionId:this.sessionId,startTime:this.startTime,modifiedTime:this.modifiedTime,summary:this.summary,isRemote:!1}}async send(e){if(e.mode==="immediate"&&this.isProcessing)this.immediatePromptProcessor.addMessage(e);else{if(this.messageQueue.push(e),this.isProcessing)return;for(this.isProcessing=!0,await this.initializeMcpHost();this.messageQueue.length>0;){let I=this.messageQueue.shift();this.abortController=I.abortController||new AbortController,await this.runAgenticLoop(I.prompt,I.attachments)}this.isProcessing=!1,this.emitEphemeral("session.idle",{})}}async abort(){this.abortController?.abort()}async initializeMcpHost(){if(!this.mcpHost&&this.mcpServers&&Object.keys(this.mcpServers).length>0)try{this.mcpHost=new _9(this.logger,{mcpServers:this.mcpServers},this.disabledTools),await this.mcpHost.startServers()}catch(e){this.logger.error(`Failed to initialize MCP host: ${Fe(e)}`)}}async buildCustomAgentTools(e,I,l,n,r,a,s){let c=async d=>await Dje({location:r,version:SOe(),currentWorkingDirectory:this.workingDir,parts:{},capabilities:{...a,customAgents:!1},tools:d,organizationCustomInstructions:this.organizationCustomInstructions,toolConfigOverrides:s}),i=(this.selectedCustomAgent?[this.selectedCustomAgent]:e).filter(d=>d.infer!==!1);return await Promise.all(i.map(async d=>{let G;if(d.mcpServers&&Object.keys(d.mcpServers).length>0){let b=await this.mcpHostCache.getOrCreateHost(d.name,d.mcpServers);b&&(G=new IZe(b,I,s.permissions))}return bMt(c,ePt,d,this.workingDir,n,l,G)}))}filterToolsForSelectedAgent(e){return this.selectedCustomAgent?KOe(e,this.selectedCustomAgent,"top-level"):e}async invokeCallbacks(e){if(u7(e))try{await this.callback.progress(e)}catch(I){this.logger.error(`Error in callback: ${Fe(I)}`)}}async getModelList(){if(!this.authInfo)return Promise.reject(new Error("Session was not created with authentication info"));try{return await oDe(this.authInfo,this.integrationId,this.sessionId,this.logger)}catch(e){throw new Error("Failed to list available models",{cause:e})}}async getClient(){if(!this.authInfo)throw new Error("Session was not created with authentication info");let e=await zN(this.authInfo),I=this.copilotUrl;!I&&e&&this.authInfo.type!=="hmac"&&(I=await zPt(this.authInfo.host,e||"",this.logger));let l=await this.getModelList(),n=await $Oe(this._selectedModel,this,l,this.logger);if(!n)throw new Error("No model available. Check policy enablement under GitHub Settings > Copilot");let r=await _Oe(n),s=new I1().setProblemStatement("").setAgentModel(r).setGithubRepoName("copilot-sdk-session").setGithubRepoCommit("copilot-sdk-commit").setGithubRepoReadWrite(!1).setCopilotIntegrationId(this.integrationId).setCopilotUrl(I).setCopilotHmacKey(this.authInfo.type==="hmac"?this.authInfo.hmac:void 0).setGithubToken(e).setCopilotToken(e).setTrajectoryOutputFile(this.trajectoryFile).setEventsLogDirectory(this.eventsLogDirectory).build();T0e();let c=await sDe(s),o=c.service?.agent?.model,i=y9(o),d=s3e(i.agent,i.model);return{client:qpe(c,this.logger,i.agent,{...d.clientOptions,model:i.model,disableHttpLogging:this.disableHttpLogging}),settings:c}}async getContextSummary(){let e=await this.getChatMessages();if(e.length===0)return"";let{client:I}=await this.getClient(),l=lPt(),n=2e4,r={role:"user",content:nPt()},a=new kE(r,this.logger);try{let s="";for await(let c of I.getCompletionWithTools(l,[...e,r],[],{failIfInitialInputsTooLong:!1,processors:{preRequest:[a],onRequestError:[a]}}))c.kind==="message"&&c.message.role==="assistant"&&(s=typeof c.message.content=="string"?c.message.content:"");return s.length>n?s.slice(0,n):s}catch(s){return this.logger.error(`Failed to summarize context: ${Fe(s)}`),""}}async runAgenticLoop(e,I=[]){if(!this.authInfo)throw new Error("Session was not created with authentication info");let l=new Map,n=new Map,r=[];try{let s=(await gw(this.hooks?.userPromptSubmitted,{timestamp:Date.now(),cwd:this.workingDir,prompt:e},this.logger))?.modifiedPrompt??e;this.emit("user.message",{content:s,attachments:I});let c=await zN(this.authInfo),o=this.copilotUrl;!o&&c&&this.authInfo.type!=="hmac"&&(o=await zPt(this.authInfo.host,c||"",this.logger));let i=await this.getModelList(),d=await $Oe(this._selectedModel,this,i,this.logger);if(!d)throw new Error("No model available. Check policy enablement under GitHub Settings > Copilot");let G=await _Oe(d),u=new I1().setProblemStatement(s).setAgentModel(G).setGithubRepoName("copilot-sdk-session").setGithubRepoCommit("copilot-sdk-commit").setGithubRepoReadWrite(!1).setCopilotIntegrationId(this.integrationId).setCopilotUrl(o).setCopilotHmacKey(this.authInfo.type==="hmac"?this.authInfo.hmac:void 0).setGithubToken(c).setCopilotToken(c).setTrajectoryOutputFile(this.trajectoryFile).setEventsLogDirectory(this.eventsLogDirectory).setFeatureFlags(this.featureFlags).setClientName(this.clientName).build();T0e();let h=await sDe(u),p=h.service?.agent?.model,W=y9(p),N=s3e(W.agent,W.model),y=qpe(h,this.logger,W.agent,{...N.clientOptions,model:W.model,disableHttpLogging:this.disableHttpLogging}),g={location:this.workingDir,timeout:3e4,toolPartialResultCallback:(de,DI)=>{this.emitEphemeral("tool.execution_partial_result",{toolCallId:de,partialOutput:DI})},permissions:this.requestPermission?{requestRequired:!0,request:this.requestPermission}:{requestRequired:!1},shellConfig:this.shellConfig??(process.platform==="win32"?NA.powerShell:NA.bash).withScriptSafetyAssessor(async function(de){return{result:"completed",commands:[{identifier:de,readOnly:!1}],possiblePaths:[],hasWriteFileRedirection:!1,canOfferSessionApproval:!1}}),...N.toolConfigOverrides},f=await(N.cli?.toolInit??Br.cli.toolInit)(g,h,this.logger,new RWe,this.callback,void 0),v=[];if(this.mcpHost)try{v=await this.mcpHost.getTools(h,this.logger,g.permissions)}catch(de){this.logger.error(`Failed to get MCP tools: ${Fe(de)}`)}let X=[];if(this.externalToolDefinitions?.length){let de=this.externalToolDispatcher;if(!de)this.logger.warning("External tool definitions provided without a dispatcher; ignoring");else for(let DI of this.externalToolDefinitions)X.push({name:DI.name,description:DI.description,input_schema:DI.parameters??{type:"object",properties:{}},callback:async(fI,$I)=>{if(!$I?.toolCallId)throw new Error("External tool invocation missing toolCallId");return await de({sessionId:this.sessionId,toolCallId:$I.toolCallId,toolName:DI.name,arguments:fI,abortSignal:$I.abortSignal})}})}let J=[...f,...v,...X].filter(de=>this.allowedTools?this.allowedTools.includes(de.name):this.disabledTools?!this.disabledTools.includes(de.name):!0),B=await V9(this.workingDir),H={...N.supports,reasoning:!0},te,Qe={progress:async de=>{if(de.kind==="message"&&de.turn===0){if(!de.callId)throw new Error("message on turn 0 event missing callId");te=de.callId}if(await this.invokeCallbacks(de),de.kind==="custom_agent_session_boundary"){let DI=de.agentId;if(DI)if(de.sessionBoundaryType==="start"){let fI=this.customAgents?.find($I=>$I.name===de.agentName);fI&&(this.activeCustomAgents.set(DI,{name:de.agentName,displayName:fI.displayName}),this.emit("custom_agent.started",{toolCallId:DI,agentName:de.agentName,agentDisplayName:fI.displayName,agentDescription:fI.description}))}else{let fI=this.activeCustomAgents.get(DI);fI&&this.emit("custom_agent.completed",{toolCallId:DI,agentName:fI.name}),this.activeCustomAgents.delete(DI)}return}if(u7(de)){if(!te)throw new Error("Custom agent event received without parentToolCallId");switch(de.kind){case"message":if(NH(de)){let DI=bt.endCurrentStreamingMessage(),fI=i7(de)?de.message.tool_calls.map($I=>({toolCallId:$I.id,name:QQ($I),arguments:DRe($I,MF)})):[];this.emit("assistant.message",{parentToolCallId:te,messageId:DI??ro(),content:typeof de.message.content=="string"?de.message.content:"",toolRequests:fI});for(let $I of fI)this.emit("tool.execution_start",{parentToolCallId:te,toolCallId:$I.toolCallId,toolName:$I.name,arguments:$I.arguments})}break;case"tool_execution":this.emit("tool.execution_complete",{parentToolCallId:te,toolCallId:de.toolCallId,success:de.toolResult.resultType==="success",result:de.toolResult.resultType==="success"?{content:de.toolResult.sessionLog||de.toolResult.textResultForLlm||""}:void 0,error:de.toolResult.resultType!=="success"?{message:(de.toolResult.resultType==="failure"?de.toolResult.error:void 0)||de.toolResult.sessionLog||de.toolResult.textResultForLlm||"Tool execution failed",code:de.toolResult.resultType}:void 0});break;case"model_call_failure":case"model_call_success":case"image_processing":case"images_removed":case"response":case"history_truncated":case"turn_started":case"turn_ended":case"turn_failed":case"turn_retry":break;default:Pu(de,`Unknown event kind: ${JSON.stringify(de)}`)}}},partialResult:async()=>{},commentReply:async()=>{},result:async()=>{},error:async()=>{}},C={client:y,settings:h,logger:this.logger,exec:new Zp(this.logger),customAgents:this.customAgents||[],organizationCustomInstructions:this.organizationCustomInstructions,callback:Qe},ee=J;if(this.customAgents&&this.customAgents.length>0){let de=await this.buildCustomAgentTools(this.customAgents,h,J,C,B.found?B.gitRoot:"",H,g);ee=[...J,...de]}r=this.filterToolsForSelectedAgent(ee),this.onToolsUpdate&&this.onToolsUpdate(r);let ve=await Dje({location:B.found?B.gitRoot:"",version:SOe(),currentWorkingDirectory:this.workingDir,parts:N.cli?.systemMessage||{},capabilities:H,tools:r,organizationCustomInstructions:this.organizationCustomInstructions,skipCustomInstructions:this.skipCustomInstructions,systemMessage:this.systemMessageConfig,toolConfigOverrides:g}),fe=await this.getChatMessages(),me=fe.findLastIndex(de=>de.role==="user"),Je=fe.filter(de=>de.role==="user").at(-1);if(!Je)throw new Error("No user message found in session messages after sending prompt");let Rt=jN(Je),ze=await this.selectedCustomAgent?.prompt();typeof Je.content=="string"?Je={...Je,content:Kje({customAgentPrompt:ze,problemStatement:Je.content,capabilities:H,hasImages:Rt,handoffContext:this.handoffContext})}:Je={...Je,content:Je.content.map(de=>de.type==="text"?{...de,text:Kje({customAgentPrompt:ze,problemStatement:de.text,capabilities:H,hasImages:Rt,handoffContext:this.handoffContext})}:de)},this.handoffContext=void 0;let Ut=fe.map((de,DI)=>DI===me?Je:de);await gw(this.hooks?.sessionStart,{timestamp:Date.now(),cwd:this.workingDir,source:"new",initialPrompt:e},this.logger);let bt=new GZe(this,()=>{},!1,this.logger),ue=new bZe(de=>{this.emitEphemeral("assistant.intent",{intent:de})}),tt=new kE(Je,this.logger),lI=new pce(this.logger),cn=y.getCompletionWithTools(ve,Ut,r,{failIfInitialInputsTooLong:!1,processors:{preRequest:[tt,lI,this.immediatePromptProcessor,new o7(this.logger)],postToolExecution:[lI],onRequestError:[tt],onStreamingChunk:[bt,ue]},executeToolsInParallel:this.executeToolsInParallel??!0,abortSignal:this.abortController?.signal,stream:this.enableStreaming});for await(let de of cn){if(this.abortController?.signal.aborted){this.emit("abort",{reason:"user initiated"}),this.emitEphemeral("session.info",{infoType:"cancellation",message:"Operation cancelled by user"});break}switch(await this.invokeCallbacks(de),de.kind){case"message":{if(NH(de)){let fI=bt.endCurrentStreamingMessage()??ro(),$I=i7(de)?await Promise.all(de.message.tool_calls.map(async nn=>{let wc=QQ(nn),dr=DRe(nn,MF);l.set(nn.id,wc),n.set(nn.id,dr);let Mr=await gw(this.hooks?.preToolUse,{timestamp:Date.now(),cwd:this.workingDir,toolName:wc,toolArgs:dr},this.logger);return{toolCallId:nn.id,name:wc,arguments:Mr?.modifiedArgs??dr}})):[];this.emit("assistant.message",{parentToolCallId:void 0,messageId:fI,content:typeof de.message.content=="string"?de.message.content:"",toolRequests:$I});for(let nn of $I)this.emit("tool.execution_start",{toolCallId:nn.toolCallId,toolName:nn.name,arguments:nn.arguments})}else(de.message.role==="system"||de.message.role==="developer")&&this.emit("system.message",{role:de.message.role,content:typeof de.message.content=="string"?de.message.content:JSON.stringify(de.message.content),name:"name"in de.message?de.message.name:void 0});break}case"model_call_failure":{let DI=new Error(de.modelCall?.error||"Model call failed");if(await gw(this.hooks?.errorOccurred,{timestamp:Date.now(),cwd:this.workingDir,error:DI,errorContext:"model_call",recoverable:!0},this.logger),Pje(de.modelCall?.error||""))return;let $I=de.modelCall?.error||"Unknown error occurred";de.modelCall.request_id&&($I+=` (Request ID: ${de.modelCall.request_id})`),this.emit("session.error",{errorType:"model_call",message:`Model call failed: ${$I}`,stack:DI.stack});break}case"tool_execution":{let fI=(await gw(this.hooks?.postToolUse,{timestamp:Date.now(),cwd:this.workingDir,toolName:l.get(de.toolCallId)||"unknown",toolArgs:n.get(de.toolCallId)||{},toolResult:de.toolResult},this.logger))?.modifiedResult??de.toolResult,$I=(fI.resultType==="failure"?fI.error:void 0)||fI.sessionLog||fI.textResultForLlm;this.emit("tool.execution_complete",{parentToolCallId:void 0,toolCallId:de.toolCallId,success:fI.resultType==="success",result:fI.resultType==="success"?{content:$I}:void 0,error:fI.resultType!=="success"?{message:$I,code:fI.resultType}:void 0});break}case"turn_started":{this.emit("assistant.turn_start",{turnId:`${de.turn}`});break}case"turn_ended":{this.emit("assistant.turn_end",{turnId:`${de.turn}`});break}case"model_call_success":{let DI=de.modelCall.model||await this.getSelectedModel(),fI=de.modelCallDurationMs||0,$I=de.responseUsage,nn=DI?qOe(DI,i):1;this.emitEphemeral("assistant.usage",{model:DI||"unknown",inputTokens:$I?.prompt_tokens||0,outputTokens:$I?.completion_tokens||0,cacheReadTokens:$I?.prompt_tokens_details?.cached_tokens||0,cacheWriteTokens:0,cost:nn,duration:fI,initiator:de.modelCall?.initiator,quotaSnapshots:de.quotaSnapshots});break}case"history_truncated":{this.emit("session.truncation",{...de.truncateResult,performedBy:de.performedBy});break}case"response":case"images_removed":case"image_processing":case"turn_failed":case"turn_retry":this.logger.debug(`Ignoring event of kind: ${de.kind}`);break;default:Pu(de,"Unhandled event type")}}}catch(a){if(await gw(this.hooks?.sessionEnd,{timestamp:Date.now(),cwd:this.workingDir,reason:"error",error:a instanceof Error?a:new Error(String(a))},this.logger),a&&typeof a=="object"&&"status"in a&&(a.status===401||a.status===403)){if("message"in a&&typeof a.message=="string"){let o=Pje(a.message);o&&this.emit("session.error",{errorType:"authentication",message:o.message})}this.emit("session.error",{errorType:"authorization",message:"Authorization error, you may need to run /login"})}a&&typeof a=="object"&&"status"in a&&a.status===402&&this.emit("session.error",{errorType:"quota",message:"Quota exceeded. Upgrade to increase your limit: https://github.com/features/copilot/plans"});let c=`Execution failed: ${a instanceof Error?a.message:a&&typeof a=="object"&&"toString"in a?Fe(a):"Unknown error occurred"}`;this.emit("session.error",{errorType:"query",message:c,stack:a instanceof Error?a.stack:void 0})}finally{await gw(this.hooks?.sessionEnd,{timestamp:Date.now(),cwd:this.workingDir,reason:"complete"},this.logger);try{for(let a of r)a.shutdown&&await a.shutdown()}catch(a){this.logger.error(`Error during session shutdown: ${Fe(a)}`)}}}},fWe=class extends CWe{repository;remoteSessionIds;constructor(e){super(e),this.repository=e.repository,this.remoteSessionIds=e.remoteSessionIds}async send(e){throw new Error("RemoteSession.send() is not implemented yet.")}async abort(){throw new Error("RemoteSession.abort() is not implemented yet.")}getMetadata(){return{sessionId:this.sessionId,startTime:this.startTime,modifiedTime:this.modifiedTime,summary:this.summary,isRemote:!0,repository:this.repository,remoteSessionIds:this.remoteSessionIds}}}});import Jul from"node:path";async function UPt(t,e,I,l){I??=p_,l??=new qo;let n=await SMt(e),{agents:r}=await DMt(l,I,t,Jul.join(Vle(),"agents"),n,!1);return r.map(a=>({name:a.id,displayName:a.displayName,description:a.description,tools:a.tools,prompt:a.prompt,mcpServers:a.mcpServers||{},infer:a.infer}))}var GDe=m(()=>{"use strict";_Mt();nMe();ZJ();sZe();IB()});var Z_,kul,xul,Bul,Sul,zul,Uul,Oul,Mul,Tul,jul,Dul,Kul,Pul,qul,_ul,$ul,ehl,thl,Ihl,lhl,nhl,rhl,ahl,shl,chl,ohl,ihl,bDe,Vw,mDe=m(()=>{"use strict";Ed();h3();PEe();IS();Z_=Ue({type:gt("text"),text:q()}),kul=Ue({type:gt("refusal"),refusal:q()}),xul=Ue({type:gt("image_url"),image_url:Ue({url:q(),detail:Qd(["auto","low","high"]).optional()})}),Bul=Ue({type:gt("input_audio"),input_audio:Ue({data:q(),format:gt("wav").or(gt("mp3"))})}),Sul=Ue({type:gt("file"),file:Ue({file_date:q().optional(),file_id:q().optional(),filename:q().optional()})}),zul=fi([Z_,xul,Bul,Sul]),Uul=Ue({name:q(),arguments:q()}),Oul=Ue({name:q(),input:q()}),Mul=Ue({id:q(),type:gt("function"),function:Uul}),Tul=Ue({id:q(),type:gt("custom"),custom:Oul}),jul=fi([Mul,Tul]),Dul=Ue({name:q(),arguments:q()}),Kul=Ue({id:q()}),Pul=Ue({content:fi([q(),Fa(Z_)]),role:gt("developer"),name:q().optional()}),qul=Ue({content:fi([q(),Fa(Z_)]),role:gt("system"),name:q().optional()}),_ul=Ue({content:fi([q(),Fa(zul)]),role:gt("user"),name:q().optional()}),$ul=Ue({content:fi([q(),Fa(fi([Z_,kul]))]).nullable().optional(),role:gt("assistant"),name:q().optional(),refusal:q().nullable().optional(),audio:Kul.nullable().optional(),function_call:Dul.nullable().optional(),tool_calls:Fa(jul).optional()}),ehl=Ue({content:fi([q(),Fa(Z_)]),role:gt("tool"),tool_call_id:q()}),thl=Ue({content:q().nullable(),role:gt("function"),name:q()}),Ihl=fi([Pul,qul,_ul,$ul,ehl,thl]),lhl=Ue({type:gt("copilot"),text:q(),isStreaming:cl().optional()}),nhl=Ue({type:gt("error"),text:q()}),rhl=Ue({type:gt("info"),text:q()}),ahl=Ue({type:gt("user"),text:q()}),shl=Ue({type:gt("tool_call_requested"),callId:q(),name:q(),toolTitle:q().optional(),intentionSummary:q().nullable(),arguments:KEe,partialOutput:q().optional(),isHidden:cl().optional(),isAlwaysExpanded:cl().optional(),showNoContent:cl().optional()}),chl=Ue({type:gt("tool_call_completed"),callId:q(),name:q(),toolTitle:q().optional(),intentionSummary:q().nullable(),result:fi([Ue({type:gt("success"),log:q(),markdown:cl().optional()}),Ue({type:gt("failure"),log:q(),markdown:cl().optional()}),Ue({type:gt("rejected"),markdown:cl().optional()}),Ue({type:gt("denied"),log:q(),markdown:cl().optional()})]),arguments:KEe,isHidden:cl().optional(),isAlwaysExpanded:cl().optional(),showNoContent:cl().optional()}),ohl=fi([lhl,nhl,rhl,ahl,shl,chl]),ihl=ohl.and(Ue({id:q(),timestamp:M$.date()})),bDe=Ue({sessionId:q(),startTime:M$.date(),chatMessages:Fa(Ihl),timeline:Fa(ihl),selectedModel:Qd(m3).optional()}),Vw=m8e(bDe.parse,"history-session")});var Or,uDe,dhl,Ghl,bhl,mhl,uhl,hhl,phl,Zhl,Whl,Nhl,Yhl,yhl,ghl,Vhl,Rhl,Ahl,Fhl,whl,Qhl,Ehl,vhl,Xhl,Hhl,Chl,fhl,Jhl,Lhl,khl,OPt,hDe=m(()=>{"use strict";Ed();mDe();Or=Ue({id:q().uuid(),timestamp:q().datetime(),parentId:q().uuid().nullable(),ephemeral:cl().optional()}),uDe=Ue({parentToolCallId:q().optional()}),dhl=Or.extend({type:gt("session.start"),data:Ue({sessionId:q(),version:pl(),producer:q(),copilotVersion:q(),startTime:q().datetime(),selectedModel:q().optional()})}),Ghl=Or.extend({type:gt("session.resume"),data:Ue({resumeTime:q().datetime(),eventCount:pl()})}),bhl=Or.extend({type:gt("session.error"),data:Ue({errorType:q(),message:q(),stack:q().optional()})}),mhl=Or.extend({type:gt("session.info"),data:Ue({infoType:q(),message:q()})}),uhl=Or.extend({type:gt("session.model_change"),data:Ue({previousModel:q().optional(),newModel:q()})}),hhl=Or.extend({type:gt("session.import_legacy"),data:Ue({legacySession:bDe,importTime:q().datetime(),sourceFile:q()})}),phl=Or.extend({type:gt("session.handoff"),data:Ue({handoffTime:q().datetime(),sourceType:Qd(["remote","local"]),repository:Ue({owner:q(),name:q(),branch:q().optional()}).optional(),context:q().optional(),summary:q().optional(),remoteSessionId:q().optional()})}),Zhl=Or.extend({type:gt("session.idle"),ephemeral:gt(!0),data:Ue({})}),Whl=Or.extend({type:gt("session.truncation"),data:Ue({tokenLimit:pl(),preTruncationTokensInMessages:pl(),preTruncationMessagesLength:pl(),postTruncationTokensInMessages:pl(),postTruncationMessagesLength:pl(),tokensRemovedDuringTruncation:pl(),messagesRemovedDuringTruncation:pl(),performedBy:q()})}),Nhl=Ue({type:Qd(["file","directory"]),path:q(),displayName:q()}),Yhl=Or.extend({type:gt("user.message"),data:Ue({content:q(),attachments:Fa(Nhl).optional()})}),yhl=Or.extend({type:gt("assistant.turn_start"),data:Ue({turnId:q()})}),ghl=Or.extend({type:gt("assistant.message"),data:Ue({messageId:q(),content:q(),chunkContent:q().optional(),totalResponseSizeBytes:pl().optional(),toolRequests:Fa(Ue({toolCallId:q(),name:q(),arguments:bW()})).optional()}).merge(uDe)}),Vhl=Or.extend({type:gt("assistant.intent"),ephemeral:gt(!0),data:Ue({intent:q()})}),Rhl=Or.extend({type:gt("assistant.turn_end"),data:Ue({turnId:q()})}),Ahl=Or.extend({type:gt("assistant.usage"),ephemeral:gt(!0),data:Ue({model:q().optional(),inputTokens:pl().optional(),outputTokens:pl().optional(),cacheReadTokens:pl().optional(),cacheWriteTokens:pl().optional(),cost:pl().optional(),duration:pl().optional(),initiator:q().optional(),quotaSnapshots:Au(q(),Ue({isUnlimitedEntitlement:cl(),entitlementRequests:pl(),usedRequests:pl(),usageAllowedWithExhaustedQuota:cl(),overage:pl(),overageAllowedWithExhaustedQuota:cl(),remainingPercentage:pl(),resetDate:S0e().optional()})).optional()})}),Fhl=Or.extend({type:gt("abort"),data:Ue({reason:q()})}),whl=Or.extend({type:gt("tool.user_requested"),data:Ue({toolCallId:q(),toolName:q(),arguments:bW()})}),Qhl=Or.extend({type:gt("tool.execution_start"),data:Ue({toolCallId:q(),toolName:q(),arguments:bW()}).merge(uDe)}),Ehl=Or.extend({type:gt("tool.execution_partial_result"),ephemeral:gt(!0),data:Ue({toolCallId:q(),partialOutput:q()})}),vhl=Or.extend({type:gt("tool.execution_complete"),data:Ue({toolCallId:q(),success:cl(),isUserRequested:cl().optional(),result:Ue({content:q()}).optional(),error:Ue({message:q(),code:q().optional()}).optional()}).merge(uDe)}),Xhl=Or.extend({type:gt("custom_agent.started"),data:Ue({toolCallId:q(),agentName:q(),agentDisplayName:q(),agentDescription:q()})}),Hhl=Or.extend({type:gt("custom_agent.completed"),data:Ue({toolCallId:q(),agentName:q()})}),Chl=Or.extend({type:gt("custom_agent.failed"),data:Ue({toolCallId:q(),agentName:q(),error:q()})}),fhl=Or.extend({type:gt("custom_agent.selected"),data:Ue({agentName:q(),agentDisplayName:q(),tools:Fa(q()).nullable()})}),Jhl=Or.extend({type:gt("hook.start"),data:Ue({hookInvocationId:q(),hookType:q(),input:bW()})}),Lhl=Or.extend({type:gt("hook.end"),data:Ue({hookInvocationId:q(),hookType:q(),output:bW(),success:cl(),error:Ue({message:q(),stack:q().optional()}).optional()})}),khl=Or.extend({type:gt("system.message"),data:Ue({content:q(),role:Qd(["system","developer"]),name:q().optional(),metadata:Ue({promptVersion:q().optional(),variables:Au(bW()).optional()}).optional()})}),OPt=OB("type",[dhl,Ghl,bhl,Zhl,mhl,uhl,hhl,phl,Whl,Yhl,yhl,Vhl,ghl,Rhl,Ahl,Fhl,whl,Qhl,Ehl,vhl,Xhl,Hhl,Chl,fhl,Jhl,Lhl,khl])});var Rw,MPt=m(()=>{"use strict";hDe();IS();Rw=u8e(OPt.parse,"session")});var TPt,pDe,jPt,DPt,KPt,PPt,qPt=m(()=>{TPt=t=>{t=1831565813+(t|=0)|0;let e=Math.imul(t^t>>>15,1|t);return e=e+Math.imul(e^e>>>7,61|e)^e,((e^e>>>14)>>>0)/4294967296},pDe=class{constructor(e){this.dictionaries=void 0,this.length=void 0,this.separator=void 0,this.style=void 0,this.seed=void 0;let{length:I,separator:l,dictionaries:n,style:r,seed:a}=e;this.dictionaries=n,this.separator=l,this.length=I,this.style=r,this.seed=a}generate(){if(!this.dictionaries)throw new Error('Cannot find any dictionary. Please provide at least one, or leave the "dictionary" field empty in the config object');if(this.length<=0)throw new Error("Invalid length provided");if(this.length>this.dictionaries.length)throw new Error(`The length cannot be bigger than the number of dictionaries.
|
|
1944
|
+
${r}`)}}l.length>0?this._chatMessages.push({role:"user",content:[{type:"text",text:I},...l]}):this._chatMessages.push({role:"user",content:I});break}case"assistant.message":{if(e.ephemeral||e.data.parentToolCallId)break;let I={role:"assistant",content:e.data.content||null};e.data.toolRequests&&e.data.toolRequests.length>0&&(I.tool_calls=e.data.toolRequests.map(l=>l.toolCallId.startsWith("custom_")?{id:l.toolCallId,type:"custom",custom:{name:l.name,input:typeof l.arguments=="string"?l.arguments:JSON.stringify(l.arguments)}}:{id:l.toolCallId,type:"function",function:{name:l.name,arguments:typeof l.arguments=="string"?l.arguments:JSON.stringify(l.arguments)}})),this._chatMessages.push(I);break}case"tool.execution_complete":{if(e.data.parentToolCallId)break;e.data.isUserRequested||this._chatMessages.push({role:"tool",tool_call_id:e.data.toolCallId,content:e.data.success?e.data.result?.content||"":e.data.error?.message||"Tool execution failed"});break}case"system.message":this._chatMessages.push({role:e.data.role,content:e.data.content,...e.data.name&&{name:e.data.name}});break;case"session.import_legacy":this._chatMessages=[...e.data.legacySession.chatMessages],e.data.legacySession.selectedModel&&(this._selectedModel=e.data.legacySession.selectedModel);break;case"abort":case"session.resume":this._chatMessages=ful(this._chatMessages,this.logger);break;case"session.handoff":e.data.context&&(this.handoffContext=e.data.context);break;case"assistant.intent":case"session.idle":case"session.error":case"session.info":case"session.truncation":case"assistant.turn_start":case"assistant.turn_end":case"assistant.usage":case"tool.user_requested":case"tool.execution_start":case"tool.execution_partial_result":case"custom_agent.started":case"custom_agent.completed":case"custom_agent.failed":case"custom_agent.selected":case"hook.start":case"hook.end":break;default:{let I=e;this.logger.error(`Unknown event type: ${I.type}`);break}}}async loadCustomAgents(){if(!this.authInfo){this.logger.debug("No auth info available, skipping custom agents load");return}this.customAgents=await UPt(this.authInfo,this.workingDir,this.integrationId,this.logger)}},Hg=class extends CWe{callback=new Fee;isProcessing=!1;messageQueue=[];immediatePromptProcessor;mcpHost;abortController;activeCustomAgents=new Map;mcpHostCache;constructor(e={}){super(e),this.immediatePromptProcessor=new dDe(this.logger,this),this.mcpHostCache=new VWe(this.logger)}updateOptions(e){if(super.updateOptions(e),e.trajectoryFile!==void 0){let I=new dZe(this.logger,e.trajectoryFile);this.callback.addCallback(I)}if(e.eventsLogDirectory!==void 0){let I=new cZe(this.logger,e.eventsLogDirectory);this.callback.addCallback(I)}}getMetadata(){return{sessionId:this.sessionId,startTime:this.startTime,modifiedTime:this.modifiedTime,summary:this.summary,isRemote:!1}}async send(e){if(e.mode==="immediate"&&this.isProcessing)this.immediatePromptProcessor.addMessage(e);else{if(this.messageQueue.push(e),this.isProcessing)return;for(this.isProcessing=!0,await this.initializeMcpHost();this.messageQueue.length>0;){let I=this.messageQueue.shift();this.abortController=I.abortController||new AbortController,await this.runAgenticLoop(I.prompt,I.attachments)}this.isProcessing=!1,this.emitEphemeral("session.idle",{})}}async abort(){this.abortController?.abort()}async initializeMcpHost(){if(!this.mcpHost&&this.mcpServers&&Object.keys(this.mcpServers).length>0)try{this.mcpHost=new _9(this.logger,{mcpServers:this.mcpServers},this.disabledTools),await this.mcpHost.startServers()}catch(e){this.logger.error(`Failed to initialize MCP host: ${Fe(e)}`)}}async buildCustomAgentTools(e,I,l,n,r,a,s){let c=async d=>await Dje({location:r,version:SOe(),currentWorkingDirectory:this.workingDir,parts:{},capabilities:{...a,customAgents:!1},tools:d,organizationCustomInstructions:this.organizationCustomInstructions,toolConfigOverrides:s}),i=(this.selectedCustomAgent?[this.selectedCustomAgent]:e).filter(d=>d.infer!==!1);return await Promise.all(i.map(async d=>{let G;if(d.mcpServers&&Object.keys(d.mcpServers).length>0){let b=await this.mcpHostCache.getOrCreateHost(d.name,d.mcpServers);b&&(G=new IZe(b,I,s.permissions))}return bMt(c,ePt,d,this.workingDir,n,l,G)}))}filterToolsForSelectedAgent(e){return this.selectedCustomAgent?KOe(e,this.selectedCustomAgent,"top-level"):e}async invokeCallbacks(e){if(u7(e))try{await this.callback.progress(e)}catch(I){this.logger.error(`Error in callback: ${Fe(I)}`)}}async getModelList(){if(!this.authInfo)return Promise.reject(new Error("Session was not created with authentication info"));try{return await oDe(this.authInfo,this.integrationId,this.sessionId,this.logger)}catch(e){throw new Error("Failed to list available models",{cause:e})}}async getClient(){if(!this.authInfo)throw new Error("Session was not created with authentication info");let e=await zN(this.authInfo),I=this.copilotUrl;!I&&e&&this.authInfo.type!=="hmac"&&(I=await zPt(this.authInfo.host,e||"",this.logger));let l=await this.getModelList(),n=await $Oe(this._selectedModel,this,l,this.logger);if(!n)throw new Error("No model available. Check policy enablement under GitHub Settings > Copilot");let r=await _Oe(n),s=new I1().setProblemStatement("").setAgentModel(r).setGithubRepoName("copilot-sdk-session").setGithubRepoCommit("copilot-sdk-commit").setGithubRepoReadWrite(!1).setCopilotIntegrationId(this.integrationId).setCopilotUrl(I).setCopilotHmacKey(this.authInfo.type==="hmac"?this.authInfo.hmac:void 0).setGithubToken(e).setCopilotToken(e).setTrajectoryOutputFile(this.trajectoryFile).setEventsLogDirectory(this.eventsLogDirectory).build();T0e();let c=await sDe(s),o=c.service?.agent?.model,i=y9(o),d=s3e(i.agent,i.model);return{client:qpe(c,this.logger,i.agent,{...d.clientOptions,model:i.model,disableHttpLogging:this.disableHttpLogging}),settings:c}}async getContextSummary(){let e=await this.getChatMessages();if(e.length===0)return"";let{client:I}=await this.getClient(),l=lPt(),n=2e4,r={role:"user",content:nPt()},a=new kE(r,this.logger);try{let s="";for await(let c of I.getCompletionWithTools(l,[...e,r],[],{failIfInitialInputsTooLong:!1,processors:{preRequest:[a],onRequestError:[a]}}))c.kind==="message"&&c.message.role==="assistant"&&(s=typeof c.message.content=="string"?c.message.content:"");return s.length>n?s.slice(0,n):s}catch(s){return this.logger.error(`Failed to summarize context: ${Fe(s)}`),""}}async runAgenticLoop(e,I=[]){if(!this.authInfo)throw new Error("Session was not created with authentication info");let l=new Map,n=new Map,r=[];try{let s=(await gw(this.hooks?.userPromptSubmitted,{timestamp:Date.now(),cwd:this.workingDir,prompt:e},this.logger))?.modifiedPrompt??e;this.emit("user.message",{content:s,attachments:I});let c=await zN(this.authInfo),o=this.copilotUrl;!o&&c&&this.authInfo.type!=="hmac"&&(o=await zPt(this.authInfo.host,c||"",this.logger));let i=await this.getModelList(),d=await $Oe(this._selectedModel,this,i,this.logger);if(!d)throw new Error("No model available. Check policy enablement under GitHub Settings > Copilot");let G=await _Oe(d),u=new I1().setProblemStatement(s).setAgentModel(G).setGithubRepoName("copilot-sdk-session").setGithubRepoCommit("copilot-sdk-commit").setGithubRepoReadWrite(!1).setCopilotIntegrationId(this.integrationId).setCopilotUrl(o).setCopilotHmacKey(this.authInfo.type==="hmac"?this.authInfo.hmac:void 0).setGithubToken(c).setCopilotToken(c).setTrajectoryOutputFile(this.trajectoryFile).setEventsLogDirectory(this.eventsLogDirectory).setFeatureFlags(this.featureFlags).setClientName(this.clientName).build();T0e();let h=await sDe(u),p=h.service?.agent?.model,W=y9(p),N=s3e(W.agent,W.model),y=qpe(h,this.logger,W.agent,{...N.clientOptions,model:W.model,disableHttpLogging:this.disableHttpLogging}),g={location:this.workingDir,timeout:3e4,toolPartialResultCallback:(de,DI)=>{this.emitEphemeral("tool.execution_partial_result",{toolCallId:de,partialOutput:DI})},permissions:this.requestPermission?{requestRequired:!0,request:this.requestPermission}:{requestRequired:!1},shellConfig:this.shellConfig??(process.platform==="win32"?NA.powerShell:NA.bash).withScriptSafetyAssessor(async function(de){return{result:"completed",commands:[{identifier:de,readOnly:!1}],possiblePaths:[],hasWriteFileRedirection:!1,canOfferSessionApproval:!1}}),...N.toolConfigOverrides},f=await(N.cli?.toolInit??Br.cli.toolInit)(g,h,this.logger,new RWe,this.callback,void 0),v=[];if(this.mcpHost)try{v=await this.mcpHost.getTools(h,this.logger,g.permissions)}catch(de){this.logger.error(`Failed to get MCP tools: ${Fe(de)}`)}let X=[];if(this.externalToolDefinitions?.length){let de=this.externalToolDispatcher;if(!de)this.logger.warning("External tool definitions provided without a dispatcher; ignoring");else for(let DI of this.externalToolDefinitions)X.push({name:DI.name,description:DI.description,input_schema:DI.parameters??{type:"object",properties:{}},callback:async(fI,$I)=>{if(!$I?.toolCallId)throw new Error("External tool invocation missing toolCallId");return await de({sessionId:this.sessionId,toolCallId:$I.toolCallId,toolName:DI.name,arguments:fI,abortSignal:$I.abortSignal})}})}let J=[...f,...v,...X].filter(de=>this.allowedTools?this.allowedTools.includes(de.name):this.disabledTools?!this.disabledTools.includes(de.name):!0),B=await V9(this.workingDir),H={...N.supports,reasoning:!0},te,Qe={progress:async de=>{if(de.kind==="message"&&de.turn===0){if(!de.callId)throw new Error("message on turn 0 event missing callId");te=de.callId}if(await this.invokeCallbacks(de),de.kind==="custom_agent_session_boundary"){let DI=de.agentId;if(DI)if(de.sessionBoundaryType==="start"){let fI=this.customAgents?.find($I=>$I.name===de.agentName);fI&&(this.activeCustomAgents.set(DI,{name:de.agentName,displayName:fI.displayName}),this.emit("custom_agent.started",{toolCallId:DI,agentName:de.agentName,agentDisplayName:fI.displayName,agentDescription:fI.description}))}else{let fI=this.activeCustomAgents.get(DI);fI&&this.emit("custom_agent.completed",{toolCallId:DI,agentName:fI.name}),this.activeCustomAgents.delete(DI)}return}if(u7(de)){if(!te)throw new Error("Custom agent event received without parentToolCallId");switch(de.kind){case"message":if(NH(de)){let DI=bt.endCurrentStreamingMessage(),fI=i7(de)?de.message.tool_calls.map($I=>({toolCallId:$I.id,name:QQ($I),arguments:DRe($I,MF)})):[];this.emit("assistant.message",{parentToolCallId:te,messageId:DI??ro(),content:typeof de.message.content=="string"?de.message.content:"",toolRequests:fI});for(let $I of fI)this.emit("tool.execution_start",{parentToolCallId:te,toolCallId:$I.toolCallId,toolName:$I.name,arguments:$I.arguments})}break;case"tool_execution":this.emit("tool.execution_complete",{parentToolCallId:te,toolCallId:de.toolCallId,success:de.toolResult.resultType==="success",result:de.toolResult.resultType==="success"?{content:de.toolResult.textResultForLlm||de.toolResult.sessionLog||""}:void 0,error:de.toolResult.resultType!=="success"?{message:(de.toolResult.resultType==="failure"?de.toolResult.error:void 0)||de.toolResult.textResultForLlm||de.toolResult.sessionLog||"Tool execution failed",code:de.toolResult.resultType}:void 0});break;case"model_call_failure":case"model_call_success":case"image_processing":case"images_removed":case"response":case"history_truncated":case"turn_started":case"turn_ended":case"turn_failed":case"turn_retry":break;default:Pu(de,`Unknown event kind: ${JSON.stringify(de)}`)}}},partialResult:async()=>{},commentReply:async()=>{},result:async()=>{},error:async()=>{}},C={client:y,settings:h,logger:this.logger,exec:new Zp(this.logger),customAgents:this.customAgents||[],organizationCustomInstructions:this.organizationCustomInstructions,callback:Qe},ee=J;if(this.customAgents&&this.customAgents.length>0){let de=await this.buildCustomAgentTools(this.customAgents,h,J,C,B.found?B.gitRoot:"",H,g);ee=[...J,...de]}r=this.filterToolsForSelectedAgent(ee),this.onToolsUpdate&&this.onToolsUpdate(r);let ve=await Dje({location:B.found?B.gitRoot:"",version:SOe(),currentWorkingDirectory:this.workingDir,parts:N.cli?.systemMessage||{},capabilities:H,tools:r,organizationCustomInstructions:this.organizationCustomInstructions,skipCustomInstructions:this.skipCustomInstructions,systemMessage:this.systemMessageConfig,toolConfigOverrides:g}),fe=await this.getChatMessages(),me=fe.findLastIndex(de=>de.role==="user"),Je=fe.filter(de=>de.role==="user").at(-1);if(!Je)throw new Error("No user message found in session messages after sending prompt");let Rt=jN(Je),ze=await this.selectedCustomAgent?.prompt();typeof Je.content=="string"?Je={...Je,content:Kje({customAgentPrompt:ze,problemStatement:Je.content,capabilities:H,hasImages:Rt,handoffContext:this.handoffContext})}:Je={...Je,content:Je.content.map(de=>de.type==="text"?{...de,text:Kje({customAgentPrompt:ze,problemStatement:de.text,capabilities:H,hasImages:Rt,handoffContext:this.handoffContext})}:de)},this.handoffContext=void 0;let Ut=fe.map((de,DI)=>DI===me?Je:de);await gw(this.hooks?.sessionStart,{timestamp:Date.now(),cwd:this.workingDir,source:"new",initialPrompt:e},this.logger);let bt=new GZe(this,()=>{},!1,this.logger),ue=new bZe(de=>{this.emitEphemeral("assistant.intent",{intent:de})}),tt=new kE(Je,this.logger),lI=new pce(this.logger),cn=y.getCompletionWithTools(ve,Ut,r,{failIfInitialInputsTooLong:!1,processors:{preRequest:[tt,lI,this.immediatePromptProcessor,new o7(this.logger)],postToolExecution:[lI],onRequestError:[tt],onStreamingChunk:[bt,ue]},executeToolsInParallel:this.executeToolsInParallel??!0,abortSignal:this.abortController?.signal,stream:this.enableStreaming});for await(let de of cn){if(this.abortController?.signal.aborted){this.emit("abort",{reason:"user initiated"}),this.emitEphemeral("session.info",{infoType:"cancellation",message:"Operation cancelled by user"});break}switch(await this.invokeCallbacks(de),de.kind){case"message":{if(NH(de)){let fI=bt.endCurrentStreamingMessage()??ro(),$I=i7(de)?await Promise.all(de.message.tool_calls.map(async nn=>{let wc=QQ(nn),dr=DRe(nn,MF);l.set(nn.id,wc),n.set(nn.id,dr);let Mr=await gw(this.hooks?.preToolUse,{timestamp:Date.now(),cwd:this.workingDir,toolName:wc,toolArgs:dr},this.logger);return{toolCallId:nn.id,name:wc,arguments:Mr?.modifiedArgs??dr}})):[];this.emit("assistant.message",{parentToolCallId:void 0,messageId:fI,content:typeof de.message.content=="string"?de.message.content:"",toolRequests:$I});for(let nn of $I)this.emit("tool.execution_start",{toolCallId:nn.toolCallId,toolName:nn.name,arguments:nn.arguments})}else(de.message.role==="system"||de.message.role==="developer")&&this.emit("system.message",{role:de.message.role,content:typeof de.message.content=="string"?de.message.content:JSON.stringify(de.message.content),name:"name"in de.message?de.message.name:void 0});break}case"model_call_failure":{let DI=new Error(de.modelCall?.error||"Model call failed");if(await gw(this.hooks?.errorOccurred,{timestamp:Date.now(),cwd:this.workingDir,error:DI,errorContext:"model_call",recoverable:!0},this.logger),Pje(de.modelCall?.error||""))return;let $I=de.modelCall?.error||"Unknown error occurred";de.modelCall.request_id&&($I+=` (Request ID: ${de.modelCall.request_id})`),this.emit("session.error",{errorType:"model_call",message:`Model call failed: ${$I}`,stack:DI.stack});break}case"tool_execution":{let fI=(await gw(this.hooks?.postToolUse,{timestamp:Date.now(),cwd:this.workingDir,toolName:l.get(de.toolCallId)||"unknown",toolArgs:n.get(de.toolCallId)||{},toolResult:de.toolResult},this.logger))?.modifiedResult??de.toolResult,$I=(fI.resultType==="failure"?fI.error:void 0)||fI.textResultForLlm||fI.sessionLog||"";this.emit("tool.execution_complete",{parentToolCallId:void 0,toolCallId:de.toolCallId,success:fI.resultType==="success",result:fI.resultType==="success"?{content:$I}:void 0,error:fI.resultType!=="success"?{message:$I,code:fI.resultType}:void 0});break}case"turn_started":{this.emit("assistant.turn_start",{turnId:`${de.turn}`});break}case"turn_ended":{this.emit("assistant.turn_end",{turnId:`${de.turn}`});break}case"model_call_success":{let DI=de.modelCall.model||await this.getSelectedModel(),fI=de.modelCallDurationMs||0,$I=de.responseUsage,nn=DI?qOe(DI,i):1;this.emitEphemeral("assistant.usage",{model:DI||"unknown",inputTokens:$I?.prompt_tokens||0,outputTokens:$I?.completion_tokens||0,cacheReadTokens:$I?.prompt_tokens_details?.cached_tokens||0,cacheWriteTokens:0,cost:nn,duration:fI,initiator:de.modelCall?.initiator,quotaSnapshots:de.quotaSnapshots});break}case"history_truncated":{this.emit("session.truncation",{...de.truncateResult,performedBy:de.performedBy});break}case"response":case"images_removed":case"image_processing":case"turn_failed":case"turn_retry":this.logger.debug(`Ignoring event of kind: ${de.kind}`);break;default:Pu(de,"Unhandled event type")}}}catch(a){if(await gw(this.hooks?.sessionEnd,{timestamp:Date.now(),cwd:this.workingDir,reason:"error",error:a instanceof Error?a:new Error(String(a))},this.logger),a&&typeof a=="object"&&"status"in a&&(a.status===401||a.status===403)){if("message"in a&&typeof a.message=="string"){let o=Pje(a.message);o&&this.emit("session.error",{errorType:"authentication",message:o.message})}this.emit("session.error",{errorType:"authorization",message:"Authorization error, you may need to run /login"})}a&&typeof a=="object"&&"status"in a&&a.status===402&&this.emit("session.error",{errorType:"quota",message:"Quota exceeded. Upgrade to increase your limit: https://github.com/features/copilot/plans"});let c=`Execution failed: ${a instanceof Error?a.message:a&&typeof a=="object"&&"toString"in a?Fe(a):"Unknown error occurred"}`;this.emit("session.error",{errorType:"query",message:c,stack:a instanceof Error?a.stack:void 0})}finally{await gw(this.hooks?.sessionEnd,{timestamp:Date.now(),cwd:this.workingDir,reason:"complete"},this.logger);try{for(let a of r)a.shutdown&&await a.shutdown()}catch(a){this.logger.error(`Error during session shutdown: ${Fe(a)}`)}}}},fWe=class extends CWe{repository;remoteSessionIds;constructor(e){super(e),this.repository=e.repository,this.remoteSessionIds=e.remoteSessionIds}async send(e){throw new Error("RemoteSession.send() is not implemented yet.")}async abort(){throw new Error("RemoteSession.abort() is not implemented yet.")}getMetadata(){return{sessionId:this.sessionId,startTime:this.startTime,modifiedTime:this.modifiedTime,summary:this.summary,isRemote:!0,repository:this.repository,remoteSessionIds:this.remoteSessionIds}}}});import Jul from"node:path";async function UPt(t,e,I,l){I??=p_,l??=new qo;let n=await SMt(e),{agents:r}=await DMt(l,I,t,Jul.join(Vle(),"agents"),n,!1);return r.map(a=>({name:a.id,displayName:a.displayName,description:a.description,tools:a.tools,prompt:a.prompt,mcpServers:a.mcpServers||{},infer:a.infer}))}var GDe=m(()=>{"use strict";_Mt();nMe();ZJ();sZe();IB()});var Z_,kul,xul,Bul,Sul,zul,Uul,Oul,Mul,Tul,jul,Dul,Kul,Pul,qul,_ul,$ul,ehl,thl,Ihl,lhl,nhl,rhl,ahl,shl,chl,ohl,ihl,bDe,Vw,mDe=m(()=>{"use strict";Ed();h3();PEe();IS();Z_=Ue({type:gt("text"),text:q()}),kul=Ue({type:gt("refusal"),refusal:q()}),xul=Ue({type:gt("image_url"),image_url:Ue({url:q(),detail:Qd(["auto","low","high"]).optional()})}),Bul=Ue({type:gt("input_audio"),input_audio:Ue({data:q(),format:gt("wav").or(gt("mp3"))})}),Sul=Ue({type:gt("file"),file:Ue({file_date:q().optional(),file_id:q().optional(),filename:q().optional()})}),zul=fi([Z_,xul,Bul,Sul]),Uul=Ue({name:q(),arguments:q()}),Oul=Ue({name:q(),input:q()}),Mul=Ue({id:q(),type:gt("function"),function:Uul}),Tul=Ue({id:q(),type:gt("custom"),custom:Oul}),jul=fi([Mul,Tul]),Dul=Ue({name:q(),arguments:q()}),Kul=Ue({id:q()}),Pul=Ue({content:fi([q(),Fa(Z_)]),role:gt("developer"),name:q().optional()}),qul=Ue({content:fi([q(),Fa(Z_)]),role:gt("system"),name:q().optional()}),_ul=Ue({content:fi([q(),Fa(zul)]),role:gt("user"),name:q().optional()}),$ul=Ue({content:fi([q(),Fa(fi([Z_,kul]))]).nullable().optional(),role:gt("assistant"),name:q().optional(),refusal:q().nullable().optional(),audio:Kul.nullable().optional(),function_call:Dul.nullable().optional(),tool_calls:Fa(jul).optional()}),ehl=Ue({content:fi([q(),Fa(Z_)]),role:gt("tool"),tool_call_id:q()}),thl=Ue({content:q().nullable(),role:gt("function"),name:q()}),Ihl=fi([Pul,qul,_ul,$ul,ehl,thl]),lhl=Ue({type:gt("copilot"),text:q(),isStreaming:cl().optional()}),nhl=Ue({type:gt("error"),text:q()}),rhl=Ue({type:gt("info"),text:q()}),ahl=Ue({type:gt("user"),text:q()}),shl=Ue({type:gt("tool_call_requested"),callId:q(),name:q(),toolTitle:q().optional(),intentionSummary:q().nullable(),arguments:KEe,partialOutput:q().optional(),isHidden:cl().optional(),isAlwaysExpanded:cl().optional(),showNoContent:cl().optional()}),chl=Ue({type:gt("tool_call_completed"),callId:q(),name:q(),toolTitle:q().optional(),intentionSummary:q().nullable(),result:fi([Ue({type:gt("success"),log:q(),markdown:cl().optional()}),Ue({type:gt("failure"),log:q(),markdown:cl().optional()}),Ue({type:gt("rejected"),markdown:cl().optional()}),Ue({type:gt("denied"),log:q(),markdown:cl().optional()})]),arguments:KEe,isHidden:cl().optional(),isAlwaysExpanded:cl().optional(),showNoContent:cl().optional()}),ohl=fi([lhl,nhl,rhl,ahl,shl,chl]),ihl=ohl.and(Ue({id:q(),timestamp:M$.date()})),bDe=Ue({sessionId:q(),startTime:M$.date(),chatMessages:Fa(Ihl),timeline:Fa(ihl),selectedModel:Qd(m3).optional()}),Vw=m8e(bDe.parse,"history-session")});var Or,uDe,dhl,Ghl,bhl,mhl,uhl,hhl,phl,Zhl,Whl,Nhl,Yhl,yhl,ghl,Vhl,Rhl,Ahl,Fhl,whl,Qhl,Ehl,vhl,Xhl,Hhl,Chl,fhl,Jhl,Lhl,khl,OPt,hDe=m(()=>{"use strict";Ed();mDe();Or=Ue({id:q().uuid(),timestamp:q().datetime(),parentId:q().uuid().nullable(),ephemeral:cl().optional()}),uDe=Ue({parentToolCallId:q().optional()}),dhl=Or.extend({type:gt("session.start"),data:Ue({sessionId:q(),version:pl(),producer:q(),copilotVersion:q(),startTime:q().datetime(),selectedModel:q().optional()})}),Ghl=Or.extend({type:gt("session.resume"),data:Ue({resumeTime:q().datetime(),eventCount:pl()})}),bhl=Or.extend({type:gt("session.error"),data:Ue({errorType:q(),message:q(),stack:q().optional()})}),mhl=Or.extend({type:gt("session.info"),data:Ue({infoType:q(),message:q()})}),uhl=Or.extend({type:gt("session.model_change"),data:Ue({previousModel:q().optional(),newModel:q()})}),hhl=Or.extend({type:gt("session.import_legacy"),data:Ue({legacySession:bDe,importTime:q().datetime(),sourceFile:q()})}),phl=Or.extend({type:gt("session.handoff"),data:Ue({handoffTime:q().datetime(),sourceType:Qd(["remote","local"]),repository:Ue({owner:q(),name:q(),branch:q().optional()}).optional(),context:q().optional(),summary:q().optional(),remoteSessionId:q().optional()})}),Zhl=Or.extend({type:gt("session.idle"),ephemeral:gt(!0),data:Ue({})}),Whl=Or.extend({type:gt("session.truncation"),data:Ue({tokenLimit:pl(),preTruncationTokensInMessages:pl(),preTruncationMessagesLength:pl(),postTruncationTokensInMessages:pl(),postTruncationMessagesLength:pl(),tokensRemovedDuringTruncation:pl(),messagesRemovedDuringTruncation:pl(),performedBy:q()})}),Nhl=Ue({type:Qd(["file","directory"]),path:q(),displayName:q()}),Yhl=Or.extend({type:gt("user.message"),data:Ue({content:q(),attachments:Fa(Nhl).optional()})}),yhl=Or.extend({type:gt("assistant.turn_start"),data:Ue({turnId:q()})}),ghl=Or.extend({type:gt("assistant.message"),data:Ue({messageId:q(),content:q(),chunkContent:q().optional(),totalResponseSizeBytes:pl().optional(),toolRequests:Fa(Ue({toolCallId:q(),name:q(),arguments:bW()})).optional()}).merge(uDe)}),Vhl=Or.extend({type:gt("assistant.intent"),ephemeral:gt(!0),data:Ue({intent:q()})}),Rhl=Or.extend({type:gt("assistant.turn_end"),data:Ue({turnId:q()})}),Ahl=Or.extend({type:gt("assistant.usage"),ephemeral:gt(!0),data:Ue({model:q().optional(),inputTokens:pl().optional(),outputTokens:pl().optional(),cacheReadTokens:pl().optional(),cacheWriteTokens:pl().optional(),cost:pl().optional(),duration:pl().optional(),initiator:q().optional(),quotaSnapshots:Au(q(),Ue({isUnlimitedEntitlement:cl(),entitlementRequests:pl(),usedRequests:pl(),usageAllowedWithExhaustedQuota:cl(),overage:pl(),overageAllowedWithExhaustedQuota:cl(),remainingPercentage:pl(),resetDate:S0e().optional()})).optional()})}),Fhl=Or.extend({type:gt("abort"),data:Ue({reason:q()})}),whl=Or.extend({type:gt("tool.user_requested"),data:Ue({toolCallId:q(),toolName:q(),arguments:bW()})}),Qhl=Or.extend({type:gt("tool.execution_start"),data:Ue({toolCallId:q(),toolName:q(),arguments:bW()}).merge(uDe)}),Ehl=Or.extend({type:gt("tool.execution_partial_result"),ephemeral:gt(!0),data:Ue({toolCallId:q(),partialOutput:q()})}),vhl=Or.extend({type:gt("tool.execution_complete"),data:Ue({toolCallId:q(),success:cl(),isUserRequested:cl().optional(),result:Ue({content:q()}).optional(),error:Ue({message:q(),code:q().optional()}).optional()}).merge(uDe)}),Xhl=Or.extend({type:gt("custom_agent.started"),data:Ue({toolCallId:q(),agentName:q(),agentDisplayName:q(),agentDescription:q()})}),Hhl=Or.extend({type:gt("custom_agent.completed"),data:Ue({toolCallId:q(),agentName:q()})}),Chl=Or.extend({type:gt("custom_agent.failed"),data:Ue({toolCallId:q(),agentName:q(),error:q()})}),fhl=Or.extend({type:gt("custom_agent.selected"),data:Ue({agentName:q(),agentDisplayName:q(),tools:Fa(q()).nullable()})}),Jhl=Or.extend({type:gt("hook.start"),data:Ue({hookInvocationId:q(),hookType:q(),input:bW()})}),Lhl=Or.extend({type:gt("hook.end"),data:Ue({hookInvocationId:q(),hookType:q(),output:bW(),success:cl(),error:Ue({message:q(),stack:q().optional()}).optional()})}),khl=Or.extend({type:gt("system.message"),data:Ue({content:q(),role:Qd(["system","developer"]),name:q().optional(),metadata:Ue({promptVersion:q().optional(),variables:Au(bW()).optional()}).optional()})}),OPt=OB("type",[dhl,Ghl,bhl,Zhl,mhl,uhl,hhl,phl,Whl,Yhl,yhl,Vhl,ghl,Rhl,Ahl,Fhl,whl,Qhl,Ehl,vhl,Xhl,Hhl,Chl,fhl,Jhl,Lhl,khl])});var Rw,MPt=m(()=>{"use strict";hDe();IS();Rw=u8e(OPt.parse,"session")});var TPt,pDe,jPt,DPt,KPt,PPt,qPt=m(()=>{TPt=t=>{t=1831565813+(t|=0)|0;let e=Math.imul(t^t>>>15,1|t);return e=e+Math.imul(e^e>>>7,61|e)^e,((e^e>>>14)>>>0)/4294967296},pDe=class{constructor(e){this.dictionaries=void 0,this.length=void 0,this.separator=void 0,this.style=void 0,this.seed=void 0;let{length:I,separator:l,dictionaries:n,style:r,seed:a}=e;this.dictionaries=n,this.separator=l,this.length=I,this.style=r,this.seed=a}generate(){if(!this.dictionaries)throw new Error('Cannot find any dictionary. Please provide at least one, or leave the "dictionary" field empty in the config object');if(this.length<=0)throw new Error("Invalid length provided");if(this.length>this.dictionaries.length)throw new Error(`The length cannot be bigger than the number of dictionaries.
|
|
1945
1945
|
Length provided: ${this.length}. Number of dictionaries provided: ${this.dictionaries.length}`);let e=this.seed;return this.dictionaries.slice(0,this.length).reduce((I,l)=>{let n;e?(n=(a=>{if(typeof a=="string"){let s=a.split("").map(o=>o.charCodeAt(0)).reduce((o,i)=>o+i,1),c=Math.floor(Number(s));return TPt(c)}return TPt(a)})(e),e=4294967296*n):n=Math.random();let r=l[Math.floor(n*l.length)]||"";if(this.style==="lowerCase")r=r.toLowerCase();else if(this.style==="capital"){let[a,...s]=r.split("");r=a.toUpperCase()+s.join("")}else this.style==="upperCase"&&(r=r.toUpperCase());return I?`${I}${this.separator}${r}`:`${r}`},"")}},jPt={separator:"_",dictionaries:[]},DPt=t=>{let e=[...t&&t.dictionaries||jPt.dictionaries],I={...jPt,...t,length:t&&t.length||e.length,dictionaries:e};if(!t||!t.dictionaries||!t.dictionaries.length)throw new Error('A "dictionaries" array must be provided. This is a breaking change introduced starting from Unique Name Generator v4. Read more about the breaking change here: https://github.com/andreasonny83/unique-names-generator#migration-guide');return new pDe(I).generate()},KPt=["able","above","absent","absolute","abstract","abundant","academic","acceptable","accepted","accessible","accurate","accused","active","actual","acute","added","additional","adequate","adjacent","administrative","adorable","advanced","adverse","advisory","aesthetic","afraid","aggregate","aggressive","agreeable","agreed","agricultural","alert","alive","alleged","allied","alone","alright","alternative","amateur","amazing","ambitious","amused","ancient","angry","annoyed","annual","anonymous","anxious","appalling","apparent","applicable","appropriate","arbitrary","architectural","armed","arrogant","artificial","artistic","ashamed","asleep","assistant","associated","atomic","attractive","automatic","autonomous","available","average","awake","aware","awful","awkward","back","bad","balanced","bare","basic","beautiful","beneficial","better","bewildered","big","binding","biological","bitter","bizarre","blank","blonde","blushing","boiling","bold","bored","boring","bottom","brainy","brave","breakable","breezy","brief","bright","brilliant","broad","broken","bumpy","burning","busy","calm","capable","careful","casual","causal","cautious","central","certain","changing","characteristic","charming","cheap","cheerful","chemical","chief","chilly","chosen","chronic","chubby","circular","civic","civil","classic","classical","clean","clear","clever","clinical","close","closed","cloudy","clumsy","coastal","cognitive","coherent","cold","collective","colorful","colossal","coloured","colourful","combined","comfortable","commercial","common","compact","comparable","comparative","compatible","competent","competitive","complete","complex","complicated","comprehensive","compulsory","conceptual","concerned","concrete","condemned","confident","confidential","confused","conscious","conservation","considerable","consistent","constant","constitutional","contemporary","content","continental","continued","continuing","continuous","controlled","controversial","convenient","conventional","convinced","convincing","cooing","cool","cooperative","corporate","correct","corresponding","costly","courageous","creative","creepy","criminal","critical","crooked","crowded","crucial","crude","cruel","cuddly","cultural","curious","curly","current","curved","cute","daily","damaged","damp","dangerous","dark","dead","deafening","dear","decent","decisive","deep","defeated","defensive","defiant","definite","deliberate","delicate","delicious","delighted","delightful","democratic","dependent","depressed","desirable","desperate","detailed","determined","developed","developing","devoted","different","difficult","digital","diplomatic","direct","dirty","disappointed","disastrous","disciplinary","disgusted","distant","distinct","distinctive","distinguished","disturbed","disturbing","diverse","divine","dizzy","domestic","dominant","double","doubtful","drab","dramatic","dreadful","driving","dry","dual","due","dull","dusty","dutch","dying","dynamic","eager","early","eastern","easy","economic","educational","eerie","effective","efficient","elaborate","elated","elderly","eldest","electoral","electric","electrical","electronic","elegant","eligible","embarrassed","embarrassing","emotional","empirical","empty","enchanting","encouraging","endless","energetic","enormous","enthusiastic","entire","entitled","envious","environmental","equal","equivalent","essential","established","estimated","ethical","eventual","everyday","evident","evil","evolutionary","exact","excellent","exceptional","excess","excessive","excited","exciting","exclusive","existing","exotic","expected","expensive","experienced","experimental","explicit","extended","extensive","external","extra","extraordinary","extreme","exuberant","faint","fair","faithful","familiar","famous","fancy","fantastic","far","fascinating","fashionable","fast","fatal","favourable","favourite","federal","fellow","few","fierce","final","financial","fine","firm","fiscal","fit","fixed","flaky","flat","flexible","fluffy","fluttering","flying","following","fond","foolish","foreign","formal","formidable","forthcoming","fortunate","forward","fragile","frail","frantic","free","frequent","fresh","friendly","frightened","front","frozen","full","fun","functional","fundamental","funny","furious","future","fuzzy","gastric","general","generous","genetic","gentle","genuine","geographical","giant","gigantic","given","glad","glamorous","gleaming","global","glorious","golden","good","gorgeous","gothic","governing","graceful","gradual","grand","grateful","greasy","great","grieving","grim","gross","grotesque","growing","grubby","grumpy","guilty","handsome","happy","hard","harsh","head","healthy","heavy","helpful","helpless","hidden","high","hilarious","hissing","historic","historical","hollow","holy","homely","hon","honest","horizontal","horrible","hostile","hot","huge","human","hungry","hurt","hushed","husky","icy","ideal","identical","ideological","ill","illegal","imaginative","immediate","immense","implicit","important","impossible","impressed","impressive","improved","inadequate","inc","inclined","increased","increasing","incredible","independent","indirect","individual","industrial","inevitable","influential","informal","inherent","initial","injured","inland","inner","innocent","innovative","inquisitive","instant","institutional","insufficient","intact","integral","integrated","intellectual","intelligent","intense","intensive","interested","interesting","interim","interior","intermediate","internal","international","invisible","involved","irrelevant","isolated","itchy","jealous","jittery","joint","jolly","joyous","judicial","juicy","junior","just","keen","key","kind","known","labour","large","late","latin","lazy","leading","left","legal","legislative","legitimate","lengthy","lesser","level","lexical","liable","light","like","likely","limited","linear","linguistic","liquid","literary","little","live","lively","living","local","logical","lonely","long","loose","lost","loud","lovely","low","loyal","ltd","lucky","mad","magic","magnetic","magnificent","main","major","mammoth","managerial","managing","manual","many","marginal","marine","marked","married","marvellous","mass","massive","mathematical","mature","maximum","mean","meaningful","mechanical","medical","medieval","melodic","melted","mental","mere","metropolitan","mid","middle","mighty","mild","military","miniature","minimal","minimum","ministerial","minor","miserable","misleading","missing","misty","mixed","moaning","mobile","moderate","modern","modest","molecular","monetary","monthly","moral","motionless","muddy","multiple","mushy","musical","mutual","mysterious","naked","narrow","nasty","national","natural","naughty","naval","near","nearby","neat","necessary","negative","neighbouring","nervous","net","neutral","new","nice","noble","noisy","normal","northern","nosy","notable","novel","nuclear","numerous","nursing","nutritious","nutty","obedient","objective","obliged","obnoxious","obvious","occasional","occupational","odd","official","ok","okay","old","only","open","operational","opposite","optimistic","ordinary","organic","organisational","original","orthodox","other","outdoor","outer","outrageous","outside","outstanding","overall","overseas","overwhelming","painful","pale","panicky","parallel","parental","parliamentary","partial","particular","passing","passive","past","patient","payable","peaceful","peculiar","perfect","permanent","persistent","personal","petite","philosophical","physical","plain","planned","plastic","pleasant","pleased","poised","polite","poor","popular","positive","possible","potential","powerful","practical","precious","precise","preferred","pregnant","preliminary","premier","prepared","present","presidential","pretty","previous","prickly","primary","prime","principal","printed","prior","private","probable","productive","professional","profitable","profound","progressive","prominent","promising","proper","proposed","prospective","protective","proud","provincial","psychiatric","psychological","public","puny","pure","purring","puzzled","quaint","qualified","quarrelsome","querulous","quick","quickest","quiet","quintessential","quixotic","racial","radical","rainy","random","rapid","rare","raspy","rational","ratty","raw","ready","real","realistic","rear","reasonable","recent","reduced","redundant","regional","registered","regular","regulatory","related","relative","relaxed","relevant","reliable","relieved","religious","reluctant","remaining","remarkable","remote","renewed","representative","repulsive","required","resident","residential","resonant","respectable","respective","responsible","resulting","retail","retired","revolutionary","rich","ridiculous","right","rigid","ripe","rising","rival","roasted","robust","rolling","romantic","rotten","rough","round","royal","rubber","rude","ruling","running","rural","sacred","sad","safe","salty","satisfactory","satisfied","scared","scary","scattered","scientific","scornful","scrawny","screeching","secondary","secret","secure","select","selected","selective","selfish","semantic","senior","sensible","sensitive","separate","serious","severe","shaggy","shaky","shallow","shared","sharp","sheer","shiny","shivering","shocked","short","shrill","shy","sick","significant","silent","silky","silly","similar","simple","single","skilled","skinny","sleepy","slight","slim","slimy","slippery","slow","small","smart","smiling","smoggy","smooth","social","soft","solar","sole","solid","sophisticated","sore","sorry","sound","sour","southern","spare","sparkling","spatial","special","specific","specified","spectacular","spicy","spiritual","splendid","spontaneous","sporting","spotless","spotty","square","squealing","stable","stale","standard","static","statistical","statutory","steady","steep","sticky","stiff","still","stingy","stormy","straight","straightforward","strange","strategic","strict","striking","striped","strong","structural","stuck","subjective","subsequent","substantial","subtle","successful","successive","sudden","sufficient","suitable","sunny","super","superb","superior","supporting","supposed","supreme","sure","surprised","surprising","surrounding","surviving","suspicious","sweet","swift","symbolic","sympathetic","systematic","tall","tame","tart","tasteless","tasty","technical","technological","teenage","temporary","tender","tense","terrible","territorial","testy","then","theoretical","thick","thin","thorough","thoughtful","thoughtless","thundering","tight","tiny","tired","top","total","tough","toxic","traditional","tragic","tremendous","tricky","tropical","troubled","typical","ugliest","ugly","ultimate","unable","unacceptable","unaware","uncertain","unchanged","uncomfortable","unconscious","underground","underlying","unemployed","uneven","unexpected","unfair","unfortunate","unhappy","uniform","uninterested","unique","united","universal","unknown","unlikely","unnecessary","unpleasant","unsightly","unusual","unwilling","upper","upset","uptight","urban","urgent","used","useful","useless","usual","vague","valid","valuable","variable","varied","various","varying","vast","verbal","vertical","very","vicarious","vicious","victorious","violent","visible","visiting","visual","vital","vitreous","vivacious","vivid","vocal","vocational","voiceless","voluminous","voluntary","vulnerable","wandering","warm","wasteful","watery","weak","wealthy","weary","wee","weekly","weird","welcome","well","western","wet","whispering","whole","wicked","wide","widespread","wild","wilful","willing","willowy","wily","wise","wispy","wittering","witty","wonderful","wooden","working","worldwide","worried","worrying","worthwhile","worthy","written","wrong","xenacious","xenial","xenogeneic","xeric","xerothermic","yabbering","yammering","yappiest","yappy","yawning","yearling","yearning","yeasty","yelling","yelping","yielding","yodelling","young","youngest","youthful","ytterbic","yucky","yummy","zany","zealous","zeroth","zestful","zesty","zippy","zonal","zoophagous","zygomorphic","zygotic"],PPt=["aardvark","aardwolf","albatross","alligator","alpaca","amphibian","anaconda","angelfish","anglerfish","ant","anteater","antelope","antlion","ape","aphid","armadillo","asp","baboon","badger","bandicoot","barnacle","barracuda","basilisk","bass","bat","bear","beaver","bedbug","bee","beetle","bird","bison","blackbird","boa","boar","bobcat","bobolink","bonobo","bovid","bug","butterfly","buzzard","camel","canid","canidae","capybara","cardinal","caribou","carp","cat","caterpillar","catfish","catshark","cattle","centipede","cephalopod","chameleon","cheetah","chickadee","chicken","chimpanzee","chinchilla","chipmunk","cicada","clam","clownfish","cobra","cockroach","cod","condor","constrictor","coral","cougar","cow","coyote","crab","crane","crawdad","crayfish","cricket","crocodile","crow","cuckoo","damselfly","deer","dingo","dinosaur","dog","dolphin","donkey","dormouse","dove","dragon","dragonfly","duck","eagle","earthworm","earwig","echidna","eel","egret","elephant","elk","emu","ermine","falcon","felidae","ferret","finch","firefly","fish","flamingo","flea","fly","flyingfish","fowl","fox","frog","galliform","gamefowl","gayal","gazelle","gecko","gerbil","gibbon","giraffe","goat","goldfish","goose","gopher","gorilla","grasshopper","grouse","guan","guanaco","guineafowl","gull","guppy","haddock","halibut","hamster","hare","harrier","hawk","hedgehog","heron","herring","hippopotamus","hookworm","hornet","horse","hoverfly","hummingbird","hyena","iguana","impala","jackal","jaguar","jay","jellyfish","junglefowl","kangaroo","kingfisher","kite","kiwi","koala","koi","krill","ladybug","lamprey","landfowl","lark","leech","lemming","lemur","leopard","leopon","limpet","lion","lizard","llama","lobster","locust","loon","louse","lungfish","lynx","macaw","mackerel","magpie","mammal","manatee","mandrill","marlin","marmoset","marmot","marsupial","marten","mastodon","meadowlark","meerkat","mink","minnow","mite","mockingbird","mole","mollusk","mongoose","monkey","moose","mosquito","moth","mouse","mule","muskox","narwhal","newt","nightingale","ocelot","octopus","opossum","orangutan","orca","ostrich","otter","owl","ox","panda","panther","parakeet","parrot","parrotfish","partridge","peacock","peafowl","pelican","penguin","perch","pheasant","pig","pigeon","pike","pinniped","piranha","planarian","platypus","pony","porcupine","porpoise","possum","prawn","primate","ptarmigan","puffin","puma","python","quail","quelea","quokka","rabbit","raccoon","rat","rattlesnake","raven","reindeer","reptile","rhinoceros","roadrunner","rodent","rook","rooster","roundworm","sailfish","salamander","salmon","sawfish","scallop","scorpion","seahorse","shark","sheep","shrew","shrimp","silkworm","silverfish","skink","skunk","sloth","slug","smelt","snail","snake","snipe","sole","sparrow","spider","spoonbill","squid","squirrel","starfish","stingray","stoat","stork","sturgeon","swallow","swan","swift","swordfish","swordtail","tahr","takin","tapir","tarantula","tarsier","termite","tern","thrush","tick","tiger","tiglon","toad","tortoise","toucan","trout","tuna","turkey","turtle","tyrannosaurus","unicorn","urial","vicuna","viper","vole","vulture","wallaby","walrus","warbler","wasp","weasel","whale","whippet","whitefish","wildcat","wildebeest","wildfowl","wolf","wolverine","wombat","woodpecker","worm","wren","xerinae","yak","zebra"]});import{execFile as xhl}from"node:child_process";import{promisify as Bhl}from"node:util";async function _Pt(t){try{let{stdout:e}=await Cg("git",["status","--porcelain","--ignore-submodules"],{cwd:t,encoding:"utf8",timeout:5e3,maxBuffer:1048576}),I=e.split(`
|
|
1946
1946
|
`).filter(a=>a.length>0),l=0,n=0,r=0;for(let a of I){if(a.length<2)continue;let s=a[0],c=a[1];s==="?"&&c==="?"?r++:(s!==" "&&s!=="?"&&l++,c!==" "&&c!=="?"&&n++)}return{staged:l,unstaged:n,untracked:r,hasChanges:I.length>0}}catch{return{staged:0,unstaged:0,untracked:0,hasChanges:!1}}}async function Shl(t){let{stdout:e}=await Cg("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:t,encoding:"utf8",timeout:5e3});return e.trim()}async function zhl(t){try{let{stdout:e}=await Cg("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:t,encoding:"utf8",timeout:5e3}),I=e.trim();if(!I||I==="HEAD")return"origin";let{stdout:l}=await Cg("git",["config",`branch.${I}.remote`],{cwd:t,encoding:"utf8",timeout:5e3});return l.trim()||"origin"}catch{return"origin"}}async function Uhl(t){let e=await zhl(t);try{let{stdout:I}=await Cg("git",["symbolic-ref",`refs/remotes/${e}/HEAD`],{cwd:t,encoding:"utf8",timeout:5e3}),l=I.match(new RegExp(`refs/remotes/${e}/(.+)`));if(l)return l[1].trim()}catch{}try{return await Cg("git",["rev-parse","--verify",`refs/remotes/${e}/main`],{cwd:t,encoding:"utf8",timeout:5e3}),"main"}catch{}try{return await Cg("git",["rev-parse","--verify",`refs/remotes/${e}/master`],{cwd:t,encoding:"utf8",timeout:5e3}),"master"}catch{return"main"}}async function Ohl(t,e){try{return await Cg("git",["rev-parse","--verify",`refs/heads/${e}`],{cwd:t,encoding:"utf8",timeout:5e3}),!0}catch{return!1}}async function Mhl(t,e){let l=["adjectives","animals"],r=[];for(let a of l)a.toLowerCase()==="adjectives"&&r.push(KPt),a.toLowerCase()==="animals"&&r.push(PPt);if(r.length===0)return`${e}/session${Date.now()}`;for(let a=0;a<5;a++){let s=`${e}/${DPt({dictionaries:r,length:r.length,separator:"-"})}`;if(!await Ohl(t,s))return s}return`${e}/session${Date.now()}`}async function Thl(t){return Mhl(t,"copilot")}async function $Pt(t){try{let[e,I,l,n]=await Promise.all([Shl(t),aZe(t),Uhl(t),Thl(t)]);if(!I)throw new Error("Could not determine GitHub repository from git remotes");return{repository:`${I.owner}/${I.name}`,baseBranch:l,headBranch:e,asyncBranch:n}}catch(e){throw new Error(`Failed to get repository info: ${e instanceof Error?e.message:String(e)}`)}}async function eqt(t,e=process.cwd()){try{await Cg("git",["checkout",t],{cwd:e,encoding:"utf8",timeout:5e3,maxBuffer:10*1024*1024})}catch(I){let l=I instanceof Error?I.message:String(I);throw new Error(`Failed to switch to branch '${t}': ${l}`)}}var Cg,tqt=m(()=>{"use strict";qPt();lMe();Cg=Bhl(xhl)});import{existsSync as jhl}from"fs";import{unlink as ZDe}from"fs/promises";import{join as Iqt}from"path";function lqt(t){if(t.role==="user")return typeof t.content=="string"?t.content:t.content.find(e=>e.type==="text")?.text}async function Dhl(t){if(jhl(t))try{return await Vnt(t,e=>{if(e.trim())try{let I=JSON.parse(e);if(I.type==="session.import_legacy"){let l=I.data.legacySession.chatMessages.find(n=>n.role==="user");if(l?.content){let n=lqt(l);if(n)return WDe(n)}}if(I.type==="user.message"){let l=I.data.content;if(l)return WDe(l)}return}catch{return}})}catch{return}}function WDe(t){let e=t.lastIndexOf("<reminder>");e!==-1&&(t=t.substring(0,e).trim());let I=t.replace(/\s+/g," ").trim();return I.length>75&&(I=I.substring(0,55).trim()+"..."),I=I.split("").filter(l=>{let n=l.charCodeAt(0);return n>=32&&n!==127}).join(""),I}var JWe,NDe,nqt=m(()=>{"use strict";ive();jRe();IB();KI();_p();yHe();mDe();MPt();m7();tqt();JWe=class{constructor(e,I,l,n=!1,r){this.session=e;this.logger=I;this.flushDebounceMs=l;this.shouldSaveSession=n;this.legacySourceFile=r;this.unsubscribe=this.session.on("*",a=>{a.ephemeral||(this.unflushedEvents.push(a),!this.shouldSaveSession&&a.type==="user.message"&&(this.shouldSaveSession=!0),a.type!=="session.resume"&&this.shouldSaveSession&&(this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=setTimeout(()=>{this.flush().catch(s=>{this.logger.error(`Error flushing session ${this.session.sessionId}: ${s instanceof Error?s.message:String(s)}`)})},this.flushDebounceMs)))})}flushTimer=null;unflushedEvents=[];migratedLegacy=!1;isFlushing=!1;needsFlushAfterCurrent=!1;unsubscribe;dispose(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.unsubscribe()}async flush(){if(!this.shouldSaveSession||this.unflushedEvents.length===0)return;if(this.isFlushing){this.needsFlushAfterCurrent=!0;return}this.isFlushing=!0,this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null);let e=this.unflushedEvents;this.unflushedEvents=[];try{if(await Rw.append(e,this.session.sessionId),this.logger.debug(`Flushed ${e.length} events to session ${this.session.sessionId}`),this.legacySourceFile&&!this.migratedLegacy){this.logger.debug(`Migrated legacy session ${this.session.sessionId} from ${this.legacySourceFile}`);try{await ZDe(this.legacySourceFile)}catch(I){this.logger.error(`Failed to delete legacy session file ${this.legacySourceFile}: ${Fe(I)}`)}this.migratedLegacy=!0}}catch(I){this.logger.error(`Failed to flush events for ${this.session.sessionId}: ${I instanceof Error?I.message:String(I)}`),this.unflushedEvents.unshift(...e)}finally{this.isFlushing=!1,this.needsFlushAfterCurrent&&(this.needsFlushAfterCurrent=!1,await this.flush())}}};NDe=class{sessionWriters={};copilotVersion;flushDebounceMs;logger;constructor({version:e,flushDebounceMs:I,...l}){this.logger=l.logger||new qo,this.copilotVersion=e||"unknown",this.flushDebounceMs=I||100}async createSession(e,I=!0){let l=await this.loadHooks(e),n=new Hg({...e,hooks:l,startTime:e?.startTime||new Date});return this.sessionWriters[n.sessionId]=new JWe(n,this.logger,this.flushDebounceMs),I&&n.emit("session.start",{sessionId:n.sessionId,version:1,producer:"copilot-agent",copilotVersion:this.copilotVersion,startTime:n.startTime.toISOString(),selectedModel:e?.model}),n}async loadHooks(e){let I=e?.workingDirectory||process.cwd(),l=await V9(I),n=l.found?l.gitRoot:I,r=Iqt(n,".github","hooks");return TRe(r,(s,c)=>YHe(s,c,n),e?.hooks,this.logger)}async getSession(e,I=!0){let l,n;try{l=await this.loadSession(e)}catch{try{let r=await this.loadLegacySession(e);l=r.session,n=r.legacySourceFile}catch{return}}return this.sessionWriters[e.sessionId]||(this.sessionWriters[e.sessionId]=new JWe(l,this.logger,this.flushDebounceMs,!0,n)),I&&l.emit("session.resume",{resumeTime:new Date().toISOString(),eventCount:l.getEvents().length}),l}async getLastSession(e={}){let I=await this.listSessions();if(I.length===0)return;I.sort((n,r)=>r.modifiedTime.getTime()-n.modifiedTime.getTime());let l=I[0].sessionId;return await this.getSession({...e,sessionId:l})}async saveSession(e){e instanceof Hg&&await this.sessionWriters[e.sessionId]?.flush()}async loadSession(e){let I=await Rw.load(e.sessionId);return await Hg.fromEvents(I,e)}async loadLegacySession(e){let l=(await Vw.directoryFiles()).filter(c=>{let o=c.match(/^session_(.+)_(\d+)\.json$/);return o&&o[1]===e.sessionId});if(l.length===0)throw new Error(`Legacy session ${e.sessionId} not found`);let n=l[0];l.length>1&&this.logger.info(`Multiple legacy sessions found for ${e.sessionId}, using newest`);let r=await Vw.load(n);if(!r)throw new Error(`Failed to load legacy session from ${n}`);let a=new Date(r.startTime),s=new Hg({...e,sessionId:r.sessionId,startTime:a});return s.emit("session.start",{sessionId:r.sessionId,version:1,producer:"copilot-agent",copilotVersion:this.copilotVersion,startTime:a.toISOString(),selectedModel:r.selectedModel}),s.emit("session.import_legacy",{legacySession:{sessionId:r.sessionId,startTime:a,chatMessages:r.chatMessages,timeline:r.timeline,selectedModel:r.selectedModel},importTime:new Date().toISOString(),sourceFile:n}),this.logger.info(`Loaded legacy session ${e.sessionId} from ${n}`),{session:s,legacySourceFile:Vw.path(n.replace(/\.json$/,""))}}async listSessions(){let e=await Rw.directoryFilesWithMetadata(),I=await Vw.directoryFilesWithMetadata(),l=await Promise.all(e.map(async a=>{let s=a.file.replace(".jsonl",""),c=Rw.path(s),o=await Dhl(c);return{sessionId:s,startTime:a.birthtime,modifiedTime:a.mtime,summary:o,isRemote:!1}})),n=(await Promise.all(I.map(async a=>{let s=a.file.match(/^session_(.+)_(\d+)\.json$/);if(!s)return null;let c=s[1],o;try{let i=await Vw.load(a.file.replace(/\.json$/,""));if(i){let d=i.chatMessages?.find(G=>G.role==="user");if(d?.content){let G=lqt(d);G&&(o=WDe(G))}}}catch{}return{sessionId:c,startTime:a.birthtime,modifiedTime:a.mtime,summary:o,isRemote:!1}}))).filter(a=>a!==null);this.logger.debug(`Found ${l.length} JSONL sessions and ${n.length} legacy sessions`);let r=new Map;for(let a of n)r.set(a.sessionId,a);for(let a of l)r.set(a.sessionId,a);return Array.from(r.values()).sort((a,s)=>s.modifiedTime.getTime()-a.modifiedTime.getTime())}async deleteSession(e){await this.closeSession(e);let I=Rw.path(e);try{await ZDe(I),this.logger.info(`Deleted session file ${I}`);return}catch{let r=(await Vw.directoryFiles()).filter(a=>{let s=a.match(/^session_(.+)_(\d+)\.json$/);return s&&s[1]===e});if(r.length===0)throw new Error(`Session file not found for ${e}`);for(let a of r){let s=Vw.path(a.replace(/\.json$/,""));this.logger.info(`Deleting legacy session file ${s}`),await ZDe(s)}}}async closeSession(e){this.logger.info(`Closing session ${e}`);let I=this.sessionWriters[e];I&&(await I.flush(),I.dispose(),delete this.sessionWriters[e])}getSessionsDirectory(){return Iqt(Rw.home(),Rw.directory())}setLogger(e){this.logger=e}async*handoffSession(e,I){if(!(e instanceof fWe))throw new Error("Can only handoff RemoteSession instances to local");let l=e.getMetadata();if(!l.repository)throw new Error("Remote session missing repository information");this.logger.info(`Handing off remote session ${l.sessionId} to local...`),yield{step:"validate-repo",status:"in-progress"};let n=process.cwd(),r;try{r=await $Pt(n)}catch(d){throw new Error(`Not in a git repository. Please navigate to your repository directory.
|
|
1947
1947
|
${Fe(d)}`)}let a=r.repository,s=`${l.repository.owner}/${l.repository.name}`;if(a!==s)throw new Error(`Repository mismatch: You are in '${a}' but the remote session is for '${s}'.
|