@github/copilot 0.0.351-13 → 0.0.351-15
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 +5 -5
- package/package.json +2 -2
- package/sdk/index.js +4 -4
package/index.js
CHANGED
|
@@ -957,7 +957,7 @@ ${n.join(`
|
|
|
957
957
|
* Cannot be used if the specified path already exists
|
|
958
958
|
* Parent directories must exist before creating the file
|
|
959
959
|
* Path *must* be absolute
|
|
960
|
-
`,input_schema:{type:"object",properties:{path:{description:"Absolute path to file to create.",type:"string"},file_text:{description:"The content of the file to be created.",type:"string"}},required:["path","file_text"]},callback:(r,a)=>n.callback({...r,command:"create"},a),summariseIntention:r=>n.summariseIntention({...r,command:"create"}),safeForTelemetry:!0},{name:"edit",description:"Tool for making string replacements in files.\n * Replaces exactly one occurrence of `old_str` with `new_str` in the specified file\n * When called multiple times in a single response, edits are independently made in the order calls are specified\n * The `old_str` parameter must match EXACTLY one or more consecutive lines from the original file\n * If `old_str` is not unique in the file, replacement will not be performed\n * Make sure to include enough context in `old_str` to make it unique\n * Path *must* be absolute\n ",input_schema:{type:"object",properties:{path:{description:"Absolute path to file to edit.",type:"string"},old_str:{description:"The string in the file to replace. Leading and ending whitespaces from file content should be preserved!",type:"string"},new_str:{description:"The new string to replace old_str with.",type:"string"}},required:["path","old_str"]},callback:(r,a)=>n.callback({...r,command:"edit"},a),shutdown:async()=>await n.shutdown(),summariseIntention:r=>n.summariseIntention({...r,command:"edit"}),safeForTelemetry:!0}]},GBe=(t,e,l)=>{let n=new NWe,r=new Map,a={truncateBasedOn:"tokenCount",truncateStyle:"middle"};return e.debug(`str_replace_editor: default options: ${JSON.stringify(a,null,2)}`),{name:"str_replace_editor",description:"Editing tool for viewing, creating and editing files\n * State is persistent across command calls and discussions with the user\n * If `path` is a file, `view` displays the result of applying `cat -n`. If `path` is a directory, `view` lists non-hidden files and directories up to 2 levels deep\n * The `create` command cannot be used if the specified `path` already exists, or if parent directories don't exist\n * If a `command` generates a long output, output will be truncated and marked with `<file too long...`\n * Path *must* be absolute\n\n Notes for using the `str_replace` command:\n * The `old_str` parameter should match EXACTLY one or more consecutive lines from the original file\n * If the `old_str` parameter is not unique in the file, replacement will not be performed. Make sure to include enough context in `old_str` to make it unique\n * The `new_str` parameter should contain the edited lines that should replace the `old_str`",input_schema:{type:"object",properties:{command:{type:"string",enum:["view","create","str_replace","insert"],description:`The commands to run. Allowed options are: ${Array.from(dBe).map(s=>`\`${s}\``).join(", ")}.`},file_text:{description:"Required parameter of `create` command; the content of the file to be created.",type:"string"},insert_line:{description:"Required parameter of `insert` command. The `new_str` will be inserted AFTER the line `insert_line` of `path`.",type:"integer"},new_str:{description:"Required parameter of `str_replace` command containing the new string. Required parameter of `insert` command containing the string to insert.",type:"string"},old_str:{description:"Required parameter of `str_replace` command containing the string in `path` to replace. Leading and ending whitespaces from file content should be preserved!",type:"string"},path:{description:"Absolute path to file or directory.",type:"string"},view_range:{description:"Optional parameter of `view` command when `path` points to a file. If none is given, the full file is shown. If provided, the file will be shown in the indicated line number range, e.g. [11, 12] will show lines 11 and 12. Indexing at 1 to start. Setting `[start_line, -1]` shows all lines from `start_line` to the end of the file.",items:{type:"integer"},type:"array"}},required:["command","path"]},shutdown:async()=>{let s=n.getTrackedEditsJsonArrString();return n.reset(),{kind:"telemetry",telemetry:{event:"str_replace_editor_shutdown",properties:{trackedEdits:s},metrics:{},restrictedProperties:{}}}},summariseIntention:s=>{switch(s.command){case"create":return`create a new file at ${s.path}.`;case"view":return`view the file at ${s.path}.`;case"str_replace":case"edit":case"insert":return`edit the file at ${s.path}.`;default:{let o=s;return`unknown command: ${JSON.stringify(s)}`}}},callback:async(s,o)=>{if(s.command==="view")return I(s,o);let c=r.get(s.path);return c||(c=new WWe(e),r.set(s.path,c)),c.enqueue(()=>I(s,o))},safeForTelemetry:!0};async function I(s,o){let c={...a,...o?.toolOptions||{}};e.debug(s.command+": "+s.path);let d={properties:{command:vRt(s.command),options:JSON.stringify(c),inputs:JSON.stringify(Object.keys(s)),resolvedPathAgainstCwd:"false",fileExtension:s.path?pWe(s.path):void 0},metrics:{resultLength:0,resultForLlmLength:0,responseTokenLimit:o?.truncationOptions?.tokenLimit},restrictedProperties:{}},m;try{if(typeof s.path!="string"||!s.path)return Ah("failure",d,{},"A path parameter is required, and must be a non-empty string.","",void 0,"Path not provided");let G=process.cwd();if(G){let p=await WRt(s.path,G);if(!Z_l(p))return e.debug(`Could not resolve path "${s.path}" against agent cwd "${G}". Need to use absolute path.`),Ah("failure",d,{},`Path "${s.path}" is not absolute. Please provide an absolute path.`,"",void 0,"Path not absolute");p!==s.path&&(e.debug(`using resolved path ${p} based on agent cwd ${G}`),s.path=p,d.properties.resolvedPathAgainstCwd="true")}switch(s.command){case"view":m=await pBe(s,d,t.permissions,e,o);break;case"str_replace":case"edit":m=await E_l(s,d,t.permissions,e,o);break;case"create":m=await R_l(s,d,t.permissions,e,o);break;case"insert":m=await Y_l(s,d,t.permissions,e,o);break;default:{let p=s,A=p.command?`Unknown command: ${p.command}`:"No command provided";return Promise.reject(new Error(`${A}. Allowed commands are: ${Array.from(dBe).join(", ")}`))}}}catch(G){m=Ah("failure",d,{},`Failed to execute
|
|
960
|
+
`,input_schema:{type:"object",properties:{path:{description:"Absolute path to file to create.",type:"string"},file_text:{description:"The content of the file to be created.",type:"string"}},required:["path","file_text"]},callback:(r,a)=>n.callback({...r,command:"create"},a),summariseIntention:r=>n.summariseIntention({...r,command:"create"}),safeForTelemetry:!0},{name:"edit",description:"Tool for making string replacements in files.\n * Replaces exactly one occurrence of `old_str` with `new_str` in the specified file\n * When called multiple times in a single response, edits are independently made in the order calls are specified\n * The `old_str` parameter must match EXACTLY one or more consecutive lines from the original file\n * If `old_str` is not unique in the file, replacement will not be performed\n * Make sure to include enough context in `old_str` to make it unique\n * Path *must* be absolute\n ",input_schema:{type:"object",properties:{path:{description:"Absolute path to file to edit.",type:"string"},old_str:{description:"The string in the file to replace. Leading and ending whitespaces from file content should be preserved!",type:"string"},new_str:{description:"The new string to replace old_str with.",type:"string"}},required:["path","old_str"]},callback:(r,a)=>n.callback({...r,command:"edit"},a),shutdown:async()=>await n.shutdown(),summariseIntention:r=>n.summariseIntention({...r,command:"edit"}),safeForTelemetry:!0}]},GBe=(t,e,l)=>{let n=new NWe,r=new Map,a={truncateBasedOn:"tokenCount",truncateStyle:"middle"};return e.debug(`str_replace_editor: default options: ${JSON.stringify(a,null,2)}`),{name:"str_replace_editor",description:"Editing tool for viewing, creating and editing files\n * State is persistent across command calls and discussions with the user\n * If `path` is a file, `view` displays the result of applying `cat -n`. If `path` is a directory, `view` lists non-hidden files and directories up to 2 levels deep\n * The `create` command cannot be used if the specified `path` already exists, or if parent directories don't exist\n * If a `command` generates a long output, output will be truncated and marked with `<file too long...`\n * Path *must* be absolute\n\n Notes for using the `str_replace` command:\n * The `old_str` parameter should match EXACTLY one or more consecutive lines from the original file\n * If the `old_str` parameter is not unique in the file, replacement will not be performed. Make sure to include enough context in `old_str` to make it unique\n * The `new_str` parameter should contain the edited lines that should replace the `old_str`",input_schema:{type:"object",properties:{command:{type:"string",enum:["view","create","str_replace","insert"],description:`The commands to run. Allowed options are: ${Array.from(dBe).map(s=>`\`${s}\``).join(", ")}.`},file_text:{description:"Required parameter of `create` command; the content of the file to be created.",type:"string"},insert_line:{description:"Required parameter of `insert` command. The `new_str` will be inserted AFTER the line `insert_line` of `path`.",type:"integer"},new_str:{description:"Required parameter of `str_replace` command containing the new string. Required parameter of `insert` command containing the string to insert.",type:"string"},old_str:{description:"Required parameter of `str_replace` command containing the string in `path` to replace. Leading and ending whitespaces from file content should be preserved!",type:"string"},path:{description:"Absolute path to file or directory.",type:"string"},view_range:{description:"Optional parameter of `view` command when `path` points to a file. If none is given, the full file is shown. If provided, the file will be shown in the indicated line number range, e.g. [11, 12] will show lines 11 and 12. Indexing at 1 to start. Setting `[start_line, -1]` shows all lines from `start_line` to the end of the file.",items:{type:"integer"},type:"array"}},required:["command","path"]},shutdown:async()=>{let s=n.getTrackedEditsJsonArrString();return n.reset(),{kind:"telemetry",telemetry:{event:"str_replace_editor_shutdown",properties:{trackedEdits:s},metrics:{},restrictedProperties:{}}}},summariseIntention:s=>{switch(s.command){case"create":return`create a new file at ${s.path}.`;case"view":return`view the file at ${s.path}.`;case"str_replace":case"edit":case"insert":return`edit the file at ${s.path}.`;default:{let o=s;return`unknown command: ${JSON.stringify(s)}`}}},callback:async(s,o)=>{if(s.command==="view")return I(s,o);let c=r.get(s.path);return c||(c=new WWe(e),r.set(s.path,c)),c.enqueue(()=>I(s,o))},safeForTelemetry:!0};async function I(s,o){let c={...a,...o?.toolOptions||{}};e.debug(s.command+": "+s.path);let d={properties:{command:vRt(s.command),options:JSON.stringify(c),inputs:JSON.stringify(Object.keys(s)),resolvedPathAgainstCwd:"false",fileExtension:s.path?pWe(s.path):void 0},metrics:{resultLength:0,resultForLlmLength:0,responseTokenLimit:o?.truncationOptions?.tokenLimit},restrictedProperties:{}},m;try{if(typeof s.path!="string"||!s.path)return Ah("failure",d,{},"A path parameter is required, and must be a non-empty string.","",void 0,"Path not provided");let G=process.cwd();if(G){let p=await WRt(s.path,G);if(!Z_l(p))return e.debug(`Could not resolve path "${s.path}" against agent cwd "${G}". Need to use absolute path.`),Ah("failure",d,{},`Path "${s.path}" is not absolute. Please provide an absolute path.`,"",void 0,"Path not absolute");p!==s.path&&(e.debug(`using resolved path ${p} based on agent cwd ${G}`),s.path=p,d.properties.resolvedPathAgainstCwd="true")}switch(s.command){case"view":m=await pBe(s,d,t.permissions,e,o);break;case"str_replace":case"edit":m=await E_l(s,d,t.permissions,e,o);break;case"create":m=await R_l(s,d,t.permissions,e,o);break;case"insert":m=await Y_l(s,d,t.permissions,e,o);break;default:{let p=s,A=p.command?`Unknown command: ${p.command}`:"No command provided";return Promise.reject(new Error(`${A}. Allowed commands are: ${Array.from(dBe).join(", ")}`))}}}catch(G){m=Ah("failure",d,{},`Failed to execute with arguments: ${JSON.stringify(s)} due to error: ${G}`,"",void 0,`Unhandled error: ${G}`)}return m.resultType!=="rejected"&&m.resultType!=="denied"&&s.path&&s.command&&typeof s.path=="string"&&typeof s.command=="string"&&n.trackEdit(s.path,vRt(s.command),m.resultType,o?.toolCallId),m}};async function pBe(t,e,l,n,r){let a={truncateBasedOn:"tokenCount",truncateStyle:"middle",...r?.toolOptions||{}},I=await A_l(t.path).then(d=>d.isDirectory()?{kind:"directory"}:{kind:"file",size:d.size}).catch(()=>({kind:"not-found"}));if(l.requestRequired){let d=await l.request({kind:"read",intention:I.kind==="directory"?`List directory: ${t.path}`:`Read file: ${t.path}`,path:t.path}),m=yWe(d,e);if(m)return m}if(I.kind==="not-found")return Ah("failure",e,{properties:{viewType:"unknown"}},`Path ${t.path} does not exist. Please provide a valid path.`,"",void 0,"Path does not exist");let s,o="";if(I.kind==="directory"){let d=await h_l(t.path);s=d.join(`
|
|
961
961
|
`);let m=`@@ -1,0 +1,${d.length} @@`;o=mne(void 0,t.path,`${m}
|
|
962
962
|
${d.map(G=>` ${G}`).join(`
|
|
963
963
|
`)}`)}else{if(I.size>CRt){let R=(I.size/1048576).toFixed(1),V=(CRt/(1024*1024)).toFixed(0);return Ah("failure",e,{properties:{viewType:"file"}},`File is too large to view (${R}MB). Maximum file size is ${V}MB. Use shell tool with head/tail commands or specify a line range with view_range parameter to view specific sections.`,"",void 0,"File too large")}let d,m;t.view_range&&t.view_range.length>=1&&(d=t.view_range.at(0),m=t.view_range.at(1)),d===void 0&&(d=1,m=void 0);let G,p;if(t.view_range&&t.view_range.length>=1){let R=await gRt(t.path,d,m);G=R.lines,p=R.totalLineCount}else G=(await uBe(t.path,"utf-8")).split(`
|
|
@@ -966,7 +966,7 @@ ${A.map(R=>` ${R}`).join(`
|
|
|
966
966
|
`).replaceAll(`\r
|
|
967
967
|
`,`
|
|
968
968
|
`)}`),s=A.map((R,V)=>`${V+d}.${R}`).join(`
|
|
969
|
-
`)}let c=V_l(s,I.kind,r?.truncationOptions,a,n);return Ah("success",e,{properties:{viewType:I.kind}},s,o,c)}async function E_l(t,e,l,n,r){let a,I=await uBe(t.path,"utf-8");if(!t.old_str)a={type:"failure",resultForLlm:"Invalid inputs: old_str is required
|
|
969
|
+
`)}let c=V_l(s,I.kind,r?.truncationOptions,a,n);return Ah("success",e,{properties:{viewType:I.kind}},s,o,c)}async function E_l(t,e,l,n,r){let a,I=await uBe(t.path,"utf-8");if(!t.old_str)a={type:"failure",resultForLlm:"Invalid inputs: old_str is required"};else if(t.old_str===t.new_str)a={type:"success",resultForLlm:"No changes made: old_str and new_str are the same",newText:I};else if(t.new_str===void 0||t.new_str===null)a={type:"failure",resultForLlm:"Invalid inputs: new_str is required"};else{let o=kRt(I),c=(t.new_str||"").replaceAll(/\r?\n/g,o),d=wRt(I,t.old_str,c),m=d.type;m=="none"?a={type:"failure",resultForLlm:`No match found: old_str not found in ${t.path}; no changes made; you might want to try again with correct old_str`,error:"No match found"}:m=="multiple"?a={type:"failure",resultForLlm:`Multiple matches found for old_str in ${t.path}; no changes made; you might want to try again and be more specific with old_str`,error:"Multiple matches found"}:(m==="exact"||m==="fuzzy")&&(a={type:"success",resultForLlm:`File ${t.path} updated with changes.`,newText:d.text})}a||(a={type:"failure",resultForLlm:`Failed to replace ${t.old_str} with ${t.new_str||""} in ${t.path}.`,error:"Failed to replace"});let s="";if(a.type==="success"){let o=a.newText,c=XRt(I,o);if(s=mne(t.path,t.path,c),l.requestRequired){let d=await l.request({kind:"write",intention:"Edit file",fileName:t.path,diff:s}),m=yWe(d,e);if(m)return m}await mBe(t.path,o)}return Ah(a.type,e,{},a.resultForLlm,s,void 0,a.type==="success"?void 0:a.error)}async function R_l(t,e,l,n,r){let a=t.file_text||"",I=g_l(t.path);if(!await AC(I))return Ah("failure",e,{},`Parent directory ${I} does not exist. You need to create it before creating the file.`,"",void 0,"Parent directory does not exist");let o=await AC(t.path);if(o)return Ah("failure",e,{},`Path ${t.path} already exists as a ${o}. Use \`view\` to check contents then edit it.`,"",void 0,"Path already exists");{let c=a.split(/\r?\n/),d=`@@ -1,0 +1,${c.length} @@`,m=mne(void 0,t.path,`${d}
|
|
970
970
|
${c.map(p=>`+${p}`).join(`
|
|
971
971
|
`)}`);if(l.requestRequired){let p=await l.request({kind:"write",intention:"Create file",fileName:t.path,diff:m}),A=yWe(p,e);if(A)return A}let G=process.platform==="win32"?a.replaceAll(/\r?\n/g,`\r
|
|
972
972
|
`):a;return await mBe(t.path,G),Ah("success",e,{},`Created file ${t.path} with ${G.length} characters`,m)}}async function Y_l(t,e,l,n,r){if(t.new_str===void 0||t.new_str===null||t.insert_line===void 0)return Ah("failure",e,{metrics:{emptyLinesAdded:0}},"Missing required arguments for command insert: insert_line and new_str","");let a=await uBe(t.path,"utf-8"),I=a.split(`
|
|
@@ -1901,9 +1901,9 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
|
1901
1901
|
`);this.baseURL=s.baseURL,this.timeout=s.timeout??A6e.DEFAULT_TIMEOUT,this.logger=s.logger??console;let o="warn";this.logLevel=o,this.logLevel=Jje(s.logLevel,"ClientOptions.logLevel",this)??Jje($2("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??o,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??uTt(),Vr(this,E1e,TTt,"f"),this._options=s,this.apiKey=typeof l=="string"?l:"Missing Key",this.organization=n,this.project=r,this.webhookSecret=a}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:l}){}async authHeaders(e){return Vn([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return c6e(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${Cw}`}defaultIdempotencyKey(){return`stainless-node-retry-${r6e()}`}makeStatusError(e,l,n,r){return Ru.generate(e,l,n,r)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!="function")return!1;let l;try{l=await e()}catch(n){throw n instanceof Yn?n:new Yn(`Failed to get token from 'apiKey' function: ${n.message}`,{cause:n})}if(typeof l!="string"||!l)throw new Yn(`Expected 'apiKey' function argument to return a string but it returned ${l}`);return this.apiKey=l,!0}buildURL(e,l,n){let r=!ht(this,h6e,"m",mOt).call(this)&&n||this.baseURL,a=ATt(e)?new URL(e):new URL(r+(r.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),I=this.defaultQuery();return gTt(I)||(l={...I,...l}),typeof l=="object"&&l&&!Array.isArray(l)&&(a.search=this.stringifyQuery(l)),a.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:l,options:n}){}get(e,l){return this.methodRequest("get",e,l)}post(e,l){return this.methodRequest("post",e,l)}patch(e,l){return this.methodRequest("patch",e,l)}put(e,l){return this.methodRequest("put",e,l)}delete(e,l){return this.methodRequest("delete",e,l)}methodRequest(e,l,n){return this.request(Promise.resolve(n).then(r=>({method:e,path:l,...r})))}request(e,l=null){return new nT(this,this.makeRequest(e,l,void 0))}async makeRequest(e,l,n){let r=await e,a=r.maxRetries??this.maxRetries;l==null&&(l=a),await this.prepareOptions(r);let{req:I,url:s,timeout:o}=await this.buildRequest(r,{retryCount:a-l});await this.prepareRequest(I,{url:s,options:r});let c="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),d=n===void 0?"":`, retryOf: ${n}`,m=Date.now();if(Im(this).debug(`[${c}] sending request`,ef({retryOfRequestLogID:n,method:r.method,url:s,options:r,headers:I.headers})),r.signal?.aborted)throw new zm;let G=new AbortController,p=await this.fetchWithTimeout(s,I,o,G).catch(Ade),A=Date.now();if(p instanceof globalThis.Error){let R=`retrying, ${l} attempts remaining`;if(r.signal?.aborted)throw new zm;let V=hde(p)||/timed? ?out/i.test(String(p)+("cause"in p?String(p.cause):""));if(l)return Im(this).info(`[${c}] connection ${V?"timed out":"failed"} - ${R}`),Im(this).debug(`[${c}] connection ${V?"timed out":"failed"} (${R})`,ef({retryOfRequestLogID:n,url:s,durationMs:A-m,message:p.message})),this.retryRequest(r,l,n??c);throw Im(this).info(`[${c}] connection ${V?"timed out":"failed"} - error; no more retries left`),Im(this).debug(`[${c}] connection ${V?"timed out":"failed"} (error; no more retries left)`,ef({retryOfRequestLogID:n,url:s,durationMs:A-m,message:p.message})),V?new jk:new Pk({cause:p})}let Z=[...p.headers.entries()].filter(([R])=>R==="x-request-id").map(([R,V])=>", "+R+": "+JSON.stringify(V)).join(""),W=`[${c}${d}${Z}] ${I.method} ${s} ${p.ok?"succeeded":"failed"} with status ${p.status} in ${A-m}ms`;if(!p.ok){let R=await this.shouldRetry(p);if(l&&R){let T=`retrying, ${l} attempts remaining`;return await mTt(p.body),Im(this).info(`${W} - ${T}`),Im(this).debug(`[${c}] response error (${T})`,ef({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,durationMs:A-m})),this.retryRequest(r,l,n??c,p.headers)}let V=R?"error; no more retries left":"error; not retryable";Im(this).info(`${W} - ${V}`);let v=await p.text().catch(T=>Ade(T).message),X=WTt(v),S=X?void 0:v;throw Im(this).debug(`[${c}] response error (${V})`,ef({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,message:S,durationMs:Date.now()-m})),this.makeStatusError(p.status,X,S,p.headers)}return Im(this).info(W),Im(this).debug(`[${c}] response start`,ef({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,durationMs:A-m})),{response:p,options:r,controller:G,requestLogID:c,retryOfRequestLogID:n,startTime:m}}getAPIList(e,l,n){return this.requestAPIList(l,{method:"get",path:e,...n})}requestAPIList(e,l){let n=this.makeRequest(l,null,void 0);return new yde(this,n,e)}async fetchWithTimeout(e,l,n,r){let{signal:a,method:I,...s}=l||{};a&&a.addEventListener("abort",()=>r.abort());let o=setTimeout(()=>r.abort(),n),c=globalThis.ReadableStream&&s.body instanceof globalThis.ReadableStream||typeof s.body=="object"&&s.body!==null&&Symbol.asyncIterator in s.body,d={signal:r.signal,...c?{duplex:"half"}:{},method:"GET",...s};I&&(d.method=I.toUpperCase());try{return await this.fetch.call(void 0,e,d)}finally{clearTimeout(o)}}async shouldRetry(e){let l=e.headers.get("x-should-retry");return l==="true"?!0:l==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,l,n,r){let a,I=r?.get("retry-after-ms");if(I){let o=parseFloat(I);Number.isNaN(o)||(a=o)}let s=r?.get("retry-after");if(s&&!a){let o=parseFloat(s);Number.isNaN(o)?a=Date.parse(s)-Date.now():a=o*1e3}if(!(a&&0<=a&&a<60*1e3)){let o=e.maxRetries??this.maxRetries;a=this.calculateDefaultRetryTimeoutMillis(l,o)}return await Fw(a),this.makeRequest(e,l-1,n)}calculateDefaultRetryTimeoutMillis(e,l){let a=l-e,I=Math.min(.5*Math.pow(2,a),8),s=1-Math.random()*.25;return I*s*1e3}async buildRequest(e,{retryCount:l=0}={}){let n={...e},{method:r,path:a,query:I,defaultBaseURL:s}=n,o=this.buildURL(a,I,s);"timeout"in n&&NTt("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:c,body:d}=this.buildBody({options:n}),m=await this.buildHeaders({options:e,method:r,bodyHeaders:c,retryCount:l});return{req:{method:r,headers:m,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&d instanceof globalThis.ReadableStream&&{duplex:"half"},...d&&{body:d},...this.fetchOptions??{},...n.fetchOptions??{}},url:o,timeout:n.timeout}}async buildHeaders({options:e,method:l,bodyHeaders:n,retryCount:r}){let a={};this.idempotencyHeader&&l!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=e.idempotencyKey);let I=Vn([a,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...BTt(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(I),I.values}buildBody({options:{body:e,headers:l}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=Vn([l]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.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:jYe(e)}:ht(this,E1e,"f").call(this,{body:e,headers:n})}};A6e=ia,E1e=new WeakMap,h6e=new WeakSet,mOt=function(){return this.baseURL!=="https://api.openai.com/v1"};ia.OpenAI=A6e;ia.DEFAULT_TIMEOUT=6e5;ia.OpenAIError=Yn;ia.APIError=Ru;ia.APIConnectionError=Pk;ia.APIConnectionTimeoutError=jk;ia.APIUserAbortError=zm;ia.NotFoundError=KK;ia.ConflictError=qK;ia.RateLimitError=e8;ia.BadRequestError=zK;ia.AuthenticationError=PK;ia.InternalServerError=t8;ia.PermissionDeniedError=jK;ia.UnprocessableEntityError=$K;ia.InvalidWebhookSignatureError=ww;ia.toFile=b1e;ia.Completions=dT;ia.Chat=tL;ia.Embeddings=mT;ia.Files=GT;ia.Images=gT;ia.Audio=fw;ia.Moderations=NT;ia.Models=ZT;ia.FineTuning=tY;ia.Graders=sL;ia.VectorStores=If;ia.Webhooks=WT;ia.Beta=Xw;ia.Batches=IT;ia.Uploads=dL;ia.Responses=cL;ia.Realtime=oL;ia.Conversations=aL;ia.Evals=IL;ia.Containers=rL;var Lde=class extends ia{constructor({baseURL:e=$2("OPENAI_BASE_URL"),apiKey:l=$2("AZURE_OPENAI_API_KEY"),apiVersion:n=$2("OPENAI_API_VERSION"),endpoint:r,deployment:a,azureADTokenProvider:I,dangerouslyAllowBrowser:s,...o}={}){if(!n)throw new Yn("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 I=="function"&&(s=!0),!I&&!l)throw new Yn("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(I&&l)throw new Yn("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(o.defaultQuery={...o.defaultQuery,"api-version":n},e){if(r)throw new Yn("baseURL and endpoint are mutually exclusive")}else{if(r||(r=process.env.AZURE_OPENAI_ENDPOINT),!r)throw new Yn("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");e=`${r}/openai`}super({apiKey:I??l,baseURL:e,...o,...s!==void 0?{dangerouslyAllowBrowser:s}:{}}),this.apiVersion="",this.apiVersion=n,this.deploymentName=a}async buildRequest(e,l={}){if(LEn.has(e.path)&&e.method==="post"&&e.body!==void 0){if(!a8(e.body))throw new Error("Expected request body to be an object");let n=this.deploymentName||e.body.model||e.__metadata?.model;n!==void 0&&!this.baseURL.includes("/deployments")&&(e.path=`/deployments/${n}${e.path}`)}return super.buildRequest(e,l)}async authHeaders(e){return typeof this._options.apiKey=="string"?Vn([{"api-key":this.apiKey}]):super.authHeaders(e)}},LEn=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"]);import{readFileSync as JEn}from"fs";import{dirname as xEn,join as R1e}from"path";import{fileURLToPath as SEn}from"url";var Jde=null;function uL(){return d0().version}function d0(){if(Jde!==null)return Jde;try{let t=SEn(import.meta.url),e=xEn(t),l=[R1e(e,"package.json"),R1e(e,"../package.json"),R1e(e,"../../package.json"),R1e(e,"../runtime/package.json")];for(let r of l)try{let a=JSON.parse(JEn(r,"utf8")),I={name:a.name||"unknown",nameNoScope:BEn(a.name||"unknown"),version:a.version||"unknown",buildMetadata:a.buildMetadata};return Jde=I,I}catch{continue}let n={name:"unknown",nameNoScope:"unknown",version:"unknown"};return Jde=n,n}catch{let e={name:"unknown",nameNoScope:"unknown",version:"unknown"};return Jde=e,e}}function BEn(t){return t.replace(/^@.*\//,"")}var bOt=Fh("keyvault-secrets");var GOt=Fh("keyvault-secrets");function Sh(t,e){return typeof t=="string"?a2e(t,e):a2e(t)}function g6e(t){return Fie(t,["key"])&&typeof t.key=="string"}function xde(t){let e=t;return e&&typeof e.getToken=="function"&&(e.signRequest===void 0||e.getToken.length>0)}var TEn="ApiVersionPolicy";function pOt(t){return{name:TEn,sendRequest:(e,l)=>{let n=new URL(e.url);return!n.searchParams.get("api-version")&&t.apiVersion&&(e.url=`${e.url}${Array.from(n.searchParams.keys()).length>0?"&":"?"}api-version=${t.apiVersion}`),l(e)}}}var OEn="keyCredentialAuthenticationPolicy";function hOt(t,e){return{name:OEn,async sendRequest(l,n){return l.headers.set(e,t.key),n(l)}}}function AOt(t,e,l={}){var n,r,a,I;let{credential:s,clientOptions:o}=l;if(s){if(xde(s)){let c=v9({credential:s,scopes:(r=(n=o?.credentials)===null||n===void 0?void 0:n.scopes)!==null&&r!==void 0?r:`${e}/.default`});t.addPolicy(c)}else if(UEn(s)){if(!(!((a=o?.credentials)===null||a===void 0)&&a.apiKeyHeaderName))throw new Error("Missing API Key Header Name");let c=hOt(s,(I=o?.credentials)===null||I===void 0?void 0:I.apiKeyHeaderName);t.addPolicy(c)}}}function gOt(t,e,l={}){let n=Kie(l);return n.addPolicy(pOt(l)),AOt(n,t,{credential:e,clientOptions:l}),n}function UEn(t){return t.key!==void 0}function eN(t){return lze(t)}function mL(t){return t.onResponse?Object.assign(Object.assign({},t),{onResponse(e,l){var n;(n=t.onResponse)===null||n===void 0||n.call(t,e,l,l)}}):t}function ZOt(t,e,l={}){let n;e&&(MEn(e)?n=e:l=e??{});let r=gOt(t,n,l),a=tze(t,Object.assign(Object.assign({},l),{pipeline:r})),I=(s,...o)=>({get:(c={})=>a.path(s,...o).get(mL(c)),post:(c={})=>a.path(s,...o).post(mL(c)),put:(c={})=>a.path(s,...o).put(mL(c)),patch:(c={})=>a.path(s,...o).patch(mL(c)),delete:(c={})=>a.path(s,...o).delete(mL(c)),head:(c={})=>a.path(s,...o).head(mL(c)),options:(c={})=>a.path(s,...o).options(mL(c)),trace:(c={})=>a.path(s,...o).trace(mL(c))});return{path:I,pathUnchecked:I,pipeline:a.pipeline}}function MEn(t){return g6e(t)||xde(t)}function Z6e(t,e,l={}){var n,r,a,I,s,o,c,d;let m=(r=(n=l.endpoint)!==null&&n!==void 0?n:l.baseUrl)!==null&&r!==void 0?r:String(t),G=(a=l?.userAgentOptions)===null||a===void 0?void 0:a.userAgentPrefix,p="azsdk-js-keyvault-secrets/1.0.0-beta.1",A=G?`${G} azsdk-js-api ${p}`:`azsdk-js-api ${p}`,Z=Object.assign(Object.assign({},l),{userAgentOptions:{userAgentPrefix:A},loggingOptions:{logger:(s=(I=l.loggingOptions)===null||I===void 0?void 0:I.logger)!==null&&s!==void 0?s:GOt.info},credentials:{scopes:(c=(o=l.credentials)===null||o===void 0?void 0:o.scopes)!==null&&c!==void 0?c:["https://vault.azure.net/.default"]}}),{apiVersion:W}=Z,R=Die(Z,["apiVersion"]),V=ZOt(m,e,R);V.pipeline.removePolicy({name:"ApiVersionPolicy"});let v=(d=l.apiVersion)!==null&&d!==void 0?d:"7.6";return V.pipeline.addPolicy({name:"ClientApiVersionPolicy",sendRequest:(X,S)=>{let O=new URL(X.url);return O.searchParams.get("api-version")||(X.url=`${X.url}${Array.from(O.searchParams.keys()).length>0?"&":"?"}api-version=${v}`),S(X)}}),Object.assign(Object.assign({},V),{apiVersion:v})}function NOt(t){return{value:t.value,tags:t.tags,contentType:t.contentType,attributes:t.secretAttributes?WOt(t.secretAttributes):t.secretAttributes}}function WOt(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 V1e(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}}var Sde;(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"})(Sde||(Sde={}));function X8(t){return{value:t.value,id:t.id,contentType:t.contentType,attributes:t.attributes?V1e(t.attributes):t.attributes,tags:t.tags,kid:t.kid,managed:t.managed}}function ry(t){return{error:t.error?yOt(t.error):t.error}}function yOt(t){return{code:t.code,message:t.message,innerError:t.innererror?yOt(t.innererror):t.innererror}}function N6e(t){return{value:t.value,id:t.id,contentType:t.contentType,attributes:t.attributes?V1e(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 EOt(t){return{contentType:t.contentType,attributes:t.secretAttributes?WOt(t.secretAttributes):t.secretAttributes,tags:t.tags}}function W6e(t){return{value:t.value?_En(t.value):t.value,nextLink:t.nextLink}}function _En(t){return t.map(e=>DEn(e))}function DEn(t){return{id:t.id,attributes:t.attributes?V1e(t.attributes):t.attributes,tags:t.tags,contentType:t.contentType,managed:t.managed}}function ROt(t){return{value:t.value?zEn(t.value):t.value,nextLink:t.nextLink}}function zEn(t){return t.map(e=>PEn(e))}function PEn(t){return{id:t.id,attributes:t.attributes?V1e(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 YOt(t){return{value:t.value&&typeof t.value=="string"?oJt(t.value,"base64url"):t.value}}function VOt(t){return{value:sJt(t.secretBundleBackup,"base64url")}}var Y1e;(function(t){t.V75="7.5",t.V76Preview2="7.6-preview.2",t.V76="7.6"})(Y1e||(Y1e={}));function w1e(t,e,l,n,r={}){var a,I;let s=(a=r.itemName)!==null&&a!==void 0?a:"value",o=(I=r.nextLinkName)!==null&&I!==void 0?I:"nextLink",c={getPage:async d=>{let m=d===void 0?await e():await t.pathUnchecked(d).get();e0n(m,n);let G=await l(m),p=qEn(G,o);return{page:$En(G,s),nextPageLink:p}},byPage:d=>{let{continuationToken:m}=d??{};return y6e(c,{pageLink:m})}};return jEn(c)}function jEn(t){var e;let l=KEn(t);return{next(){return l.next()},[Symbol.asyncIterator](){return this},byPage:(e=t?.byPage)!==null&&e!==void 0?e:n=>{let{continuationToken:r}=n??{};return y6e(t,{pageLink:r})}}}function KEn(t){return Wk(this,arguments,function*(){var l,n,r,a;let I=y6e(t);try{for(var s=!0,o=C9(I),c;c=yield Sc(o.next()),l=c.done,!l;s=!0)a=c.value,s=!1,yield Sc(yield*e3t(C9(a)))}catch(d){n={error:d}}finally{try{!s&&!l&&(r=o.return)&&(yield Sc(r.call(o)))}finally{if(n)throw n.error}}})}function y6e(t){return Wk(this,arguments,function*(l,n={}){let{pageLink:r}=n,a=yield Sc(l.getPage(r??l.firstPageLink));if(!a)return yield Sc(void 0);let I=a.page;for(I.continuationToken=a.nextPageLink,yield yield Sc(I);a.nextPageLink;){if(a=yield Sc(l.getPage(a.nextPageLink)),!a)return yield Sc(void 0);I=a.page,I.continuationToken=a.nextPageLink,yield yield Sc(I)}})}function qEn(t,e){if(!e)return;let l=t[e];if(typeof l!="string"&&typeof l<"u"&&l!==null)throw new Cv(`Body Property ${e} should be a string or undefined or null but got ${typeof l}`);if(l!==null)return l}function $En(t,e){let l=t[e];if(!Array.isArray(l))throw new Cv(`Couldn't paginate response
|
|
1902
1902
|
Body doesn't contain an array property with name: ${e}`);return l??[]}function e0n(t,e){if(!e.includes(t.status))throw Sh(`Pagination failed with unexpected statusCode ${t.status}`,t)}function k8(t,e,l){return(e??l==="+")||l==="#"?wOt(t):QOt(t)}function wOt(t){return t.split(/(%[0-9A-Fa-f]{2})/g).map(e=>/%[0-9A-Fa-f]/.test(e)?e:encodeURI(e)).join("")}function QOt(t){return encodeURIComponent(t).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function Bde(t){return t!=null}function E6e(t){return[!!t&&[";","?","&"].includes(t),t&&["?","&"].includes(t)?"=":""]}function Q1e(t,e=!1){return e?!t||t==="+"?"":t:!t||t==="+"||t==="#"?",":t==="?"?"&":t}function t0n(t){let e=t.isFirst,{op:l,varName:n,varValue:r,reserved:a}=t,I=[],[s,o]=E6e(l);if(Array.isArray(r))for(let c of r.filter(Bde))I.push(`${Q1e(l,e)}`),s&&n&&(I.push(`${encodeURIComponent(n)}`),c===""?I.push(o):I.push("=")),I.push(k8(c,a,l)),e=!1;else if(typeof r=="object")for(let c of Object.keys(r)){let d=r[c];Bde(d)&&(I.push(`${Q1e(l,e)}`),c&&(I.push(`${encodeURIComponent(c)}`),s&&d===""?I.push(o):I.push("=")),I.push(k8(d,a,l)),e=!1)}return I.join("")}function l0n(t){let{op:e,varName:l,varValue:n,isFirst:r,reserved:a}=t,I=[],s=Q1e(e,r),[o,c]=E6e(e);if(o&&l){if(I.push(k8(l,a,e)),n==="")return c||I.push(c),I.join("")?`${s}${I.join("")}`:void 0;I.push("=")}let d=[];if(Array.isArray(n))for(let m of n.filter(Bde))d.push(k8(m,a,e));else if(typeof n=="object")for(let m of Object.keys(n))Bde(n[m])&&(d.push(QOt(m)),d.push(k8(n[m],a,e)));return I.push(d.join(",")),I.join(",")?`${s}${I.join("")}`:void 0}function n0n(t){let{op:e,varName:l,modifier:n,isFirst:r,reserved:a,varValue:I}=t;if(Bde(I))if(["string","number","boolean"].includes(typeof I)){let s=I.toString(),[o,c]=E6e(e),d=[Q1e(e,r)];return o&&l&&(d.push(l),s===""?d.push(c):d.push("=")),n&&n!=="*"&&(s=s.substring(0,parseInt(n,10))),d.push(k8(s,a,e)),d.join("")}else return n==="*"?t0n(t):l0n(t);else return}function ay(t,e,l){return t.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g,(n,r,a)=>{if(!r)return wOt(a);let I;["+","#",".","/",";","?","&"].includes(r[0])&&(I=r[0],r=r.slice(1));let s=r.split(/,/g),o=[];for(let c of s){let d=/([^:\*]*)(?::(\d+)|(\*))?/.exec(c);if(!d||!d[1])continue;let m=n0n({isFirst:o.length===0,op:I,varValue:e[d[1]],varName:d[1],modifier:d[2]||d[3],reserved:l?.allowReserved});m&&o.push(m)}return o.join("")})}function r0n(t,e,l={requestOptions:{}}){var n,r;let a=ay("/secrets/restore{?api%2Dversion}",{"api%2Dversion":t.apiVersion},{allowReserved:(n=l?.requestOptions)===null||n===void 0?void 0:n.skipUrlEncoding});return t.path(a).post(Object.assign(Object.assign({},eN(l)),{contentType:"application/json",headers:Object.assign({accept:"application/json"},(r=l.requestOptions)===null||r===void 0?void 0:r.headers),body:VOt(e)}))}async function a0n(t){if(!["200"].includes(t.status)){let l=Sh(t);throw l.details=ry(t.body),l}return X8(t.body)}async function R6e(t,e,l={requestOptions:{}}){let n=await r0n(t,e,l);return a0n(n)}function I0n(t,e,l={requestOptions:{}}){var n,r;let a=ay("/secrets/{secret-name}/backup{?api%2Dversion}",{"secret-name":e,"api%2Dversion":t.apiVersion},{allowReserved:(n=l?.requestOptions)===null||n===void 0?void 0:n.skipUrlEncoding});return t.path(a).post(Object.assign(Object.assign({},eN(l)),{headers:Object.assign({accept:"application/json"},(r=l.requestOptions)===null||r===void 0?void 0:r.headers)}))}async function s0n(t){if(!["200"].includes(t.status)){let l=Sh(t);throw l.details=ry(t.body),l}return YOt(t.body)}async function Y6e(t,e,l={requestOptions:{}}){let n=await I0n(t,e,l);return s0n(n)}function o0n(t,e,l={requestOptions:{}}){var n,r;let a=ay("/deletedsecrets/{secret-name}/recover{?api%2Dversion}",{"secret-name":e,"api%2Dversion":t.apiVersion},{allowReserved:(n=l?.requestOptions)===null||n===void 0?void 0:n.skipUrlEncoding});return t.path(a).post(Object.assign(Object.assign({},eN(l)),{headers:Object.assign({accept:"application/json"},(r=l.requestOptions)===null||r===void 0?void 0:r.headers)}))}async function i0n(t){if(!["200"].includes(t.status)){let l=Sh(t);throw l.details=ry(t.body),l}return X8(t.body)}async function V6e(t,e,l={requestOptions:{}}){let n=await o0n(t,e,l);return i0n(n)}function c0n(t,e,l={requestOptions:{}}){var n,r;let a=ay("/deletedsecrets/{secret-name}{?api%2Dversion}",{"secret-name":e,"api%2Dversion":t.apiVersion},{allowReserved:(n=l?.requestOptions)===null||n===void 0?void 0:n.skipUrlEncoding});return t.path(a).delete(Object.assign(Object.assign({},eN(l)),{headers:Object.assign({accept:"application/json"},(r=l.requestOptions)===null||r===void 0?void 0:r.headers)}))}async function d0n(t){if(!["204"].includes(t.status)){let l=Sh(t);throw l.details=ry(t.body),l}}async function w6e(t,e,l={requestOptions:{}}){let n=await c0n(t,e,l);return d0n(n)}function u0n(t,e,l={requestOptions:{}}){var n,r;let a=ay("/deletedsecrets/{secret-name}{?api%2Dversion}",{"secret-name":e,"api%2Dversion":t.apiVersion},{allowReserved:(n=l?.requestOptions)===null||n===void 0?void 0:n.skipUrlEncoding});return t.path(a).get(Object.assign(Object.assign({},eN(l)),{headers:Object.assign({accept:"application/json"},(r=l.requestOptions)===null||r===void 0?void 0:r.headers)}))}async function m0n(t){if(!["200"].includes(t.status)){let l=Sh(t);throw l.details=ry(t.body),l}return N6e(t.body)}async function Q6e(t,e,l={requestOptions:{}}){let n=await u0n(t,e,l);return m0n(n)}function b0n(t,e={requestOptions:{}}){var l,n;let r=ay("/deletedsecrets{?api%2Dversion,maxresults}",{"api%2Dversion":t.apiVersion,maxresults:e?.maxresults},{allowReserved:(l=e?.requestOptions)===null||l===void 0?void 0:l.skipUrlEncoding});return t.path(r).get(Object.assign(Object.assign({},eN(e)),{headers:Object.assign({accept:"application/json"},(n=e.requestOptions)===null||n===void 0?void 0:n.headers)}))}async function G0n(t){if(!["200"].includes(t.status)){let l=Sh(t);throw l.details=ry(t.body),l}return ROt(t.body)}function F6e(t,e={requestOptions:{}}){return w1e(t,()=>b0n(t,e),G0n,["200"],{itemName:"value",nextLinkName:"nextLink"})}function p0n(t,e,l={requestOptions:{}}){var n,r;let a=ay("/secrets/{secret-name}/versions{?api%2Dversion,maxresults}",{"secret-name":e,"api%2Dversion":t.apiVersion,maxresults:l?.maxresults},{allowReserved:(n=l?.requestOptions)===null||n===void 0?void 0:n.skipUrlEncoding});return t.path(a).get(Object.assign(Object.assign({},eN(l)),{headers:Object.assign({accept:"application/json"},(r=l.requestOptions)===null||r===void 0?void 0:r.headers)}))}async function h0n(t){if(!["200"].includes(t.status)){let l=Sh(t);throw l.details=ry(t.body),l}return W6e(t.body)}function C6e(t,e,l={requestOptions:{}}){return w1e(t,()=>p0n(t,e,l),h0n,["200"],{itemName:"value",nextLinkName:"nextLink"})}function A0n(t,e={requestOptions:{}}){var l,n;let r=ay("/secrets{?api%2Dversion,maxresults}",{"api%2Dversion":t.apiVersion,maxresults:e?.maxresults},{allowReserved:(l=e?.requestOptions)===null||l===void 0?void 0:l.skipUrlEncoding});return t.path(r).get(Object.assign(Object.assign({},eN(e)),{headers:Object.assign({accept:"application/json"},(n=e.requestOptions)===null||n===void 0?void 0:n.headers)}))}async function g0n(t){if(!["200"].includes(t.status)){let l=Sh(t);throw l.details=ry(t.body),l}return W6e(t.body)}function v6e(t,e={requestOptions:{}}){return w1e(t,()=>A0n(t,e),g0n,["200"],{itemName:"value",nextLinkName:"nextLink"})}function Z0n(t,e,l,n={requestOptions:{}}){var r,a;let I=ay("/secrets/{secret-name}/{secret-version}{?api%2Dversion}",{"secret-name":e,"secret-version":l,"api%2Dversion":t.apiVersion},{allowReserved:(r=n?.requestOptions)===null||r===void 0?void 0:r.skipUrlEncoding});return t.path(I).get(Object.assign(Object.assign({},eN(n)),{headers:Object.assign({accept:"application/json"},(a=n.requestOptions)===null||a===void 0?void 0:a.headers)}))}async function N0n(t){if(!["200"].includes(t.status)){let l=Sh(t);throw l.details=ry(t.body),l}return X8(t.body)}async function f6e(t,e,l,n={requestOptions:{}}){let r=await Z0n(t,e,l,n);return N0n(r)}function W0n(t,e,l,n,r={requestOptions:{}}){var a,I;let s=ay("/secrets/{secret-name}/{secret-version}{?api%2Dversion}",{"secret-name":e,"secret-version":l,"api%2Dversion":t.apiVersion},{allowReserved:(a=r?.requestOptions)===null||a===void 0?void 0:a.skipUrlEncoding});return t.path(s).patch(Object.assign(Object.assign({},eN(r)),{contentType:"application/json",headers:Object.assign({accept:"application/json"},(I=r.requestOptions)===null||I===void 0?void 0:I.headers),body:EOt(n)}))}async function y0n(t){if(!["200"].includes(t.status)){let l=Sh(t);throw l.details=ry(t.body),l}return X8(t.body)}async function H6e(t,e,l,n,r={requestOptions:{}}){let a=await W0n(t,e,l,n,r);return y0n(a)}function E0n(t,e,l={requestOptions:{}}){var n,r;let a=ay("/secrets/{secret-name}{?api%2Dversion}",{"secret-name":e,"api%2Dversion":t.apiVersion},{allowReserved:(n=l?.requestOptions)===null||n===void 0?void 0:n.skipUrlEncoding});return t.path(a).delete(Object.assign(Object.assign({},eN(l)),{headers:Object.assign({accept:"application/json"},(r=l.requestOptions)===null||r===void 0?void 0:r.headers)}))}async function R0n(t){if(!["200"].includes(t.status)){let l=Sh(t);throw l.details=ry(t.body),l}return N6e(t.body)}async function X6e(t,e,l={requestOptions:{}}){let n=await E0n(t,e,l);return R0n(n)}function Y0n(t,e,l,n={requestOptions:{}}){var r,a;let I=ay("/secrets/{secret-name}{?api%2Dversion}",{"secret-name":e,"api%2Dversion":t.apiVersion},{allowReserved:(r=n?.requestOptions)===null||r===void 0?void 0:r.skipUrlEncoding});return t.path(I).put(Object.assign(Object.assign({},eN(n)),{contentType:"application/json",headers:Object.assign({accept:"application/json"},(a=n.requestOptions)===null||a===void 0?void 0:a.headers),body:NOt(l)}))}async function V0n(t){if(!["200"].includes(t.status)){let l=Sh(t);throw l.details=ry(t.body),l}return X8(t.body)}async function k6e(t,e,l,n={requestOptions:{}}){let r=await Y0n(t,e,l,n);return V0n(r)}var Tde=class{constructor(e,l,n={}){var r;let a=(r=n?.userAgentOptions)===null||r===void 0?void 0:r.userAgentPrefix,I=a?`${a} azsdk-js-client`:"azsdk-js-client";this._client=Z6e(e,l,Object.assign(Object.assign({},n),{userAgentOptions:{userAgentPrefix:I}})),this.pipeline=this._client.pipeline}restoreSecret(e,l={requestOptions:{}}){return R6e(this._client,e,l)}backupSecret(e,l={requestOptions:{}}){return Y6e(this._client,e,l)}recoverDeletedSecret(e,l={requestOptions:{}}){return V6e(this._client,e,l)}purgeDeletedSecret(e,l={requestOptions:{}}){return w6e(this._client,e,l)}getDeletedSecret(e,l={requestOptions:{}}){return Q6e(this._client,e,l)}getDeletedSecrets(e={requestOptions:{}}){return F6e(this._client,e)}getSecretVersions(e,l={requestOptions:{}}){return C6e(this._client,e,l)}getSecrets(e={requestOptions:{}}){return v6e(this._client,e)}getSecret(e,l,n={requestOptions:{}}){return f6e(this._client,e,l,n)}updateSecret(e,l,n,r={requestOptions:{}}){return H6e(this._client,e,l,n,r)}deleteSecret(e,l={requestOptions:{}}){return X6e(this._client,e,l)}setSecret(e,l,n={requestOptions:{}}){return k6e(this._client,e,l,n)}};var w0n=["authorization","authorization_url","resource","scope","tenantId","claims","error"];function L6e(t){let e=/,? +/,l=t.split(e).reduce((n,r)=>{if(r.match(/\w="/)){let[a,...I]=r.split("=");if(w0n.includes(a))return Object.assign(Object.assign({},n),{[a]:I.join("=").slice(1,-1)})}return n},{});if(l.authorization)try{let n=new URL(l.authorization).pathname.substring(1);n&&(l.tenantId=n)}catch{throw new Error(`The challenge authorization URI '${l.authorization}' is invalid.`)}return l}var Q0n={forcedRefreshWindowInMs:1e3,retryIntervalInMs:3e3,refreshWindowInMs:1e3*60*2};async function F0n(t,e,l){async function n(){if(Date.now()<l)try{return await t()}catch{return null}else{let a=await t();if(a===null)throw new Error("Failed to refresh access token.");return a}}let r=await n();for(;r===null;)await Zk(e),r=await n();return r}function FOt(t,e){let l=null,n=null,r,a=Object.assign(Object.assign({},Q0n),e),I={get isRefreshing(){return l!==null},get shouldRefresh(){var o;return I.isRefreshing?!1:n?.refreshAfterTimestamp&&n.refreshAfterTimestamp<Date.now()?!0:((o=n?.expiresOnTimestamp)!==null&&o!==void 0?o:0)-a.refreshWindowInMs<Date.now()},get mustRefresh(){return n===null||n.expiresOnTimestamp-a.forcedRefreshWindowInMs<Date.now()}};function s(o,c){var d;return I.isRefreshing||(l=F0n(()=>t.getToken(o,c),a.retryIntervalInMs,(d=n?.expiresOnTimestamp)!==null&&d!==void 0?d:Date.now()).then(G=>(l=null,n=G,r=c.tenantId,n)).catch(G=>{throw l=null,n=null,r=void 0,G})),l}return async(o,c)=>{let d=!!c.claims,m=r!==c.tenantId;return d&&(n=null),m||d||I.mustRefresh?s(o,c):(I.shouldRefresh&&s(o,c),n)}}var COt=Fh("keyvault-common");function C0n(t,e){let l;try{l=new URL(t)}catch{throw new Error(`The challenge contains invalid scope '${t}'`)}if(!new URL(e.url).hostname.endsWith(`.${l.hostname}`))throw new Error(`The challenge resource '${l.hostname}' does not match the requested domain. Set disableChallengeResourceVerification to true in your client options to disable. See https://aka.ms/azsdk/blog/vault-uri for more information.`)}var v0n="keyVaultAuthenticationPolicy";function vOt(t,e={}){let{disableChallengeResourceVerification:l}=e,n={status:"none"},r=FOt(t);function a(d){return{abortSignal:d.abortSignal,requestOptions:{timeout:d.timeout>0?d.timeout:void 0},tracingOptions:d.tracingOptions}}async function I(d){let m=a(d);switch(n.status){case"none":n={status:"started",originalBody:d.body},d.body=null;break;case"started":break;case"complete":{let G=await r(n.scopes,Object.assign(Object.assign({},m),{enableCae:!0,tenantId:n.tenantId}));G&&d.headers.set("authorization",`Bearer ${G.token}`);break}}}async function s(d,m,G){if(m.status!==401)return m;d.body===null&&n.status==="started"&&(d.body=n.originalBody);let p=a(d),A=m.headers.get("WWW-Authenticate");if(!A)return COt.warning("keyVaultAuthentication policy encountered a 401 response without a corresponding WWW-Authenticate header. This is unexpected. Not handling the 401 response."),m;let Z=L6e(A),W=Z.resource?Z.resource+"/.default":Z.scope;if(!W)return m;l||C0n(W,d);let R=await r([W],Object.assign(Object.assign({},p),{enableCae:!0,tenantId:Z.tenantId}));return R?(d.headers.set("Authorization",`Bearer ${R.token}`),n={status:"complete",scopes:[W],tenantId:Z.tenantId},G(d)):m}async function o(d,m,G){if(n.status!=="complete"||m.status!==401)return m;let p=a(d),A=m.headers.get("WWW-Authenticate");if(!A)return m;let{claims:Z,error:W}=L6e(A);if(W!=="insufficient_claims"||Z===void 0)return m;let R=atob(Z),V=await r(n.scopes,Object.assign(Object.assign({},p),{enableCae:!0,tenantId:n.tenantId,claims:R}));return d.headers.set("Authorization",`Bearer ${V.token}`),G(d)}async function c(d,m){await I(d);let G=await m(d);return G=await s(d,G,m),G=await o(d,G,m),G}return{name:v0n,sendRequest:c}}function fOt(t,e){if(typeof t!="string"||!(t=t.trim()))throw new Error("Invalid collection argument");if(typeof e!="string"||!(e=e.trim()))throw new Error("Invalid identifier argument");let l;try{l=new URL(e)}catch{throw new Error(`Invalid ${t} identifier: ${e}. Not a valid URI`)}let n=(l.pathname||"").split("/");if(n.length!==3&&n.length!==4)throw new Error(`Invalid ${t} identifier: ${e}. Bad number of segments: ${n.length}`);if(t!==n[1])throw new Error(`Invalid ${t} identifier: ${e}. segment [1] should be "${t}", found "${n[1]}"`);let r=`${l.protocol}//${l.host}`,a=n[2],I=n.length===4?n[3]:void 0;return{vaultUrl:r,name:a,version:I}}function J6e(t){let l=t.split("/")[3];return Object.assign({sourceId:t},fOt(l,t))}function Yg(t){let e=t,l=t,n=J6e(e.id),r=e.attributes;delete e.attributes;let a={value:e.value,name:n.name,properties:{expiresOn:r?.expires,createdOn:r?.created,updatedOn:r?.updated,enabled:r?.enabled,notBefore:r?.notBefore,recoverableDays:r?.recoverableDays,recoveryLevel:r?.recoveryLevel,id:e.id,contentType:e.contentType,tags:e.tags,managed:e.managed,vaultUrl:n.vaultUrl,version:n.version,name:n.name,certificateKeyId:e.kid}};return l.recoveryId&&(a.properties.recoveryId=l.recoveryId,a.properties.scheduledPurgeDate=l.scheduledPurgeDate,a.properties.deletedOn=l.deletedDate,a.recoveryId=l.recoveryId,a.scheduledPurgeDate=l.scheduledPurgeDate,a.deletedOn=l.deletedDate),r&&(r.vaultUrl&&delete a.properties.vaultUrl,r.expires&&delete a.properties.expires,r.created&&delete a.properties.created,r.updated&&delete a.properties.updated),a}function F1e(t,e,l){let n;return{async next(){n??(n=t(Object.assign(Object.assign({},e),{maxresults:void 0})));let r=await n.next();return Object.assign(Object.assign({},r),{value:r.value&&l(r.value)})},[Symbol.asyncIterator](){return this},byPage(r){return Wk(this,arguments,function*(){var I,s,o,c;let d=t(Object.assign(Object.assign({},e),{maxresults:r?.maxPageSize})).byPage(r);try{for(var m=!0,G=C9(d),p;p=yield Sc(G.next()),I=p.done,!I;m=!0)c=p.value,m=!1,yield yield Sc(c.map(l))}catch(A){s={error:A}}finally{try{!m&&!I&&(o=G.return)&&(yield Sc(o.call(G)))}finally{if(s)throw s.error}}})}}}var C1e="4.10.0";var tN=kB({namespace:"Microsoft.KeyVault",packageName:"@azure/keyvault-secrets",packageVersion:C1e});var x6e=Fh("core-lro");var S6e=class t extends Error{constructor(e){super(e),this.name="PollerStoppedError",Object.setPrototypeOf(this,t.prototype)}},B6e=class t extends Error{constructor(e){super(e),this.name="PollerCancelledError",Object.setPrototypeOf(this,t.prototype)}},Ode=class{constructor(e){this.resolveOnUnsuccessful=!1,this.stopped=!0,this.pollProgressCallbacks=[],this.operation=e,this.promise=new Promise((l,n)=>{this.resolve=l,this.reject=n}),this.promise.catch(()=>{})}async startPolling(e={}){for(this.stopped&&(this.stopped=!1);!this.isStopped()&&!this.isDone();)await this.poll(e),await this.delay()}async pollOnce(e={}){this.isDone()||(this.operation=await this.operation.update({abortSignal:e.abortSignal,fireProgress:this.fireProgress.bind(this)})),this.processUpdatedState()}fireProgress(e){for(let l of this.pollProgressCallbacks)l(e)}async cancelOnce(e={}){this.operation=await this.operation.cancel(e)}poll(e={}){if(!this.pollOncePromise){this.pollOncePromise=this.pollOnce(e);let l=()=>{this.pollOncePromise=void 0};this.pollOncePromise.then(l,l).catch(this.reject)}return this.pollOncePromise}processUpdatedState(){if(this.operation.state.error&&(this.stopped=!0,!this.resolveOnUnsuccessful))throw this.reject(this.operation.state.error),this.operation.state.error;if(this.operation.state.isCancelled&&(this.stopped=!0,!this.resolveOnUnsuccessful)){let e=new B6e("Operation was canceled");throw this.reject(e),e}this.isDone()&&this.resolve&&this.resolve(this.getResult())}async pollUntilDone(e={}){return this.stopped&&this.startPolling(e).catch(this.reject),this.processUpdatedState(),this.promise}onProgress(e){return this.pollProgressCallbacks.push(e),()=>{this.pollProgressCallbacks=this.pollProgressCallbacks.filter(l=>l!==e)}}isDone(){let e=this.operation.state;return!!(e.isCompleted||e.isCancelled||e.error)}stopPolling(){this.stopped||(this.stopped=!0,this.reject&&this.reject(new S6e("This poller is already stopped")))}isStopped(){return this.stopped}cancelOperation(e={}){if(!this.cancelPromise)this.cancelPromise=this.cancelOnce(e);else if(e.abortSignal)throw new Error("A cancel request is currently pending");return this.cancelPromise}getOperationState(){return this.operation.state}getResult(){return this.operation.state.result}toString(){return this.operation.toString()}};var L8=class extends Ode{constructor(){super(...arguments),this.intervalInMs=2e3}async delay(){return Zk(this.intervalInMs)}},J8=class{constructor(e,l={}){this.state=e,this.cancelMessage="",l.cancelMessage&&(this.cancelMessage=l.cancelMessage)}async update(){throw new Error("Operation not supported.")}async cancel(){throw new Error(this.cancelMessage)}toString(){return JSON.stringify({state:this.state})}};var v1e=class extends J8{constructor(e,l,n={}){super(e,{cancelMessage:"Canceling the deletion of a secret is not supported."}),this.state=e,this.client=l,this.operationOptions=n}deleteSecret(e,l={}){return tN.withSpan("DeleteSecretPoller.deleteSecret",l,async n=>{let r=await this.client.deleteSecret(e,n);return Yg(r)})}getDeletedSecret(e,l={}){return tN.withSpan("DeleteSecretPoller.getDeletedSecret",l,async n=>{let r=await this.client.getDeletedSecret(e,n);return Yg(r)})}async update(e={}){let l=this.state,{name:n}=l;if(e.abortSignal&&(this.operationOptions.abortSignal=e.abortSignal),!l.isStarted){let r=await this.deleteSecret(n,this.operationOptions);l.isStarted=!0,l.result=r,r.properties.recoveryId||(l.isCompleted=!0)}if(!l.isCompleted)try{l.result=await this.getDeletedSecret(n,this.operationOptions),l.isCompleted=!0}catch(r){if(r.statusCode===403)l.isCompleted=!0;else if(r.statusCode!==404)throw l.error=r,l.isCompleted=!0,r}return this}};var f1e=class extends L8{constructor(e){let{client:l,name:n,operationOptions:r,intervalInMs:a=2e3,resumeFrom:I}=e,s;I&&(s=JSON.parse(I).state);let o=new v1e(Object.assign(Object.assign({},s),{name:n}),l,r);super(o),this.intervalInMs=a}};var H1e=class extends J8{constructor(e,l,n={}){super(e,{cancelMessage:"Canceling the recovery of a deleted secret is not supported."}),this.state=e,this.client=l,this.options=n}getSecret(e,l={}){return tN.withSpan("RecoverDeletedSecretPoller.getSecret",l,async n=>{let r=await this.client.getSecret(e,l&&l.version?l.version:"",n);return Yg(r)})}recoverDeletedSecret(e,l={}){return tN.withSpan("RecoverDeletedSecretPoller.recoverDeletedSecret",l,async n=>{let r=await this.client.recoverDeletedSecret(e,n);return Yg(r)})}async update(e={}){let l=this.state,{name:n}=l;if(e.abortSignal&&(this.options.abortSignal=e.abortSignal),!l.isStarted){try{l.result=(await this.getSecret(n,this.options)).properties,l.isCompleted=!0}catch{}l.isCompleted||(l.result=(await this.recoverDeletedSecret(n,this.options)).properties,l.isStarted=!0)}if(!l.isCompleted)try{l.result=(await this.getSecret(n,this.options)).properties,l.isCompleted=!0}catch(r){if(r.statusCode===403)l.isCompleted=!0;else if(r.statusCode!==404)throw l.error=r,l.isCompleted=!0,r}return this}};var X1e=class extends L8{constructor(e){let{client:l,name:n,operationOptions:r,intervalInMs:a=2e3,resumeFrom:I}=e,s;I&&(s=JSON.parse(I).state);let o=new H1e(Object.assign(Object.assign({},s),{name:n}),l,r);super(o),this.intervalInMs=a}};var k1e=class{constructor(e,l,n={}){var r,a;this.vaultUrl=e;let I=Object.assign(Object.assign({},n),{userAgentOptions:{userAgentPrefix:`${(a=(r=n.userAgentOptions)===null||r===void 0?void 0:r.userAgentPrefix)!==null&&a!==void 0?a:""} azsdk-js-keyvault-secrets/${C1e}`},apiVersion:n.serviceVersion||"7.6",loggingOptions:{logger:bOt.info,additionalAllowedHeaderNames:["x-ms-keyvault-region","x-ms-keyvault-network-info","x-ms-keyvault-service-version"]}});this.client=new Tde(this.vaultUrl,l,I),this.client.pipeline.removePolicy({name:m2e}),this.client.pipeline.addPolicy(vOt(l,n),{}),this.client.pipeline.addPolicy({name:"ContentTypePolicy",sendRequest(s,o){var c;return((c=s.headers.get("Content-Type"))!==null&&c!==void 0?c:"").startsWith("application/json")&&s.headers.set("Content-Type","application/json"),o(s)}})}setSecret(e,l,n={}){let{enabled:r,notBefore:a,expiresOn:I,tags:s}=n,o=Die(n,["enabled","notBefore","expiresOn","tags"]);return tN.withSpan("SecretClient.setSecret",o,async c=>{let d=await this.client.setSecret(e,{value:l,secretAttributes:{enabled:r,notBefore:a,expires:I},tags:s},c);return Yg(d)})}async beginDeleteSecret(e,l={}){let n=new f1e(Object.assign(Object.assign({name:e,client:this.client},l),{operationOptions:l}));return await n.poll(),n}async updateSecretProperties(e,l,n={}){let{enabled:r,notBefore:a,expiresOn:I,tags:s}=n,o=Die(n,["enabled","notBefore","expiresOn","tags"]);return tN.withSpan("SecretClient.updateSecretProperties",o,async c=>{let d=await this.client.updateSecret(e,l,{secretAttributes:{enabled:r,notBefore:a,expires:I},tags:s},c);return Yg(d).properties})}getSecret(e,l={}){return tN.withSpan("SecretClient.getSecret",l,async n=>{let r=await this.client.getSecret(e,l&&l.version?l.version:"",n);return Yg(r)})}getDeletedSecret(e,l={}){return tN.withSpan("SecretClient.getDeletedSecret",l,async n=>{let r=await this.client.getDeletedSecret(e,n);return Yg(r)})}purgeDeletedSecret(e,l={}){return tN.withSpan("SecretClient.purgeDeletedSecret",l,async n=>{await this.client.purgeDeletedSecret(e,n)})}async beginRecoverDeletedSecret(e,l={}){let n=new X1e(Object.assign(Object.assign({name:e,client:this.client},l),{operationOptions:l}));return await n.poll(),n}backupSecret(e,l={}){return tN.withSpan("SecretClient.backupSecret",l,async n=>(await this.client.backupSecret(e,n)).value)}restoreSecretBackup(e,l={}){return tN.withSpan("SecretClient.restoreSecretBackup",l,async n=>{let r=await this.client.restoreSecret({secretBundleBackup:e},n);return Yg(r).properties})}listPropertiesOfSecretVersions(e,l={}){return F1e(n=>this.client.getSecretVersions(e,n),l,n=>Yg(n).properties)}listPropertiesOfSecrets(e={}){return F1e(this.client.getSecrets.bind(this.client),e,l=>Yg(l).properties)}listDeletedSecrets(e={}){return F1e(this.client.getDeletedSecrets.bind(this.client),e,Yg)}};var T6e=class{client;logger;constructor(e,l){if(this.logger=l,e){this.logger.debug(`Using Azure Key Vault at ${e}`);let n=new Gw;this.client=new k1e(e,n)}else this.logger.debug("No Azure Key Vault URI provided, secret provider disabled")}async getSecret(e){if(this.client)try{return(await this.client.getSecret(e)).value}catch(l){if(this.logger.warning(`Error fetching secret ${e}: ${l}`),l?.code==="SecretNotFound")return;throw l}}};function HOt(t,e){let l=t.api?.copilot?.azureKeyVaultUri;return O6e(l,e)}function O6e(t,e){return new T6e(t,e)}import{createHmac as J0n}from"crypto";var L1e=class t{static encode(e){let l=t.hmacGetBytes(e),I=(Math.floor(Date.now()/1e3)+30).toString(),s=Buffer.from(I,"ascii"),d=J0n("sha256",l).update(s).digest().toString("hex").toUpperCase();return`${I}.${d}`}static hmacGetBytes(e){return Buffer.from(e,"ascii")}};var x0n="X-GitHub-Api-Version",S0n="2025-05-01",yT=class t extends ia{constructor(l,n,r,a){super({baseURL:l,apiKey:"",logLevel:Ute()?"debug":"info"});this.headers=n;this.runnerLogger=r;this.hmacKey=a}static baseHeaders={"Content-Type":"application/json",Accept:"application/json","X-Interaction-Type":"conversation-agent","Openai-Intent":"conversation-agent","X-Initiator":"user",[x0n]:S0n};hmacKey;additionalHeaders={};static createWithOAuthToken(l,n,r,a,I,s){let o={...this.defaultHeaders(r,I),Authorization:`Bearer ${a}`,...s??{}};return l.debug(`Creating copilot-client for integration ID ${r} with token authentication. User-agent: ${o["User-Agent"]}`),new t(n,o,l)}static createWithHmac(l,n,r,a,I,s,o){let c={...this.defaultHeaders(r,I),Authorization:"",...o??{}};return s&&(c["X-GitHub-User"]=s),l.debug(`Creating copilot-client for integration ID ${r} with key authentication. User-agent: ${c["User-Agent"]}`),new t(n,c,l,a)}static defaultHeaders(l,n){let r=d0();return{...t.baseHeaders,"Copilot-Integration-Id":l,"User-Agent":`${r.nameNoScope}/${r.version} (${process.platform} ${process.version}) OpenAI/${Cw}`,"X-Interaction-Id":n}}async prepareOptions(l){this.hmacKey&&(this.headers["Request-HMAC"]=L1e.encode(this.hmacKey)),l.headers={...this.headers,...this.additionalHeaders,...l.headers},await super.prepareOptions(l)}setInitiatorHeader(l){this.headers["X-Initiator"]=l}setAdditionalHeaders(l){this.additionalHeaders=l}async listModels(){let l={method:"get",path:""};await this.prepareOptions(l);let n={};if(l.headers)for(let[s,o]of Object.entries(l.headers))typeof o=="string"&&(n[s]=o);let r=`${this.baseURL}/models`,a=await fetch(r,{method:l.method,headers:n});if(!a.ok)return this.runnerLogger.error(`Failed to list models: ${a.status} ${a.statusText}: ${await a.text()}`),a.status===421&&this.runnerLogger.error(`Verify the authenticated user against subscription-based Copilot API endpoint used: ${this.baseURL}`),[];let I=await a.json();return this.runnerLogger.debug(`Successfully listed ${I.data.length} models`),I.data}},x8=class{async createClient(e,l,n){l.startGroup("configured settings:",8),l.debug(JSON.stringify(e,null,2)),l.endGroup(8);let r=e.api?.copilot?.token,a=e.api?.copilot?.hmacKey,I=!!(a||r);if(!I){l.debug("No Copilot HMAC key or GitHub OAuth token provided, trying secret provider");let m=HOt(e,l);try{a=await m.getSecret("capi-hmac-key")}catch(G){l.debug(`Failed to get Copilot HMAC key from secret provider:
|
|
1903
1903
|
${G}`)}try{r=await m.getSecret("capi-token")}catch(G){l.debug(`Failed to get Copilot GitHub OAuth token from secret provider:
|
|
1904
|
-
${G}`)}I=!!(a||r)}let s,o=dZt(e),c=_te(e),d=e.api?.copilot?.sessionId??$F(e);if(l.debug(`Using Copilot API at ${o} with integration ID ${c}`),r&&(l.debug("Using GitHub OAuth token for Copilot API"),s=yT.createWithOAuthToken(l,o,c,r,d,n?.requestHeaders)),a){l.debug("Using Copilot HMAC key for Copilot API");let m=process.env.GITHUB_USER_ID;m?l.debug(`Using user ID ${m} for Copilot HMAC key`):l.debug("No user ID provided for Copilot HMAC key"),s=yT.createWithHmac(l,o,c,a,d,m,n?.requestHeaders)}if(s===void 0)throw new Error("No GitHub OAuth token or Copilot HMAC key provided");return s}},S8=class t extends Ru{request_id;constructor(e){super(e.status,e.error,e.message,e.headers),this.name="CAPIError",this.cause=e.cause,this.ghRequestId=e.headers?.get("x-github-request-id")||this.requestID,this.request_id=this.requestID}ghRequestId;static fromAPIError(e){if(!(!e||!(e instanceof Ru)))return new t(e)}};var U6e={type:"ephemeral"},bL=class t{constructor(e,l,n,r){this.settings=l;this.logger=n;this.clientOptions=t.initDefaultOptions(r),n.info(" "),n.debug(`Using model: ${this.model}`),this.clientPromise=e.createClient(l,n,r),this.modelPromise=this.clientPromise.then(async()=>{let a=await this.getModel();return n.debug(`Got model info: ${JSON.stringify(a,null,2)}`),a})}clientOptions;clientPromise;modelPromise;get model(){return this.clientOptions.model}static initDefaultOptions(e){return{model:e?.model||bMe.model,toolTokenBudgetProportion:e?.toolTokenBudgetProportion??.25,retryPolicy:{maxRetries:e?.retryPolicy?.maxRetries??5,errorCodesToRetry:e?.retryPolicy?.errorCodesToRetry??[],rateLimitRetryPolicy:{defaultRetryAfterSeconds:e?.retryPolicy?.rateLimitRetryPolicy?.defaultRetryAfterSeconds??5,initialRetryBackoffExtraSeconds:e?.retryPolicy?.rateLimitRetryPolicy?.initialRetryBackoffExtraSeconds??1,retryBackoffExtraGrowth:e?.retryPolicy?.rateLimitRetryPolicy?.retryBackoffExtraGrowth??2,maxRetryAfterSeconds:e?.retryPolicy?.rateLimitRetryPolicy?.maxRetryAfterSeconds??180}},thinkingMode:e?.thinkingMode??!1,requestHeaders:e?.requestHeaders??{}}}getCompletionOptions(e,l){let n={snippy:{enabled:!1}};return{temperature:0,top_p:.95,frequency_penalty:0,presence_penalty:0,tool_choice:l?.toolChoice,...n}}makeRequest(e,l,n,r,a,I,s){return e.chat.completions.create({model:l,messages:[...n],...r,tools:a},{maxRetries:I,headers:s?.requestHeaders,signal:s?.abortSignal}).withResponse()}makeRequestStreaming(e,l,n,r,a,I,s){return e.chat.completions.create({model:l,messages:[...n],...r,tools:a,stream:!0,stream_options:{include_usage:!0}},{maxRetries:I,headers:s?.requestHeaders,signal:s?.abortSignal}).withResponse()}async*getCompletionWithTools(e,l,n,r){let a=this.model,I=await this.clientPromise,s=await this.modelPromise,o=g5(n),c=[{role:"system",content:e,copilot_cache_control:U6e},...l.map(Z=>eoe(Z))],d=n.map((Z,W)=>({type:"function",function:{name:Z.name,description:Z.description,parameters:Z.input_schema},copilot_cache_control:W===n.length-1?U6e:void 0}));this.logger.startGroup("Completion request configuration: ",8),this.logger.debug("Client options: "),this.logger.debug(JSON.stringify(this.clientOptions,null,2)),this.logger.debug("Request options: "),this.logger.debug(JSON.stringify(r??{},null,2)),this.logger.debug("Tools: "),this.logger.debug(JSON.stringify(d,null,2)),this.logger.endGroup(8);let m=this.getCompletionOptions(n,r),G=r?.initialTurnCount!==void 0?r.initialTurnCount+1:0,p=!1,A=!1;for(;!p&&!A;){let Z=Date.now();yield{kind:"turn_started",model:a,modelInfo:s,turn:G,timestampMs:Z};let W=0,R=0,V=0,v=[429,503,500,400],X=this.clientOptions.retryPolicy.maxRetries,S=this.clientOptions.retryPolicy.rateLimitRetryPolicy.initialRetryBackoffExtraSeconds,O=0,T=this.clientOptions.retryPolicy.rateLimitRetryPolicy.maxRetryAfterSeconds,P,x;try{let D=[],ae;do{V>0&&(yield{kind:"turn_retry",model:a,modelInfo:s,turn:G,timestampMs:Date.now()});try{let Ge={};for(let U of r?.processors?.preRequest||[]){let re=U.preRequest({turn:G,retry:V,messages:c,toolDefinitions:d,modelInfo:s,additionalRequestHeaders:Ge,getCompletionWithToolsOptions:r});for await(let se of re)yield se}if(this.logger.startGroup("Sending request to the AI model",8),to(this.settings,"copilot_swe_agent_request_logging")){let U=JSON.stringify(c,null,2),re=JSON.stringify(m,null,2);this.logger.debug(`Request messages: ${U}`),this.logger.debug(`Request options: ${re}`)}D=c.map((U,re)=>re===c.length-1?{...U,copilot_cache_control:U6e}:U),W=Date.now(),I.setAdditionalHeaders(Ge);let he;if(r?.stream){let U=await this.makeRequestStreaming(I,a,D,m,d,X,r);he=await T0n(U,I,r)}else he=await this.makeRequest(I,a,D,m,d,X,r);R=Date.now()-W,P=he.data,ae={model:a,api_id:P.id,request_id:he.response.headers.get("x-github-request-id")||void 0,initiator:r?.requestHeaders?.["X-Initiator"]||Ge["X-Initiator"]};let K={};he.response.headers.forEach((U,re)=>{if(re.toLowerCase().startsWith(n6e)){let se=kTt(U);se&&(K[re.replace(n6e,"")]=se)}}),yield{kind:"model_call_success",turn:G,callId:r?.callId,modelCallDurationMs:R,modelCall:ae,responseChunk:HXt(P),responseUsage:P.usage,requestMessages:JSON.stringify(D),quotaSnapshots:K},this.logger.debug(`response (Request-ID ${he.request_id}):`),this.logger.debug("data:"),this.logger.debug(JSON.stringify(he.data,null,2))}catch(Ge){R=Date.now()-W;let he=S8.fromAPIError(Ge),K=he?.error;if(he){yield{kind:"model_call_failure",turn:G,modelCallDurationMs:R,requestMessages:JSON.stringify(D),modelCall:{model:a,status:he.status,error:JSON.stringify(he?.error||he?.message||"unknown error"),api_id:he.requestID||void 0,request_id:he.headers?.get("x-github-request-id")||""}},x=he;let re=he.ghRequestId||he.headers?.get("x-github-request-id")||he.requestID;this.logger.error(`error (Request-ID ${re})`),this.logger.error(JSON.stringify(he,Object.getOwnPropertyNames(he),2)),this.logger.debug(`Failed to get response from the AI model: ${he}`),K&&this.logger.debug(`Inner error: ${JSON.stringify(K,null,2)}`);let se;for(let Re of r?.processors?.onRequestError||[])se=await Re.onRequestError({turn:G,retry:V,maxRetries:X,error:K,modelInfo:s,getCompletionWithToolsOptions:r})||se;let We=he.status,me=We?this.clientOptions.retryPolicy.errorCodesToRetry.some(Re=>Array.isArray(Re)?We>=Re[0]&&(Re[1]===void 0||We<=Re[1]):We===Re):!1,ve;if(se)ve=se.retryAfter;else if(he.status!==402){if(he.status===413){this.logger.debug("Request is too large, trying to remove images from the request");let Re=0;for(let ye=c.length-1;ye>=0;ye--)P4(c[ye])&&(c.splice(ye,1),Re++,yield{kind:"images_removed",turn:G,imagesRemoved:1,largeImagesRemoved:1});Re>0?(this.logger.info(`Images have been removed from the request due to size constraints. Please resize images to be smaller than ${EE(s.capabilities.limits.vision?.max_prompt_image_size||0)}.`),this.logger.debug(`Removed ${Re} image messages from the request`),ve=1):this.logger.debug("No image messages found in the request - unsure why the request is too large - will fail")}else if((typeof he.status=="number"&&v.includes(he.status)||me)&&(ve=parseInt(he.headers?.get("retry-after")||`${this.clientOptions.retryPolicy.rateLimitRetryPolicy.defaultRetryAfterSeconds}`,10)+S,S*=this.clientOptions.retryPolicy.rateLimitRetryPolicy.retryBackoffExtraGrowth,V==X-1))for(let Re=c.length-1;Re>=0;Re--)P4(c[Re])&&(this.logger.debug(`Removing image message at index ${Re} to avoid failure`),c.splice(Re,1),yield{kind:"images_removed",turn:G,imagesRemoved:1})}if(ve!==void 0&&ve<=T){let Re=.8+Math.random()*.4,ye=ve*Re;this.logger.debug(`Retrying after ${ye} seconds...`),await new Promise(Ie=>setTimeout(Ie,ye*1e3)),O+=ye,this.logger.debug(`Retrying after ${ve} seconds... Will try again now!`);continue}else ve?this.logger.error(`Retry after ${ve} seconds is too long. Giving up.`):this.logger.error("Retry after is not set. Giving up.")}let U=he||Ge;for(let re of r?.processors?.onRequestError||[])await re.preErrorThrow(Ge);throw this.logger.error("error"),this.logger.error(JSON.stringify(U,null,2)),U}finally{I.setAdditionalHeaders({}),this.logger.endGroup(8)}}while(!P&&V++<X);if(!P){this.logger.debug("Recent messages prior to failure:");for(let he=Math.max(0,c.length-6);he<c.length;he++)this.logger.debug(`${he}: ${JSON.stringify(c[he],null,2)}`);let Ge=new Error(`Failed to get response from the AI model; retried ${V-1} times (total retry wait time: ${O} seconds)`,{cause:x});throw this.isRateLimitExceededError(Ge)&&(this.logger.info(`Rate limit exceeded after ${V-1} retries, will fail job but skip Sentry reporting`),Ge.skipReport=!0),Ge}for(let Ge of P.choices.map(he=>he.message))B0n(Ge.tool_calls||[]),c.push(Ge),yield{kind:"message",turn:G,callId:r?.callId,modelCall:ae,message:eoe(F6(Ge))};if(this.isToolCallResponse(P)){let he=(s.capabilities.limits.max_prompt_tokens||s.capabilities.limits.max_context_window_tokens)*this.clientOptions.toolTokenBudgetProportion,K=LRt(a,he,this,this.settings),re=P.choices.filter(ve=>ve.message.tool_calls!==void 0).flatMap(ve=>ve.message.tool_calls||[]).filter(kA),se=new Map;for(let ve of r?.processors?.preToolsExecution||[]){let Re=await ve.preToolsExecution({turn:G,toolCalls:re,modelInfo:s});if(Re)for(let[ye,Ie]of Re)se.set(ye,Ie)}let We=re.filter(ve=>!se.has(ve.id)),me=this.mergeToolResults(se,re,We,o,K,r?.executeToolsInParallel);for await(let ve of me){ve.toolResult.resultType==="rejected"&&(A=!0);let Re={role:"tool",tool_call_id:ve.originalCall.id,content:ve.toolResult.textResultForLlm};c.push(Re),yield{kind:"message",turn:G,callId:r?.callId,modelCall:ae,message:eoe(Re)},yield{kind:"tool_execution",turn:G,callId:r?.callId,toolCallId:ve.originalCall.id,toolResult:ve.toolResult,durationMs:ve.durationMs};for(let ye of r?.processors?.postToolExecution||[])await ye.postToolExecution({toolCall:ve.originalCall,toolResult:ve.toolResult,turn:G,modelInfo:s})}}else for(let Ge of P.choices.map(he=>he.message))yield{kind:"response",turn:G,callId:r?.callId,modelCall:{model:a,api_id:P.id},response:eoe(F6(Ge))},p=!0}catch(D){let ae;throw D instanceof Error&&D.cause&&D.cause instanceof S8?ae=`${D} (Cause: ${D.cause})`:ae=`${D}`,yield{kind:"turn_failed",model:a,modelInfo:s,turn:G,error:ae,timestampMs:Date.now()},D}finally{let D=Date.now();yield{kind:"turn_ended",model:a,modelInfo:s,turn:G,timestampMs:D},G++}}}async*mergeToolResults(e,l,n,r,a,I=!1){for(let[s,o]of e){let c=l.find(d=>d.id===s);c&&(yield{durationMs:0,originalCall:c,toolResult:o})}n.length>0&&(yield*this.callTools(n,r,a,I))}async*callTools(e,l,n,r=!1){if(e.length===0)throw new Error("Tool call is missing");this.logger.debug(`Tool calls count: ${e.length}`);let a=e.some(s=>{let o=l[s.function.name];return $k(o)}),I=r&&!a;if(a&&r&&this.logger.debug("Custom agent detected in tool calls, forcing sequential execution"),I)this.logger.debug("Running tool calls in parallel"),yield*FRt(e.map(s=>()=>this.callTool(s,l,n)));else{this.logger.debug("Running tool calls sequentially");for(let s of e)yield await this.callTool(s,l,n)}}async callTool(e,l,n){let r=0,a=e?.function.name;if(!a)throw new Error("Tool name is missing");let I=e?.function.arguments;if(I==null)throw new Error("Tool call arguments are missing");let s=e?.id;if(!s)throw new Error("Tool call id is missing");let o,c=l[a];try{let d=eL(I);if(!c||!c.callback)o={textResultForLlm:`Tool '${a}' does not exist. Available tools that can be called are ${Object.keys(l).join(", ")}.`,resultType:"failure",error:`Tool '${a}' does not exist.`,sessionLog:`<error>Tool '${a}' does not exist.</error>`,toolTelemetry:{}};else{let m=c.callback,G=Date.now(),p={...n,toolCallId:s,toolOptions:this.settings.service?.tools?.[a]},A=await m({...d},p);r=Date.now()-G,o=typeof A=="string"?{textResultForLlm:A,resultType:"success",toolTelemetry:{}}:A}}catch(d){d instanceof SyntaxError?(o={textResultForLlm:`The arguments for the tool call '${a}' were not valid JSON. The arguments have been cleared. Arguments: ${I}. JSON parse error: ${d.message}`,resultType:"failure",error:`${d.message}`,sessionLog:`<error>Failed to execute \`${a}\` tool with arguments: ${I} due to syntax error: ${d.message}</error>`,toolTelemetry:{properties:{wasSyntaxError:"true"}}},e.function.arguments="{}"):o={textResultForLlm:`Failed to execute \`${a}\` tool with arguments: ${I} due to error: ${d}`,resultType:"failure",error:d instanceof Error?d.message:`${d}`,sessionLog:`<error>Failed to execute \`${a}\` tool with arguments: ${I}</error>`,toolTelemetry:{}}}return{durationMs:r,originalCall:e,toolResult:o}}isToolCallResponse(e){return e.choices.find(l=>l.message.tool_calls!==void 0)!==void 0}isRateLimitExceededError(e){if(e instanceof Error){if(e.message?.includes("exceeded maximum number of retries")&&e.message?.includes("rate-limited requests"))return!0;if(e.message?.includes("Failed to get response from the AI model")&&e.cause instanceof S8)return e.cause.status===429}return!1}async getModel(){let e=this.clientOptions.model,l={id:e,name:e,capabilities:{supports:{vision:!1},limits:{max_prompt_tokens:9e4,max_context_window_tokens:128e3,vision:{max_prompt_image_size:3145728,max_prompt_images:1,supported_media_types:["image/jpeg","image/png","image/webp"]}}}};return(await(await this.clientPromise).listModels()).filter(I=>I.id===e).at(0)||l}};function B0n(t){for(let e of t)e.function.name=e.function.name.replace(/[^a-zA-Z0-9_-]+/g,"_")}async function T0n(t,e,l){let n=O0n(t.data,e).toReadableStream(),r=nf.fromReadableStream(n),a=l?.processors?.onStreamingChunk;if(a?.length)for await(let I of r){l?.abortSignal?.throwIfAborted();let s={chunk:I};for(let o of a)o.onStreamingChunk(s)}return{data:await r.finalChatCompletion(),response:t.response,request_id:t.request_id}}function O0n(t,e){let l=new Map;return new c0(async function*(){for await(let n of t)n.choices?.forEach(r=>{if(r.delta.role??="assistant",!!r.delta?.tool_calls?.length){r.finish_reason??="tool_calls";let I=l.get(r.index);I||(I={nextSequenceNumber:0,mappings:new Map},l.set(r.index,I)),r.delta.tool_calls?.forEach(s=>{let o=I.mappings.get(s.index);if(o!==void 0)s.id&&o.callId!==s.id&&(o.sequenceNumber=I.nextSequenceNumber++,o.callId=s.id),s.index=o.sequenceNumber;else{let c={callId:s.id,sequenceNumber:I.nextSequenceNumber++};I.mappings.set(s.index,c),s.index=c.sequenceNumber}})}}),yield n},t.controller,e)}var J1e=class extends bL{constructor(e,l,n){let r=new x8;super(r,e,l,n)}};var x1e=class t{constructor(e,l,n,r){this.settings=l;this.logger=n;this.clientOptions=t.initDefaultOptions(r),this.logger.info(`Using responses with model: ${this.model}`),this.clientPromise=e.createClient(l,n,this.clientOptions)}clientOptions;clientPromise;get model(){return this.clientOptions.model}static initDefaultOptions(e){return{model:e?.model||"o4-mini",toolTokenBudgetProportion:e?.toolTokenBudgetProportion??.25,retryPolicy:{maxRetries:e?.retryPolicy?.maxRetries??5,errorCodesToRetry:e?.retryPolicy?.errorCodesToRetry??[],rateLimitRetryPolicy:{defaultRetryAfterSeconds:e?.retryPolicy?.rateLimitRetryPolicy?.defaultRetryAfterSeconds??5,initialRetryBackoffExtraSeconds:e?.retryPolicy?.rateLimitRetryPolicy?.initialRetryBackoffExtraSeconds??1,retryBackoffExtraGrowth:e?.retryPolicy?.rateLimitRetryPolicy?.retryBackoffExtraGrowth??2,maxRetryAfterSeconds:e?.retryPolicy?.rateLimitRetryPolicy?.maxRetryAfterSeconds??60}},thinkingMode:e?.thinkingMode??!0,requestHeaders:e?.requestHeaders??{}}}makeRequest(e,l,n,r,a,I,s,o){return e.responses.create({model:l,previous_response_id:I,instructions:n,input:r,parallel_tool_calls:a.length>0?!0:void 0,tools:a,reasoning:{summary:"auto",effort:"medium"},store:!1,include:["reasoning.encrypted_content"]},{maxRetries:s||this.clientOptions.retryPolicy.maxRetries,headers:o?.requestHeaders,signal:o?.abortSignal}).withResponse()}async*getCompletionWithTools(e,l,n,r){let a=await this.clientPromise,I=g5(n),s=n.map(W=>({name:W.name,description:W.description,parameters:W.input_schema,strict:!1,type:"function"})),o=0,c=this.clientOptions.retryPolicy.maxRetries,d=this.clientOptions.retryPolicy.rateLimitRetryPolicy.initialRetryBackoffExtraSeconds,m=0,G=this.clientOptions.retryPolicy.rateLimitRetryPolicy.maxRetryAfterSeconds,p=l.flatMap(_6e),A,Z=!1;for(;!Z;){let W;do{W=void 0;try{let R=await this.makeRequest(a,this.model,e,p,s,void 0,c,r);A=R.data,p.push(...A.output),this.logger.debug(`response (Request-ID ${R.request_id}):`),this.logger.debug("data:"),this.logger.debug(JSON.stringify(R.data,null,2))}catch(R){let V=R,v=V.error;if(V){W=V,this.logger.error(`error (Request-ID ${V.requestID})`),this.logger.error(JSON.stringify(V,null,2)),this.logger.debug(`Failed to get response from the AI model: ${V}`),v&&this.logger.debug(`Inner error: ${JSON.stringify(v,null,2)}`);let X=V.status,S=X?this.clientOptions.retryPolicy.errorCodesToRetry.some(T=>Array.isArray(T)?X>=T[0]&&(T[1]===void 0||X<=T[1]):X===T):!1,O;if((V.status===429||S)&&(O=parseInt(V.headers?.get("retry-after")||`${this.clientOptions.retryPolicy.rateLimitRetryPolicy.defaultRetryAfterSeconds}`,10)+d,d*=this.clientOptions.retryPolicy.rateLimitRetryPolicy.retryBackoffExtraGrowth),O!==void 0&&O<=G){this.logger.debug(`Retrying after ${O} seconds...`),await new Promise(T=>setTimeout(T,O*1e3)),m+=O,this.logger.debug(`Retrying after ${O} seconds... Will try again now!`);continue}else O?this.logger.error(`Retry after ${O} seconds is too long. Giving up.`):this.logger.error("Retry after is not set. Giving up.")}throw this.logger.error("error"),this.logger.error(JSON.stringify(R,null,2)),R}finally{this.logger.endGroup(8)}}while(W&&o++<c);if(!A||W){this.logger.debug("Recent messages prior to failure:");for(let R=Math.max(0,p.length-6);R<p.length;R++)this.logger.debug(`${R}: ${JSON.stringify(p[R],null,2)}`);throw new Error(`Failed to get response from the AI model; retried ${o-1} times (total retry wait time: ${m} seconds)`,{cause:W})}for(let R of A.output)yield{kind:"message",message:M6e(R)};if(this.requiresToolOutput(A)){let V=(await this.runTool(A,I)).map(v=>({type:"function_call_output",call_id:v.toolCallId,output:v.textResultForLlm}));p.push(...V);for(let v of V)yield{kind:"message",message:M6e(v)}}else yield{kind:"response",response:{content:A.output_text,refusal:null,role:"assistant"}},Z=!0}}async runTool(e,l,n){let r=e.output.filter(I=>I.type==="function_call");if(!r||r.length===0)throw new Error("Tool calls in response are missing");let a=[];for(let I of r){let s=I.name;if(!s)throw new Error("Tool name is missing");let o=I.arguments;if(!o)throw new Error("Tool call arguments are missing");let c=I.call_id;if(!c)throw new Error("Tool call id is missing");let d,m=l[s];try{let G=eL(o);if(!m||!m.callback)d={textResultForLlm:`Tool '${s}' does not exist. Available tools that can be called are ${Object.keys(l).join(", ")}.`,resultType:"failure",error:`Tool '${s}' does not exist.`,sessionLog:`<error>Tool '${s}' does not exist.</error>`,toolTelemetry:{}};else{let p=m.callback,A={...n,toolCallId:c,toolOptions:this.settings.service?.tools?.[s],settings:this.settings},Z=await p({...G},A);d=typeof Z=="string"?{textResultForLlm:Z,resultType:"success",toolTelemetry:{}}:Z}}catch(G){d={textResultForLlm:`Failed to execute \`${s}\` tool with arguments: ${o} due to error: ${G}`,resultType:"failure",error:G instanceof Error?G.message:`${G}`,sessionLog:`<error>Failed to execute \`${s}\` tool with arguments: ${o}</error>`,toolTelemetry:{properties:{wasSyntaxError:G instanceof SyntaxError?"true":"false"}}}}a.push({toolCallId:c,textResultForLlm:d.textResultForLlm,sessionLog:d.resultType=="success"?d.sessionLog:d.error?`<error>${d.error}</error>`:void 0})}return a}requiresToolOutput(e){return e.output.filter(l=>l.type==="function_call").length>0}};function _6e(t){if(t.role==="function")throw new Error("Function role is not supported");let e=[];if(t.reasoning_opaque&&e.push({id:t.reasoning_opaque,type:"reasoning",summary:t.reasoning_text?[{text:t.reasoning_text,type:"summary_text"}]:[],encrypted_content:t.encrypted_content}),t.role==="assistant"&&t.tool_calls&&t.tool_calls.length>0&&kA(t.tool_calls[0])){let l=t.tool_calls[0];return[...e,{type:"function_call",id:t.id,name:l.function.name,arguments:l.function.arguments,call_id:l.id}]}if(t.role==="tool")return[...e,{type:"function_call_output",id:`fc_${t.tool_call_id}`,call_id:t.tool_call_id,output:typeof t.content=="string"?t.content:t.content.map(l=>l.text).join(" ")??""}];if(!t.content)return e;if(t.role==="assistant"){let l=t.id||crypto.randomUUID();return l.startsWith("msg_")||(l=`msg_${l}`),[...e,{type:"message",id:l,role:t.role,content:[{annotations:[],type:"output_text",text:typeof t.content=="string"?t.content:t.content?.map(n=>n.type==="text"?n.text:"").join(" ")??""}],status:"completed"}]}return[...e,{role:t.role,content:typeof t.content=="string"?[{type:"input_text",text:t.content}]:t.content.map(l=>{if(l.type==="text")return{type:"input_text",text:l.text};if(l.type==="image_url")return{type:"input_image",detail:l.image_url.detail||"auto",image_url:l.image_url.url}}).filter(l=>l!==void 0),type:"message"}]}function M6e(t){if(t.type==="reasoning")return{role:"assistant",reasoning_opaque:t.id,reasoning_text:t.summary?t.summary.map(e=>e.text).join(" "):void 0,content:"",encrypted_content:t.encrypted_content};if(t.type==="function_call")return{role:"assistant",id:t.id,tool_calls:[{id:t.call_id,type:"function",function:{name:t.name,arguments:t.arguments}}],content:""};if(t.type==="function_call_output")return{role:"tool",content:t.output,tool_call_id:t.call_id};if(t.type==="message")return{id:"id"in t?t.id:void 0,role:t.role,content:typeof t.content=="string"?t.content:t.content?.map(e=>e.type==="input_text"||e.type==="output_text"?e.text:"").join(" ")??""};throw new Error(`Unknown item type: ${t.type}`)}function U0n(t){let e;t.incomplete_details?.reason==="content_filter"?e="content_filter":t.incomplete_details?.reason==="max_output_tokens"?e="length":e=t.output.some(r=>r.type==="function_call")?"tool_calls":"stop";let n=t.output.filter(r=>r.type==="message"||r.type==="reasoning"||r.type==="function_call").map(r=>M6e(r)).filter(r=>r.role==="assistant").map((r,a)=>({message:{content:Array.isArray(r.content)?r.content.map(I=>typeof I=="string"?I:"text"in I?I.text:"").join(" "):r.content||null,refusal:r.refusal||null,role:r.role||null,tool_calls:r.tool_calls?.filter(I=>I.type==="function"),reasoning_opaque:r.reasoning_opaque,reasoning_text:r.reasoning_text,encrypted_content:r.encrypted_content},index:a,finish_reason:e,logprobs:null}));return{id:t.id,choices:n,created:t.created_at,model:t.model,object:"chat.completion",usage:{completion_tokens:t.usage?.output_tokens||0,prompt_tokens:t.usage?.input_tokens||0,total_tokens:t.usage?.total_tokens||0}}}function XOt(t){return{request_id:t.request_id,data:U0n(t.data),response:t.response}}var S1e=class extends bL{makeResponsesRequest(e,l,n,r,a,I,s){let o=n.find(p=>p.role==="system")?.content||"",c=Array.isArray(o)?o.join(`
|
|
1904
|
+
${G}`)}I=!!(a||r)}let s,o=dZt(e),c=_te(e),d=e.api?.copilot?.sessionId??$F(e);if(l.debug(`Using Copilot API at ${o} with integration ID ${c}`),r&&(l.debug("Using GitHub OAuth token for Copilot API"),s=yT.createWithOAuthToken(l,o,c,r,d,n?.requestHeaders)),a){l.debug("Using Copilot HMAC key for Copilot API");let m=process.env.GITHUB_USER_ID;m?l.debug(`Using user ID ${m} for Copilot HMAC key`):l.debug("No user ID provided for Copilot HMAC key"),s=yT.createWithHmac(l,o,c,a,d,m,n?.requestHeaders)}if(s===void 0)throw new Error("No GitHub OAuth token or Copilot HMAC key provided");return s}},S8=class t extends Ru{request_id;constructor(e){super(e.status,e.error,e.message,e.headers),this.name="CAPIError",this.cause=e.cause,this.ghRequestId=e.headers?.get("x-github-request-id")||this.requestID,this.request_id=this.requestID}ghRequestId;static fromAPIError(e){if(!(!e||!(e instanceof Ru)))return new t(e)}};var U6e={type:"ephemeral"},bL=class t{constructor(e,l,n,r){this.settings=l;this.logger=n;this.clientOptions=t.initDefaultOptions(r),n.info(" "),n.debug(`Using model: ${this.model}`),this.clientPromise=e.createClient(l,n,r),this.modelPromise=this.clientPromise.then(async()=>{let a=await this.getModel();return n.debug(`Got model info: ${JSON.stringify(a,null,2)}`),a})}clientOptions;clientPromise;modelPromise;get model(){return this.clientOptions.model}static initDefaultOptions(e){return{model:e?.model||bMe.model,toolTokenBudgetProportion:e?.toolTokenBudgetProportion??.25,retryPolicy:{maxRetries:e?.retryPolicy?.maxRetries??5,errorCodesToRetry:e?.retryPolicy?.errorCodesToRetry??[],rateLimitRetryPolicy:{defaultRetryAfterSeconds:e?.retryPolicy?.rateLimitRetryPolicy?.defaultRetryAfterSeconds??5,initialRetryBackoffExtraSeconds:e?.retryPolicy?.rateLimitRetryPolicy?.initialRetryBackoffExtraSeconds??1,retryBackoffExtraGrowth:e?.retryPolicy?.rateLimitRetryPolicy?.retryBackoffExtraGrowth??2,maxRetryAfterSeconds:e?.retryPolicy?.rateLimitRetryPolicy?.maxRetryAfterSeconds??180}},thinkingMode:e?.thinkingMode??!1,requestHeaders:e?.requestHeaders??{}}}getCompletionOptions(e,l){let n={snippy:{enabled:!1}};return{temperature:0,top_p:.95,frequency_penalty:0,presence_penalty:0,tool_choice:l?.toolChoice,...n}}makeRequest(e,l,n,r,a,I,s){return e.chat.completions.create({model:l,messages:[...n],...r,tools:a},{maxRetries:I,headers:s?.requestHeaders,signal:s?.abortSignal}).withResponse()}makeRequestStreaming(e,l,n,r,a,I,s){return e.chat.completions.create({model:l,messages:[...n],...r,tools:a,stream:!0,stream_options:{include_usage:!0}},{maxRetries:I,headers:s?.requestHeaders,signal:s?.abortSignal}).withResponse()}async*getCompletionWithTools(e,l,n,r){let a=this.model,I=await this.clientPromise,s=await this.modelPromise,o=g5(n),c=[{role:"system",content:e,copilot_cache_control:U6e},...l.map(Z=>eoe(Z))],d=n.map((Z,W)=>({type:"function",function:{name:Z.name,description:Z.description,parameters:Z.input_schema},copilot_cache_control:W===n.length-1?U6e:void 0}));this.logger.startGroup("Completion request configuration: ",8),this.logger.debug("Client options: "),this.logger.debug(JSON.stringify(this.clientOptions,null,2)),this.logger.debug("Request options: "),this.logger.debug(JSON.stringify(r??{},null,2)),this.logger.debug("Tools: "),this.logger.debug(JSON.stringify(d,null,2)),this.logger.endGroup(8);let m=this.getCompletionOptions(n,r),G=r?.initialTurnCount!==void 0?r.initialTurnCount+1:0,p=!1,A=!1;for(;!p&&!A;){let Z=Date.now();yield{kind:"turn_started",model:a,modelInfo:s,turn:G,timestampMs:Z};let W=0,R=0,V=0,v=[429,503,500,400],X=this.clientOptions.retryPolicy.maxRetries,S=this.clientOptions.retryPolicy.rateLimitRetryPolicy.initialRetryBackoffExtraSeconds,O=0,T=this.clientOptions.retryPolicy.rateLimitRetryPolicy.maxRetryAfterSeconds,P,x;try{let D=[],ae;do{V>0&&(yield{kind:"turn_retry",model:a,modelInfo:s,turn:G,timestampMs:Date.now()});try{let Ge={};for(let U of r?.processors?.preRequest||[]){let re=U.preRequest({turn:G,retry:V,messages:c,toolDefinitions:d,modelInfo:s,additionalRequestHeaders:Ge,getCompletionWithToolsOptions:r});for await(let se of re)yield se}if(this.logger.startGroup("Sending request to the AI model",8),to(this.settings,"copilot_swe_agent_request_logging")){let U=JSON.stringify(c,null,2),re=JSON.stringify(m,null,2);this.logger.debug(`Request messages: ${U}`),this.logger.debug(`Request options: ${re}`)}D=c.map((U,re)=>re===c.length-1?{...U,copilot_cache_control:U6e}:U),W=Date.now(),I.setAdditionalHeaders(Ge);let he;if(r?.stream){let U=await this.makeRequestStreaming(I,a,D,m,d,X,r);he=await T0n(U,I,r)}else he=await this.makeRequest(I,a,D,m,d,X,r);R=Date.now()-W,P=he.data,ae={model:a,api_id:P.id,request_id:he.response.headers.get("x-github-request-id")||void 0,initiator:r?.requestHeaders?.["X-Initiator"]||Ge["X-Initiator"]};let K={};he.response.headers.forEach((U,re)=>{if(re.toLowerCase().startsWith(n6e)){let se=kTt(U);se&&(K[re.replace(n6e,"")]=se)}}),yield{kind:"model_call_success",turn:G,callId:r?.callId,modelCallDurationMs:R,modelCall:ae,responseChunk:HXt(P),responseUsage:P.usage,requestMessages:JSON.stringify(D),quotaSnapshots:K},this.logger.debug(`response (Request-ID ${he.request_id}):`),this.logger.debug("data:"),this.logger.debug(JSON.stringify(he.data,null,2))}catch(Ge){R=Date.now()-W;let he=S8.fromAPIError(Ge),K=he?.error;if(he){yield{kind:"model_call_failure",turn:G,callId:r?.callId,modelCallDurationMs:R,requestMessages:JSON.stringify(D),modelCall:{model:a,status:he.status,error:JSON.stringify(he?.error||he?.message||"unknown error"),api_id:he.requestID||void 0,request_id:he.headers?.get("x-github-request-id")||""}},x=he;let re=he.ghRequestId||he.headers?.get("x-github-request-id")||he.requestID;this.logger.error(`error (Request-ID ${re})`),this.logger.error(JSON.stringify(he,Object.getOwnPropertyNames(he),2)),this.logger.debug(`Failed to get response from the AI model: ${he}`),K&&this.logger.debug(`Inner error: ${JSON.stringify(K,null,2)}`);let se;for(let Re of r?.processors?.onRequestError||[])se=await Re.onRequestError({turn:G,retry:V,maxRetries:X,error:K,modelInfo:s,getCompletionWithToolsOptions:r})||se;let We=he.status,me=We?this.clientOptions.retryPolicy.errorCodesToRetry.some(Re=>Array.isArray(Re)?We>=Re[0]&&(Re[1]===void 0||We<=Re[1]):We===Re):!1,ve;if(se)ve=se.retryAfter;else if(he.status!==402){if(he.status===413){this.logger.debug("Request is too large, trying to remove images from the request");let Re=0;for(let ye=c.length-1;ye>=0;ye--)P4(c[ye])&&(c.splice(ye,1),Re++,yield{kind:"images_removed",turn:G,imagesRemoved:1,largeImagesRemoved:1});Re>0?(this.logger.info(`Images have been removed from the request due to size constraints. Please resize images to be smaller than ${EE(s.capabilities.limits.vision?.max_prompt_image_size||0)}.`),this.logger.debug(`Removed ${Re} image messages from the request`),ve=1):this.logger.debug("No image messages found in the request - unsure why the request is too large - will fail")}else if((typeof he.status=="number"&&v.includes(he.status)||me)&&(ve=parseInt(he.headers?.get("retry-after")||`${this.clientOptions.retryPolicy.rateLimitRetryPolicy.defaultRetryAfterSeconds}`,10)+S,S*=this.clientOptions.retryPolicy.rateLimitRetryPolicy.retryBackoffExtraGrowth,V==X-1))for(let Re=c.length-1;Re>=0;Re--)P4(c[Re])&&(this.logger.debug(`Removing image message at index ${Re} to avoid failure`),c.splice(Re,1),yield{kind:"images_removed",turn:G,imagesRemoved:1})}if(ve!==void 0&&ve<=T){let Re=.8+Math.random()*.4,ye=ve*Re;this.logger.debug(`Retrying after ${ye} seconds...`),await new Promise(Ie=>setTimeout(Ie,ye*1e3)),O+=ye,this.logger.debug(`Retrying after ${ve} seconds... Will try again now!`);continue}else ve?this.logger.error(`Retry after ${ve} seconds is too long. Giving up.`):this.logger.error("Retry after is not set. Giving up.")}let U=he||Ge;for(let re of r?.processors?.onRequestError||[])await re.preErrorThrow(Ge);throw this.logger.error("error"),this.logger.error(JSON.stringify(U,null,2)),U}finally{I.setAdditionalHeaders({}),this.logger.endGroup(8)}}while(!P&&V++<X);if(!P){this.logger.debug("Recent messages prior to failure:");for(let he=Math.max(0,c.length-6);he<c.length;he++)this.logger.debug(`${he}: ${JSON.stringify(c[he],null,2)}`);let Ge=new Error(`Failed to get response from the AI model; retried ${V-1} times (total retry wait time: ${O} seconds)`,{cause:x});throw this.isRateLimitExceededError(Ge)&&(this.logger.info(`Rate limit exceeded after ${V-1} retries, will fail job but skip Sentry reporting`),Ge.skipReport=!0),Ge}for(let Ge of P.choices.map(he=>he.message))B0n(Ge.tool_calls||[]),c.push(Ge),yield{kind:"message",turn:G,callId:r?.callId,modelCall:ae,message:eoe(F6(Ge))};if(this.isToolCallResponse(P)){let he=(s.capabilities.limits.max_prompt_tokens||s.capabilities.limits.max_context_window_tokens)*this.clientOptions.toolTokenBudgetProportion,K=LRt(a,he,this,this.settings),re=P.choices.filter(ve=>ve.message.tool_calls!==void 0).flatMap(ve=>ve.message.tool_calls||[]).filter(kA),se=new Map;for(let ve of r?.processors?.preToolsExecution||[]){let Re=await ve.preToolsExecution({turn:G,toolCalls:re,modelInfo:s});if(Re)for(let[ye,Ie]of Re)se.set(ye,Ie)}let We=re.filter(ve=>!se.has(ve.id)),me=this.mergeToolResults(se,re,We,o,K,r?.executeToolsInParallel);for await(let ve of me){ve.toolResult.resultType==="rejected"&&(A=!0);let Re={role:"tool",tool_call_id:ve.originalCall.id,content:ve.toolResult.textResultForLlm};c.push(Re),yield{kind:"message",turn:G,callId:r?.callId,modelCall:ae,message:eoe(Re)},yield{kind:"tool_execution",turn:G,callId:r?.callId,toolCallId:ve.originalCall.id,toolResult:ve.toolResult,durationMs:ve.durationMs};for(let ye of r?.processors?.postToolExecution||[])await ye.postToolExecution({toolCall:ve.originalCall,toolResult:ve.toolResult,turn:G,modelInfo:s})}}else for(let Ge of P.choices.map(he=>he.message))yield{kind:"response",turn:G,callId:r?.callId,modelCall:{model:a,api_id:P.id},response:eoe(F6(Ge))},p=!0}catch(D){let ae;throw D instanceof Error&&D.cause&&D.cause instanceof S8?ae=`${D} (Cause: ${D.cause})`:ae=`${D}`,yield{kind:"turn_failed",model:a,modelInfo:s,turn:G,error:ae,timestampMs:Date.now()},D}finally{let D=Date.now();yield{kind:"turn_ended",model:a,modelInfo:s,turn:G,timestampMs:D},G++}}}async*mergeToolResults(e,l,n,r,a,I=!1){for(let[s,o]of e){let c=l.find(d=>d.id===s);c&&(yield{durationMs:0,originalCall:c,toolResult:o})}n.length>0&&(yield*this.callTools(n,r,a,I))}async*callTools(e,l,n,r=!1){if(e.length===0)throw new Error("Tool call is missing");this.logger.debug(`Tool calls count: ${e.length}`);let a=e.some(s=>{let o=l[s.function.name];return $k(o)}),I=r&&!a;if(a&&r&&this.logger.debug("Custom agent detected in tool calls, forcing sequential execution"),I)this.logger.debug("Running tool calls in parallel"),yield*FRt(e.map(s=>()=>this.callTool(s,l,n)));else{this.logger.debug("Running tool calls sequentially");for(let s of e)yield await this.callTool(s,l,n)}}async callTool(e,l,n){let r=0,a=e?.function.name;if(!a)throw new Error("Tool name is missing");let I=e?.function.arguments;if(I==null)throw new Error("Tool call arguments are missing");let s=e?.id;if(!s)throw new Error("Tool call id is missing");let o,c=l[a];try{let d=eL(I);if(!c||!c.callback)o={textResultForLlm:`Tool '${a}' does not exist. Available tools that can be called are ${Object.keys(l).join(", ")}.`,resultType:"failure",error:`Tool '${a}' does not exist.`,sessionLog:`<error>Tool '${a}' does not exist.</error>`,toolTelemetry:{}};else{let m=c.callback,G=Date.now(),p={...n,toolCallId:s,toolOptions:this.settings.service?.tools?.[a]},A=await m({...d},p);r=Date.now()-G,o=typeof A=="string"?{textResultForLlm:A,resultType:"success",toolTelemetry:{}}:A}}catch(d){d instanceof SyntaxError?(o={textResultForLlm:`The arguments for the tool call '${a}' were not valid JSON. The arguments have been cleared. Arguments: ${I}. JSON parse error: ${d.message}`,resultType:"failure",error:`${d.message}`,sessionLog:`<error>Failed to execute \`${a}\` tool with arguments: ${I} due to syntax error: ${d.message}</error>`,toolTelemetry:{properties:{wasSyntaxError:"true"}}},e.function.arguments="{}"):o={textResultForLlm:`Failed to execute \`${a}\` tool with arguments: ${I} due to error: ${d}`,resultType:"failure",error:d instanceof Error?d.message:`${d}`,sessionLog:`<error>Failed to execute \`${a}\` tool with arguments: ${I}</error>`,toolTelemetry:{}}}return{durationMs:r,originalCall:e,toolResult:o}}isToolCallResponse(e){return e.choices.find(l=>l.message.tool_calls!==void 0)!==void 0}isRateLimitExceededError(e){if(e instanceof Error){if(e.message?.includes("exceeded maximum number of retries")&&e.message?.includes("rate-limited requests"))return!0;if(e.message?.includes("Failed to get response from the AI model")&&e.cause instanceof S8)return e.cause.status===429}return!1}async getModel(){let e=this.clientOptions.model,l={id:e,name:e,capabilities:{supports:{vision:!1},limits:{max_prompt_tokens:9e4,max_context_window_tokens:128e3,vision:{max_prompt_image_size:3145728,max_prompt_images:1,supported_media_types:["image/jpeg","image/png","image/webp"]}}}};return(await(await this.clientPromise).listModels()).filter(I=>I.id===e).at(0)||l}};function B0n(t){for(let e of t)e.function.name=e.function.name.replace(/[^a-zA-Z0-9_-]+/g,"_")}async function T0n(t,e,l){let n=O0n(t.data,e).toReadableStream(),r=nf.fromReadableStream(n),a=l?.processors?.onStreamingChunk;if(a?.length)for await(let I of r){l?.abortSignal?.throwIfAborted();let s={chunk:I};for(let o of a)o.onStreamingChunk(s)}return{data:await r.finalChatCompletion(),response:t.response,request_id:t.request_id}}function O0n(t,e){let l=new Map;return new c0(async function*(){for await(let n of t)n.choices?.forEach(r=>{if(r.delta.role??="assistant",!!r.delta?.tool_calls?.length){r.finish_reason??="tool_calls";let I=l.get(r.index);I||(I={nextSequenceNumber:0,mappings:new Map},l.set(r.index,I)),r.delta.tool_calls?.forEach(s=>{let o=I.mappings.get(s.index);if(o!==void 0)s.id&&o.callId!==s.id&&(o.sequenceNumber=I.nextSequenceNumber++,o.callId=s.id),s.index=o.sequenceNumber;else{let c={callId:s.id,sequenceNumber:I.nextSequenceNumber++};I.mappings.set(s.index,c),s.index=c.sequenceNumber}})}}),yield n},t.controller,e)}var J1e=class extends bL{constructor(e,l,n){let r=new x8;super(r,e,l,n)}};var x1e=class t{constructor(e,l,n,r){this.settings=l;this.logger=n;this.clientOptions=t.initDefaultOptions(r),this.logger.info(`Using responses with model: ${this.model}`),this.clientPromise=e.createClient(l,n,this.clientOptions)}clientOptions;clientPromise;get model(){return this.clientOptions.model}static initDefaultOptions(e){return{model:e?.model||"o4-mini",toolTokenBudgetProportion:e?.toolTokenBudgetProportion??.25,retryPolicy:{maxRetries:e?.retryPolicy?.maxRetries??5,errorCodesToRetry:e?.retryPolicy?.errorCodesToRetry??[],rateLimitRetryPolicy:{defaultRetryAfterSeconds:e?.retryPolicy?.rateLimitRetryPolicy?.defaultRetryAfterSeconds??5,initialRetryBackoffExtraSeconds:e?.retryPolicy?.rateLimitRetryPolicy?.initialRetryBackoffExtraSeconds??1,retryBackoffExtraGrowth:e?.retryPolicy?.rateLimitRetryPolicy?.retryBackoffExtraGrowth??2,maxRetryAfterSeconds:e?.retryPolicy?.rateLimitRetryPolicy?.maxRetryAfterSeconds??60}},thinkingMode:e?.thinkingMode??!0,requestHeaders:e?.requestHeaders??{}}}makeRequest(e,l,n,r,a,I,s,o){return e.responses.create({model:l,previous_response_id:I,instructions:n,input:r,parallel_tool_calls:a.length>0?!0:void 0,tools:a,reasoning:{summary:"auto",effort:"medium"},store:!1,include:["reasoning.encrypted_content"]},{maxRetries:s||this.clientOptions.retryPolicy.maxRetries,headers:o?.requestHeaders,signal:o?.abortSignal}).withResponse()}async*getCompletionWithTools(e,l,n,r){let a=await this.clientPromise,I=g5(n),s=n.map(W=>({name:W.name,description:W.description,parameters:W.input_schema,strict:!1,type:"function"})),o=0,c=this.clientOptions.retryPolicy.maxRetries,d=this.clientOptions.retryPolicy.rateLimitRetryPolicy.initialRetryBackoffExtraSeconds,m=0,G=this.clientOptions.retryPolicy.rateLimitRetryPolicy.maxRetryAfterSeconds,p=l.flatMap(_6e),A,Z=!1;for(;!Z;){let W;do{W=void 0;try{let R=await this.makeRequest(a,this.model,e,p,s,void 0,c,r);A=R.data,p.push(...A.output),this.logger.debug(`response (Request-ID ${R.request_id}):`),this.logger.debug("data:"),this.logger.debug(JSON.stringify(R.data,null,2))}catch(R){let V=R,v=V.error;if(V){W=V,this.logger.error(`error (Request-ID ${V.requestID})`),this.logger.error(JSON.stringify(V,null,2)),this.logger.debug(`Failed to get response from the AI model: ${V}`),v&&this.logger.debug(`Inner error: ${JSON.stringify(v,null,2)}`);let X=V.status,S=X?this.clientOptions.retryPolicy.errorCodesToRetry.some(T=>Array.isArray(T)?X>=T[0]&&(T[1]===void 0||X<=T[1]):X===T):!1,O;if((V.status===429||S)&&(O=parseInt(V.headers?.get("retry-after")||`${this.clientOptions.retryPolicy.rateLimitRetryPolicy.defaultRetryAfterSeconds}`,10)+d,d*=this.clientOptions.retryPolicy.rateLimitRetryPolicy.retryBackoffExtraGrowth),O!==void 0&&O<=G){this.logger.debug(`Retrying after ${O} seconds...`),await new Promise(T=>setTimeout(T,O*1e3)),m+=O,this.logger.debug(`Retrying after ${O} seconds... Will try again now!`);continue}else O?this.logger.error(`Retry after ${O} seconds is too long. Giving up.`):this.logger.error("Retry after is not set. Giving up.")}throw this.logger.error("error"),this.logger.error(JSON.stringify(R,null,2)),R}finally{this.logger.endGroup(8)}}while(W&&o++<c);if(!A||W){this.logger.debug("Recent messages prior to failure:");for(let R=Math.max(0,p.length-6);R<p.length;R++)this.logger.debug(`${R}: ${JSON.stringify(p[R],null,2)}`);throw new Error(`Failed to get response from the AI model; retried ${o-1} times (total retry wait time: ${m} seconds)`,{cause:W})}for(let R of A.output)yield{kind:"message",message:M6e(R)};if(this.requiresToolOutput(A)){let V=(await this.runTool(A,I)).map(v=>({type:"function_call_output",call_id:v.toolCallId,output:v.textResultForLlm}));p.push(...V);for(let v of V)yield{kind:"message",message:M6e(v)}}else yield{kind:"response",response:{content:A.output_text,refusal:null,role:"assistant"}},Z=!0}}async runTool(e,l,n){let r=e.output.filter(I=>I.type==="function_call");if(!r||r.length===0)throw new Error("Tool calls in response are missing");let a=[];for(let I of r){let s=I.name;if(!s)throw new Error("Tool name is missing");let o=I.arguments;if(!o)throw new Error("Tool call arguments are missing");let c=I.call_id;if(!c)throw new Error("Tool call id is missing");let d,m=l[s];try{let G=eL(o);if(!m||!m.callback)d={textResultForLlm:`Tool '${s}' does not exist. Available tools that can be called are ${Object.keys(l).join(", ")}.`,resultType:"failure",error:`Tool '${s}' does not exist.`,sessionLog:`<error>Tool '${s}' does not exist.</error>`,toolTelemetry:{}};else{let p=m.callback,A={...n,toolCallId:c,toolOptions:this.settings.service?.tools?.[s],settings:this.settings},Z=await p({...G},A);d=typeof Z=="string"?{textResultForLlm:Z,resultType:"success",toolTelemetry:{}}:Z}}catch(G){d={textResultForLlm:`Failed to execute \`${s}\` tool with arguments: ${o} due to error: ${G}`,resultType:"failure",error:G instanceof Error?G.message:`${G}`,sessionLog:`<error>Failed to execute \`${s}\` tool with arguments: ${o}</error>`,toolTelemetry:{properties:{wasSyntaxError:G instanceof SyntaxError?"true":"false"}}}}a.push({toolCallId:c,textResultForLlm:d.textResultForLlm,sessionLog:d.resultType=="success"?d.sessionLog:d.error?`<error>${d.error}</error>`:void 0})}return a}requiresToolOutput(e){return e.output.filter(l=>l.type==="function_call").length>0}};function _6e(t){if(t.role==="function")throw new Error("Function role is not supported");let e=[];if(t.reasoning_opaque&&e.push({id:t.reasoning_opaque,type:"reasoning",summary:t.reasoning_text?[{text:t.reasoning_text,type:"summary_text"}]:[],encrypted_content:t.encrypted_content}),t.role==="assistant"&&t.tool_calls&&t.tool_calls.length>0&&kA(t.tool_calls[0])){let l=t.tool_calls[0];return[...e,{type:"function_call",id:t.id,name:l.function.name,arguments:l.function.arguments,call_id:l.id}]}if(t.role==="tool")return[...e,{type:"function_call_output",id:`fc_${t.tool_call_id}`,call_id:t.tool_call_id,output:typeof t.content=="string"?t.content:t.content.map(l=>l.text).join(" ")??""}];if(!t.content)return e;if(t.role==="assistant"){let l=t.id||crypto.randomUUID();return l.startsWith("msg_")||(l=`msg_${l}`),[...e,{type:"message",id:l,role:t.role,content:[{annotations:[],type:"output_text",text:typeof t.content=="string"?t.content:t.content?.map(n=>n.type==="text"?n.text:"").join(" ")??""}],status:"completed"}]}return[...e,{role:t.role,content:typeof t.content=="string"?[{type:"input_text",text:t.content}]:t.content.map(l=>{if(l.type==="text")return{type:"input_text",text:l.text};if(l.type==="image_url")return{type:"input_image",detail:l.image_url.detail||"auto",image_url:l.image_url.url}}).filter(l=>l!==void 0),type:"message"}]}function M6e(t){if(t.type==="reasoning")return{role:"assistant",reasoning_opaque:t.id,reasoning_text:t.summary?t.summary.map(e=>e.text).join(" "):void 0,content:"",encrypted_content:t.encrypted_content};if(t.type==="function_call")return{role:"assistant",id:t.id,tool_calls:[{id:t.call_id,type:"function",function:{name:t.name,arguments:t.arguments}}],content:""};if(t.type==="function_call_output")return{role:"tool",content:t.output,tool_call_id:t.call_id};if(t.type==="message")return{id:"id"in t?t.id:void 0,role:t.role,content:typeof t.content=="string"?t.content:t.content?.map(e=>e.type==="input_text"||e.type==="output_text"?e.text:"").join(" ")??""};throw new Error(`Unknown item type: ${t.type}`)}function U0n(t){let e;t.incomplete_details?.reason==="content_filter"?e="content_filter":t.incomplete_details?.reason==="max_output_tokens"?e="length":e=t.output.some(r=>r.type==="function_call")?"tool_calls":"stop";let n=t.output.filter(r=>r.type==="message"||r.type==="reasoning"||r.type==="function_call").map(r=>M6e(r)).filter(r=>r.role==="assistant").map((r,a)=>({message:{content:Array.isArray(r.content)?r.content.map(I=>typeof I=="string"?I:"text"in I?I.text:"").join(" "):r.content||null,refusal:r.refusal||null,role:r.role||null,tool_calls:r.tool_calls?.filter(I=>I.type==="function"),reasoning_opaque:r.reasoning_opaque,reasoning_text:r.reasoning_text,encrypted_content:r.encrypted_content},index:a,finish_reason:e,logprobs:null}));return{id:t.id,choices:n,created:t.created_at,model:t.model,object:"chat.completion",usage:{completion_tokens:t.usage?.output_tokens||0,prompt_tokens:t.usage?.input_tokens||0,total_tokens:t.usage?.total_tokens||0}}}function XOt(t){return{request_id:t.request_id,data:U0n(t.data),response:t.response}}var S1e=class extends bL{makeResponsesRequest(e,l,n,r,a,I,s){let o=n.find(p=>p.role==="system")?.content||"",c=Array.isArray(o)?o.join(`
|
|
1905
1905
|
`):o,m=n.filter(p=>p.role!=="system").flatMap(_6e),G=a.filter(p=>p.type==="function").map(p=>({name:p.function.name,description:p.function.description,parameters:p.function.parameters||null,strict:!1,type:"function"}));return this.logger.debug(`Making responses request with input: ${JSON.stringify(m,null,2)}`),e.responses.create({model:l,previous_response_id:void 0,instructions:c,input:m,parallel_tool_calls:a.length>0?!0:void 0,tools:G,reasoning:{summary:"auto",effort:"medium"},store:!1,include:["reasoning.encrypted_content"]},{maxRetries:I||this.clientOptions.retryPolicy.maxRetries,headers:s?.requestHeaders,signal:s?.abortSignal}).withResponse()}makeRequest(e,l,n,r,a,I,s){return this.makeResponsesRequest(e,l,n,r,a,I,s).then(XOt)}};var B1e=class extends S1e{constructor(e,l,n){let r=new x8;super(r,e,l,n)}};var Ude=class{constructor(e,l,n){this.settings=e;this.logger=l;this.clientOptions=n;this.chatClient=new J1e(e,l,n)}chatClient;get model(){return this.chatClient.model}async*getCompletionWithTools(e,l,n,r){let a=await this.chatClient.modelPromise;(this.clientOptions?.thinkingMode||to(this.settings,"copilot_swe_agent_enable_responses_api"))&&a&&a.supported_endpoints?.includes("/responses")?yield*new B1e(this.settings,this.logger,{model:this.chatClient.model,...this.clientOptions}).getCompletionWithTools(e,l,n,r):yield*this.chatClient.getCompletionWithTools(e,l,n,r)}};var T1e=class extends bL{constructor(e,l,n,r){super(e,l,n,r)}getCompletionOptions(e,l){return{...this.model.startsWith("gpt-4")?{temperature:0,top_p:.95,frequency_penalty:0,presence_penalty:0,parallel_tool_calls:e?!1:void 0}:{},tool_choice:l?.toolChoice}}async*getCompletionWithTools(e,l,n,r){let a=await super.getCompletionWithTools(e,l,n,r);for await(let I of a)I.kind==="message"?yield{...I,message:F6({...I.message,reasoning_text:I.message?.cot_summary})}:yield I}};var O1e=class extends x1e{constructor(e,l,n,r){super(e,l,n,r)}};var D6e=class extends Lde{constructor(e){super(e)}setInitiatorHeader(e){}setAdditionalHeaders(e){}listModels(){return Promise.resolve([])}},U1e=class{async createClient(e,l,n){l.startGroup("configured settings:",8),l.debug(JSON.stringify(e,null,2)),l.endGroup(8);let r=e.api?.openai?.apiKey,a=e.api?.openai?.azureKeyVaultUri,I=e.api?.openai?.azureSecretName;if(!r&&a){l.debug("No API_KEY provided, trying secret provider");let d=O6e(a,l);try{r=await d.getSecret(I||"azure-openai-api-key")}catch(m){l.debug(`Failed to get API Key from secret provider:
|
|
1906
|
-
${m}`)}}let s=cZt(e);l.debug(`Using Azure Open API at ${s}`);let c={baseURL:`${new URL(s).origin}/openai`,apiVersion:e.api?.openai?.azure?.apiVersion||"2024-10-21",deployment:n?.model,defaultHeaders:n?.requestHeaders};if(r)c={...c,apiKey:r},l.debug("Using Azure OpenAI API Key");else{let d=new Gw,G=Pze(d,"https://cognitiveservices.azure.com/.default");c={...c,azureADTokenProvider:G},l.debug("Using Azure Managed Identity")}return new D6e(c)}};var z6e=class extends ia{constructor(e){super(e)}setInitiatorHeader(e){}setAdditionalHeaders(e){}listModels(){return Promise.resolve([])}},M1e=class{async createClient(e,l,n){l.startGroup("configured settings:",8),l.debug(JSON.stringify(e,null,2)),l.endGroup(8);let r=iZt(e),a=e.api?.openai?.baseUrl,I=n?.requestHeaders;return new z6e({baseURL:a,apiKey:r,defaultHeaders:I})}};function Mde(t,e,l,n){switch(l){case"sweagent-aip":return new V2e(t,e,n);case"sweagent-anthropic":return new PYe(t,e,n);case"sweagent-capi":return new Ude(t,e,n);case"sweagent-openai":return n?.thinkingMode?new O1e(kOt(t),t,e,n):new T1e(kOt(t),t,e,n);default:return new Ude(t,e,n)}}function kOt(t){return t.api?.openai?.azure?.url?new U1e:new M1e}var ET=class{logger;forcePremiumRequest=!1;constructor(e){this.logger=e}async*preRequest(e){e.turn===0||this.forcePremiumRequest?(e.additionalRequestHeaders["X-Initiator"]="user",this.logger.debug("InitiatorHeaderProcessor: Setting X-Initiator to 'user'")):(e.additionalRequestHeaders["X-Initiator"]="agent",this.logger.debug("InitiatorHeaderProcessor: Setting X-Initiator to 'agent'")),this.resetPremiumRequest(),yield*[]}setForcePremiumRequest(){this.forcePremiumRequest=!0}toJSON(){return JSON.stringify({type:"InitiatorHeaderProcessor"})}resetPremiumRequest(){this.forcePremiumRequest=!1}},B8=class{logger;constructor(e){this.logger=e}async*preRequest(e){e.additionalRequestHeaders["X-Initiator"]="agent",this.logger.debug("FreeRequestProcessor: Setting X-Initiator to 'agent'"),yield*[]}setForcePremiumRequest(){}toJSON(){return JSON.stringify({type:"FreeRequestProcessor"})}};function GL(t){return t.kind==="message"&&t.message.role==="assistant"}function LOt(t){return t.kind==="message"&&t.message.role==="user"}function T8(t){return t.kind==="message"&&t.message.role==="assistant"&&!!t.message.tool_calls}function _1e(t){return t.kind==="message"&&t.message.role==="tool"}function M0n(t,e){return t.toolCalls.find(l=>l.toolCallId===e)}function _0n(t,e,l){let n=l.function.name;try{let r=JSON.parse(l.function.arguments||"{}"),a=e.find(c=>c.name===n),I=a?.safeForTelemetry||{name:!1,inputsNames:!1},s=$k(a),o;if(s&&t.customAgents&&t.settings){let c=t.customAgents.find(d=>d.name===n);if(c){let d=t.settings.github?.repo?.name??"",m=d.split("/"),G=m.length===2?m[0]:"",p=m.length===2?m[1]:d,A=c.mcpServers?Object.keys(c.mcpServers).join(","):"",Z=c.mcpServers?Object.keys(c.mcpServers).length:0;o={repoOwner:G,repoName:p,displayName:c.name,mcpServerNames:A,mcpServerCount:Z}}}return{toolCallId:l.id,toolName:n,arguments:l.function.arguments,safeForTelemetryToolName:I===!0||I.name?n:IS(n),safeForTelemetryArguments:I===!0||I.inputsNames?XTt(r):"",isCustomAgent:s,customAgentInfo:o}}catch{return{toolCallId:l.id,toolName:n,arguments:l.function.arguments,safeForTelemetryToolName:IS(n),safeForTelemetryArguments:"",isCustomAgent:!1,customAgentInfo:void 0}}}var D1e=class{constructor(e,l,n){this.runtimeContext=e;this.forAgent=l;this.toolsInUse=n}turnDataCache=new Map;emittedTurns=new Set;getTurnData(){return this.turnDataCache}async ingestEvent(e){let l,n;if("turn"in e&&typeof e.turn=="number"){if(l=e.turn+1,this.emittedTurns.has(l))return;this.turnDataCache.has(l)||this.turnDataCache.set(l,{featureFlagsAsString:WJe(this.runtimeContext.settings),toolCalls:[],toolCallExecutions:[],turn:l}),n=this.turnDataCache.get(l)}else return;e.kind==="tool_execution"?await this.ingestToolExecutionEventAndEmitToolCallExecutedTelemetry(n,e):e.kind==="turn_started"||e.kind==="turn_failed"||e.kind==="turn_retry"||e.kind==="turn_ended"?(n={...n,model:e.model,modelInfo:JSON.stringify(e.modelInfo)},e.kind==="turn_started"?n={...n,startTimeMs:e.timestampMs}:e.kind==="turn_retry"?n={...n,endTimeMs:e.timestampMs,retriesUsed:(n.retriesUsed??0)+1}:e.kind==="turn_failed"?n={...n,endTimeMs:e.timestampMs,error:e.error}:e.kind==="turn_ended"&&(n={...n,endTimeMs:e.timestampMs})):e.kind==="history_truncated"?n={...n,truncateEvent:e}:e.kind==="image_processing"?n={...n,imageProcessingMetrics:e.imageProcessingMetrics}:e.kind==="images_removed"?n={...n,largeImagesRemoved:(n.largeImagesRemoved??0)+(e.largeImagesRemoved?1:0),imagesRemoved:(n.imagesRemoved??0)+(e.imagesRemoved?1:0)}:e.kind==="model_call_success"||e.kind==="model_call_failure"?(n={...n,modelCallDurationMs:e.modelCallDurationMs,api_call_id:e.modelCall.api_id,provider_call_id:e.modelCall.request_id,conversationStructureSummary:fXt(e.requestMessages)},e.kind==="model_call_success"&&(n={...n,responsePromptTokens:e.responseUsage?.prompt_tokens,responseCompletionTokens:e.responseUsage?.completion_tokens,responseTotalTokens:e.responseUsage?.total_tokens})):LOt(e)&&e.source==="jit-instruction"?n={...n,jitInstructionsAdded:(n?.jitInstructionsAdded??0)+1}:GL(e)&&e.message.tool_calls?n={...n,toolCalls:n.toolCalls.concat(e.message.tool_calls.map(r=>({..._0n(this.runtimeContext,this.toolsInUse,r)})))}:_1e(e)&&(n={...n,toolCallExecutions:n.toolCallExecutions.concat([e.message.tool_call_id])}),this.turnDataCache.set(l,n),e.kind==="turn_ended"&&(await this.emitTurnTelemetry(l),this.emittedTurns.add(l),this.turnDataCache.delete(l))}async emitTurnTelemetry(e){let l=this.turnDataCache.get(e);if(l){let n={kind:"telemetry",telemetry:{event:"get_completion_with_tools_turn",properties:{model:l.model||"default",modelInfo:l.modelInfo||"{}",api_call_id:l.api_call_id,provider_call_id:l.provider_call_id,agent:this.forAgent,toolCalls:JSON.stringify(l.toolCalls.map(r=>({toolCallId:r.toolCallId,toolName:r.safeForTelemetryToolName}))),toolCallExecutions:JSON.stringify(l.toolCallExecutions),error:l.error,featureFlags:WJe(this.runtimeContext.settings),conversationStructureSummary:l.conversationStructureSummary,truncationPerformedBy:l.truncateEvent?.performedBy},metrics:{turn:e,turnDurationMs:l.endTimeMs!==void 0&&l.startTimeMs!==void 0?l.endTimeMs-l.startTimeMs:0,modelCallDurationMs:l.modelCallDurationMs,retriesUsed:l.retriesUsed??0,numToolCalls:l.toolCalls.length,numToolExecutions:l.toolCallExecutions.length,largeImagesRemoved:l.largeImagesRemoved,imagesRemoved:l.imagesRemoved,responsePromptTokens:l.responsePromptTokens,responseCompletionTokens:l.responseCompletionTokens,responseTotalTokens:l.responseTotalTokens,jitInstructionsAdded:l.jitInstructionsAdded,...l.truncateEvent?.truncateResult,...l.imageProcessingMetrics},restrictedProperties:{}}};await this.runtimeContext.callback?.progress(n)}}async ingestToolExecutionEventAndEmitToolCallExecutedTelemetry(e,l){let n=l.toolCallId,r=M0n(e,n);if(r){let a=l.toolResult,I={kind:"telemetry",telemetry:{event:"tool_call_executed",properties:{...a.toolTelemetry.properties,resultType:a.resultType,toolCallId:n,arguments:r.safeForTelemetryArguments,toolName:r.safeForTelemetryToolName,api_call_id:e.api_call_id,isCustomAgent:r.isCustomAgent?"true":"false"},restrictedProperties:{...a.toolTelemetry.restrictedProperties,arguments:r.arguments,result:a.textResultForLlm,toolName:r.toolName,error:a.error,customAgent:r.customAgentInfo?JSON.stringify({repoOwner:r.customAgentInfo.repoOwner,repoName:r.customAgentInfo.repoName,displayName:r.customAgentInfo.displayName,mcpServerNames:r.customAgentInfo.mcpServerNames}):void 0},metrics:{...a.toolTelemetry.metrics,durationMs:l.durationMs,customAgentMcpServerCount:r.customAgentInfo?.mcpServerCount}}};await this.runtimeContext.callback?.progress(I)}}};var JOt={shell:["bash","powershell"],bash:["bash"],powershell:["powershell"],read:["view"],NotebookRead:["view"],edit:["str_replace_editor","create","edit"],MultiEdit:["str_replace_editor","create","edit"],Write:["str_replace_editor","create","edit"],NotebookEdit:["str_replace_editor","create","edit"],search:["search"],Grep:["search"],Glob:["search"],"custom-agent":[]};function D0n(t,e,l){if(!t.endsWith("/*"))return!1;let n=t.slice(0,-2).toLowerCase();for(let r of e)P6e(r).startsWith(n+"/")&&l.add(r);return!0}function z0n(t,e,l){t.startsWith("github/")&&(t=t.replace("github/","github-mcp-server/"));let n=e.get(t.toLowerCase());return n?(l.add(n),!0):!1}function P0n(t,e,l,n){if(!t.includes("/"))return!1;let[r,a]=t.split("/",2),I=a.toLowerCase(),s=e.get(I);if(s)return l.add(s),!0;let o=!1,c=n[I];if(c)for(let d of c){let m=e.get(d.toLowerCase());m&&(l.add(m),o=!0)}return o}function j0n(t,e,l){if(t!=="shell")return!1;let n=process.platform==="win32"?"powershell":"bash",r=process.platform==="win32"?"bash":"powershell",a=e.get(n.toLowerCase());return a||(a=e.get(r.toLowerCase())),a?(l.add(a),!0):!1}function K0n(t,e,l,n){let r=n[t.toLowerCase()];if(!r)return!1;let a=!1;for(let I of r){let s=e.get(I.toLowerCase());s&&(l.add(s),a=!0)}return a}function xOt(t,e,l=[]){let n=new Map,r=new Set;for(let s of e)n.set(P6e(s),s);let a=[...JOt["custom-agent"]];for(let s of l)$k(s)&&a.push(P6e(s));let I={};for(let[s,o]of Object.entries(JOt))I[s.toLowerCase()]=o;I["custom-agent"]=a,I.task=a;for(let s of t){let o=s.toLowerCase();D0n(o,e,r)||K0n(o,n,r,I)||z0n(o,n,r)||P0n(o,n,r,I)||j0n(o,n,r)}return Array.from(r)}var P6e=t=>(t.namespacedName||t.name).toLowerCase();var _de=class{async*preRequest(e){yield*[]}handleCallbackResponse(e){}getUserMessages(){return[]}clearUserMessages(){}canProcessUserMessages(){return!1}toJSON(){return JSON.stringify({type:"NoopUserMessageProcessor"})}};var z1e={start:"\u25B6\uFE0F Begin custom agent",end:"\u23F9\uFE0F End custom agent"},q0n=void 0,Dde=class{constructor(e,l=q0n){this.runtimeContext=e;this.agentId=l;this.gitHandlers={silent:new pZ(new xd,this.runtimeContext.exec),logging:new pZ(this.runtimeContext.logger,this.runtimeContext.exec)}}gitHandlers;async agent(e,l,n,r,a,I,s,o=new _de,c){let d=async(A,Z,W)=>{let R={role:"user",content:A};return await this.runtimeContext.callback?.progress({kind:"message",turn:0,callId:this.agentId,message:R}),await this.runCompletionWithTools(e,l,[...Z??[],R],I,s,a,{executeToolsInParallel:to(this.runtimeContext.settings,"copilot_swe_agent_parallel_tool_execution"),initialTurnCount:W},c,o)},m=r,G=n??[],p;for(;m;){let A=await d(m,G,p);p=A.finalTurnCount,G=A.messages,m=await c?.onResult(A.postCompletionWithToolsCommitHash)}for(let A of I)if(A.shutdown){let Z=await A.shutdown();Z&&await this.runtimeContext.callback?.progress(Z)}return{finalTurnCount:p||0,messages:G}}async runCompletionWithTools(e,l,n,r,a,I,s,o,c=new _de){let d=this.runtimeContext.callback?new D1e(this.runtimeContext,"sweagent-capi",r):void 0,m=this.gitHandlers.logging,G=await m.getCurrentCommitHash(e),p=n.filter(X=>X.role==="user").at(-1),A=this.createCompletionWithToolsProcessors(e,G,r,a,c,I,o,p),Z=this.runtimeContext.client.getCompletionWithTools(l,n,r,{...s,callId:this.agentId,processors:A}),W=0,R=[...n],V=[];for await(let X of Z){if(to(this.runtimeContext.settings,"copilot_swe_agent_progress_commands")){let S=await this.runtimeContext.callback?.progress(X,{accepts_user_messages:c.canProcessUserMessages()});c.handleCallbackResponse(S)}else await this.runtimeContext.callback?.progress(X);d&&await d.ingestEvent(X),(X.kind==="message"||X.kind==="response")&&(X.kind==="message"&&R.push(X.message),X.kind==="response"&&V.push(X.response),W=Math.max(W,X.turn??0))}let v=await m.getCurrentCommitHash(e);return{finalTurnCount:W,messages:R,resultMessages:V,preCompletionWithToolsCommitHash:G,postCompletionWithToolsCommitHash:v}}createCompletionWithToolsProcessors(e,l,n,r,a,I,s,o){let c=new d0e(this.runtimeContext.logger,this.runtimeContext.settings,n.find(p=>p.name==="github-mcp-server-get_file_contents")),d=new b0e(this.runtimeContext.settings,this.runtimeContext.logger,this.gitHandlers.silent,e,l,I),m=new j4(o,this.runtimeContext.logger),G=[d,c,m];return to(this.runtimeContext.settings,"copilot_swe_agent_progress_commands")&&G.push(a),G.push(r),{preRequest:G.filter(p=>p!==void 0),preToolsExecution:[s].filter(p=>p!==void 0),postToolExecution:[c,s].filter(p=>p!==void 0),onRequestError:[c,m].filter(p=>p!==void 0)}}};function $0n(t){let e=t.content;if(typeof e=="string")return e;if(!Array.isArray(e)||e.length===0||!("text"in e[0]))throw new Error("Expected text content in response");return e[0].text}async function eRn(t,e,l,n){if(!e.mcpServers||Object.keys(e.mcpServers).length===0||!n)return l;t.info(`Custom agent ${e.name} is using MCP servers: ${Object.keys(e.mcpServers).join(", ")}`);let r=l;for(let[a,I]of Object.entries(e.mcpServers))try{t.info(`Adding MCP server '${a}' for custom agent '${e.name}'`),r=await tRn(t,e,a,I,r,n)}catch(s){t.error(`Encountered an issue when trying to add MCP ${a} for custom agent '${e.name}': ${s}`)}return r}async function tRn(t,e,l,n,r,a){let I=await a.addServerAndGetTools(l,n,t);if(I.length>0){t.info(`Adding ${I.length} new tools from server '${l}' for custom agent '${e.name}'`);for(let s of I)t.info(`Adding new tool: ${s.name}`),r.push(s)}return r}async function SOt(t,e,l){!t.callback||!l||(e==="begin"?await t.callback.progress({kind:"title_and_body_content",title:`${z1e.start}: ${l}`,body:`All messages from here to '${z1e.end}' are from the ${l} custom agent.`}):await t.callback.progress({kind:"title_and_body_content",title:`${z1e.end}: ${l}`,body:`All messages from here back to '${z1e.start}' are from the ${l} custom agent.`}))}function TOt(t,e,l,n,r,a,I){async function s(o,c){let d=c?.toolCallId;await SOt(r,"begin",l.name);let m=await l.prompt();r.logger.info(`Starting custom agent as tool: ${l.name}`),r.logger.info(`Custom agent system prompt: ${m}`),r.logger.info(`Candidate tools for custom agent: ${a.map(X=>X.namespacedName||X.name).join(", ")}`),r.logger.info(`Requested tools for custom agent: ${l.tools?.join(", ")??"none"}`),a=await eRn(r.logger,l,a,I);let G=rRn(a,l,"tool");r.logger.info(`Custom agent tools after filtering: ${G.map(X=>X.name).join(", ")}`);let p=new Dde(r,d),A=await t(G),Z=new B8(r.logger),W=e(m,o.prompt),R=await p.agent(n,A,void 0,W,{},G,Z),V=R.messages[R.messages.length-1],v=V?$0n(V):"No response from tool";return await SOt(r,"end",l.name),{textResultForLlm:v,resultType:"success",toolTelemetry:{}}}return{name:l.name,description:`${l6e} ${l.description}`,input_schema:{type:"object",properties:{prompt:{type:"string",description:"The prompt for the agent."}},required:["prompt"]},callback:s}}var P1e=class{constructor(e,l,n={requestRequired:!1}){this.mcpHost=e;this.settings=l;this.permissions=n}async addServerAndGetTools(e,l,n){try{await this.mcpHost.startServer(e,l),n.info(`Successfully started MCP server '${e}'`);let a=(await this.mcpHost.getTools(this.settings,n,this.permissions)).filter(I=>I.name.startsWith(`${e}-`)||I.namespacedName?.startsWith(`${e}/`));return n.info(`Found ${a.length} MCP tools from server '${e}'`),a}catch(r){return n.error(`Failed to add MCP server '${e}': ${r}`),[]}}},lRn=[aS,bWe],nRn=[HRt],BOt=[aS,bWe];function rRn(t,e,l){if(!e?.tools||e.tools.length===1&&e.tools[0]==="*")return t.filter(s=>l==="top-level"||!BOt.includes(s.name));let n=t.filter(s=>$k(s)),r=l==="top-level"?lRn:nRn;return xOt([...e.tools,...r],t,n).filter(s=>l==="top-level"||!BOt.includes(s.name))}async function j6e(t,e,l,n,r){try{return(await n.invokeTool("blackbird-mcp-server/search_repository_with_agent",{task:t,depth:2,owner:e,repo:l,numSnippets:10},"hidden_characters")).textResultForLlm}catch(a){return r.error(`Error during Blackbird search: ${a}`),""}}var UOt=t=>to(t,"copilot_swe_agent_search")||Pgt(t,"SearchAgentExperiment")==="enabled",OOt="search";function K6e(t){return t!==null&&typeof t=="object"&&"question"in t&&"reason"in t&&"searchCommand"in t}var aRn=(t,e,l)=>`
|
|
1906
|
+
${m}`)}}let s=cZt(e);l.debug(`Using Azure Open API at ${s}`);let c={baseURL:`${new URL(s).origin}/openai`,apiVersion:e.api?.openai?.azure?.apiVersion||"2024-10-21",deployment:n?.model,defaultHeaders:n?.requestHeaders};if(r)c={...c,apiKey:r},l.debug("Using Azure OpenAI API Key");else{let d=new Gw,G=Pze(d,"https://cognitiveservices.azure.com/.default");c={...c,azureADTokenProvider:G},l.debug("Using Azure Managed Identity")}return new D6e(c)}};var z6e=class extends ia{constructor(e){super(e)}setInitiatorHeader(e){}setAdditionalHeaders(e){}listModels(){return Promise.resolve([])}},M1e=class{async createClient(e,l,n){l.startGroup("configured settings:",8),l.debug(JSON.stringify(e,null,2)),l.endGroup(8);let r=iZt(e),a=e.api?.openai?.baseUrl,I=n?.requestHeaders;return new z6e({baseURL:a,apiKey:r,defaultHeaders:I})}};function Mde(t,e,l,n){switch(l){case"sweagent-aip":return new V2e(t,e,n);case"sweagent-anthropic":return new PYe(t,e,n);case"sweagent-capi":return new Ude(t,e,n);case"sweagent-openai":return n?.thinkingMode?new O1e(kOt(t),t,e,n):new T1e(kOt(t),t,e,n);default:return new Ude(t,e,n)}}function kOt(t){return t.api?.openai?.azure?.url?new U1e:new M1e}var ET=class{logger;forcePremiumRequest=!1;constructor(e){this.logger=e}async*preRequest(e){e.turn===0||this.forcePremiumRequest?(e.additionalRequestHeaders["X-Initiator"]="user",this.logger.debug("InitiatorHeaderProcessor: Setting X-Initiator to 'user'")):(e.additionalRequestHeaders["X-Initiator"]="agent",this.logger.debug("InitiatorHeaderProcessor: Setting X-Initiator to 'agent'")),this.resetPremiumRequest(),yield*[]}setForcePremiumRequest(){this.forcePremiumRequest=!0}toJSON(){return JSON.stringify({type:"InitiatorHeaderProcessor"})}resetPremiumRequest(){this.forcePremiumRequest=!1}},B8=class{logger;constructor(e){this.logger=e}async*preRequest(e){e.additionalRequestHeaders["X-Initiator"]="agent",this.logger.debug("FreeRequestProcessor: Setting X-Initiator to 'agent'"),yield*[]}setForcePremiumRequest(){}toJSON(){return JSON.stringify({type:"FreeRequestProcessor"})}};function GL(t){return t.kind==="message"&&t.message.role==="assistant"}function LOt(t){return t.kind==="message"&&t.message.role==="user"}function T8(t){return t.kind==="message"&&t.message.role==="assistant"&&!!t.message.tool_calls}function _1e(t){return t.kind==="message"&&t.message.role==="tool"}function M0n(t,e){return t.toolCalls.find(l=>l.toolCallId===e)}function _0n(t,e,l){let n=l.function.name;try{let r=JSON.parse(l.function.arguments||"{}"),a=e.find(c=>c.name===n),I=a?.safeForTelemetry||{name:!1,inputsNames:!1},s=$k(a),o;if(s&&t.customAgents&&t.settings){let c=t.customAgents.find(d=>d.name===n);if(c){let d=t.settings.github?.repo?.name??"",m=d.split("/"),G=m.length===2?m[0]:"",p=m.length===2?m[1]:d,A=c.mcpServers?Object.keys(c.mcpServers).join(","):"",Z=c.mcpServers?Object.keys(c.mcpServers).length:0;o={repoOwner:G,repoName:p,displayName:c.name,mcpServerNames:A,mcpServerCount:Z}}}return{toolCallId:l.id,toolName:n,arguments:l.function.arguments,safeForTelemetryToolName:I===!0||I.name?n:IS(n),safeForTelemetryArguments:I===!0||I.inputsNames?XTt(r):"",isCustomAgent:s,customAgentInfo:o}}catch{return{toolCallId:l.id,toolName:n,arguments:l.function.arguments,safeForTelemetryToolName:IS(n),safeForTelemetryArguments:"",isCustomAgent:!1,customAgentInfo:void 0}}}var D1e=class{constructor(e,l,n){this.runtimeContext=e;this.forAgent=l;this.toolsInUse=n}turnDataCache=new Map;emittedTurns=new Set;getTurnData(){return this.turnDataCache}async ingestEvent(e){let l,n;if("turn"in e&&typeof e.turn=="number"){if(l=e.turn+1,this.emittedTurns.has(l))return;this.turnDataCache.has(l)||this.turnDataCache.set(l,{featureFlagsAsString:WJe(this.runtimeContext.settings),toolCalls:[],toolCallExecutions:[],turn:l}),n=this.turnDataCache.get(l)}else return;e.kind==="tool_execution"?await this.ingestToolExecutionEventAndEmitToolCallExecutedTelemetry(n,e):e.kind==="turn_started"||e.kind==="turn_failed"||e.kind==="turn_retry"||e.kind==="turn_ended"?(n={...n,model:e.model,modelInfo:JSON.stringify(e.modelInfo)},e.kind==="turn_started"?n={...n,startTimeMs:e.timestampMs}:e.kind==="turn_retry"?n={...n,endTimeMs:e.timestampMs,retriesUsed:(n.retriesUsed??0)+1}:e.kind==="turn_failed"?n={...n,endTimeMs:e.timestampMs,error:e.error}:e.kind==="turn_ended"&&(n={...n,endTimeMs:e.timestampMs})):e.kind==="history_truncated"?n={...n,truncateEvent:e}:e.kind==="image_processing"?n={...n,imageProcessingMetrics:e.imageProcessingMetrics}:e.kind==="images_removed"?n={...n,largeImagesRemoved:(n.largeImagesRemoved??0)+(e.largeImagesRemoved?1:0),imagesRemoved:(n.imagesRemoved??0)+(e.imagesRemoved?1:0)}:e.kind==="model_call_success"||e.kind==="model_call_failure"?(n={...n,callId:e.callId,modelCallDurationMs:e.modelCallDurationMs,api_call_id:e.modelCall.api_id,provider_call_id:e.modelCall.request_id,conversationStructureSummary:fXt(e.requestMessages)},e.kind==="model_call_success"&&(n={...n,responsePromptTokens:e.responseUsage?.prompt_tokens,responseCompletionTokens:e.responseUsage?.completion_tokens,responseTotalTokens:e.responseUsage?.total_tokens})):LOt(e)&&e.source==="jit-instruction"?n={...n,jitInstructionsAdded:(n?.jitInstructionsAdded??0)+1}:GL(e)&&e.message.tool_calls?n={...n,toolCalls:n.toolCalls.concat(e.message.tool_calls.map(r=>({..._0n(this.runtimeContext,this.toolsInUse,r)})))}:_1e(e)&&(n={...n,toolCallExecutions:n.toolCallExecutions.concat([e.message.tool_call_id])}),this.turnDataCache.set(l,n),e.kind==="turn_ended"&&(await this.emitTurnTelemetry(l),this.emittedTurns.add(l),this.turnDataCache.delete(l))}async emitTurnTelemetry(e){let l=this.turnDataCache.get(e);if(l){let n={kind:"telemetry",telemetry:{event:"get_completion_with_tools_turn",properties:{callId:l.callId,model:l.model||"default",modelInfo:l.modelInfo||"{}",api_call_id:l.api_call_id,provider_call_id:l.provider_call_id,agent:this.forAgent,toolCalls:JSON.stringify(l.toolCalls.map(r=>({toolCallId:r.toolCallId,toolName:r.safeForTelemetryToolName}))),toolCallExecutions:JSON.stringify(l.toolCallExecutions),error:l.error,featureFlags:WJe(this.runtimeContext.settings),conversationStructureSummary:l.conversationStructureSummary,truncationPerformedBy:l.truncateEvent?.performedBy},metrics:{turn:e,turnDurationMs:l.endTimeMs!==void 0&&l.startTimeMs!==void 0?l.endTimeMs-l.startTimeMs:0,modelCallDurationMs:l.modelCallDurationMs,retriesUsed:l.retriesUsed??0,numToolCalls:l.toolCalls.length,numToolExecutions:l.toolCallExecutions.length,largeImagesRemoved:l.largeImagesRemoved,imagesRemoved:l.imagesRemoved,responsePromptTokens:l.responsePromptTokens,responseCompletionTokens:l.responseCompletionTokens,responseTotalTokens:l.responseTotalTokens,jitInstructionsAdded:l.jitInstructionsAdded,...l.truncateEvent?.truncateResult,...l.imageProcessingMetrics},restrictedProperties:{}}};await this.runtimeContext.callback?.progress(n)}}async ingestToolExecutionEventAndEmitToolCallExecutedTelemetry(e,l){let n=l.toolCallId,r=M0n(e,n);if(r){let a=l.toolResult,I={kind:"telemetry",telemetry:{event:"tool_call_executed",properties:{...a.toolTelemetry.properties,completionWithToolsCallId:l.callId,resultType:a.resultType,toolCallId:n,arguments:r.safeForTelemetryArguments,toolName:r.safeForTelemetryToolName,api_call_id:e.api_call_id,isCustomAgent:r.isCustomAgent?"true":"false"},restrictedProperties:{...a.toolTelemetry.restrictedProperties,arguments:r.arguments,result:a.textResultForLlm,toolName:r.toolName,error:a.error,customAgent:r.customAgentInfo?JSON.stringify({repoOwner:r.customAgentInfo.repoOwner,repoName:r.customAgentInfo.repoName,displayName:r.customAgentInfo.displayName,mcpServerNames:r.customAgentInfo.mcpServerNames}):void 0},metrics:{...a.toolTelemetry.metrics,durationMs:l.durationMs,customAgentMcpServerCount:r.customAgentInfo?.mcpServerCount}}};await this.runtimeContext.callback?.progress(I)}}};var JOt={shell:["bash","powershell"],bash:["bash"],powershell:["powershell"],read:["view"],NotebookRead:["view"],edit:["str_replace_editor","create","edit"],MultiEdit:["str_replace_editor","create","edit"],Write:["str_replace_editor","create","edit"],NotebookEdit:["str_replace_editor","create","edit"],search:["search"],Grep:["search"],Glob:["search"],"custom-agent":[]};function D0n(t,e,l){if(!t.endsWith("/*"))return!1;let n=t.slice(0,-2).toLowerCase();for(let r of e)P6e(r).startsWith(n+"/")&&l.add(r);return!0}function z0n(t,e,l){t.startsWith("github/")&&(t=t.replace("github/","github-mcp-server/"));let n=e.get(t.toLowerCase());return n?(l.add(n),!0):!1}function P0n(t,e,l,n){if(!t.includes("/"))return!1;let[r,a]=t.split("/",2),I=a.toLowerCase(),s=e.get(I);if(s)return l.add(s),!0;let o=!1,c=n[I];if(c)for(let d of c){let m=e.get(d.toLowerCase());m&&(l.add(m),o=!0)}return o}function j0n(t,e,l){if(t!=="shell")return!1;let n=process.platform==="win32"?"powershell":"bash",r=process.platform==="win32"?"bash":"powershell",a=e.get(n.toLowerCase());return a||(a=e.get(r.toLowerCase())),a?(l.add(a),!0):!1}function K0n(t,e,l,n){let r=n[t.toLowerCase()];if(!r)return!1;let a=!1;for(let I of r){let s=e.get(I.toLowerCase());s&&(l.add(s),a=!0)}return a}function xOt(t,e,l=[]){let n=new Map,r=new Set;for(let s of e)n.set(P6e(s),s);let a=[...JOt["custom-agent"]];for(let s of l)$k(s)&&a.push(P6e(s));let I={};for(let[s,o]of Object.entries(JOt))I[s.toLowerCase()]=o;I["custom-agent"]=a,I.task=a;for(let s of t){let o=s.toLowerCase();D0n(o,e,r)||K0n(o,n,r,I)||z0n(o,n,r)||P0n(o,n,r,I)||j0n(o,n,r)}return Array.from(r)}var P6e=t=>(t.namespacedName||t.name).toLowerCase();var _de=class{async*preRequest(e){yield*[]}handleCallbackResponse(e){}getUserMessages(){return[]}clearUserMessages(){}canProcessUserMessages(){return!1}toJSON(){return JSON.stringify({type:"NoopUserMessageProcessor"})}};var z1e={start:"\u25B6\uFE0F Begin custom agent",end:"\u23F9\uFE0F End custom agent"},q0n=void 0,Dde=class{constructor(e,l=q0n){this.runtimeContext=e;this.agentId=l;this.gitHandlers={silent:new pZ(new xd,this.runtimeContext.exec),logging:new pZ(this.runtimeContext.logger,this.runtimeContext.exec)}}gitHandlers;async agent(e,l,n,r,a,I,s,o=new _de,c){let d=async(A,Z,W)=>{let R={role:"user",content:A};return await this.runtimeContext.callback?.progress({kind:"message",turn:0,callId:this.agentId,message:R}),await this.runCompletionWithTools(e,l,[...Z??[],R],I,s,a,{executeToolsInParallel:to(this.runtimeContext.settings,"copilot_swe_agent_parallel_tool_execution"),initialTurnCount:W},c,o)},m=r,G=n??[],p;for(;m;){let A=await d(m,G,p);p=A.finalTurnCount,G=A.messages,m=await c?.onResult(A.postCompletionWithToolsCommitHash)}for(let A of I)if(A.shutdown){let Z=await A.shutdown();Z&&await this.runtimeContext.callback?.progress(Z)}return{finalTurnCount:p||0,messages:G}}async runCompletionWithTools(e,l,n,r,a,I,s,o,c=new _de){let d=this.runtimeContext.callback?new D1e(this.runtimeContext,"sweagent-capi",r):void 0,m=this.gitHandlers.logging,G=await m.getCurrentCommitHash(e),p=n.filter(X=>X.role==="user").at(-1),A=this.createCompletionWithToolsProcessors(e,G,r,a,c,I,o,p),Z=this.runtimeContext.client.getCompletionWithTools(l,n,r,{...s,callId:this.agentId,processors:A}),W=0,R=[...n],V=[];for await(let X of Z){if(to(this.runtimeContext.settings,"copilot_swe_agent_progress_commands")){let S=await this.runtimeContext.callback?.progress(X,{accepts_user_messages:c.canProcessUserMessages()});c.handleCallbackResponse(S)}else await this.runtimeContext.callback?.progress(X);d&&await d.ingestEvent(X),(X.kind==="message"||X.kind==="response")&&(X.kind==="message"&&R.push(X.message),X.kind==="response"&&V.push(X.response),W=Math.max(W,X.turn??0))}let v=await m.getCurrentCommitHash(e);return{finalTurnCount:W,messages:R,resultMessages:V,preCompletionWithToolsCommitHash:G,postCompletionWithToolsCommitHash:v}}createCompletionWithToolsProcessors(e,l,n,r,a,I,s,o){let c=new d0e(this.runtimeContext.logger,this.runtimeContext.settings,n.find(p=>p.name==="github-mcp-server-get_file_contents")),d=new b0e(this.runtimeContext.settings,this.runtimeContext.logger,this.gitHandlers.silent,e,l,I),m=new j4(o,this.runtimeContext.logger),G=[d,c,m];return to(this.runtimeContext.settings,"copilot_swe_agent_progress_commands")&&G.push(a),G.push(r),{preRequest:G.filter(p=>p!==void 0),preToolsExecution:[s].filter(p=>p!==void 0),postToolExecution:[c,s].filter(p=>p!==void 0),onRequestError:[c,m].filter(p=>p!==void 0)}}};function $0n(t){let e=t.content;if(typeof e=="string")return e;if(!Array.isArray(e)||e.length===0||!("text"in e[0]))throw new Error("Expected text content in response");return e[0].text}async function eRn(t,e,l,n){if(!e.mcpServers||Object.keys(e.mcpServers).length===0||!n)return l;t.info(`Custom agent ${e.name} is using MCP servers: ${Object.keys(e.mcpServers).join(", ")}`);let r=l;for(let[a,I]of Object.entries(e.mcpServers))try{t.info(`Adding MCP server '${a}' for custom agent '${e.name}'`),r=await tRn(t,e,a,I,r,n)}catch(s){t.error(`Encountered an issue when trying to add MCP ${a} for custom agent '${e.name}': ${s}`)}return r}async function tRn(t,e,l,n,r,a){let I=await a.addServerAndGetTools(l,n,t);if(I.length>0){t.info(`Adding ${I.length} new tools from server '${l}' for custom agent '${e.name}'`);for(let s of I)t.info(`Adding new tool: ${s.name}`),r.push(s)}return r}async function SOt(t,e,l){!t.callback||!l||(e==="begin"?await t.callback.progress({kind:"title_and_body_content",title:`${z1e.start}: ${l}`,body:`All messages from here to '${z1e.end}' are from the ${l} custom agent.`}):await t.callback.progress({kind:"title_and_body_content",title:`${z1e.end}: ${l}`,body:`All messages from here back to '${z1e.start}' are from the ${l} custom agent.`}))}function TOt(t,e,l,n,r,a,I){async function s(o,c){let d=c?.toolCallId;await SOt(r,"begin",l.name);let m=await l.prompt();r.logger.info(`Starting custom agent as tool: ${l.name}`),r.logger.info(`Custom agent system prompt: ${m}`),r.logger.info(`Candidate tools for custom agent: ${a.map(X=>X.namespacedName||X.name).join(", ")}`),r.logger.info(`Requested tools for custom agent: ${l.tools?.join(", ")??"none"}`),a=await eRn(r.logger,l,a,I);let G=rRn(a,l,"tool");r.logger.info(`Custom agent tools after filtering: ${G.map(X=>X.name).join(", ")}`);let p=new Dde(r,d),A=await t(G),Z=new B8(r.logger),W=e(m,o.prompt),R=await p.agent(n,A,void 0,W,{},G,Z),V=R.messages[R.messages.length-1],v=V?$0n(V):"No response from tool";return await SOt(r,"end",l.name),{textResultForLlm:v,resultType:"success",toolTelemetry:{}}}return{name:l.name,description:`${l6e} ${l.description}`,input_schema:{type:"object",properties:{prompt:{type:"string",description:"The prompt for the agent."}},required:["prompt"]},callback:s}}var P1e=class{constructor(e,l,n={requestRequired:!1}){this.mcpHost=e;this.settings=l;this.permissions=n}async addServerAndGetTools(e,l,n){try{await this.mcpHost.startServer(e,l),n.info(`Successfully started MCP server '${e}'`);let a=(await this.mcpHost.getTools(this.settings,n,this.permissions)).filter(I=>I.name.startsWith(`${e}-`)||I.namespacedName?.startsWith(`${e}/`));return n.info(`Found ${a.length} MCP tools from server '${e}'`),a}catch(r){return n.error(`Failed to add MCP server '${e}': ${r}`),[]}}},lRn=[aS,bWe],nRn=[HRt],BOt=[aS,bWe];function rRn(t,e,l){if(!e?.tools||e.tools.length===1&&e.tools[0]==="*")return t.filter(s=>l==="top-level"||!BOt.includes(s.name));let n=t.filter(s=>$k(s)),r=l==="top-level"?lRn:nRn;return xOt([...e.tools,...r],t,n).filter(s=>l==="top-level"||!BOt.includes(s.name))}async function j6e(t,e,l,n,r){try{return(await n.invokeTool("blackbird-mcp-server/search_repository_with_agent",{task:t,depth:2,owner:e,repo:l,numSnippets:10},"hidden_characters")).textResultForLlm}catch(a){return r.error(`Error during Blackbird search: ${a}`),""}}var UOt=t=>to(t,"copilot_swe_agent_search")||Pgt(t,"SearchAgentExperiment")==="enabled",OOt="search";function K6e(t){return t!==null&&typeof t=="object"&&"question"in t&&"reason"in t&&"searchCommand"in t}var aRn=(t,e,l)=>`
|
|
1907
1907
|
You are a question answering agent that is a component of GitHub Copilot coding agent. Your task is to take the given question
|
|
1908
1908
|
and answer it using the given facts.
|
|
1909
1909
|
|
|
@@ -2447,7 +2447,7 @@ ${e}`:""),isTruncated:!1}}function Ail(t){let e=Math.floor((Date.now()-t.getTime
|
|
|
2447
2447
|
`,l+="</function_results>",l}formatMessage(e,l){return!l||!l.trim()?"":`
|
|
2448
2448
|
${this.escapeXml(this.secretFilter.filterSecrets(l.trim()))}
|
|
2449
2449
|
`}escapeXml(e){return e}};function dCe(t){switch(t.kind){case"log":case"session_logging_disabled":case"telemetry":case"title_and_body_content":return!1;case"message":case"response":case"model_call_failure":case"model_call_success":case"tool_execution":case"turn_started":case"turn_ended":case"turn_failed":case"turn_retry":case"history_truncated":case"image_processing":case"images_removed":return!0}}var uCe=class{toolCalls={};trajectoryOutputFile;trajectoryStream;trajectoryFormatter=new cCe;logger;constructor(e,l){this.logger=e,this.trajectoryOutputFile=l,this.initTrajectoryOutputFileIfNeeded()}async progress(e){if(dCe(e)){if(this.trajectoryStream){if(GL(e)){e.message.content&&this.handleAssistantMessageWithContent(e.message.content),e.message.reasoning_text&&this.handleAssistantMessageWithContent(e.message.reasoning_text),T8(e)&&this.handleAssistantToolCalls(e.message.tool_calls);return}else if(_1e(e)){this.handleToolCallId(e.message.tool_call_id,e.message.content);return}}}else return}partialResult(e){return Promise.resolve()}commentReply(e){return Promise.resolve()}async result(e){if(typeof e=="object"&&(e.blockedRequests=e.blockedRequests??await this.getBlockedRequests()),this.trajectoryStream)return await new Promise(l=>{this.trajectoryStream?.end(()=>{this.trajectoryStream=void 0,l()})})}async error(e){if(this.trajectoryStream)return await new Promise(l=>{this.trajectoryStream?.end(()=>{this.trajectoryStream=void 0,l()})})}handleAssistantMessageWithContent(e){this.trajectoryStream&&this.writeTrajectoryAssistantMessage(e)}handleAssistantToolCalls(e){for(let l of e){let n=l.id;this.toolCalls[n]=l,this.trajectoryStream&&this.writeTrajectoryToolCall(l)}}handleToolCallId(e,l){let n=this.toolCalls[e];n&&(delete this.toolCalls[e],kA(n)&&n.function.name&&this.trajectoryStream&&this.writeTrajectoryFunctionResult(l))}initTrajectoryOutputFileIfNeeded(){if(this.trajectoryOutputFile)try{let e=Jil.dirname(this.trajectoryOutputFile);E7.existsSync(e)||E7.mkdirSync(e,{recursive:!0}),this.trajectoryStream=E7.createWriteStream(this.trajectoryOutputFile,{flags:"w"})}catch(e){let l={text:e instanceof Error?e.message:String(e),name:e instanceof Error?e.name:"Error",stack:e instanceof Error?e.stack:void 0};this.logger.error(`ERROR: ${JSON.stringify(l,null,2)}`),this.trajectoryStream=void 0}}writeTrajectoryAssistantMessage(e){let l=typeof e=="string"?e:JSON.stringify(e),n=this.trajectoryFormatter.formatMessage("assistant",l);n&&this.writeToTrajectoryFile(n)}writeTrajectoryToolCall(e){let l=this.trajectoryFormatter.formatToolCall(e);this.writeToTrajectoryFile(l)}writeTrajectoryFunctionResult(e){let l=typeof e=="string"?e:JSON.stringify(e),n=this.trajectoryFormatter.formatToolResult(l);this.writeToTrajectoryFile(n)}writeToTrajectoryFile(e){this.trajectoryStream&&this.trajectoryStream.write(e+`
|
|
2450
|
-
`)}async getBlockedRequests(){try{return await Lil()}catch(e){return this.logger.error(`Error parsing firewall logs: ${e}`),[]}}};function xil(){let t=[],e=[],l=!1;return{next(n){l||(e.length>0?e.shift()({value:n,done:!1}):t.push(n))},done(){l||(l=!0,e.forEach(n=>n({value:void 0,done:!0})))},async*iterator(){for(;;)if(t.length>0)yield t.shift();else{if(l)return;{let n=await new Promise(r=>{e.push(r)});if(n.done)return;yield n.value}}}}}async function*Sil(t,e="all"){let l=t.map(n=>({iterator:n,next:n.next()}));for(;l.length>0;){let{done:n,value:r,index:a,iterator:I}=await Promise.race(l.map((s,o)=>s.next.then(c=>({index:o,...c,iterator:s.iterator}))));if(n){if(e==="any")return;l.splice(a,1)}else l[a].next=I.next(),yield r}}import{homedir as uPn}from"os";var mPn=10,Bil=["grep","egrep","fgrep","rg"],Til=["awk","gawk","mawk","nawk"];function Ctt(t,e){let l=[],n=["HOME","TMPDIR","TEMP","TMP","PWD","USER","USERNAME","USERPROFILE","APPDATA","LOCALAPPDATA"],r=!1,a=e;switch(t){case"bash":{let I=/\$\{?([A-Z_][A-Z0-9_]*)\}?/gi,s=[...e.matchAll(I)];for(let o=s.length-1;o>=0;o--){let c=s[o],d=c[1];if(n.some(m=>m.toLowerCase()===d.toLowerCase())){let m=process.env[d];m&&c.index!==void 0&&(a=a.slice(0,c.index)+m+a.slice(c.index+c[0].length),r=!0)}}break}case"powershell":{let I=/\$\{?env:([A-Z_][A-Z0-9_]*)\}?/gi,s=[...a.matchAll(I),...a.matchAll(/\$\{?HOME\}?/gi)];s.sort((o,c)=>(o.index??0)-(c.index??0));for(let o=s.length-1;o>=0;o--){let c=s[o],d=c[0].toUpperCase(),m=d==="$HOME"||d==="${HOME}",G=m?"HOME":c[1];if(n.some(p=>p.toLowerCase()===G.toLowerCase())){let p=m?uPn():process.env[G];p&&c.index!==void 0&&(a=a.slice(0,c.index)+p+a.slice(c.index+c[0].length),r=!0)}}break}default:wo(t,`Unknown shell type: ${t}`)}return r&&a!==e&&l.push(a),l.push(e),l}function bPn(t){let e=new Set,l=!1,n=new Set,r=[];for(let a=1;a<t.length;a++){let I=t[a],s=I.text;if(s==="--")break;if(s==="-e"||s==="--regexp"){a+1<t.length&&(e.add(a+1),a++);continue}if(!(s.startsWith("-e")&&s.length>2)&&!s.startsWith("--regexp=")){if(s==="-f"||s==="--file"){l=!0,a+1<t.length&&a++;continue}if(s.startsWith("-f")&&s.length>2){let o=s.slice(2);o&&rQ(o)&&r.push({path:o,charIndex:I.charIndex+2}),l=!0;continue}if(s.startsWith("--file=")){let o=s.split("=",2)[1];o&&rQ(o)&&r.push({path:o,charIndex:I.charIndex+7}),l=!0;continue}if(s==="--include-dir"){if(a+1<t.length){let o=t[a+1];rQ(o.text)&&r.push({path:o.text,charIndex:o.charIndex}),a++}continue}if(s.startsWith("--include-dir=")){let o=s.split("=",2)[1];o&&rQ(o)&&r.push({path:o,charIndex:I.charIndex+14});continue}if(s==="--include"||s==="--exclude"||s==="--exclude-dir"){a+1<t.length&&a++;continue}s.startsWith("--include=")||s.startsWith("--exclude=")||s.startsWith("--exclude-dir=")}}if(l)for(let a of e)n.add(a);else{let a=!1;for(let I=1;I<t.length;I++)if(!t[I].text.startsWith("-")){e.add(I),a=!0;break}if(a)for(let I of e)n.add(I)}return{skipIndexes:n,paths:r}}function GPn(t){let e=new Set,l=[],n=!1;for(let r=1;r<t.length;r++){let a=t[r],I=a.text;if(I==="--")break;if(I==="-f"||I==="--file"){n=!0,r+1<t.length&&r++;continue}if(I.startsWith("-f")&&I.length>2){let s=I.slice(2);s&&rQ(s)&&l.push({path:s,charIndex:a.charIndex+2}),n=!0;continue}if(I.startsWith("--file=")){let s=I.split("=",2)[1];s&&rQ(s)&&l.push({path:s,charIndex:a.charIndex+7}),n=!0;continue}if(I==="-v"||I==="-F"||I.startsWith("-v")||I.startsWith("-F")){(I==="-v"||I==="-F")&&r+1<t.length&&r++;continue}I.startsWith("--")}if(!n){for(let r=1;r<t.length;r++)if(!t[r].text.startsWith("-")){e.add(r);break}}return{skipIndexes:e,paths:l}}function pPn(t){let e=new Set,l=[];if(t[0].text==="gh"&&t[1].text==="api"){e.add(1);let n=t[2];n&&!n.text.startsWith("-")&&e.add(2)}return{skipIndexes:e,paths:l}}function hPn(t){let e=new Set,l=[],n=!1;for(let r=1;r<t.length;r++){let a=t[r],I=a.text;if(I==="--")break;if(I==="-e"||I==="--expression"){r+1<t.length&&(e.add(r+1),r++);continue}if(!(I.startsWith("-e")&&I.length>2)&&!I.startsWith("--expression=")){if(I==="-f"||I==="--file"){n=!0,r+1<t.length&&r++;continue}if(I.startsWith("-f")&&I.length>2){let s=I.slice(2);s&&rQ(s)&&l.push({path:s,charIndex:a.charIndex+2}),n=!0;continue}if(I.startsWith("--file=")){let s=I.split("=",2)[1];s&&rQ(s)&&l.push({path:s,charIndex:a.charIndex+7}),n=!0;continue}I==="-i"||I.startsWith("-i")||I.startsWith("--")}}if(!n){for(let r=1;r<t.length;r++)if(!t[r].text.startsWith("-")){e.add(r);break}}return{skipIndexes:e,paths:l}}function APn(t){let e=new Set,l=[],n=new Set(["-name","-iname","-path","-ipath","-regex","-iregex","-lname","-ilname","-user","-group","-type","-size","-perm","-mtime","-mmin","-maxdepth","-mindepth"]);for(let r=1;r<t.length;r++){let I=t[r].text;if(I){if(I==="--"){r++;continue}if(n.has(I)){r+1<t.length&&(e.add(r+1),r++);continue}for(let s of n)if(I.startsWith(s+"="))break}}return{skipIndexes:e,paths:l}}function vtt(t,e){let l=[],n=gPn(e);if(n.length===0)return[];let r=n[0].text,a=new Set,I=n.findIndex(d=>/^([;&|<]|\d*>)/.test(d.text)),s=I===-1?n:n.slice(0,I);if(Bil.includes(r)){let{skipIndexes:d,paths:m}=bPn(s);a=new Set([...a,...d]),l.push(...m)}if(Til.includes(r)){let{skipIndexes:d,paths:m}=GPn(s);a=new Set([...a,...d]),l.push(...m)}if(r==="sed"){let{skipIndexes:d,paths:m}=hPn(s);a=new Set([...a,...d]),l.push(...m)}if(r==="gh"){let{skipIndexes:d,paths:m}=pPn(s);a=new Set([...a,...d]),l.push(...m)}if(r==="find"&&process.platform!=="win32"){let{skipIndexes:d,paths:m}=APn(s);a=new Set([...a,...d]),l.push(...m)}if(r==="echo")for(let d=1;d<s.length;d++){let m=s[d];m&&(m.text.startsWith("-")||a.add(d))}for(let d=0;d<n.length;d++){let m=n[d];if(!a.has(d)&&!m.text.startsWith("-")){if(rQ(m.text)){let G=Ctt(t,m.text);l.push(...G.map(p=>({path:p,charIndex:m.charIndex})))}if(m.text.includes(">")||m.text.includes("<")){let G=m.text.match(/[0-9]*[><]+(.+)/);if(G&&G[1]){let p=Ctt(t,G[1]);l.push(...p.map(A=>({path:A,charIndex:m.charIndex+m.text.indexOf(G[1])})))}}if((m.text===">"||m.text===">>"||m.text==="<")&&d+1<n.length){let G=n[d+1];if(rQ(G.text)){let p=Ctt(t,G.text);l.push(...p.map(A=>({path:A,charIndex:G.charIndex})))}}}}let o=new Set,c=[];for(let d of l){let m=`${d.path}|${d.charIndex}`;o.has(m)||(o.add(m),c.push(d))}return c}function gPn(t){let e=[],l=/(\s+|;|&+|\|+|>+|<+)/y,n=null,r=!1,a="";for(let I=0;I<t.length;I++){let s=t[I];if(n&&r)s===a?(r=!1,a="",n&&(e.push(n),n=null)):n.text+=s;else if(s==='"'||s==="'")r=!0,a=s;else{l.lastIndex=I;let o=l.exec(t);if(o){n&&(e.push(n),n=null);let c=o[0];c.trim().length>0&&(e.push({text:c,charIndex:I}),I+=c.length-1)}else n?n.text+=s:n={text:s,charIndex:I}}}return n&&e.push(n),e}function rQ(t){if(t=t.replace(/^['"]|['"]$/g,""),!t)return!1;if(/\$\{?[A-Z_][A-Z0-9_]*\}?/i.test(t)||process.platform==="win32"&&/%[A-Z_][A-Z0-9_]*%/i.test(t)||t.startsWith("/"))return!0;let e=process.platform==="win32";return e&&(t.startsWith("\\")||/^[a-zA-Z]:/.test(t))||t.startsWith("./")||t.startsWith("../")||t==="."||t===".."||/^(\.\.\/)+/.test(t)||e&&(t.startsWith(".\\")||t.startsWith("..\\"))||t.startsWith("~/")||t==="~"||t.includes("/")||new RegExp(`\\.[a-zA-Z0-9]{1,${mPn}}$`).test(t)?!0:t.length>2&&/^[a-zA-Z0-9_.-\s]+$/.test(t)?!["true","false","null","undefined","www","com","org","echo",...Til,...Bil,"sed","find","sort","head","tail","touch","cat","and","or","not","if","then","else","fi","do","done","while","for","case","esac","function","return"].includes(t.toLowerCase()):!1}import scl from"node:path";var ZPn=Object.defineProperty,yt=(t,e)=>ZPn(t,"name",{value:e,configurable:!0}),Oil=2,ur=4,ftt=4*ur,hN=5*ur,aQ=2*ur,Ebe=2*ur+2*aQ,tJ={row:0,column:0},lJ=Symbol("INTERNAL");function R7(t){if(t!==lJ)throw new Error("Illegal constructor")}yt(R7,"assertInternal");function ybe(t){return!!t&&typeof t.row=="number"&&typeof t.column=="number"}yt(ybe,"isPoint");function Mil(t){Ve=t}yt(Mil,"setModule");var Ve,NPn=class{static{yt(this,"LookaheadIterator")}0=0;language;constructor(t,e,l){R7(t),this[0]=e,this.language=l}get currentTypeId(){return Ve._ts_lookahead_iterator_current_symbol(this[0])}get currentType(){return this.language.types[this.currentTypeId]||"ERROR"}delete(){Ve._ts_lookahead_iterator_delete(this[0]),this[0]=0}reset(t,e){return Ve._ts_lookahead_iterator_reset(this[0],t[0],e)?(this.language=t,!0):!1}resetState(t){return!!Ve._ts_lookahead_iterator_reset_state(this[0],t)}[Symbol.iterator](){return{next:yt(()=>Ve._ts_lookahead_iterator_next(this[0])?{done:!1,value:this.currentType}:{done:!0,value:""},"next")}}};function Jtt(t,e,l,n){let r=l-e,a=t.textCallback(e,n);if(a){for(e+=a.length;e<l;){let I=t.textCallback(e,n);if(I&&I.length>0)e+=I.length,a+=I;else break}e>l&&(a=a.slice(0,r))}return a??""}yt(Jtt,"getText");var WPn=class ktt{static{yt(this,"Tree")}0=0;textCallback;language;constructor(e,l,n,r){R7(e),this[0]=l,this.language=n,this.textCallback=r}copy(){let e=Ve._ts_tree_copy(this[0]);return new ktt(lJ,e,this.language,this.textCallback)}delete(){Ve._ts_tree_delete(this[0]),this[0]=0}get rootNode(){return Ve._ts_tree_root_node_wasm(this[0]),Ad(this)}rootNodeWithOffset(e,l){let n=nr+hN;return Ve.setValue(n,e,"i32"),x0(n+ur,l),Ve._ts_tree_root_node_with_offset_wasm(this[0]),Ad(this)}edit(e){zil(e),Ve._ts_tree_edit_wasm(this[0])}walk(){return this.rootNode.walk()}getChangedRanges(e){if(!(e instanceof ktt))throw new TypeError("Argument must be a Tree");Ve._ts_tree_get_changed_ranges_wasm(this[0],e[0]);let l=Ve.getValue(nr,"i32"),n=Ve.getValue(nr+ur,"i32"),r=new Array(l);if(l>0){let a=n;for(let I=0;I<l;I++)r[I]=bCe(a),a+=Ebe;Ve._free(n)}return r}getIncludedRanges(){Ve._ts_tree_included_ranges_wasm(this[0]);let e=Ve.getValue(nr,"i32"),l=Ve.getValue(nr+ur,"i32"),n=new Array(e);if(e>0){let r=l;for(let a=0;a<e;a++)n[a]=bCe(r),r+=Ebe;Ve._free(l)}return n}},yPn=class _il{static{yt(this,"TreeCursor")}0=0;1=0;2=0;3=0;tree;constructor(e,l){R7(e),this.tree=l,iy(this)}copy(){let e=new _il(lJ,this.tree);return Ve._ts_tree_cursor_copy_wasm(this.tree[0]),iy(e),e}delete(){zi(this),Ve._ts_tree_cursor_delete_wasm(this.tree[0]),this[0]=this[1]=this[2]=0}get currentNode(){return zi(this),Ve._ts_tree_cursor_current_node_wasm(this.tree[0]),Ad(this.tree)}get currentFieldId(){return zi(this),Ve._ts_tree_cursor_current_field_id_wasm(this.tree[0])}get currentFieldName(){return this.tree.language.fields[this.currentFieldId]}get currentDepth(){return zi(this),Ve._ts_tree_cursor_current_depth_wasm(this.tree[0])}get currentDescendantIndex(){return zi(this),Ve._ts_tree_cursor_current_descendant_index_wasm(this.tree[0])}get nodeType(){return this.tree.language.types[this.nodeTypeId]||"ERROR"}get nodeTypeId(){return zi(this),Ve._ts_tree_cursor_current_node_type_id_wasm(this.tree[0])}get nodeStateId(){return zi(this),Ve._ts_tree_cursor_current_node_state_id_wasm(this.tree[0])}get nodeId(){return zi(this),Ve._ts_tree_cursor_current_node_id_wasm(this.tree[0])}get nodeIsNamed(){return zi(this),Ve._ts_tree_cursor_current_node_is_named_wasm(this.tree[0])===1}get nodeIsMissing(){return zi(this),Ve._ts_tree_cursor_current_node_is_missing_wasm(this.tree[0])===1}get nodeText(){zi(this);let e=Ve._ts_tree_cursor_start_index_wasm(this.tree[0]),l=Ve._ts_tree_cursor_end_index_wasm(this.tree[0]);Ve._ts_tree_cursor_start_position_wasm(this.tree[0]);let n=SO(nr);return Jtt(this.tree,e,l,n)}get startPosition(){return zi(this),Ve._ts_tree_cursor_start_position_wasm(this.tree[0]),SO(nr)}get endPosition(){return zi(this),Ve._ts_tree_cursor_end_position_wasm(this.tree[0]),SO(nr)}get startIndex(){return zi(this),Ve._ts_tree_cursor_start_index_wasm(this.tree[0])}get endIndex(){return zi(this),Ve._ts_tree_cursor_end_index_wasm(this.tree[0])}gotoFirstChild(){zi(this);let e=Ve._ts_tree_cursor_goto_first_child_wasm(this.tree[0]);return iy(this),e===1}gotoLastChild(){zi(this);let e=Ve._ts_tree_cursor_goto_last_child_wasm(this.tree[0]);return iy(this),e===1}gotoParent(){zi(this);let e=Ve._ts_tree_cursor_goto_parent_wasm(this.tree[0]);return iy(this),e===1}gotoNextSibling(){zi(this);let e=Ve._ts_tree_cursor_goto_next_sibling_wasm(this.tree[0]);return iy(this),e===1}gotoPreviousSibling(){zi(this);let e=Ve._ts_tree_cursor_goto_previous_sibling_wasm(this.tree[0]);return iy(this),e===1}gotoDescendant(e){zi(this),Ve._ts_tree_cursor_goto_descendant_wasm(this.tree[0],e),iy(this)}gotoFirstChildForIndex(e){zi(this),Ve.setValue(nr+ftt,e,"i32");let l=Ve._ts_tree_cursor_goto_first_child_for_index_wasm(this.tree[0]);return iy(this),l===1}gotoFirstChildForPosition(e){zi(this),x0(nr+ftt,e);let l=Ve._ts_tree_cursor_goto_first_child_for_position_wasm(this.tree[0]);return iy(this),l===1}reset(e){za(e),zi(this,nr+hN),Ve._ts_tree_cursor_reset_wasm(this.tree[0]),iy(this)}resetTo(e){zi(this,nr),zi(e,nr+ftt),Ve._ts_tree_cursor_reset_to_wasm(this.tree[0],e.tree[0]),iy(this)}},EPn=class{static{yt(this,"Node")}0=0;_children;_namedChildren;constructor(t,{id:e,tree:l,startIndex:n,startPosition:r,other:a}){R7(t),this[0]=a,this.id=e,this.tree=l,this.startIndex=n,this.startPosition=r}id;startIndex;startPosition;tree;get typeId(){return za(this),Ve._ts_node_symbol_wasm(this.tree[0])}get grammarId(){return za(this),Ve._ts_node_grammar_symbol_wasm(this.tree[0])}get type(){return this.tree.language.types[this.typeId]||"ERROR"}get grammarType(){return this.tree.language.types[this.grammarId]||"ERROR"}get isNamed(){return za(this),Ve._ts_node_is_named_wasm(this.tree[0])===1}get isExtra(){return za(this),Ve._ts_node_is_extra_wasm(this.tree[0])===1}get isError(){return za(this),Ve._ts_node_is_error_wasm(this.tree[0])===1}get isMissing(){return za(this),Ve._ts_node_is_missing_wasm(this.tree[0])===1}get hasChanges(){return za(this),Ve._ts_node_has_changes_wasm(this.tree[0])===1}get hasError(){return za(this),Ve._ts_node_has_error_wasm(this.tree[0])===1}get endIndex(){return za(this),Ve._ts_node_end_index_wasm(this.tree[0])}get endPosition(){return za(this),Ve._ts_node_end_point_wasm(this.tree[0]),SO(nr)}get text(){return Jtt(this.tree,this.startIndex,this.endIndex,this.startPosition)}get parseState(){return za(this),Ve._ts_node_parse_state_wasm(this.tree[0])}get nextParseState(){return za(this),Ve._ts_node_next_parse_state_wasm(this.tree[0])}equals(t){return this.tree===t.tree&&this.id===t.id}child(t){return za(this),Ve._ts_node_child_wasm(this.tree[0],t),Ad(this.tree)}namedChild(t){return za(this),Ve._ts_node_named_child_wasm(this.tree[0],t),Ad(this.tree)}childForFieldId(t){return za(this),Ve._ts_node_child_by_field_id_wasm(this.tree[0],t),Ad(this.tree)}childForFieldName(t){let e=this.tree.language.fields.indexOf(t);return e!==-1?this.childForFieldId(e):null}fieldNameForChild(t){za(this);let e=Ve._ts_node_field_name_for_child_wasm(this.tree[0],t);return e?Ve.AsciiToString(e):null}fieldNameForNamedChild(t){za(this);let e=Ve._ts_node_field_name_for_named_child_wasm(this.tree[0],t);return e?Ve.AsciiToString(e):null}childrenForFieldName(t){let e=this.tree.language.fields.indexOf(t);return e!==-1&&e!==0?this.childrenForFieldId(e):[]}childrenForFieldId(t){za(this),Ve._ts_node_children_by_field_id_wasm(this.tree[0],t);let e=Ve.getValue(nr,"i32"),l=Ve.getValue(nr+ur,"i32"),n=new Array(e);if(e>0){let r=l;for(let a=0;a<e;a++)n[a]=Ad(this.tree,r),r+=hN;Ve._free(l)}return n}firstChildForIndex(t){za(this);let e=nr+hN;return Ve.setValue(e,t,"i32"),Ve._ts_node_first_child_for_byte_wasm(this.tree[0]),Ad(this.tree)}firstNamedChildForIndex(t){za(this);let e=nr+hN;return Ve.setValue(e,t,"i32"),Ve._ts_node_first_named_child_for_byte_wasm(this.tree[0]),Ad(this.tree)}get childCount(){return za(this),Ve._ts_node_child_count_wasm(this.tree[0])}get namedChildCount(){return za(this),Ve._ts_node_named_child_count_wasm(this.tree[0])}get firstChild(){return this.child(0)}get firstNamedChild(){return this.namedChild(0)}get lastChild(){return this.child(this.childCount-1)}get lastNamedChild(){return this.namedChild(this.namedChildCount-1)}get children(){if(!this._children){za(this),Ve._ts_node_children_wasm(this.tree[0]);let t=Ve.getValue(nr,"i32"),e=Ve.getValue(nr+ur,"i32");if(this._children=new Array(t),t>0){let l=e;for(let n=0;n<t;n++)this._children[n]=Ad(this.tree,l),l+=hN;Ve._free(e)}}return this._children}get namedChildren(){if(!this._namedChildren){za(this),Ve._ts_node_named_children_wasm(this.tree[0]);let t=Ve.getValue(nr,"i32"),e=Ve.getValue(nr+ur,"i32");if(this._namedChildren=new Array(t),t>0){let l=e;for(let n=0;n<t;n++)this._namedChildren[n]=Ad(this.tree,l),l+=hN;Ve._free(e)}}return this._namedChildren}descendantsOfType(t,e=tJ,l=tJ){Array.isArray(t)||(t=[t]);let n=[],r=this.tree.language.types;for(let c of t)c=="ERROR"&&n.push(65535);for(let c=0,d=r.length;c<d;c++)t.includes(r[c])&&n.push(c);let a=Ve._malloc(ur*n.length);for(let c=0,d=n.length;c<d;c++)Ve.setValue(a+c*ur,n[c],"i32");za(this),Ve._ts_node_descendants_of_type_wasm(this.tree[0],a,n.length,e.row,e.column,l.row,l.column);let I=Ve.getValue(nr,"i32"),s=Ve.getValue(nr+ur,"i32"),o=new Array(I);if(I>0){let c=s;for(let d=0;d<I;d++)o[d]=Ad(this.tree,c),c+=hN}return Ve._free(s),Ve._free(a),o}get nextSibling(){return za(this),Ve._ts_node_next_sibling_wasm(this.tree[0]),Ad(this.tree)}get previousSibling(){return za(this),Ve._ts_node_prev_sibling_wasm(this.tree[0]),Ad(this.tree)}get nextNamedSibling(){return za(this),Ve._ts_node_next_named_sibling_wasm(this.tree[0]),Ad(this.tree)}get previousNamedSibling(){return za(this),Ve._ts_node_prev_named_sibling_wasm(this.tree[0]),Ad(this.tree)}get descendantCount(){return za(this),Ve._ts_node_descendant_count_wasm(this.tree[0])}get parent(){return za(this),Ve._ts_node_parent_wasm(this.tree[0]),Ad(this.tree)}childWithDescendant(t){return za(this),za(t,1),Ve._ts_node_child_with_descendant_wasm(this.tree[0]),Ad(this.tree)}descendantForIndex(t,e=t){if(typeof t!="number"||typeof e!="number")throw new Error("Arguments must be numbers");za(this);let l=nr+hN;return Ve.setValue(l,t,"i32"),Ve.setValue(l+ur,e,"i32"),Ve._ts_node_descendant_for_index_wasm(this.tree[0]),Ad(this.tree)}namedDescendantForIndex(t,e=t){if(typeof t!="number"||typeof e!="number")throw new Error("Arguments must be numbers");za(this);let l=nr+hN;return Ve.setValue(l,t,"i32"),Ve.setValue(l+ur,e,"i32"),Ve._ts_node_named_descendant_for_index_wasm(this.tree[0]),Ad(this.tree)}descendantForPosition(t,e=t){if(!ybe(t)||!ybe(e))throw new Error("Arguments must be {row, column} objects");za(this);let l=nr+hN;return x0(l,t),x0(l+aQ,e),Ve._ts_node_descendant_for_position_wasm(this.tree[0]),Ad(this.tree)}namedDescendantForPosition(t,e=t){if(!ybe(t)||!ybe(e))throw new Error("Arguments must be {row, column} objects");za(this);let l=nr+hN;return x0(l,t),x0(l+aQ,e),Ve._ts_node_named_descendant_for_position_wasm(this.tree[0]),Ad(this.tree)}walk(){return za(this),Ve._ts_tree_cursor_new_wasm(this.tree[0]),new yPn(lJ,this.tree)}edit(t){if(this.startIndex>=t.oldEndIndex){this.startIndex=t.newEndIndex+(this.startIndex-t.oldEndIndex);let e,l;this.startPosition.row>t.oldEndPosition.row?(e=this.startPosition.row-t.oldEndPosition.row,l=this.startPosition.column):(e=0,l=this.startPosition.column,this.startPosition.column>=t.oldEndPosition.column&&(l=this.startPosition.column-t.oldEndPosition.column)),e>0?(this.startPosition.row+=e,this.startPosition.column=l):this.startPosition.column+=l}else this.startIndex>t.startIndex&&(this.startIndex=t.newEndIndex,this.startPosition.row=t.newEndPosition.row,this.startPosition.column=t.newEndPosition.column)}toString(){za(this);let t=Ve._ts_node_to_string_wasm(this.tree[0]),e=Ve.AsciiToString(t);return Ve._free(t),e}};function Ltt(t,e,l,n,r){for(let a=0,I=r.length;a<I;a++){let s=Ve.getValue(l,"i32");l+=ur;let o=Ad(e,l);l+=hN,r[a]={patternIndex:n,name:t.captureNames[s],node:o}}return l}yt(Ltt,"unmarshalCaptures");function za(t,e=0){let l=nr+e*hN;Ve.setValue(l,t.id,"i32"),l+=ur,Ve.setValue(l,t.startIndex,"i32"),l+=ur,Ve.setValue(l,t.startPosition.row,"i32"),l+=ur,Ve.setValue(l,t.startPosition.column,"i32"),l+=ur,Ve.setValue(l,t[0],"i32")}yt(za,"marshalNode");function Ad(t,e=nr){let l=Ve.getValue(e,"i32");if(e+=ur,l===0)return null;let n=Ve.getValue(e,"i32");e+=ur;let r=Ve.getValue(e,"i32");e+=ur;let a=Ve.getValue(e,"i32");e+=ur;let I=Ve.getValue(e,"i32");return new EPn(lJ,{id:l,tree:t,startIndex:n,startPosition:{row:r,column:a},other:I})}yt(Ad,"unmarshalNode");function zi(t,e=nr){Ve.setValue(e+0*ur,t[0],"i32"),Ve.setValue(e+1*ur,t[1],"i32"),Ve.setValue(e+2*ur,t[2],"i32"),Ve.setValue(e+3*ur,t[3],"i32")}yt(zi,"marshalTreeCursor");function iy(t){t[0]=Ve.getValue(nr+0*ur,"i32"),t[1]=Ve.getValue(nr+1*ur,"i32"),t[2]=Ve.getValue(nr+2*ur,"i32"),t[3]=Ve.getValue(nr+3*ur,"i32")}yt(iy,"unmarshalTreeCursor");function x0(t,e){Ve.setValue(t,e.row,"i32"),Ve.setValue(t+ur,e.column,"i32")}yt(x0,"marshalPoint");function SO(t){return{row:Ve.getValue(t,"i32")>>>0,column:Ve.getValue(t+ur,"i32")>>>0}}yt(SO,"unmarshalPoint");function Dil(t,e){x0(t,e.startPosition),t+=aQ,x0(t,e.endPosition),t+=aQ,Ve.setValue(t,e.startIndex,"i32"),t+=ur,Ve.setValue(t,e.endIndex,"i32"),t+=ur}yt(Dil,"marshalRange");function bCe(t){let e={};return e.startPosition=SO(t),t+=aQ,e.endPosition=SO(t),t+=aQ,e.startIndex=Ve.getValue(t,"i32")>>>0,t+=ur,e.endIndex=Ve.getValue(t,"i32")>>>0,e}yt(bCe,"unmarshalRange");function zil(t,e=nr){x0(e,t.startPosition),e+=aQ,x0(e,t.oldEndPosition),e+=aQ,x0(e,t.newEndPosition),e+=aQ,Ve.setValue(e,t.startIndex,"i32"),e+=ur,Ve.setValue(e,t.oldEndIndex,"i32"),e+=ur,Ve.setValue(e,t.newEndIndex,"i32"),e+=ur}yt(zil,"marshalEdit");function Pil(t){let e=Ve.getValue(t,"i32"),l=Ve.getValue(t+=ur,"i32"),n=Ve.getValue(t+=ur,"i32");return{major_version:e,minor_version:l,patch_version:n}}yt(Pil,"unmarshalLanguageMetadata");var RPn=1,YPn=2,VPn=/[\w-]+/g,rbI={Zero:0,ZeroOrOne:1,ZeroOrMore:2,One:3,OneOrMore:4},Uil=yt(t=>t.type==="capture","isCaptureStep"),xtt=yt(t=>t.type==="string","isStringStep"),ZY={Syntax:1,NodeName:2,FieldName:3,CaptureName:4,PatternStructure:5},Wbe=class jil extends Error{constructor(e,l,n,r){super(jil.formatMessage(e,l)),this.kind=e,this.info=l,this.index=n,this.length=r,this.name="QueryError"}static{yt(this,"QueryError")}static formatMessage(e,l){switch(e){case ZY.NodeName:return`Bad node name '${l.word}'`;case ZY.FieldName:return`Bad field name '${l.word}'`;case ZY.CaptureName:return`Bad capture name @${l.word}`;case ZY.PatternStructure:return`Bad pattern structure at offset ${l.suffix}`;case ZY.Syntax:return`Bad syntax at offset ${l.suffix}`}}};function Kil(t,e,l,n){if(t.length!==3)throw new Error(`Wrong number of arguments to \`#${l}\` predicate. Expected 2, got ${t.length-1}`);if(!Uil(t[1]))throw new Error(`First argument of \`#${l}\` predicate must be a capture. Got "${t[1].value}"`);let r=l==="eq?"||l==="any-eq?",a=!l.startsWith("any-");if(Uil(t[2])){let I=t[1].name,s=t[2].name;n[e].push(o=>{let c=[],d=[];for(let G of o)G.name===I&&c.push(G.node),G.name===s&&d.push(G.node);let m=yt((G,p,A)=>A?G.text===p.text:G.text!==p.text,"compare");return a?c.every(G=>d.some(p=>m(G,p,r))):c.some(G=>d.some(p=>m(G,p,r)))})}else{let I=t[1].name,s=t[2].value,o=yt(d=>d.text===s,"matches"),c=yt(d=>d.text!==s,"doesNotMatch");n[e].push(d=>{let m=[];for(let p of d)p.name===I&&m.push(p.node);let G=r?o:c;return a?m.every(G):m.some(G)})}}yt(Kil,"parseAnyPredicate");function qil(t,e,l,n){if(t.length!==3)throw new Error(`Wrong number of arguments to \`#${l}\` predicate. Expected 2, got ${t.length-1}.`);if(t[1].type!=="capture")throw new Error(`First argument of \`#${l}\` predicate must be a capture. Got "${t[1].value}".`);if(t[2].type!=="string")throw new Error(`Second argument of \`#${l}\` predicate must be a string. Got @${t[2].name}.`);let r=l==="match?"||l==="any-match?",a=!l.startsWith("any-"),I=t[1].name,s=new RegExp(t[2].value);n[e].push(o=>{let c=[];for(let m of o)m.name===I&&c.push(m.node.text);let d=yt((m,G)=>G?s.test(m):!s.test(m),"test");return c.length===0?!r:a?c.every(m=>d(m,r)):c.some(m=>d(m,r))})}yt(qil,"parseMatchPredicate");function $il(t,e,l,n){if(t.length<2)throw new Error(`Wrong number of arguments to \`#${l}\` predicate. Expected at least 1. Got ${t.length-1}.`);if(t[1].type!=="capture")throw new Error(`First argument of \`#${l}\` predicate must be a capture. Got "${t[1].value}".`);let r=l==="any-of?",a=t[1].name,I=t.slice(2);if(!I.every(xtt))throw new Error(`Arguments to \`#${l}\` predicate must be strings.".`);let s=I.map(o=>o.value);n[e].push(o=>{let c=[];for(let d of o)d.name===a&&c.push(d.node.text);return c.length===0?!r:c.every(d=>s.includes(d))===r})}yt($il,"parseAnyOfPredicate");function ecl(t,e,l,n,r){if(t.length<2||t.length>3)throw new Error(`Wrong number of arguments to \`#${l}\` predicate. Expected 1 or 2. Got ${t.length-1}.`);if(!t.every(xtt))throw new Error(`Arguments to \`#${l}\` predicate must be strings.".`);let a=l==="is?"?n:r;a[e]||(a[e]={}),a[e][t[1].value]=t[2]?.value??null}yt(ecl,"parseIsPredicate");function tcl(t,e,l){if(t.length<2||t.length>3)throw new Error(`Wrong number of arguments to \`#set!\` predicate. Expected 1 or 2. Got ${t.length-1}.`);if(!t.every(xtt))throw new Error('Arguments to `#set!` predicate must be strings.".');l[e]||(l[e]={}),l[e][t[1].value]=t[2]?.value??null}yt(tcl,"parseSetDirective");function lcl(t,e,l,n,r,a,I,s,o,c,d){if(e===RPn){let m=n[l];a.push({type:"capture",name:m})}else if(e===YPn)a.push({type:"string",value:r[l]});else if(a.length>0){if(a[0].type!=="string")throw new Error("Predicates must begin with a literal value");let m=a[0].value;switch(m){case"any-not-eq?":case"not-eq?":case"any-eq?":case"eq?":Kil(a,t,m,I);break;case"any-not-match?":case"not-match?":case"any-match?":case"match?":qil(a,t,m,I);break;case"not-any-of?":case"any-of?":$il(a,t,m,I);break;case"is?":case"is-not?":ecl(a,t,m,c,d);break;case"set!":tcl(a,t,o);break;default:s[t].push({operator:m,operands:a.slice(1)})}a.length=0}}yt(lcl,"parsePattern");var wPn=class{static{yt(this,"Query")}0=0;exceededMatchLimit;textPredicates;captureNames;captureQuantifiers;predicates;setProperties;assertedProperties;refutedProperties;matchLimit;constructor(t,e){let l=Ve.lengthBytesUTF8(e),n=Ve._malloc(l+1);Ve.stringToUTF8(e,n,l+1);let r=Ve._ts_query_new(t[0],n,l,nr,nr+ur);if(!r){let W=Ve.getValue(nr+ur,"i32"),R=Ve.getValue(nr,"i32"),V=Ve.UTF8ToString(n,R).length,v=e.slice(V,V+100).split(`
|
|
2450
|
+
`)}async getBlockedRequests(){try{return await Lil()}catch(e){return this.logger.error(`Error parsing firewall logs: ${e}`),[]}}};function xil(){let t=[],e=[],l=!1;return{next(n){l||(e.length>0?e.shift()({value:n,done:!1}):t.push(n))},done(){l||(l=!0,e.forEach(n=>n({value:void 0,done:!0})))},async*iterator(){for(;;)if(t.length>0)yield t.shift();else{if(l)return;{let n=await new Promise(r=>{e.push(r)});if(n.done)return;yield n.value}}}}}async function*Sil(t,e="all"){let l=t.map(n=>({iterator:n,next:n.next()}));for(;l.length>0;){let{done:n,value:r,index:a,iterator:I}=await Promise.race(l.map((s,o)=>s.next.then(c=>({index:o,...c,iterator:s.iterator}))));if(n){if(e==="any")return;l.splice(a,1)}else l[a].next=I.next(),yield r}}import{homedir as uPn}from"os";var mPn=10,Bil=["grep","egrep","fgrep","rg"],Til=["awk","gawk","mawk","nawk"];function Ctt(t,e){let l=[],n=["HOME","TMPDIR","TEMP","TMP","PWD","USER","USERNAME","USERPROFILE","APPDATA","LOCALAPPDATA"],r=!1,a=e;switch(t){case"bash":{let I=/\$\{?([A-Z_][A-Z0-9_]*)\}?/gi,s=[...e.matchAll(I)];for(let o=s.length-1;o>=0;o--){let c=s[o],d=c[1];if(n.some(m=>m.toLowerCase()===d.toLowerCase())){let m=process.env[d];m&&c.index!==void 0&&(a=a.slice(0,c.index)+m+a.slice(c.index+c[0].length),r=!0)}}break}case"powershell":{let I=/\$\{?env:([A-Z_][A-Z0-9_]*)\}?/gi,s=[...a.matchAll(I),...a.matchAll(/\$\{?HOME\}?/gi)];s.sort((o,c)=>(o.index??0)-(c.index??0));for(let o=s.length-1;o>=0;o--){let c=s[o],d=c[0].toUpperCase(),m=d==="$HOME"||d==="${HOME}",G=m?"HOME":c[1];if(n.some(p=>p.toLowerCase()===G.toLowerCase())){let p=m?uPn():process.env[G];p&&c.index!==void 0&&(a=a.slice(0,c.index)+p+a.slice(c.index+c[0].length),r=!0)}}break}default:wo(t,`Unknown shell type: ${t}`)}return r&&a!==e&&l.push(a),l.push(e),l}function bPn(t){let e=new Set,l=!1,n=new Set,r=[];for(let a=1;a<t.length;a++){let I=t[a],s=I.text;if(s==="--")break;if(s==="-e"||s==="--regexp"){a+1<t.length&&(e.add(a+1),a++);continue}if(!(s.startsWith("-e")&&s.length>2)&&!s.startsWith("--regexp=")){if(s==="-f"||s==="--file"){l=!0,a+1<t.length&&a++;continue}if(s.startsWith("-f")&&s.length>2){let o=s.slice(2);o&&rQ(o)&&r.push({path:o,charIndex:I.charIndex+2}),l=!0;continue}if(s.startsWith("--file=")){let o=s.split("=",2)[1];o&&rQ(o)&&r.push({path:o,charIndex:I.charIndex+7}),l=!0;continue}if(s==="--include-dir"){if(a+1<t.length){let o=t[a+1];rQ(o.text)&&r.push({path:o.text,charIndex:o.charIndex}),a++}continue}if(s.startsWith("--include-dir=")){let o=s.split("=",2)[1];o&&rQ(o)&&r.push({path:o,charIndex:I.charIndex+14});continue}if(s==="--include"||s==="--exclude"||s==="--exclude-dir"){a+1<t.length&&a++;continue}s.startsWith("--include=")||s.startsWith("--exclude=")||s.startsWith("--exclude-dir=")}}if(l)for(let a of e)n.add(a);else{let a=!1;for(let I=1;I<t.length;I++)if(!t[I].text.startsWith("-")){e.add(I),a=!0;break}if(a)for(let I of e)n.add(I)}return{skipIndexes:n,paths:r}}function GPn(t){let e=new Set,l=[],n=!1;for(let r=1;r<t.length;r++){let a=t[r],I=a.text;if(I==="--")break;if(I==="-f"||I==="--file"){n=!0,r+1<t.length&&r++;continue}if(I.startsWith("-f")&&I.length>2){let s=I.slice(2);s&&rQ(s)&&l.push({path:s,charIndex:a.charIndex+2}),n=!0;continue}if(I.startsWith("--file=")){let s=I.split("=",2)[1];s&&rQ(s)&&l.push({path:s,charIndex:a.charIndex+7}),n=!0;continue}if(I==="-v"||I==="-F"||I.startsWith("-v")||I.startsWith("-F")){(I==="-v"||I==="-F")&&r+1<t.length&&r++;continue}I.startsWith("--")}if(!n){for(let r=1;r<t.length;r++)if(!t[r].text.startsWith("-")){e.add(r);break}}return{skipIndexes:e,paths:l}}function pPn(t){let e=new Set,l=[];if(t[0].text==="gh"&&t[1].text==="api"){e.add(1);let n=t[2];n&&!n.text.startsWith("-")&&e.add(2)}return{skipIndexes:e,paths:l}}function hPn(t){let e=new Set,l=[],n=!1;for(let r=1;r<t.length;r++){let a=t[r],I=a.text;if(I==="--")break;if(I==="-e"||I==="--expression"){r+1<t.length&&(e.add(r+1),r++);continue}if(!(I.startsWith("-e")&&I.length>2)&&!I.startsWith("--expression=")){if(I==="-f"||I==="--file"){n=!0,r+1<t.length&&r++;continue}if(I.startsWith("-f")&&I.length>2){let s=I.slice(2);s&&rQ(s)&&l.push({path:s,charIndex:a.charIndex+2}),n=!0;continue}if(I.startsWith("--file=")){let s=I.split("=",2)[1];s&&rQ(s)&&l.push({path:s,charIndex:a.charIndex+7}),n=!0;continue}I==="-i"||I.startsWith("-i")||I.startsWith("--")}}if(!n){for(let r=1;r<t.length;r++)if(!t[r].text.startsWith("-")){e.add(r);break}}return{skipIndexes:e,paths:l}}function APn(t){let e=new Set,l=[],n=new Set(["-name","-iname","-path","-ipath","-regex","-iregex","-lname","-ilname","-user","-group","-type","-size","-perm","-mtime","-mmin","-maxdepth","-mindepth"]);for(let r=1;r<t.length;r++){let I=t[r].text;if(I){if(I==="--"){r++;continue}if(n.has(I)){r+1<t.length&&(e.add(r+1),r++);continue}for(let s of n)if(I.startsWith(s+"="))break}}return{skipIndexes:e,paths:l}}function vtt(t,e){let l=[],n=gPn(e);if(n.length===0)return[];let r=n[0].text,a=new Set,I=n.findIndex(d=>/^([;&|<]|\d*>)/.test(d.text)),s=I===-1?n:n.slice(0,I);if(Bil.includes(r)){let{skipIndexes:d,paths:m}=bPn(s);a=new Set([...a,...d]),l.push(...m)}if(Til.includes(r)){let{skipIndexes:d,paths:m}=GPn(s);a=new Set([...a,...d]),l.push(...m)}if(r==="sed"){let{skipIndexes:d,paths:m}=hPn(s);a=new Set([...a,...d]),l.push(...m)}if(r==="gh"){let{skipIndexes:d,paths:m}=pPn(s);a=new Set([...a,...d]),l.push(...m)}if(r==="find"&&process.platform!=="win32"){let{skipIndexes:d,paths:m}=APn(s);a=new Set([...a,...d]),l.push(...m)}if(r==="echo")for(let d=1;d<s.length;d++){let m=s[d];m&&(m.text.startsWith("-")||a.add(d))}for(let d=0;d<n.length;d++){let m=n[d];if(!a.has(d)&&!m.text.startsWith("-")){if(rQ(m.text)){let G=Ctt(t,m.text);l.push(...G.map(p=>({path:p,charIndex:m.charIndex})))}if(m.text.includes(">")||m.text.includes("<")){let G=m.text.match(/[0-9]*[><]+(.+)/);if(G&&G[1]){let p=Ctt(t,G[1]);l.push(...p.map(A=>({path:A,charIndex:m.charIndex+m.text.indexOf(G[1])})))}}if((m.text===">"||m.text===">>"||m.text==="<")&&d+1<n.length){let G=n[d+1];if(rQ(G.text)){let p=Ctt(t,G.text);l.push(...p.map(A=>({path:A,charIndex:G.charIndex})))}}}}let o=new Set,c=[];for(let d of l){let m=`${d.path}|${d.charIndex}`;o.has(m)||(o.add(m),c.push(d))}return c}function gPn(t){let e=[],l=/(\s+|;|&+|\|+|>+|<+)/y,n=null,r=!1,a="";for(let I=0;I<t.length;I++){let s=t[I];if(n&&r)s===a?(r=!1,a="",n&&(e.push(n),n=null)):n.text+=s;else if(s==='"'||s==="'")r=!0,a=s;else{l.lastIndex=I;let o=l.exec(t);if(o){n&&(e.push(n),n=null);let c=o[0];c.trim().length>0&&(e.push({text:c,charIndex:I}),I+=c.length-1)}else n?n.text+=s:n={text:s,charIndex:I}}}return n&&e.push(n),e}function rQ(t){if(t=t.replace(/^['"]|['"]$/g,""),!t)return!1;if(t.startsWith("/*")||t.endsWith("*/")){let l=t.split("/"),n=!1,r=!1,a=!1;for(let I=0;I<l.length;I++){let s=l[I];if(s!==""){if(s==="*"||s==="**"){r=!0;continue}if(/^[-*]+$/.test(s)){a=!0;continue}/[a-zA-Z0-9._]/.test(s)&&(n=!0)}}return!!(n||r&&!a)}if(/\$\{?[A-Z_][A-Z0-9_]*\}?/i.test(t)||process.platform==="win32"&&/%[A-Z_][A-Z0-9_]*%/i.test(t)||t.startsWith("/"))return!0;let e=process.platform==="win32";return e&&(t.startsWith("\\")||/^[a-zA-Z]:/.test(t))||t.startsWith("./")||t.startsWith("../")||t==="."||t===".."||/^(\.\.\/)+/.test(t)||e&&(t.startsWith(".\\")||t.startsWith("..\\"))||t.startsWith("~/")||t==="~"||t.includes("/")||new RegExp(`\\.[a-zA-Z0-9]{1,${mPn}}$`).test(t)?!0:t.length>2&&/^[a-zA-Z0-9_.-\s]+$/.test(t)?!["true","false","null","undefined","www","com","org","echo",...Til,...Bil,"sed","find","sort","head","tail","touch","cat","and","or","not","if","then","else","fi","do","done","while","for","case","esac","function","return"].includes(t.toLowerCase()):!1}import scl from"node:path";var ZPn=Object.defineProperty,yt=(t,e)=>ZPn(t,"name",{value:e,configurable:!0}),Oil=2,ur=4,ftt=4*ur,hN=5*ur,aQ=2*ur,Ebe=2*ur+2*aQ,tJ={row:0,column:0},lJ=Symbol("INTERNAL");function R7(t){if(t!==lJ)throw new Error("Illegal constructor")}yt(R7,"assertInternal");function ybe(t){return!!t&&typeof t.row=="number"&&typeof t.column=="number"}yt(ybe,"isPoint");function Mil(t){Ve=t}yt(Mil,"setModule");var Ve,NPn=class{static{yt(this,"LookaheadIterator")}0=0;language;constructor(t,e,l){R7(t),this[0]=e,this.language=l}get currentTypeId(){return Ve._ts_lookahead_iterator_current_symbol(this[0])}get currentType(){return this.language.types[this.currentTypeId]||"ERROR"}delete(){Ve._ts_lookahead_iterator_delete(this[0]),this[0]=0}reset(t,e){return Ve._ts_lookahead_iterator_reset(this[0],t[0],e)?(this.language=t,!0):!1}resetState(t){return!!Ve._ts_lookahead_iterator_reset_state(this[0],t)}[Symbol.iterator](){return{next:yt(()=>Ve._ts_lookahead_iterator_next(this[0])?{done:!1,value:this.currentType}:{done:!0,value:""},"next")}}};function Jtt(t,e,l,n){let r=l-e,a=t.textCallback(e,n);if(a){for(e+=a.length;e<l;){let I=t.textCallback(e,n);if(I&&I.length>0)e+=I.length,a+=I;else break}e>l&&(a=a.slice(0,r))}return a??""}yt(Jtt,"getText");var WPn=class ktt{static{yt(this,"Tree")}0=0;textCallback;language;constructor(e,l,n,r){R7(e),this[0]=l,this.language=n,this.textCallback=r}copy(){let e=Ve._ts_tree_copy(this[0]);return new ktt(lJ,e,this.language,this.textCallback)}delete(){Ve._ts_tree_delete(this[0]),this[0]=0}get rootNode(){return Ve._ts_tree_root_node_wasm(this[0]),Ad(this)}rootNodeWithOffset(e,l){let n=nr+hN;return Ve.setValue(n,e,"i32"),x0(n+ur,l),Ve._ts_tree_root_node_with_offset_wasm(this[0]),Ad(this)}edit(e){zil(e),Ve._ts_tree_edit_wasm(this[0])}walk(){return this.rootNode.walk()}getChangedRanges(e){if(!(e instanceof ktt))throw new TypeError("Argument must be a Tree");Ve._ts_tree_get_changed_ranges_wasm(this[0],e[0]);let l=Ve.getValue(nr,"i32"),n=Ve.getValue(nr+ur,"i32"),r=new Array(l);if(l>0){let a=n;for(let I=0;I<l;I++)r[I]=bCe(a),a+=Ebe;Ve._free(n)}return r}getIncludedRanges(){Ve._ts_tree_included_ranges_wasm(this[0]);let e=Ve.getValue(nr,"i32"),l=Ve.getValue(nr+ur,"i32"),n=new Array(e);if(e>0){let r=l;for(let a=0;a<e;a++)n[a]=bCe(r),r+=Ebe;Ve._free(l)}return n}},yPn=class _il{static{yt(this,"TreeCursor")}0=0;1=0;2=0;3=0;tree;constructor(e,l){R7(e),this.tree=l,iy(this)}copy(){let e=new _il(lJ,this.tree);return Ve._ts_tree_cursor_copy_wasm(this.tree[0]),iy(e),e}delete(){zi(this),Ve._ts_tree_cursor_delete_wasm(this.tree[0]),this[0]=this[1]=this[2]=0}get currentNode(){return zi(this),Ve._ts_tree_cursor_current_node_wasm(this.tree[0]),Ad(this.tree)}get currentFieldId(){return zi(this),Ve._ts_tree_cursor_current_field_id_wasm(this.tree[0])}get currentFieldName(){return this.tree.language.fields[this.currentFieldId]}get currentDepth(){return zi(this),Ve._ts_tree_cursor_current_depth_wasm(this.tree[0])}get currentDescendantIndex(){return zi(this),Ve._ts_tree_cursor_current_descendant_index_wasm(this.tree[0])}get nodeType(){return this.tree.language.types[this.nodeTypeId]||"ERROR"}get nodeTypeId(){return zi(this),Ve._ts_tree_cursor_current_node_type_id_wasm(this.tree[0])}get nodeStateId(){return zi(this),Ve._ts_tree_cursor_current_node_state_id_wasm(this.tree[0])}get nodeId(){return zi(this),Ve._ts_tree_cursor_current_node_id_wasm(this.tree[0])}get nodeIsNamed(){return zi(this),Ve._ts_tree_cursor_current_node_is_named_wasm(this.tree[0])===1}get nodeIsMissing(){return zi(this),Ve._ts_tree_cursor_current_node_is_missing_wasm(this.tree[0])===1}get nodeText(){zi(this);let e=Ve._ts_tree_cursor_start_index_wasm(this.tree[0]),l=Ve._ts_tree_cursor_end_index_wasm(this.tree[0]);Ve._ts_tree_cursor_start_position_wasm(this.tree[0]);let n=SO(nr);return Jtt(this.tree,e,l,n)}get startPosition(){return zi(this),Ve._ts_tree_cursor_start_position_wasm(this.tree[0]),SO(nr)}get endPosition(){return zi(this),Ve._ts_tree_cursor_end_position_wasm(this.tree[0]),SO(nr)}get startIndex(){return zi(this),Ve._ts_tree_cursor_start_index_wasm(this.tree[0])}get endIndex(){return zi(this),Ve._ts_tree_cursor_end_index_wasm(this.tree[0])}gotoFirstChild(){zi(this);let e=Ve._ts_tree_cursor_goto_first_child_wasm(this.tree[0]);return iy(this),e===1}gotoLastChild(){zi(this);let e=Ve._ts_tree_cursor_goto_last_child_wasm(this.tree[0]);return iy(this),e===1}gotoParent(){zi(this);let e=Ve._ts_tree_cursor_goto_parent_wasm(this.tree[0]);return iy(this),e===1}gotoNextSibling(){zi(this);let e=Ve._ts_tree_cursor_goto_next_sibling_wasm(this.tree[0]);return iy(this),e===1}gotoPreviousSibling(){zi(this);let e=Ve._ts_tree_cursor_goto_previous_sibling_wasm(this.tree[0]);return iy(this),e===1}gotoDescendant(e){zi(this),Ve._ts_tree_cursor_goto_descendant_wasm(this.tree[0],e),iy(this)}gotoFirstChildForIndex(e){zi(this),Ve.setValue(nr+ftt,e,"i32");let l=Ve._ts_tree_cursor_goto_first_child_for_index_wasm(this.tree[0]);return iy(this),l===1}gotoFirstChildForPosition(e){zi(this),x0(nr+ftt,e);let l=Ve._ts_tree_cursor_goto_first_child_for_position_wasm(this.tree[0]);return iy(this),l===1}reset(e){za(e),zi(this,nr+hN),Ve._ts_tree_cursor_reset_wasm(this.tree[0]),iy(this)}resetTo(e){zi(this,nr),zi(e,nr+ftt),Ve._ts_tree_cursor_reset_to_wasm(this.tree[0],e.tree[0]),iy(this)}},EPn=class{static{yt(this,"Node")}0=0;_children;_namedChildren;constructor(t,{id:e,tree:l,startIndex:n,startPosition:r,other:a}){R7(t),this[0]=a,this.id=e,this.tree=l,this.startIndex=n,this.startPosition=r}id;startIndex;startPosition;tree;get typeId(){return za(this),Ve._ts_node_symbol_wasm(this.tree[0])}get grammarId(){return za(this),Ve._ts_node_grammar_symbol_wasm(this.tree[0])}get type(){return this.tree.language.types[this.typeId]||"ERROR"}get grammarType(){return this.tree.language.types[this.grammarId]||"ERROR"}get isNamed(){return za(this),Ve._ts_node_is_named_wasm(this.tree[0])===1}get isExtra(){return za(this),Ve._ts_node_is_extra_wasm(this.tree[0])===1}get isError(){return za(this),Ve._ts_node_is_error_wasm(this.tree[0])===1}get isMissing(){return za(this),Ve._ts_node_is_missing_wasm(this.tree[0])===1}get hasChanges(){return za(this),Ve._ts_node_has_changes_wasm(this.tree[0])===1}get hasError(){return za(this),Ve._ts_node_has_error_wasm(this.tree[0])===1}get endIndex(){return za(this),Ve._ts_node_end_index_wasm(this.tree[0])}get endPosition(){return za(this),Ve._ts_node_end_point_wasm(this.tree[0]),SO(nr)}get text(){return Jtt(this.tree,this.startIndex,this.endIndex,this.startPosition)}get parseState(){return za(this),Ve._ts_node_parse_state_wasm(this.tree[0])}get nextParseState(){return za(this),Ve._ts_node_next_parse_state_wasm(this.tree[0])}equals(t){return this.tree===t.tree&&this.id===t.id}child(t){return za(this),Ve._ts_node_child_wasm(this.tree[0],t),Ad(this.tree)}namedChild(t){return za(this),Ve._ts_node_named_child_wasm(this.tree[0],t),Ad(this.tree)}childForFieldId(t){return za(this),Ve._ts_node_child_by_field_id_wasm(this.tree[0],t),Ad(this.tree)}childForFieldName(t){let e=this.tree.language.fields.indexOf(t);return e!==-1?this.childForFieldId(e):null}fieldNameForChild(t){za(this);let e=Ve._ts_node_field_name_for_child_wasm(this.tree[0],t);return e?Ve.AsciiToString(e):null}fieldNameForNamedChild(t){za(this);let e=Ve._ts_node_field_name_for_named_child_wasm(this.tree[0],t);return e?Ve.AsciiToString(e):null}childrenForFieldName(t){let e=this.tree.language.fields.indexOf(t);return e!==-1&&e!==0?this.childrenForFieldId(e):[]}childrenForFieldId(t){za(this),Ve._ts_node_children_by_field_id_wasm(this.tree[0],t);let e=Ve.getValue(nr,"i32"),l=Ve.getValue(nr+ur,"i32"),n=new Array(e);if(e>0){let r=l;for(let a=0;a<e;a++)n[a]=Ad(this.tree,r),r+=hN;Ve._free(l)}return n}firstChildForIndex(t){za(this);let e=nr+hN;return Ve.setValue(e,t,"i32"),Ve._ts_node_first_child_for_byte_wasm(this.tree[0]),Ad(this.tree)}firstNamedChildForIndex(t){za(this);let e=nr+hN;return Ve.setValue(e,t,"i32"),Ve._ts_node_first_named_child_for_byte_wasm(this.tree[0]),Ad(this.tree)}get childCount(){return za(this),Ve._ts_node_child_count_wasm(this.tree[0])}get namedChildCount(){return za(this),Ve._ts_node_named_child_count_wasm(this.tree[0])}get firstChild(){return this.child(0)}get firstNamedChild(){return this.namedChild(0)}get lastChild(){return this.child(this.childCount-1)}get lastNamedChild(){return this.namedChild(this.namedChildCount-1)}get children(){if(!this._children){za(this),Ve._ts_node_children_wasm(this.tree[0]);let t=Ve.getValue(nr,"i32"),e=Ve.getValue(nr+ur,"i32");if(this._children=new Array(t),t>0){let l=e;for(let n=0;n<t;n++)this._children[n]=Ad(this.tree,l),l+=hN;Ve._free(e)}}return this._children}get namedChildren(){if(!this._namedChildren){za(this),Ve._ts_node_named_children_wasm(this.tree[0]);let t=Ve.getValue(nr,"i32"),e=Ve.getValue(nr+ur,"i32");if(this._namedChildren=new Array(t),t>0){let l=e;for(let n=0;n<t;n++)this._namedChildren[n]=Ad(this.tree,l),l+=hN;Ve._free(e)}}return this._namedChildren}descendantsOfType(t,e=tJ,l=tJ){Array.isArray(t)||(t=[t]);let n=[],r=this.tree.language.types;for(let c of t)c=="ERROR"&&n.push(65535);for(let c=0,d=r.length;c<d;c++)t.includes(r[c])&&n.push(c);let a=Ve._malloc(ur*n.length);for(let c=0,d=n.length;c<d;c++)Ve.setValue(a+c*ur,n[c],"i32");za(this),Ve._ts_node_descendants_of_type_wasm(this.tree[0],a,n.length,e.row,e.column,l.row,l.column);let I=Ve.getValue(nr,"i32"),s=Ve.getValue(nr+ur,"i32"),o=new Array(I);if(I>0){let c=s;for(let d=0;d<I;d++)o[d]=Ad(this.tree,c),c+=hN}return Ve._free(s),Ve._free(a),o}get nextSibling(){return za(this),Ve._ts_node_next_sibling_wasm(this.tree[0]),Ad(this.tree)}get previousSibling(){return za(this),Ve._ts_node_prev_sibling_wasm(this.tree[0]),Ad(this.tree)}get nextNamedSibling(){return za(this),Ve._ts_node_next_named_sibling_wasm(this.tree[0]),Ad(this.tree)}get previousNamedSibling(){return za(this),Ve._ts_node_prev_named_sibling_wasm(this.tree[0]),Ad(this.tree)}get descendantCount(){return za(this),Ve._ts_node_descendant_count_wasm(this.tree[0])}get parent(){return za(this),Ve._ts_node_parent_wasm(this.tree[0]),Ad(this.tree)}childWithDescendant(t){return za(this),za(t,1),Ve._ts_node_child_with_descendant_wasm(this.tree[0]),Ad(this.tree)}descendantForIndex(t,e=t){if(typeof t!="number"||typeof e!="number")throw new Error("Arguments must be numbers");za(this);let l=nr+hN;return Ve.setValue(l,t,"i32"),Ve.setValue(l+ur,e,"i32"),Ve._ts_node_descendant_for_index_wasm(this.tree[0]),Ad(this.tree)}namedDescendantForIndex(t,e=t){if(typeof t!="number"||typeof e!="number")throw new Error("Arguments must be numbers");za(this);let l=nr+hN;return Ve.setValue(l,t,"i32"),Ve.setValue(l+ur,e,"i32"),Ve._ts_node_named_descendant_for_index_wasm(this.tree[0]),Ad(this.tree)}descendantForPosition(t,e=t){if(!ybe(t)||!ybe(e))throw new Error("Arguments must be {row, column} objects");za(this);let l=nr+hN;return x0(l,t),x0(l+aQ,e),Ve._ts_node_descendant_for_position_wasm(this.tree[0]),Ad(this.tree)}namedDescendantForPosition(t,e=t){if(!ybe(t)||!ybe(e))throw new Error("Arguments must be {row, column} objects");za(this);let l=nr+hN;return x0(l,t),x0(l+aQ,e),Ve._ts_node_named_descendant_for_position_wasm(this.tree[0]),Ad(this.tree)}walk(){return za(this),Ve._ts_tree_cursor_new_wasm(this.tree[0]),new yPn(lJ,this.tree)}edit(t){if(this.startIndex>=t.oldEndIndex){this.startIndex=t.newEndIndex+(this.startIndex-t.oldEndIndex);let e,l;this.startPosition.row>t.oldEndPosition.row?(e=this.startPosition.row-t.oldEndPosition.row,l=this.startPosition.column):(e=0,l=this.startPosition.column,this.startPosition.column>=t.oldEndPosition.column&&(l=this.startPosition.column-t.oldEndPosition.column)),e>0?(this.startPosition.row+=e,this.startPosition.column=l):this.startPosition.column+=l}else this.startIndex>t.startIndex&&(this.startIndex=t.newEndIndex,this.startPosition.row=t.newEndPosition.row,this.startPosition.column=t.newEndPosition.column)}toString(){za(this);let t=Ve._ts_node_to_string_wasm(this.tree[0]),e=Ve.AsciiToString(t);return Ve._free(t),e}};function Ltt(t,e,l,n,r){for(let a=0,I=r.length;a<I;a++){let s=Ve.getValue(l,"i32");l+=ur;let o=Ad(e,l);l+=hN,r[a]={patternIndex:n,name:t.captureNames[s],node:o}}return l}yt(Ltt,"unmarshalCaptures");function za(t,e=0){let l=nr+e*hN;Ve.setValue(l,t.id,"i32"),l+=ur,Ve.setValue(l,t.startIndex,"i32"),l+=ur,Ve.setValue(l,t.startPosition.row,"i32"),l+=ur,Ve.setValue(l,t.startPosition.column,"i32"),l+=ur,Ve.setValue(l,t[0],"i32")}yt(za,"marshalNode");function Ad(t,e=nr){let l=Ve.getValue(e,"i32");if(e+=ur,l===0)return null;let n=Ve.getValue(e,"i32");e+=ur;let r=Ve.getValue(e,"i32");e+=ur;let a=Ve.getValue(e,"i32");e+=ur;let I=Ve.getValue(e,"i32");return new EPn(lJ,{id:l,tree:t,startIndex:n,startPosition:{row:r,column:a},other:I})}yt(Ad,"unmarshalNode");function zi(t,e=nr){Ve.setValue(e+0*ur,t[0],"i32"),Ve.setValue(e+1*ur,t[1],"i32"),Ve.setValue(e+2*ur,t[2],"i32"),Ve.setValue(e+3*ur,t[3],"i32")}yt(zi,"marshalTreeCursor");function iy(t){t[0]=Ve.getValue(nr+0*ur,"i32"),t[1]=Ve.getValue(nr+1*ur,"i32"),t[2]=Ve.getValue(nr+2*ur,"i32"),t[3]=Ve.getValue(nr+3*ur,"i32")}yt(iy,"unmarshalTreeCursor");function x0(t,e){Ve.setValue(t,e.row,"i32"),Ve.setValue(t+ur,e.column,"i32")}yt(x0,"marshalPoint");function SO(t){return{row:Ve.getValue(t,"i32")>>>0,column:Ve.getValue(t+ur,"i32")>>>0}}yt(SO,"unmarshalPoint");function Dil(t,e){x0(t,e.startPosition),t+=aQ,x0(t,e.endPosition),t+=aQ,Ve.setValue(t,e.startIndex,"i32"),t+=ur,Ve.setValue(t,e.endIndex,"i32"),t+=ur}yt(Dil,"marshalRange");function bCe(t){let e={};return e.startPosition=SO(t),t+=aQ,e.endPosition=SO(t),t+=aQ,e.startIndex=Ve.getValue(t,"i32")>>>0,t+=ur,e.endIndex=Ve.getValue(t,"i32")>>>0,e}yt(bCe,"unmarshalRange");function zil(t,e=nr){x0(e,t.startPosition),e+=aQ,x0(e,t.oldEndPosition),e+=aQ,x0(e,t.newEndPosition),e+=aQ,Ve.setValue(e,t.startIndex,"i32"),e+=ur,Ve.setValue(e,t.oldEndIndex,"i32"),e+=ur,Ve.setValue(e,t.newEndIndex,"i32"),e+=ur}yt(zil,"marshalEdit");function Pil(t){let e=Ve.getValue(t,"i32"),l=Ve.getValue(t+=ur,"i32"),n=Ve.getValue(t+=ur,"i32");return{major_version:e,minor_version:l,patch_version:n}}yt(Pil,"unmarshalLanguageMetadata");var RPn=1,YPn=2,VPn=/[\w-]+/g,rbI={Zero:0,ZeroOrOne:1,ZeroOrMore:2,One:3,OneOrMore:4},Uil=yt(t=>t.type==="capture","isCaptureStep"),xtt=yt(t=>t.type==="string","isStringStep"),ZY={Syntax:1,NodeName:2,FieldName:3,CaptureName:4,PatternStructure:5},Wbe=class jil extends Error{constructor(e,l,n,r){super(jil.formatMessage(e,l)),this.kind=e,this.info=l,this.index=n,this.length=r,this.name="QueryError"}static{yt(this,"QueryError")}static formatMessage(e,l){switch(e){case ZY.NodeName:return`Bad node name '${l.word}'`;case ZY.FieldName:return`Bad field name '${l.word}'`;case ZY.CaptureName:return`Bad capture name @${l.word}`;case ZY.PatternStructure:return`Bad pattern structure at offset ${l.suffix}`;case ZY.Syntax:return`Bad syntax at offset ${l.suffix}`}}};function Kil(t,e,l,n){if(t.length!==3)throw new Error(`Wrong number of arguments to \`#${l}\` predicate. Expected 2, got ${t.length-1}`);if(!Uil(t[1]))throw new Error(`First argument of \`#${l}\` predicate must be a capture. Got "${t[1].value}"`);let r=l==="eq?"||l==="any-eq?",a=!l.startsWith("any-");if(Uil(t[2])){let I=t[1].name,s=t[2].name;n[e].push(o=>{let c=[],d=[];for(let G of o)G.name===I&&c.push(G.node),G.name===s&&d.push(G.node);let m=yt((G,p,A)=>A?G.text===p.text:G.text!==p.text,"compare");return a?c.every(G=>d.some(p=>m(G,p,r))):c.some(G=>d.some(p=>m(G,p,r)))})}else{let I=t[1].name,s=t[2].value,o=yt(d=>d.text===s,"matches"),c=yt(d=>d.text!==s,"doesNotMatch");n[e].push(d=>{let m=[];for(let p of d)p.name===I&&m.push(p.node);let G=r?o:c;return a?m.every(G):m.some(G)})}}yt(Kil,"parseAnyPredicate");function qil(t,e,l,n){if(t.length!==3)throw new Error(`Wrong number of arguments to \`#${l}\` predicate. Expected 2, got ${t.length-1}.`);if(t[1].type!=="capture")throw new Error(`First argument of \`#${l}\` predicate must be a capture. Got "${t[1].value}".`);if(t[2].type!=="string")throw new Error(`Second argument of \`#${l}\` predicate must be a string. Got @${t[2].name}.`);let r=l==="match?"||l==="any-match?",a=!l.startsWith("any-"),I=t[1].name,s=new RegExp(t[2].value);n[e].push(o=>{let c=[];for(let m of o)m.name===I&&c.push(m.node.text);let d=yt((m,G)=>G?s.test(m):!s.test(m),"test");return c.length===0?!r:a?c.every(m=>d(m,r)):c.some(m=>d(m,r))})}yt(qil,"parseMatchPredicate");function $il(t,e,l,n){if(t.length<2)throw new Error(`Wrong number of arguments to \`#${l}\` predicate. Expected at least 1. Got ${t.length-1}.`);if(t[1].type!=="capture")throw new Error(`First argument of \`#${l}\` predicate must be a capture. Got "${t[1].value}".`);let r=l==="any-of?",a=t[1].name,I=t.slice(2);if(!I.every(xtt))throw new Error(`Arguments to \`#${l}\` predicate must be strings.".`);let s=I.map(o=>o.value);n[e].push(o=>{let c=[];for(let d of o)d.name===a&&c.push(d.node.text);return c.length===0?!r:c.every(d=>s.includes(d))===r})}yt($il,"parseAnyOfPredicate");function ecl(t,e,l,n,r){if(t.length<2||t.length>3)throw new Error(`Wrong number of arguments to \`#${l}\` predicate. Expected 1 or 2. Got ${t.length-1}.`);if(!t.every(xtt))throw new Error(`Arguments to \`#${l}\` predicate must be strings.".`);let a=l==="is?"?n:r;a[e]||(a[e]={}),a[e][t[1].value]=t[2]?.value??null}yt(ecl,"parseIsPredicate");function tcl(t,e,l){if(t.length<2||t.length>3)throw new Error(`Wrong number of arguments to \`#set!\` predicate. Expected 1 or 2. Got ${t.length-1}.`);if(!t.every(xtt))throw new Error('Arguments to `#set!` predicate must be strings.".');l[e]||(l[e]={}),l[e][t[1].value]=t[2]?.value??null}yt(tcl,"parseSetDirective");function lcl(t,e,l,n,r,a,I,s,o,c,d){if(e===RPn){let m=n[l];a.push({type:"capture",name:m})}else if(e===YPn)a.push({type:"string",value:r[l]});else if(a.length>0){if(a[0].type!=="string")throw new Error("Predicates must begin with a literal value");let m=a[0].value;switch(m){case"any-not-eq?":case"not-eq?":case"any-eq?":case"eq?":Kil(a,t,m,I);break;case"any-not-match?":case"not-match?":case"any-match?":case"match?":qil(a,t,m,I);break;case"not-any-of?":case"any-of?":$il(a,t,m,I);break;case"is?":case"is-not?":ecl(a,t,m,c,d);break;case"set!":tcl(a,t,o);break;default:s[t].push({operator:m,operands:a.slice(1)})}a.length=0}}yt(lcl,"parsePattern");var wPn=class{static{yt(this,"Query")}0=0;exceededMatchLimit;textPredicates;captureNames;captureQuantifiers;predicates;setProperties;assertedProperties;refutedProperties;matchLimit;constructor(t,e){let l=Ve.lengthBytesUTF8(e),n=Ve._malloc(l+1);Ve.stringToUTF8(e,n,l+1);let r=Ve._ts_query_new(t[0],n,l,nr,nr+ur);if(!r){let W=Ve.getValue(nr+ur,"i32"),R=Ve.getValue(nr,"i32"),V=Ve.UTF8ToString(n,R).length,v=e.slice(V,V+100).split(`
|
|
2451
2451
|
`)[0],X=v.match(VPn)?.[0]??"";switch(Ve._free(n),W){case ZY.Syntax:throw new Wbe(ZY.Syntax,{suffix:`${V}: '${v}'...`},V,0);case ZY.NodeName:throw new Wbe(W,{word:X},V,X.length);case ZY.FieldName:throw new Wbe(W,{word:X},V,X.length);case ZY.CaptureName:throw new Wbe(W,{word:X},V,X.length);case ZY.PatternStructure:throw new Wbe(W,{suffix:`${V}: '${v}'...`},V,0)}}let a=Ve._ts_query_string_count(r),I=Ve._ts_query_capture_count(r),s=Ve._ts_query_pattern_count(r),o=new Array(I),c=new Array(s),d=new Array(a);for(let W=0;W<I;W++){let R=Ve._ts_query_capture_name_for_id(r,W,nr),V=Ve.getValue(nr,"i32");o[W]=Ve.UTF8ToString(R,V)}for(let W=0;W<s;W++){let R=new Array(I);for(let V=0;V<I;V++){let v=Ve._ts_query_capture_quantifier_for_id(r,W,V);R[V]=v}c[W]=R}for(let W=0;W<a;W++){let R=Ve._ts_query_string_value_for_id(r,W,nr),V=Ve.getValue(nr,"i32");d[W]=Ve.UTF8ToString(R,V)}let m=new Array(s),G=new Array(s),p=new Array(s),A=new Array(s),Z=new Array(s);for(let W=0;W<s;W++){let R=Ve._ts_query_predicates_for_pattern(r,W,nr),V=Ve.getValue(nr,"i32");A[W]=[],Z[W]=[];let v=new Array,X=R;for(let S=0;S<V;S++){let O=Ve.getValue(X,"i32");X+=ur;let T=Ve.getValue(X,"i32");X+=ur,lcl(W,O,T,o,d,v,Z,A,m,G,p)}Object.freeze(Z[W]),Object.freeze(A[W]),Object.freeze(m[W]),Object.freeze(G[W]),Object.freeze(p[W])}Ve._free(n),this[0]=r,this.captureNames=o,this.captureQuantifiers=c,this.textPredicates=Z,this.predicates=A,this.setProperties=m,this.assertedProperties=G,this.refutedProperties=p,this.exceededMatchLimit=!1}delete(){Ve._ts_query_delete(this[0]),this[0]=0}matches(t,e={}){let l=e.startPosition??tJ,n=e.endPosition??tJ,r=e.startIndex??0,a=e.endIndex??0,I=e.matchLimit??4294967295,s=e.maxStartDepth??4294967295,o=e.timeoutMicros??0,c=e.progressCallback;if(typeof I!="number")throw new Error("Arguments must be numbers");if(this.matchLimit=I,a!==0&&r>a)throw new Error("`startIndex` cannot be greater than `endIndex`");if(n!==tJ&&(l.row>n.row||l.row===n.row&&l.column>n.column))throw new Error("`startPosition` cannot be greater than `endPosition`");c&&(Ve.currentQueryProgressCallback=c),za(t),Ve._ts_query_matches_wasm(this[0],t.tree[0],l.row,l.column,n.row,n.column,r,a,I,s,o);let d=Ve.getValue(nr,"i32"),m=Ve.getValue(nr+ur,"i32"),G=Ve.getValue(nr+2*ur,"i32"),p=new Array(d);this.exceededMatchLimit=!!G;let A=0,Z=m;for(let W=0;W<d;W++){let R=Ve.getValue(Z,"i32");Z+=ur;let V=Ve.getValue(Z,"i32");Z+=ur;let v=new Array(V);if(Z=Ltt(this,t.tree,Z,R,v),this.textPredicates[R].every(X=>X(v))){p[A]={pattern:R,patternIndex:R,captures:v};let X=this.setProperties[R];p[A].setProperties=X;let S=this.assertedProperties[R];p[A].assertedProperties=S;let O=this.refutedProperties[R];p[A].refutedProperties=O,A++}}return p.length=A,Ve._free(m),Ve.currentQueryProgressCallback=null,p}captures(t,e={}){let l=e.startPosition??tJ,n=e.endPosition??tJ,r=e.startIndex??0,a=e.endIndex??0,I=e.matchLimit??4294967295,s=e.maxStartDepth??4294967295,o=e.timeoutMicros??0,c=e.progressCallback;if(typeof I!="number")throw new Error("Arguments must be numbers");if(this.matchLimit=I,a!==0&&r>a)throw new Error("`startIndex` cannot be greater than `endIndex`");if(n!==tJ&&(l.row>n.row||l.row===n.row&&l.column>n.column))throw new Error("`startPosition` cannot be greater than `endPosition`");c&&(Ve.currentQueryProgressCallback=c),za(t),Ve._ts_query_captures_wasm(this[0],t.tree[0],l.row,l.column,n.row,n.column,r,a,I,s,o);let d=Ve.getValue(nr,"i32"),m=Ve.getValue(nr+ur,"i32"),G=Ve.getValue(nr+2*ur,"i32"),p=new Array;this.exceededMatchLimit=!!G;let A=new Array,Z=m;for(let W=0;W<d;W++){let R=Ve.getValue(Z,"i32");Z+=ur;let V=Ve.getValue(Z,"i32");Z+=ur;let v=Ve.getValue(Z,"i32");if(Z+=ur,A.length=V,Z=Ltt(this,t.tree,Z,R,A),this.textPredicates[R].every(X=>X(A))){let X=A[v],S=this.setProperties[R];X.setProperties=S;let O=this.assertedProperties[R];X.assertedProperties=O;let T=this.refutedProperties[R];X.refutedProperties=T,p.push(X)}}return Ve._free(m),Ve.currentQueryProgressCallback=null,p}predicatesForPattern(t){return this.predicates[t]}disableCapture(t){let e=Ve.lengthBytesUTF8(t),l=Ve._malloc(e+1);Ve.stringToUTF8(t,l,e+1),Ve._ts_query_disable_capture(this[0],l,e),Ve._free(l)}disablePattern(t){if(t>=this.predicates.length)throw new Error(`Pattern index is ${t} but the pattern count is ${this.predicates.length}`);Ve._ts_query_disable_pattern(this[0],t)}didExceedMatchLimit(){return this.exceededMatchLimit}startIndexForPattern(t){if(t>=this.predicates.length)throw new Error(`Pattern index is ${t} but the pattern count is ${this.predicates.length}`);return Ve._ts_query_start_byte_for_pattern(this[0],t)}endIndexForPattern(t){if(t>=this.predicates.length)throw new Error(`Pattern index is ${t} but the pattern count is ${this.predicates.length}`);return Ve._ts_query_end_byte_for_pattern(this[0],t)}patternCount(){return Ve._ts_query_pattern_count(this[0])}captureIndexForName(t){return this.captureNames.indexOf(t)}isPatternRooted(t){return Ve._ts_query_is_pattern_rooted(this[0],t)===1}isPatternNonLocal(t){return Ve._ts_query_is_pattern_non_local(this[0],t)===1}isPatternGuaranteedAtStep(t){return Ve._ts_query_is_pattern_guaranteed_at_step(this[0],t)===1}},QPn=/^tree_sitter_\w+$/,Stt=class ncl{static{yt(this,"Language")}0=0;types;fields;constructor(e,l){R7(e),this[0]=l,this.types=new Array(Ve._ts_language_symbol_count(this[0]));for(let n=0,r=this.types.length;n<r;n++)Ve._ts_language_symbol_type(this[0],n)<2&&(this.types[n]=Ve.UTF8ToString(Ve._ts_language_symbol_name(this[0],n)));this.fields=new Array(Ve._ts_language_field_count(this[0])+1);for(let n=0,r=this.fields.length;n<r;n++){let a=Ve._ts_language_field_name_for_id(this[0],n);a!==0?this.fields[n]=Ve.UTF8ToString(a):this.fields[n]=null}}get name(){let e=Ve._ts_language_name(this[0]);return e===0?null:Ve.UTF8ToString(e)}get version(){return Ve._ts_language_version(this[0])}get abiVersion(){return Ve._ts_language_abi_version(this[0])}get metadata(){Ve._ts_language_metadata(this[0]);let e=Ve.getValue(nr,"i32"),l=Ve.getValue(nr+ur,"i32");return e===0?null:Pil(l)}get fieldCount(){return this.fields.length-1}get stateCount(){return Ve._ts_language_state_count(this[0])}fieldIdForName(e){let l=this.fields.indexOf(e);return l!==-1?l:null}fieldNameForId(e){return this.fields[e]??null}idForNodeType(e,l){let n=Ve.lengthBytesUTF8(e),r=Ve._malloc(n+1);Ve.stringToUTF8(e,r,n+1);let a=Ve._ts_language_symbol_for_name(this[0],r,n,l?1:0);return Ve._free(r),a||null}get nodeTypeCount(){return Ve._ts_language_symbol_count(this[0])}nodeTypeForId(e){let l=Ve._ts_language_symbol_name(this[0],e);return l?Ve.UTF8ToString(l):null}nodeTypeIsNamed(e){return!!Ve._ts_language_type_is_named_wasm(this[0],e)}nodeTypeIsVisible(e){return!!Ve._ts_language_type_is_visible_wasm(this[0],e)}get supertypes(){Ve._ts_language_supertypes_wasm(this[0]);let e=Ve.getValue(nr,"i32"),l=Ve.getValue(nr+ur,"i32"),n=new Array(e);if(e>0){let r=l;for(let a=0;a<e;a++)n[a]=Ve.getValue(r,"i16"),r+=Oil}return n}subtypes(e){Ve._ts_language_subtypes_wasm(this[0],e);let l=Ve.getValue(nr,"i32"),n=Ve.getValue(nr+ur,"i32"),r=new Array(l);if(l>0){let a=n;for(let I=0;I<l;I++)r[I]=Ve.getValue(a,"i16"),a+=Oil}return r}nextState(e,l){return Ve._ts_language_next_state(this[0],e,l)}lookaheadIterator(e){let l=Ve._ts_lookahead_iterator_new(this[0],e);return l?new NPn(lJ,l,this):null}query(e){return console.warn("Language.query is deprecated. Use new Query(language, source) instead."),new wPn(this,e)}static async load(e){let l;e instanceof Uint8Array?l=Promise.resolve(e):globalThis.process?.versions.node?l=(await import("fs/promises")).readFile(e):l=fetch(e).then(s=>s.arrayBuffer().then(o=>{if(s.ok)return new Uint8Array(o);{let c=new TextDecoder("utf-8").decode(o);throw new Error(`Language.load failed with status ${s.status}.
|
|
2452
2452
|
|
|
2453
2453
|
${c}`)}}));let n=await Ve.loadWebAssemblyModule(await l,{loadAsync:!0}),r=Object.keys(n),a=r.find(s=>QPn.test(s)&&!s.includes("external_scanner_"));if(!a)throw console.log(`Couldn't find language function in WASM file. Symbols:
|
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.351-
|
|
4
|
+
"version": "0.0.351-15",
|
|
5
5
|
"license": "SEE LICENSE IN LICENSE.md",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"repository": {
|
|
@@ -37,6 +37,6 @@
|
|
|
37
37
|
"worker/**/*"
|
|
38
38
|
],
|
|
39
39
|
"buildMetadata": {
|
|
40
|
-
"gitCommit": "
|
|
40
|
+
"gitCommit": "ef9b0b1"
|
|
41
41
|
}
|
|
42
42
|
}
|
package/sdk/index.js
CHANGED
|
@@ -413,7 +413,7 @@ ${l.join(`
|
|
|
413
413
|
* Cannot be used if the specified path already exists
|
|
414
414
|
* Parent directories must exist before creating the file
|
|
415
415
|
* Path *must* be absolute
|
|
416
|
-
`,input_schema:{type:"object",properties:{path:{description:"Absolute path to file to create.",type:"string"},file_text:{description:"The content of the file to be created.",type:"string"}},required:["path","file_text"]},callback:(n,c)=>l.callback({...n,command:"create"},c),summariseIntention:n=>l.summariseIntention({...n,command:"create"}),safeForTelemetry:!0},{name:"edit",description:"Tool for making string replacements in files.\n * Replaces exactly one occurrence of `old_str` with `new_str` in the specified file\n * When called multiple times in a single response, edits are independently made in the order calls are specified\n * The `old_str` parameter must match EXACTLY one or more consecutive lines from the original file\n * If `old_str` is not unique in the file, replacement will not be performed\n * Make sure to include enough context in `old_str` to make it unique\n * Path *must* be absolute\n ",input_schema:{type:"object",properties:{path:{description:"Absolute path to file to edit.",type:"string"},old_str:{description:"The string in the file to replace. Leading and ending whitespaces from file content should be preserved!",type:"string"},new_str:{description:"The new string to replace old_str with.",type:"string"}},required:["path","old_str"]},callback:(n,c)=>l.callback({...n,command:"edit"},c),shutdown:async()=>await l.shutdown(),summariseIntention:n=>l.summariseIntention({...n,command:"edit"}),safeForTelemetry:!0}]},Xre=(t,e,I)=>{let l=new ET,n=new Map,c={truncateBasedOn:"tokenCount",truncateStyle:"middle"};return e.debug(`str_replace_editor: default options: ${JSON.stringify(c,null,2)}`),{name:"str_replace_editor",description:"Editing tool for viewing, creating and editing files\n * State is persistent across command calls and discussions with the user\n * If `path` is a file, `view` displays the result of applying `cat -n`. If `path` is a directory, `view` lists non-hidden files and directories up to 2 levels deep\n * The `create` command cannot be used if the specified `path` already exists, or if parent directories don't exist\n * If a `command` generates a long output, output will be truncated and marked with `<file too long...`\n * Path *must* be absolute\n\n Notes for using the `str_replace` command:\n * The `old_str` parameter should match EXACTLY one or more consecutive lines from the original file\n * If the `old_str` parameter is not unique in the file, replacement will not be performed. Make sure to include enough context in `old_str` to make it unique\n * The `new_str` parameter should contain the edited lines that should replace the `old_str`",input_schema:{type:"object",properties:{command:{type:"string",enum:["view","create","str_replace","insert"],description:`The commands to run. Allowed options are: ${Array.from(Fre).map(s=>`\`${s}\``).join(", ")}.`},file_text:{description:"Required parameter of `create` command; the content of the file to be created.",type:"string"},insert_line:{description:"Required parameter of `insert` command. The `new_str` will be inserted AFTER the line `insert_line` of `path`.",type:"integer"},new_str:{description:"Required parameter of `str_replace` command containing the new string. Required parameter of `insert` command containing the string to insert.",type:"string"},old_str:{description:"Required parameter of `str_replace` command containing the string in `path` to replace. Leading and ending whitespaces from file content should be preserved!",type:"string"},path:{description:"Absolute path to file or directory.",type:"string"},view_range:{description:"Optional parameter of `view` command when `path` points to a file. If none is given, the full file is shown. If provided, the file will be shown in the indicated line number range, e.g. [11, 12] will show lines 11 and 12. Indexing at 1 to start. Setting `[start_line, -1]` shows all lines from `start_line` to the end of the file.",items:{type:"integer"},type:"array"}},required:["command","path"]},shutdown:async()=>{let s=l.getTrackedEditsJsonArrString();return l.reset(),{kind:"telemetry",telemetry:{event:"str_replace_editor_shutdown",properties:{trackedEdits:s},metrics:{},restrictedProperties:{}}}},summariseIntention:s=>{switch(s.command){case"create":return`create a new file at ${s.path}.`;case"view":return`view the file at ${s.path}.`;case"str_replace":case"edit":case"insert":return`edit the file at ${s.path}.`;default:{let a=s;return`unknown command: ${JSON.stringify(s)}`}}},callback:async(s,a)=>{if(s.command==="view")return r(s,a);let o=n.get(s.path);return o||(o=new HT(e),n.set(s.path,o)),o.enqueue(()=>r(s,a))},safeForTelemetry:!0};async function r(s,a){let o={...c,...a?.toolOptions||{}};e.debug(s.command+": "+s.path);let G={properties:{command:ave(s.command),options:JSON.stringify(o),inputs:JSON.stringify(Object.keys(s)),resolvedPathAgainstCwd:"false",fileExtension:s.path?AT(s.path):void 0},metrics:{resultLength:0,resultForLlmLength:0,responseTokenLimit:a?.truncationOptions?.tokenLimit},restrictedProperties:{}},i;try{if(typeof s.path!="string"||!s.path)return Os("failure",G,{},"A path parameter is required, and must be a non-empty string.","",void 0,"Path not provided");let d=process.cwd();if(d){let b=await $He(s.path,d);if(!_yI(b))return e.debug(`Could not resolve path "${s.path}" against agent cwd "${d}". Need to use absolute path.`),Os("failure",G,{},`Path "${s.path}" is not absolute. Please provide an absolute path.`,"",void 0,"Path not absolute");b!==s.path&&(e.debug(`using resolved path ${b} based on agent cwd ${d}`),s.path=b,G.properties.resolvedPathAgainstCwd="true")}switch(s.command){case"view":i=await Ere(s,G,t.permissions,e,a);break;case"str_replace":case"edit":i=await t0I(s,G,t.permissions,e,a);break;case"create":i=await l0I(s,G,t.permissions,e,a);break;case"insert":i=await n0I(s,G,t.permissions,e,a);break;default:{let b=s,m=b.command?`Unknown command: ${b.command}`:"No command provided";return Promise.reject(new Error(`${m}. Allowed commands are: ${Array.from(Fre).join(", ")}`))}}}catch(d){i=Os("failure",G,{},`Failed to execute
|
|
416
|
+
`,input_schema:{type:"object",properties:{path:{description:"Absolute path to file to create.",type:"string"},file_text:{description:"The content of the file to be created.",type:"string"}},required:["path","file_text"]},callback:(n,c)=>l.callback({...n,command:"create"},c),summariseIntention:n=>l.summariseIntention({...n,command:"create"}),safeForTelemetry:!0},{name:"edit",description:"Tool for making string replacements in files.\n * Replaces exactly one occurrence of `old_str` with `new_str` in the specified file\n * When called multiple times in a single response, edits are independently made in the order calls are specified\n * The `old_str` parameter must match EXACTLY one or more consecutive lines from the original file\n * If `old_str` is not unique in the file, replacement will not be performed\n * Make sure to include enough context in `old_str` to make it unique\n * Path *must* be absolute\n ",input_schema:{type:"object",properties:{path:{description:"Absolute path to file to edit.",type:"string"},old_str:{description:"The string in the file to replace. Leading and ending whitespaces from file content should be preserved!",type:"string"},new_str:{description:"The new string to replace old_str with.",type:"string"}},required:["path","old_str"]},callback:(n,c)=>l.callback({...n,command:"edit"},c),shutdown:async()=>await l.shutdown(),summariseIntention:n=>l.summariseIntention({...n,command:"edit"}),safeForTelemetry:!0}]},Xre=(t,e,I)=>{let l=new ET,n=new Map,c={truncateBasedOn:"tokenCount",truncateStyle:"middle"};return e.debug(`str_replace_editor: default options: ${JSON.stringify(c,null,2)}`),{name:"str_replace_editor",description:"Editing tool for viewing, creating and editing files\n * State is persistent across command calls and discussions with the user\n * If `path` is a file, `view` displays the result of applying `cat -n`. If `path` is a directory, `view` lists non-hidden files and directories up to 2 levels deep\n * The `create` command cannot be used if the specified `path` already exists, or if parent directories don't exist\n * If a `command` generates a long output, output will be truncated and marked with `<file too long...`\n * Path *must* be absolute\n\n Notes for using the `str_replace` command:\n * The `old_str` parameter should match EXACTLY one or more consecutive lines from the original file\n * If the `old_str` parameter is not unique in the file, replacement will not be performed. Make sure to include enough context in `old_str` to make it unique\n * The `new_str` parameter should contain the edited lines that should replace the `old_str`",input_schema:{type:"object",properties:{command:{type:"string",enum:["view","create","str_replace","insert"],description:`The commands to run. Allowed options are: ${Array.from(Fre).map(s=>`\`${s}\``).join(", ")}.`},file_text:{description:"Required parameter of `create` command; the content of the file to be created.",type:"string"},insert_line:{description:"Required parameter of `insert` command. The `new_str` will be inserted AFTER the line `insert_line` of `path`.",type:"integer"},new_str:{description:"Required parameter of `str_replace` command containing the new string. Required parameter of `insert` command containing the string to insert.",type:"string"},old_str:{description:"Required parameter of `str_replace` command containing the string in `path` to replace. Leading and ending whitespaces from file content should be preserved!",type:"string"},path:{description:"Absolute path to file or directory.",type:"string"},view_range:{description:"Optional parameter of `view` command when `path` points to a file. If none is given, the full file is shown. If provided, the file will be shown in the indicated line number range, e.g. [11, 12] will show lines 11 and 12. Indexing at 1 to start. Setting `[start_line, -1]` shows all lines from `start_line` to the end of the file.",items:{type:"integer"},type:"array"}},required:["command","path"]},shutdown:async()=>{let s=l.getTrackedEditsJsonArrString();return l.reset(),{kind:"telemetry",telemetry:{event:"str_replace_editor_shutdown",properties:{trackedEdits:s},metrics:{},restrictedProperties:{}}}},summariseIntention:s=>{switch(s.command){case"create":return`create a new file at ${s.path}.`;case"view":return`view the file at ${s.path}.`;case"str_replace":case"edit":case"insert":return`edit the file at ${s.path}.`;default:{let a=s;return`unknown command: ${JSON.stringify(s)}`}}},callback:async(s,a)=>{if(s.command==="view")return r(s,a);let o=n.get(s.path);return o||(o=new HT(e),n.set(s.path,o)),o.enqueue(()=>r(s,a))},safeForTelemetry:!0};async function r(s,a){let o={...c,...a?.toolOptions||{}};e.debug(s.command+": "+s.path);let G={properties:{command:ave(s.command),options:JSON.stringify(o),inputs:JSON.stringify(Object.keys(s)),resolvedPathAgainstCwd:"false",fileExtension:s.path?AT(s.path):void 0},metrics:{resultLength:0,resultForLlmLength:0,responseTokenLimit:a?.truncationOptions?.tokenLimit},restrictedProperties:{}},i;try{if(typeof s.path!="string"||!s.path)return Os("failure",G,{},"A path parameter is required, and must be a non-empty string.","",void 0,"Path not provided");let d=process.cwd();if(d){let b=await $He(s.path,d);if(!_yI(b))return e.debug(`Could not resolve path "${s.path}" against agent cwd "${d}". Need to use absolute path.`),Os("failure",G,{},`Path "${s.path}" is not absolute. Please provide an absolute path.`,"",void 0,"Path not absolute");b!==s.path&&(e.debug(`using resolved path ${b} based on agent cwd ${d}`),s.path=b,G.properties.resolvedPathAgainstCwd="true")}switch(s.command){case"view":i=await Ere(s,G,t.permissions,e,a);break;case"str_replace":case"edit":i=await t0I(s,G,t.permissions,e,a);break;case"create":i=await l0I(s,G,t.permissions,e,a);break;case"insert":i=await n0I(s,G,t.permissions,e,a);break;default:{let b=s,m=b.command?`Unknown command: ${b.command}`:"No command provided";return Promise.reject(new Error(`${m}. Allowed commands are: ${Array.from(Fre).join(", ")}`))}}}catch(d){i=Os("failure",G,{},`Failed to execute with arguments: ${JSON.stringify(s)} due to error: ${d}`,"",void 0,`Unhandled error: ${d}`)}return i.resultType!=="rejected"&&i.resultType!=="denied"&&s.path&&s.command&&typeof s.path=="string"&&typeof s.command=="string"&&l.trackEdit(s.path,ave(s.command),i.resultType,a?.toolCallId),i}};async function Ere(t,e,I,l,n){let c={truncateBasedOn:"tokenCount",truncateStyle:"middle",...n?.toolOptions||{}},r=await PyI(t.path).then(G=>G.isDirectory()?{kind:"directory"}:{kind:"file",size:G.size}).catch(()=>({kind:"not-found"}));if(I.requestRequired){let G=await I.request({kind:"read",intention:r.kind==="directory"?`List directory: ${t.path}`:`Read file: ${t.path}`,path:t.path}),i=vT(G,e);if(i)return i}if(r.kind==="not-found")return Os("failure",e,{properties:{viewType:"unknown"}},`Path ${t.path} does not exist. Please provide a valid path.`,"",void 0,"Path does not exist");let s,a="";if(r.kind==="directory"){let G=await KyI(t.path);s=G.join(`
|
|
417
417
|
`);let i=`@@ -1,0 +1,${G.length} @@`;a=aJ(void 0,t.path,`${i}
|
|
418
418
|
${G.map(d=>` ${d}`).join(`
|
|
419
419
|
`)}`)}else{if(r.size>sve){let Z=(r.size/1048576).toFixed(1),N=(sve/(1024*1024)).toFixed(0);return Os("failure",e,{properties:{viewType:"file"}},`File is too large to view (${Z}MB). Maximum file size is ${N}MB. Use shell tool with head/tail commands or specify a line range with view_range parameter to view specific sections.`,"",void 0,"File too large")}let G,i;t.view_range&&t.view_range.length>=1&&(G=t.view_range.at(0),i=t.view_range.at(1)),G===void 0&&(G=1,i=void 0);let d,b;if(t.view_range&&t.view_range.length>=1){let Z=await PHe(t.path,G,i);d=Z.lines,b=Z.totalLineCount}else d=(await Are(t.path,"utf-8")).split(`
|
|
@@ -422,7 +422,7 @@ ${m.map(Z=>` ${Z}`).join(`
|
|
|
422
422
|
`).replaceAll(`\r
|
|
423
423
|
`,`
|
|
424
424
|
`)}`),s=m.map((Z,N)=>`${N+G}.${Z}`).join(`
|
|
425
|
-
`)}let o=c0I(s,r.kind,n?.truncationOptions,c,l);return Os("success",e,{properties:{viewType:r.kind}},s,a,o)}async function t0I(t,e,I,l,n){let c,r=await Are(t.path,"utf-8");if(!t.old_str)c={type:"failure",resultForLlm:"Invalid inputs: old_str is required
|
|
425
|
+
`)}let o=c0I(s,r.kind,n?.truncationOptions,c,l);return Os("success",e,{properties:{viewType:r.kind}},s,a,o)}async function t0I(t,e,I,l,n){let c,r=await Are(t.path,"utf-8");if(!t.old_str)c={type:"failure",resultForLlm:"Invalid inputs: old_str is required"};else if(t.old_str===t.new_str)c={type:"success",resultForLlm:"No changes made: old_str and new_str are the same",newText:r};else if(t.new_str===void 0||t.new_str===null)c={type:"failure",resultForLlm:"Invalid inputs: new_str is required"};else{let a=ive(r),o=(t.new_str||"").replaceAll(/\r?\n/g,a),G=cve(r,t.old_str,o),i=G.type;i=="none"?c={type:"failure",resultForLlm:`No match found: old_str not found in ${t.path}; no changes made; you might want to try again with correct old_str`,error:"No match found"}:i=="multiple"?c={type:"failure",resultForLlm:`Multiple matches found for old_str in ${t.path}; no changes made; you might want to try again and be more specific with old_str`,error:"Multiple matches found"}:(i==="exact"||i==="fuzzy")&&(c={type:"success",resultForLlm:`File ${t.path} updated with changes.`,newText:G.text})}c||(c={type:"failure",resultForLlm:`Failed to replace ${t.old_str} with ${t.new_str||""} in ${t.path}.`,error:"Failed to replace"});let s="";if(c.type==="success"){let a=c.newText,o=Gve(r,a);if(s=aJ(t.path,t.path,o),I.requestRequired){let G=await I.request({kind:"write",intention:"Edit file",fileName:t.path,diff:s}),i=vT(G,e);if(i)return i}await Qre(t.path,a)}return Os(c.type,e,{},c.resultForLlm,s,void 0,c.type==="success"?void 0:c.error)}async function l0I(t,e,I,l,n){let c=t.file_text||"",r=qyI(t.path);if(!await cJ(r))return Os("failure",e,{},`Parent directory ${r} does not exist. You need to create it before creating the file.`,"",void 0,"Parent directory does not exist");let a=await cJ(t.path);if(a)return Os("failure",e,{},`Path ${t.path} already exists as a ${a}. Use \`view\` to check contents then edit it.`,"",void 0,"Path already exists");{let o=c.split(/\r?\n/),G=`@@ -1,0 +1,${o.length} @@`,i=aJ(void 0,t.path,`${G}
|
|
426
426
|
${o.map(b=>`+${b}`).join(`
|
|
427
427
|
`)}`);if(I.requestRequired){let b=await I.request({kind:"write",intention:"Create file",fileName:t.path,diff:i}),m=vT(b,e);if(m)return m}let d=process.platform==="win32"?c.replaceAll(/\r?\n/g,`\r
|
|
428
428
|
`):c;return await Qre(t.path,d),Os("success",e,{},`Created file ${t.path} with ${d.length} characters`,i)}}async function n0I(t,e,I,l,n){if(t.new_str===void 0||t.new_str===null||t.insert_line===void 0)return Os("failure",e,{metrics:{emptyLinesAdded:0}},"Missing required arguments for command insert: insert_line and new_str","");let c=await Are(t.path,"utf-8"),r=c.split(`
|
|
@@ -605,7 +605,7 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
|
605
605
|
`);this.baseURL=s.baseURL,this.timeout=s.timeout??ebe.DEFAULT_TIMEOUT,this.logger=s.logger??console;let a="warn";this.logLevel=a,this.logLevel=Nde(s.logLevel,"ClientOptions.logLevel",this)??Nde(Nb("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??a,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??XBe(),ZI(this,r6,ize,"f"),this._options=s,this.apiKey=typeof I=="string"?I:"Missing Key",this.organization=l,this.project=n,this.webhookSecret=c}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 Te([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Tde(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${Nh}`}defaultIdempotencyKey(){return`stainless-node-retry-${Bde()}`}makeStatusError(e,I,l,n){return dc.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 Me?l:new Me(`Failed to get token from 'apiKey' function: ${l.message}`,{cause:l})}if(typeof I!="string"||!I)throw new Me(`Expected 'apiKey' function argument to return a string but it returned ${I}`);return this.apiKey=I,!0}buildURL(e,I,l){let n=!T(this,$de,"m",Lze).call(this)&&l||this.baseURL,c=LBe(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),r=this.defaultQuery();return fBe(r)||(I={...r,...I}),typeof I=="object"&&I&&!Array.isArray(I)&&(c.search=this.stringifyQuery(I)),c.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 e0(this,this.makeRequest(e,I,void 0))}async makeRequest(e,I,l){let n=await e,c=n.maxRetries??this.maxRetries;I==null&&(I=c),await this.prepareOptions(n);let{req:r,url:s,timeout:a}=await this.buildRequest(n,{retryCount:c-I});await this.prepareRequest(r,{url:s,options:n});let o="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),G=l===void 0?"":`, retryOf: ${l}`,i=Date.now();if(Xc(this).debug(`[${o}] sending request`,aZ({retryOfRequestLogID:l,method:n.method,url:s,options:n,headers:r.headers})),n.signal?.aborted)throw new Dc;let d=new AbortController,b=await this.fetchWithTimeout(s,r,a,d).catch(Ff),m=Date.now();if(b instanceof globalThis.Error){let Z=`retrying, ${I} attempts remaining`;if(n.signal?.aborted)throw new Dc;let N=gf(b)||/timed? ?out/i.test(String(b)+("cause"in b?String(b.cause):""));if(I)return Xc(this).info(`[${o}] connection ${N?"timed out":"failed"} - ${Z}`),Xc(this).debug(`[${o}] connection ${N?"timed out":"failed"} (${Z})`,aZ({retryOfRequestLogID:l,url:s,durationMs:m-i,message:b.message})),this.retryRequest(n,I,l??o);throw Xc(this).info(`[${o}] connection ${N?"timed out":"failed"} - error; no more retries left`),Xc(this).debug(`[${o}] connection ${N?"timed out":"failed"} (error; no more retries left)`,aZ({retryOfRequestLogID:l,url:s,durationMs:m-i,message:b.message})),N?new WY:new ZY({cause:b})}let h=[...b.headers.entries()].filter(([Z])=>Z==="x-request-id").map(([Z,N])=>", "+Z+": "+JSON.stringify(N)).join(""),u=`[${o}${G}${h}] ${r.method} ${s} ${b.ok?"succeeded":"failed"} with status ${b.status} in ${m-i}ms`;if(!b.ok){let Z=await this.shouldRetry(b);if(I&&Z){let v=`retrying, ${I} attempts remaining`;return await EBe(b.body),Xc(this).info(`${u} - ${v}`),Xc(this).debug(`[${o}] response error (${v})`,aZ({retryOfRequestLogID:l,url:b.url,status:b.status,headers:b.headers,durationMs:m-i})),this.retryRequest(n,I,l??o,b.headers)}let N=Z?"error; no more retries left":"error; not retryable";Xc(this).info(`${u} - ${N}`);let g=await b.text().catch(v=>Ff(v).message),y=BBe(g),F=y?void 0:g;throw Xc(this).debug(`[${o}] response error (${N})`,aZ({retryOfRequestLogID:l,url:b.url,status:b.status,headers:b.headers,message:F,durationMs:Date.now()-i})),this.makeStatusError(b.status,y,F,b.headers)}return Xc(this).info(u),Xc(this).debug(`[${o}] response start`,aZ({retryOfRequestLogID:l,url:b.url,status:b.status,headers:b.headers,durationMs:m-i})),{response:b,options:n,controller:d,requestLogID:o,retryOfRequestLogID:l,startTime:i}}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 Ef(this,l,e)}async fetchWithTimeout(e,I,l,n){let{signal:c,method:r,...s}=I||{};c&&c.addEventListener("abort",()=>n.abort());let a=setTimeout(()=>n.abort(),l),o=globalThis.ReadableStream&&s.body instanceof globalThis.ReadableStream||typeof s.body=="object"&&s.body!==null&&Symbol.asyncIterator in s.body,G={signal:n.signal,...o?{duplex:"half"}:{},method:"GET",...s};r&&(G.method=r.toUpperCase());try{return await this.fetch.call(void 0,e,G)}finally{clearTimeout(a)}}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 c,r=n?.get("retry-after-ms");if(r){let a=parseFloat(r);Number.isNaN(a)||(c=a)}let s=n?.get("retry-after");if(s&&!c){let a=parseFloat(s);Number.isNaN(a)?c=Date.parse(s)-Date.now():c=a*1e3}if(!(c&&0<=c&&c<60*1e3)){let a=e.maxRetries??this.maxRetries;c=this.calculateDefaultRetryTimeoutMillis(I,a)}return await Wh(c),this.makeRequest(e,I-1,l)}calculateDefaultRetryTimeoutMillis(e,I){let c=I-e,r=Math.min(.5*Math.pow(2,c),8),s=1-Math.random()*.25;return r*s*1e3}async buildRequest(e,{retryCount:I=0}={}){let l={...e},{method:n,path:c,query:r,defaultBaseURL:s}=l,a=this.buildURL(c,r,s);"timeout"in l&&xBe("timeout",l.timeout),l.timeout=l.timeout??this.timeout;let{bodyHeaders:o,body:G}=this.buildBody({options:l}),i=await this.buildHeaders({options:e,method:n,bodyHeaders:o,retryCount:I});return{req:{method:n,headers:i,...l.signal&&{signal:l.signal},...globalThis.ReadableStream&&G instanceof globalThis.ReadableStream&&{duplex:"half"},...G&&{body:G},...this.fetchOptions??{},...l.fetchOptions??{}},url:a,timeout:l.timeout}}async buildHeaders({options:e,method:I,bodyHeaders:l,retryCount:n}){let c={};this.idempotencyHeader&&I!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),c[this.idempotencyHeader]=e.idempotencyKey);let r=Te([c,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(n),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Gze(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,l,e.headers]);return this.validateHeaders(r),r.values}buildBody({options:{body:e,headers:I}}){if(!e)return{bodyHeaders:void 0,body:void 0};let l=Te([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:HP(e)}:T(this,r6,"f").call(this,{body:e,headers:l})}};ebe=JI,r6=new WeakMap,$de=new WeakSet,Lze=function(){return this.baseURL!=="https://api.openai.com/v1"};JI.OpenAI=ebe;JI.DEFAULT_TIMEOUT=6e5;JI.OpenAIError=Me;JI.APIError=dc;JI.APIConnectionError=ZY;JI.APIConnectionTimeoutError=WY;JI.APIUserAbortError=Dc;JI.NotFoundError=$w;JI.ConflictError=eX;JI.RateLimitError=tX;JI.BadRequestError=Pw;JI.AuthenticationError=qw;JI.InternalServerError=lX;JI.PermissionDeniedError=_w;JI.UnprocessableEntityError=IX;JI.InvalidWebhookSignatureError=uh;JI.toFile=PP;JI.Completions=o0;JI.Chat=VY;JI.Embeddings=i0;JI.Files=b0;JI.Images=u0;JI.Audio=Vh;JI.Moderations=W0;JI.Models=Z0;JI.FineTuning=Vb;JI.Graders=QY;JI.VectorStores=mZ;JI.Webhooks=N0;JI.Beta=yh;JI.Batches=n0;JI.Uploads=HY;JI.Responses=EY;JI.Realtime=wY;JI.Conversations=FY;JI.Evals=AY;JI.Containers=gY;var Tf=class extends JI{constructor({baseURL:e=Nb("OPENAI_BASE_URL"),apiKey:I=Nb("AZURE_OPENAI_API_KEY"),apiVersion:l=Nb("OPENAI_API_VERSION"),endpoint:n,deployment:c,azureADTokenProvider:r,dangerouslyAllowBrowser:s,...a}={}){if(!l)throw new Me("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 r=="function"&&(s=!0),!r&&!I)throw new Me("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(r&&I)throw new Me("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(a.defaultQuery={...a.defaultQuery,"api-version":l},e){if(n)throw new Me("baseURL and endpoint are mutually exclusive")}else{if(n||(n=process.env.AZURE_OPENAI_ENDPOINT),!n)throw new Me("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");e=`${n}/openai`}super({apiKey:r??I,baseURL:e,...a,...s!==void 0?{dangerouslyAllowBrowser:s}:{}}),this.apiVersion="",this.apiVersion=l,this.deploymentName=c}async buildRequest(e,I={}){if(t3I.has(e.path)&&e.method==="post"&&e.body!==void 0){if(!sX(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"?Te([{"api-key":this.apiKey}]):super.authHeaders(e)}},t3I=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"]);import{readFileSync as l3I}from"fs";import{dirname as n3I,join as s6}from"path";import{fileURLToPath as c3I}from"url";var jf=null;function fze(){return Ibe().version}function Ibe(){if(jf!==null)return jf;try{let t=c3I(import.meta.url),e=n3I(t),I=[s6(e,"package.json"),s6(e,"../package.json"),s6(e,"../../package.json"),s6(e,"../runtime/package.json")];for(let n of I)try{let c=JSON.parse(l3I(n,"utf8")),r={name:c.name||"unknown",nameNoScope:r3I(c.name||"unknown"),version:c.version||"unknown",buildMetadata:c.buildMetadata};return jf=r,r}catch{continue}let l={name:"unknown",nameNoScope:"unknown",version:"unknown"};return jf=l,l}catch{let e={name:"unknown",nameNoScope:"unknown",version:"unknown"};return jf=e,e}}function r3I(t){return t.replace(/^@.*\//,"")}var kze=Ms("keyvault-secrets");var xze=Ms("keyvault-secrets");function ta(t,e){return typeof t=="string"?UD(t,e):UD(t)}function tbe(t){return f4(t,["key"])&&typeof t.key=="string"}function Df(t){let e=t;return e&&typeof e.getToken=="function"&&(e.signRequest===void 0||e.getToken.length>0)}var s3I="ApiVersionPolicy";function Bze(t){return{name:s3I,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 a3I="keyCredentialAuthenticationPolicy";function zze(t,e){return{name:a3I,async sendRequest(I,l){return I.headers.set(e,t.key),l(I)}}}function Uze(t,e,I={}){var l,n,c,r;let{credential:s,clientOptions:a}=I;if(s){if(Df(s)){let o=wy({credential:s,scopes:(n=(l=a?.credentials)===null||l===void 0?void 0:l.scopes)!==null&&n!==void 0?n:`${e}/.default`});t.addPolicy(o)}else if(o3I(s)){if(!(!((c=a?.credentials)===null||c===void 0)&&c.apiKeyHeaderName))throw new Error("Missing API Key Header Name");let o=zze(s,(r=a?.credentials)===null||r===void 0?void 0:r.apiKeyHeaderName);t.addPolicy(o)}}}function Sze(t,e,I={}){let l=cL(I);return l.addPolicy(Bze(I)),Uze(l,t,{credential:e,clientOptions:I}),l}function o3I(t){return t.key!==void 0}function jo(t){return koe(t)}function vY(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 Oze(t,e,I={}){let l;e&&(G3I(e)?l=e:I=e??{});let n=Sze(t,l,I),c=foe(t,Object.assign(Object.assign({},I),{pipeline:n})),r=(s,...a)=>({get:(o={})=>c.path(s,...a).get(vY(o)),post:(o={})=>c.path(s,...a).post(vY(o)),put:(o={})=>c.path(s,...a).put(vY(o)),patch:(o={})=>c.path(s,...a).patch(vY(o)),delete:(o={})=>c.path(s,...a).delete(vY(o)),head:(o={})=>c.path(s,...a).head(vY(o)),options:(o={})=>c.path(s,...a).options(vY(o)),trace:(o={})=>c.path(s,...a).trace(vY(o))});return{path:r,pathUnchecked:r,pipeline:c.pipeline}}function G3I(t){return tbe(t)||Df(t)}function lbe(t,e,I={}){var l,n,c,r,s,a,o,G;let i=(n=(l=I.endpoint)!==null&&l!==void 0?l:I.baseUrl)!==null&&n!==void 0?n:String(t),d=(c=I?.userAgentOptions)===null||c===void 0?void 0:c.userAgentPrefix,b="azsdk-js-keyvault-secrets/1.0.0-beta.1",m=d?`${d} azsdk-js-api ${b}`:`azsdk-js-api ${b}`,h=Object.assign(Object.assign({},I),{userAgentOptions:{userAgentPrefix:m},loggingOptions:{logger:(s=(r=I.loggingOptions)===null||r===void 0?void 0:r.logger)!==null&&s!==void 0?s:xze.info},credentials:{scopes:(o=(a=I.credentials)===null||a===void 0?void 0:a.scopes)!==null&&o!==void 0?o:["https://vault.azure.net/.default"]}}),{apiVersion:u}=h,Z=IL(h,["apiVersion"]),N=Oze(i,e,Z);N.pipeline.removePolicy({name:"ApiVersionPolicy"});let g=(G=I.apiVersion)!==null&&G!==void 0?G:"7.6";return N.pipeline.addPolicy({name:"ClientApiVersionPolicy",sendRequest:(y,F)=>{let f=new URL(y.url);return f.searchParams.get("api-version")||(y.url=`${y.url}${Array.from(f.searchParams.keys()).length>0?"&":"?"}api-version=${g}`),F(y)}}),Object.assign(Object.assign({},N),{apiVersion:g})}function Mze(t){return{value:t.value,tags:t.tags,contentType:t.contentType,attributes:t.secretAttributes?Tze(t.secretAttributes):t.secretAttributes}}function Tze(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 o6(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}}var Kf;(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"})(Kf||(Kf={}));function BX(t){return{value:t.value,id:t.id,contentType:t.contentType,attributes:t.attributes?o6(t.attributes):t.attributes,tags:t.tags,kid:t.kid,managed:t.managed}}function oi(t){return{error:t.error?jze(t.error):t.error}}function jze(t){return{code:t.code,message:t.message,innerError:t.innererror?jze(t.innererror):t.innererror}}function nbe(t){return{value:t.value,id:t.id,contentType:t.contentType,attributes:t.attributes?o6(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 Dze(t){return{contentType:t.contentType,attributes:t.secretAttributes?Tze(t.secretAttributes):t.secretAttributes,tags:t.tags}}function cbe(t){return{value:t.value?i3I(t.value):t.value,nextLink:t.nextLink}}function i3I(t){return t.map(e=>d3I(e))}function d3I(t){return{id:t.id,attributes:t.attributes?o6(t.attributes):t.attributes,tags:t.tags,contentType:t.contentType,managed:t.managed}}function Kze(t){return{value:t.value?b3I(t.value):t.value,nextLink:t.nextLink}}function b3I(t){return t.map(e=>m3I(e))}function m3I(t){return{id:t.id,attributes:t.attributes?o6(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 Pze(t){return{value:t.value&&typeof t.value=="string"?pLe(t.value,"base64url"):t.value}}function qze(t){return{value:hLe(t.secretBundleBackup,"base64url")}}var a6;(function(t){t.V75="7.5",t.V76Preview2="7.6-preview.2",t.V76="7.6"})(a6||(a6={}));function G6(t,e,I,l,n={}){var c,r;let s=(c=n.itemName)!==null&&c!==void 0?c:"value",a=(r=n.nextLinkName)!==null&&r!==void 0?r:"nextLink",o={getPage:async G=>{let i=G===void 0?await e():await t.pathUnchecked(G).get();W3I(i,l);let d=await I(i),b=u3I(d,a);return{page:Z3I(d,s),nextPageLink:b}},byPage:G=>{let{continuationToken:i}=G??{};return rbe(o,{pageLink:i})}};return h3I(o)}function h3I(t){var e;let I=p3I(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 rbe(t,{pageLink:n})}}}function p3I(t){return MN(this,arguments,function*(){var I,l,n,c;let r=rbe(t);try{for(var s=!0,a=Qy(r),o;o=yield Fn(a.next()),I=o.done,!I;s=!0)c=o.value,s=!1,yield Fn(yield*ufe(Qy(c)))}catch(G){l={error:G}}finally{try{!s&&!I&&(n=a.return)&&(yield Fn(n.call(a)))}finally{if(l)throw l.error}}})}function rbe(t){return MN(this,arguments,function*(I,l={}){let{pageLink:n}=l,c=yield Fn(I.getPage(n??I.firstPageLink));if(!c)return yield Fn(void 0);let r=c.page;for(r.continuationToken=c.nextPageLink,yield yield Fn(r);c.nextPageLink;){if(c=yield Fn(I.getPage(c.nextPageLink)),!c)return yield Fn(void 0);r=c.page,r.continuationToken=c.nextPageLink,yield yield Fn(r)}})}function u3I(t,e){if(!e)return;let I=t[e];if(typeof I!="string"&&typeof I<"u"&&I!==null)throw new xu(`Body Property ${e} should be a string or undefined or null but got ${typeof I}`);if(I!==null)return I}function Z3I(t,e){let I=t[e];if(!Array.isArray(I))throw new xu(`Couldn't paginate response
|
|
606
606
|
Body doesn't contain an array property with name: ${e}`);return I??[]}function W3I(t,e){if(!e.includes(t.status))throw ta(`Pagination failed with unexpected statusCode ${t.status}`,t)}function zX(t,e,I){return(e??I==="+")||I==="#"?_ze(t):$ze(t)}function _ze(t){return t.split(/(%[0-9A-Fa-f]{2})/g).map(e=>/%[0-9A-Fa-f]/.test(e)?e:encodeURI(e)).join("")}function $ze(t){return encodeURIComponent(t).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function Pf(t){return t!=null}function sbe(t){return[!!t&&[";","?","&"].includes(t),t&&["?","&"].includes(t)?"=":""]}function i6(t,e=!1){return e?!t||t==="+"?"":t:!t||t==="+"||t==="#"?",":t==="?"?"&":t}function N3I(t){let e=t.isFirst,{op:I,varName:l,varValue:n,reserved:c}=t,r=[],[s,a]=sbe(I);if(Array.isArray(n))for(let o of n.filter(Pf))r.push(`${i6(I,e)}`),s&&l&&(r.push(`${encodeURIComponent(l)}`),o===""?r.push(a):r.push("=")),r.push(zX(o,c,I)),e=!1;else if(typeof n=="object")for(let o of Object.keys(n)){let G=n[o];Pf(G)&&(r.push(`${i6(I,e)}`),o&&(r.push(`${encodeURIComponent(o)}`),s&&G===""?r.push(a):r.push("=")),r.push(zX(G,c,I)),e=!1)}return r.join("")}function Y3I(t){let{op:e,varName:I,varValue:l,isFirst:n,reserved:c}=t,r=[],s=i6(e,n),[a,o]=sbe(e);if(a&&I){if(r.push(zX(I,c,e)),l==="")return o||r.push(o),r.join("")?`${s}${r.join("")}`:void 0;r.push("=")}let G=[];if(Array.isArray(l))for(let i of l.filter(Pf))G.push(zX(i,c,e));else if(typeof l=="object")for(let i of Object.keys(l))Pf(l[i])&&(G.push($ze(i)),G.push(zX(l[i],c,e)));return r.push(G.join(",")),r.join(",")?`${s}${r.join("")}`:void 0}function V3I(t){let{op:e,varName:I,modifier:l,isFirst:n,reserved:c,varValue:r}=t;if(Pf(r))if(["string","number","boolean"].includes(typeof r)){let s=r.toString(),[a,o]=sbe(e),G=[i6(e,n)];return a&&I&&(G.push(I),s===""?G.push(o):G.push("=")),l&&l!=="*"&&(s=s.substring(0,parseInt(l,10))),G.push(zX(s,c,e)),G.join("")}else return l==="*"?N3I(t):Y3I(t);else return}function Gi(t,e,I){return t.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g,(l,n,c)=>{if(!n)return _ze(c);let r;["+","#",".","/",";","?","&"].includes(n[0])&&(r=n[0],n=n.slice(1));let s=n.split(/,/g),a=[];for(let o of s){let G=/([^:\*]*)(?::(\d+)|(\*))?/.exec(o);if(!G||!G[1])continue;let i=V3I({isFirst:a.length===0,op:r,varValue:e[G[1]],varName:G[1],modifier:G[2]||G[3],reserved:I?.allowReserved});i&&a.push(i)}return a.join("")})}function R3I(t,e,I={requestOptions:{}}){var l,n;let c=Gi("/secrets/restore{?api%2Dversion}",{"api%2Dversion":t.apiVersion},{allowReserved:(l=I?.requestOptions)===null||l===void 0?void 0:l.skipUrlEncoding});return t.path(c).post(Object.assign(Object.assign({},jo(I)),{contentType:"application/json",headers:Object.assign({accept:"application/json"},(n=I.requestOptions)===null||n===void 0?void 0:n.headers),body:qze(e)}))}async function y3I(t){if(!["200"].includes(t.status)){let I=ta(t);throw I.details=oi(t.body),I}return BX(t.body)}async function abe(t,e,I={requestOptions:{}}){let l=await R3I(t,e,I);return y3I(l)}function g3I(t,e,I={requestOptions:{}}){var l,n;let c=Gi("/secrets/{secret-name}/backup{?api%2Dversion}",{"secret-name":e,"api%2Dversion":t.apiVersion},{allowReserved:(l=I?.requestOptions)===null||l===void 0?void 0:l.skipUrlEncoding});return t.path(c).post(Object.assign(Object.assign({},jo(I)),{headers:Object.assign({accept:"application/json"},(n=I.requestOptions)===null||n===void 0?void 0:n.headers)}))}async function F3I(t){if(!["200"].includes(t.status)){let I=ta(t);throw I.details=oi(t.body),I}return Pze(t.body)}async function obe(t,e,I={requestOptions:{}}){let l=await g3I(t,e,I);return F3I(l)}function A3I(t,e,I={requestOptions:{}}){var l,n;let c=Gi("/deletedsecrets/{secret-name}/recover{?api%2Dversion}",{"secret-name":e,"api%2Dversion":t.apiVersion},{allowReserved:(l=I?.requestOptions)===null||l===void 0?void 0:l.skipUrlEncoding});return t.path(c).post(Object.assign(Object.assign({},jo(I)),{headers:Object.assign({accept:"application/json"},(n=I.requestOptions)===null||n===void 0?void 0:n.headers)}))}async function Q3I(t){if(!["200"].includes(t.status)){let I=ta(t);throw I.details=oi(t.body),I}return BX(t.body)}async function Gbe(t,e,I={requestOptions:{}}){let l=await A3I(t,e,I);return Q3I(l)}function w3I(t,e,I={requestOptions:{}}){var l,n;let c=Gi("/deletedsecrets/{secret-name}{?api%2Dversion}",{"secret-name":e,"api%2Dversion":t.apiVersion},{allowReserved:(l=I?.requestOptions)===null||l===void 0?void 0:l.skipUrlEncoding});return t.path(c).delete(Object.assign(Object.assign({},jo(I)),{headers:Object.assign({accept:"application/json"},(n=I.requestOptions)===null||n===void 0?void 0:n.headers)}))}async function X3I(t){if(!["204"].includes(t.status)){let I=ta(t);throw I.details=oi(t.body),I}}async function ibe(t,e,I={requestOptions:{}}){let l=await w3I(t,e,I);return X3I(l)}function E3I(t,e,I={requestOptions:{}}){var l,n;let c=Gi("/deletedsecrets/{secret-name}{?api%2Dversion}",{"secret-name":e,"api%2Dversion":t.apiVersion},{allowReserved:(l=I?.requestOptions)===null||l===void 0?void 0:l.skipUrlEncoding});return t.path(c).get(Object.assign(Object.assign({},jo(I)),{headers:Object.assign({accept:"application/json"},(n=I.requestOptions)===null||n===void 0?void 0:n.headers)}))}async function H3I(t){if(!["200"].includes(t.status)){let I=ta(t);throw I.details=oi(t.body),I}return nbe(t.body)}async function dbe(t,e,I={requestOptions:{}}){let l=await E3I(t,e,I);return H3I(l)}function v3I(t,e={requestOptions:{}}){var I,l;let n=Gi("/deletedsecrets{?api%2Dversion,maxresults}",{"api%2Dversion":t.apiVersion,maxresults:e?.maxresults},{allowReserved:(I=e?.requestOptions)===null||I===void 0?void 0:I.skipUrlEncoding});return t.path(n).get(Object.assign(Object.assign({},jo(e)),{headers:Object.assign({accept:"application/json"},(l=e.requestOptions)===null||l===void 0?void 0:l.headers)}))}async function C3I(t){if(!["200"].includes(t.status)){let I=ta(t);throw I.details=oi(t.body),I}return Kze(t.body)}function bbe(t,e={requestOptions:{}}){return G6(t,()=>v3I(t,e),C3I,["200"],{itemName:"value",nextLinkName:"nextLink"})}function J3I(t,e,I={requestOptions:{}}){var l,n;let c=Gi("/secrets/{secret-name}/versions{?api%2Dversion,maxresults}",{"secret-name":e,"api%2Dversion":t.apiVersion,maxresults:I?.maxresults},{allowReserved:(l=I?.requestOptions)===null||l===void 0?void 0:l.skipUrlEncoding});return t.path(c).get(Object.assign(Object.assign({},jo(I)),{headers:Object.assign({accept:"application/json"},(n=I.requestOptions)===null||n===void 0?void 0:n.headers)}))}async function L3I(t){if(!["200"].includes(t.status)){let I=ta(t);throw I.details=oi(t.body),I}return cbe(t.body)}function mbe(t,e,I={requestOptions:{}}){return G6(t,()=>J3I(t,e,I),L3I,["200"],{itemName:"value",nextLinkName:"nextLink"})}function f3I(t,e={requestOptions:{}}){var I,l;let n=Gi("/secrets{?api%2Dversion,maxresults}",{"api%2Dversion":t.apiVersion,maxresults:e?.maxresults},{allowReserved:(I=e?.requestOptions)===null||I===void 0?void 0:I.skipUrlEncoding});return t.path(n).get(Object.assign(Object.assign({},jo(e)),{headers:Object.assign({accept:"application/json"},(l=e.requestOptions)===null||l===void 0?void 0:l.headers)}))}async function k3I(t){if(!["200"].includes(t.status)){let I=ta(t);throw I.details=oi(t.body),I}return cbe(t.body)}function hbe(t,e={requestOptions:{}}){return G6(t,()=>f3I(t,e),k3I,["200"],{itemName:"value",nextLinkName:"nextLink"})}function x3I(t,e,I,l={requestOptions:{}}){var n,c;let r=Gi("/secrets/{secret-name}/{secret-version}{?api%2Dversion}",{"secret-name":e,"secret-version":I,"api%2Dversion":t.apiVersion},{allowReserved:(n=l?.requestOptions)===null||n===void 0?void 0:n.skipUrlEncoding});return t.path(r).get(Object.assign(Object.assign({},jo(l)),{headers:Object.assign({accept:"application/json"},(c=l.requestOptions)===null||c===void 0?void 0:c.headers)}))}async function B3I(t){if(!["200"].includes(t.status)){let I=ta(t);throw I.details=oi(t.body),I}return BX(t.body)}async function pbe(t,e,I,l={requestOptions:{}}){let n=await x3I(t,e,I,l);return B3I(n)}function z3I(t,e,I,l,n={requestOptions:{}}){var c,r;let s=Gi("/secrets/{secret-name}/{secret-version}{?api%2Dversion}",{"secret-name":e,"secret-version":I,"api%2Dversion":t.apiVersion},{allowReserved:(c=n?.requestOptions)===null||c===void 0?void 0:c.skipUrlEncoding});return t.path(s).patch(Object.assign(Object.assign({},jo(n)),{contentType:"application/json",headers:Object.assign({accept:"application/json"},(r=n.requestOptions)===null||r===void 0?void 0:r.headers),body:Dze(l)}))}async function U3I(t){if(!["200"].includes(t.status)){let I=ta(t);throw I.details=oi(t.body),I}return BX(t.body)}async function ube(t,e,I,l,n={requestOptions:{}}){let c=await z3I(t,e,I,l,n);return U3I(c)}function S3I(t,e,I={requestOptions:{}}){var l,n;let c=Gi("/secrets/{secret-name}{?api%2Dversion}",{"secret-name":e,"api%2Dversion":t.apiVersion},{allowReserved:(l=I?.requestOptions)===null||l===void 0?void 0:l.skipUrlEncoding});return t.path(c).delete(Object.assign(Object.assign({},jo(I)),{headers:Object.assign({accept:"application/json"},(n=I.requestOptions)===null||n===void 0?void 0:n.headers)}))}async function O3I(t){if(!["200"].includes(t.status)){let I=ta(t);throw I.details=oi(t.body),I}return nbe(t.body)}async function Zbe(t,e,I={requestOptions:{}}){let l=await S3I(t,e,I);return O3I(l)}function M3I(t,e,I,l={requestOptions:{}}){var n,c;let r=Gi("/secrets/{secret-name}{?api%2Dversion}",{"secret-name":e,"api%2Dversion":t.apiVersion},{allowReserved:(n=l?.requestOptions)===null||n===void 0?void 0:n.skipUrlEncoding});return t.path(r).put(Object.assign(Object.assign({},jo(l)),{contentType:"application/json",headers:Object.assign({accept:"application/json"},(c=l.requestOptions)===null||c===void 0?void 0:c.headers),body:Mze(I)}))}async function T3I(t){if(!["200"].includes(t.status)){let I=ta(t);throw I.details=oi(t.body),I}return BX(t.body)}async function Wbe(t,e,I,l={requestOptions:{}}){let n=await M3I(t,e,I,l);return T3I(n)}var qf=class{constructor(e,I,l={}){var n;let c=(n=l?.userAgentOptions)===null||n===void 0?void 0:n.userAgentPrefix,r=c?`${c} azsdk-js-client`:"azsdk-js-client";this._client=lbe(e,I,Object.assign(Object.assign({},l),{userAgentOptions:{userAgentPrefix:r}})),this.pipeline=this._client.pipeline}restoreSecret(e,I={requestOptions:{}}){return abe(this._client,e,I)}backupSecret(e,I={requestOptions:{}}){return obe(this._client,e,I)}recoverDeletedSecret(e,I={requestOptions:{}}){return Gbe(this._client,e,I)}purgeDeletedSecret(e,I={requestOptions:{}}){return ibe(this._client,e,I)}getDeletedSecret(e,I={requestOptions:{}}){return dbe(this._client,e,I)}getDeletedSecrets(e={requestOptions:{}}){return bbe(this._client,e)}getSecretVersions(e,I={requestOptions:{}}){return mbe(this._client,e,I)}getSecrets(e={requestOptions:{}}){return hbe(this._client,e)}getSecret(e,I,l={requestOptions:{}}){return pbe(this._client,e,I,l)}updateSecret(e,I,l,n={requestOptions:{}}){return ube(this._client,e,I,l,n)}deleteSecret(e,I={requestOptions:{}}){return Zbe(this._client,e,I)}setSecret(e,I,l={requestOptions:{}}){return Wbe(this._client,e,I,l)}};var j3I=["authorization","authorization_url","resource","scope","tenantId","claims","error"];function Nbe(t){let e=/,? +/,I=t.split(e).reduce((l,n)=>{if(n.match(/\w="/)){let[c,...r]=n.split("=");if(j3I.includes(c))return Object.assign(Object.assign({},l),{[c]:r.join("=").slice(1,-1)})}return l},{});if(I.authorization)try{let l=new URL(I.authorization).pathname.substring(1);l&&(I.tenantId=l)}catch{throw new Error(`The challenge authorization URI '${I.authorization}' is invalid.`)}return I}var D3I={forcedRefreshWindowInMs:1e3,retryIntervalInMs:3e3,refreshWindowInMs:1e3*60*2};async function K3I(t,e,I){async function l(){if(Date.now()<I)try{return await t()}catch{return null}else{let c=await t();if(c===null)throw new Error("Failed to refresh access token.");return c}}let n=await l();for(;n===null;)await UN(e),n=await l();return n}function eUe(t,e){let I=null,l=null,n,c=Object.assign(Object.assign({},D3I),e),r={get isRefreshing(){return I!==null},get shouldRefresh(){var a;return r.isRefreshing?!1:l?.refreshAfterTimestamp&&l.refreshAfterTimestamp<Date.now()?!0:((a=l?.expiresOnTimestamp)!==null&&a!==void 0?a:0)-c.refreshWindowInMs<Date.now()},get mustRefresh(){return l===null||l.expiresOnTimestamp-c.forcedRefreshWindowInMs<Date.now()}};function s(a,o){var G;return r.isRefreshing||(I=K3I(()=>t.getToken(a,o),c.retryIntervalInMs,(G=l?.expiresOnTimestamp)!==null&&G!==void 0?G:Date.now()).then(d=>(I=null,l=d,n=o.tenantId,l)).catch(d=>{throw I=null,l=null,n=void 0,d})),I}return async(a,o)=>{let G=!!o.claims,i=n!==o.tenantId;return G&&(l=null),i||G||r.mustRefresh?s(a,o):(r.shouldRefresh&&s(a,o),l)}}var IUe=Ms("keyvault-common");function P3I(t,e){let I;try{I=new URL(t)}catch{throw new Error(`The challenge contains invalid scope '${t}'`)}if(!new URL(e.url).hostname.endsWith(`.${I.hostname}`))throw new Error(`The challenge resource '${I.hostname}' does not match the requested domain. Set disableChallengeResourceVerification to true in your client options to disable. See https://aka.ms/azsdk/blog/vault-uri for more information.`)}var q3I="keyVaultAuthenticationPolicy";function tUe(t,e={}){let{disableChallengeResourceVerification:I}=e,l={status:"none"},n=eUe(t);function c(G){return{abortSignal:G.abortSignal,requestOptions:{timeout:G.timeout>0?G.timeout:void 0},tracingOptions:G.tracingOptions}}async function r(G){let i=c(G);switch(l.status){case"none":l={status:"started",originalBody:G.body},G.body=null;break;case"started":break;case"complete":{let d=await n(l.scopes,Object.assign(Object.assign({},i),{enableCae:!0,tenantId:l.tenantId}));d&&G.headers.set("authorization",`Bearer ${d.token}`);break}}}async function s(G,i,d){if(i.status!==401)return i;G.body===null&&l.status==="started"&&(G.body=l.originalBody);let b=c(G),m=i.headers.get("WWW-Authenticate");if(!m)return IUe.warning("keyVaultAuthentication policy encountered a 401 response without a corresponding WWW-Authenticate header. This is unexpected. Not handling the 401 response."),i;let h=Nbe(m),u=h.resource?h.resource+"/.default":h.scope;if(!u)return i;I||P3I(u,G);let Z=await n([u],Object.assign(Object.assign({},b),{enableCae:!0,tenantId:h.tenantId}));return Z?(G.headers.set("Authorization",`Bearer ${Z.token}`),l={status:"complete",scopes:[u],tenantId:h.tenantId},d(G)):i}async function a(G,i,d){if(l.status!=="complete"||i.status!==401)return i;let b=c(G),m=i.headers.get("WWW-Authenticate");if(!m)return i;let{claims:h,error:u}=Nbe(m);if(u!=="insufficient_claims"||h===void 0)return i;let Z=atob(h),N=await n(l.scopes,Object.assign(Object.assign({},b),{enableCae:!0,tenantId:l.tenantId,claims:Z}));return G.headers.set("Authorization",`Bearer ${N.token}`),d(G)}async function o(G,i){await r(G);let d=await i(G);return d=await s(G,d,i),d=await a(G,d,i),d}return{name:q3I,sendRequest:o}}function lUe(t,e){if(typeof t!="string"||!(t=t.trim()))throw new Error("Invalid collection argument");if(typeof e!="string"||!(e=e.trim()))throw new Error("Invalid identifier argument");let I;try{I=new URL(e)}catch{throw new Error(`Invalid ${t} identifier: ${e}. Not a valid URI`)}let l=(I.pathname||"").split("/");if(l.length!==3&&l.length!==4)throw new Error(`Invalid ${t} identifier: ${e}. Bad number of segments: ${l.length}`);if(t!==l[1])throw new Error(`Invalid ${t} identifier: ${e}. segment [1] should be "${t}", found "${l[1]}"`);let n=`${I.protocol}//${I.host}`,c=l[2],r=l.length===4?l[3]:void 0;return{vaultUrl:n,name:c,version:r}}function Ybe(t){let I=t.split("/")[3];return Object.assign({sourceId:t},lUe(I,t))}function za(t){let e=t,I=t,l=Ybe(e.id),n=e.attributes;delete e.attributes;let c={value:e.value,name:l.name,properties:{expiresOn:n?.expires,createdOn:n?.created,updatedOn:n?.updated,enabled:n?.enabled,notBefore:n?.notBefore,recoverableDays:n?.recoverableDays,recoveryLevel:n?.recoveryLevel,id:e.id,contentType:e.contentType,tags:e.tags,managed:e.managed,vaultUrl:l.vaultUrl,version:l.version,name:l.name,certificateKeyId:e.kid}};return I.recoveryId&&(c.properties.recoveryId=I.recoveryId,c.properties.scheduledPurgeDate=I.scheduledPurgeDate,c.properties.deletedOn=I.deletedDate,c.recoveryId=I.recoveryId,c.scheduledPurgeDate=I.scheduledPurgeDate,c.deletedOn=I.deletedDate),n&&(n.vaultUrl&&delete c.properties.vaultUrl,n.expires&&delete c.properties.expires,n.created&&delete c.properties.created,n.updated&&delete c.properties.updated),c}function d6(t,e,I){let l;return{async next(){l??(l=t(Object.assign(Object.assign({},e),{maxresults:void 0})));let n=await l.next();return Object.assign(Object.assign({},n),{value:n.value&&I(n.value)})},[Symbol.asyncIterator](){return this},byPage(n){return MN(this,arguments,function*(){var r,s,a,o;let G=t(Object.assign(Object.assign({},e),{maxresults:n?.maxPageSize})).byPage(n);try{for(var i=!0,d=Qy(G),b;b=yield Fn(d.next()),r=b.done,!r;i=!0)o=b.value,i=!1,yield yield Fn(o.map(I))}catch(m){s={error:m}}finally{try{!i&&!r&&(a=d.return)&&(yield Fn(a.call(d)))}finally{if(s)throw s.error}}})}}}var b6="4.10.0";var Do=ER({namespace:"Microsoft.KeyVault",packageName:"@azure/keyvault-secrets",packageVersion:b6});var Vbe=Ms("core-lro");var Rbe=class t extends Error{constructor(e){super(e),this.name="PollerStoppedError",Object.setPrototypeOf(this,t.prototype)}},ybe=class t extends Error{constructor(e){super(e),this.name="PollerCancelledError",Object.setPrototypeOf(this,t.prototype)}},_f=class{constructor(e){this.resolveOnUnsuccessful=!1,this.stopped=!0,this.pollProgressCallbacks=[],this.operation=e,this.promise=new Promise((I,l)=>{this.resolve=I,this.reject=l}),this.promise.catch(()=>{})}async startPolling(e={}){for(this.stopped&&(this.stopped=!1);!this.isStopped()&&!this.isDone();)await this.poll(e),await this.delay()}async pollOnce(e={}){this.isDone()||(this.operation=await this.operation.update({abortSignal:e.abortSignal,fireProgress:this.fireProgress.bind(this)})),this.processUpdatedState()}fireProgress(e){for(let I of this.pollProgressCallbacks)I(e)}async cancelOnce(e={}){this.operation=await this.operation.cancel(e)}poll(e={}){if(!this.pollOncePromise){this.pollOncePromise=this.pollOnce(e);let I=()=>{this.pollOncePromise=void 0};this.pollOncePromise.then(I,I).catch(this.reject)}return this.pollOncePromise}processUpdatedState(){if(this.operation.state.error&&(this.stopped=!0,!this.resolveOnUnsuccessful))throw this.reject(this.operation.state.error),this.operation.state.error;if(this.operation.state.isCancelled&&(this.stopped=!0,!this.resolveOnUnsuccessful)){let e=new ybe("Operation was canceled");throw this.reject(e),e}this.isDone()&&this.resolve&&this.resolve(this.getResult())}async pollUntilDone(e={}){return this.stopped&&this.startPolling(e).catch(this.reject),this.processUpdatedState(),this.promise}onProgress(e){return this.pollProgressCallbacks.push(e),()=>{this.pollProgressCallbacks=this.pollProgressCallbacks.filter(I=>I!==e)}}isDone(){let e=this.operation.state;return!!(e.isCompleted||e.isCancelled||e.error)}stopPolling(){this.stopped||(this.stopped=!0,this.reject&&this.reject(new Rbe("This poller is already stopped")))}isStopped(){return this.stopped}cancelOperation(e={}){if(!this.cancelPromise)this.cancelPromise=this.cancelOnce(e);else if(e.abortSignal)throw new Error("A cancel request is currently pending");return this.cancelPromise}getOperationState(){return this.operation.state}getResult(){return this.operation.state.result}toString(){return this.operation.toString()}};var UX=class extends _f{constructor(){super(...arguments),this.intervalInMs=2e3}async delay(){return UN(this.intervalInMs)}},SX=class{constructor(e,I={}){this.state=e,this.cancelMessage="",I.cancelMessage&&(this.cancelMessage=I.cancelMessage)}async update(){throw new Error("Operation not supported.")}async cancel(){throw new Error(this.cancelMessage)}toString(){return JSON.stringify({state:this.state})}};var m6=class extends SX{constructor(e,I,l={}){super(e,{cancelMessage:"Canceling the deletion of a secret is not supported."}),this.state=e,this.client=I,this.operationOptions=l}deleteSecret(e,I={}){return Do.withSpan("DeleteSecretPoller.deleteSecret",I,async l=>{let n=await this.client.deleteSecret(e,l);return za(n)})}getDeletedSecret(e,I={}){return Do.withSpan("DeleteSecretPoller.getDeletedSecret",I,async l=>{let n=await this.client.getDeletedSecret(e,l);return za(n)})}async update(e={}){let I=this.state,{name:l}=I;if(e.abortSignal&&(this.operationOptions.abortSignal=e.abortSignal),!I.isStarted){let n=await this.deleteSecret(l,this.operationOptions);I.isStarted=!0,I.result=n,n.properties.recoveryId||(I.isCompleted=!0)}if(!I.isCompleted)try{I.result=await this.getDeletedSecret(l,this.operationOptions),I.isCompleted=!0}catch(n){if(n.statusCode===403)I.isCompleted=!0;else if(n.statusCode!==404)throw I.error=n,I.isCompleted=!0,n}return this}};var h6=class extends UX{constructor(e){let{client:I,name:l,operationOptions:n,intervalInMs:c=2e3,resumeFrom:r}=e,s;r&&(s=JSON.parse(r).state);let a=new m6(Object.assign(Object.assign({},s),{name:l}),I,n);super(a),this.intervalInMs=c}};var p6=class extends SX{constructor(e,I,l={}){super(e,{cancelMessage:"Canceling the recovery of a deleted secret is not supported."}),this.state=e,this.client=I,this.options=l}getSecret(e,I={}){return Do.withSpan("RecoverDeletedSecretPoller.getSecret",I,async l=>{let n=await this.client.getSecret(e,I&&I.version?I.version:"",l);return za(n)})}recoverDeletedSecret(e,I={}){return Do.withSpan("RecoverDeletedSecretPoller.recoverDeletedSecret",I,async l=>{let n=await this.client.recoverDeletedSecret(e,l);return za(n)})}async update(e={}){let I=this.state,{name:l}=I;if(e.abortSignal&&(this.options.abortSignal=e.abortSignal),!I.isStarted){try{I.result=(await this.getSecret(l,this.options)).properties,I.isCompleted=!0}catch{}I.isCompleted||(I.result=(await this.recoverDeletedSecret(l,this.options)).properties,I.isStarted=!0)}if(!I.isCompleted)try{I.result=(await this.getSecret(l,this.options)).properties,I.isCompleted=!0}catch(n){if(n.statusCode===403)I.isCompleted=!0;else if(n.statusCode!==404)throw I.error=n,I.isCompleted=!0,n}return this}};var u6=class extends UX{constructor(e){let{client:I,name:l,operationOptions:n,intervalInMs:c=2e3,resumeFrom:r}=e,s;r&&(s=JSON.parse(r).state);let a=new p6(Object.assign(Object.assign({},s),{name:l}),I,n);super(a),this.intervalInMs=c}};var Z6=class{constructor(e,I,l={}){var n,c;this.vaultUrl=e;let r=Object.assign(Object.assign({},l),{userAgentOptions:{userAgentPrefix:`${(c=(n=l.userAgentOptions)===null||n===void 0?void 0:n.userAgentPrefix)!==null&&c!==void 0?c:""} azsdk-js-keyvault-secrets/${b6}`},apiVersion:l.serviceVersion||"7.6",loggingOptions:{logger:kze.info,additionalAllowedHeaderNames:["x-ms-keyvault-region","x-ms-keyvault-network-info","x-ms-keyvault-service-version"]}});this.client=new qf(this.vaultUrl,I,r),this.client.pipeline.removePolicy({name:PD}),this.client.pipeline.addPolicy(tUe(I,l),{}),this.client.pipeline.addPolicy({name:"ContentTypePolicy",sendRequest(s,a){var o;return((o=s.headers.get("Content-Type"))!==null&&o!==void 0?o:"").startsWith("application/json")&&s.headers.set("Content-Type","application/json"),a(s)}})}setSecret(e,I,l={}){let{enabled:n,notBefore:c,expiresOn:r,tags:s}=l,a=IL(l,["enabled","notBefore","expiresOn","tags"]);return Do.withSpan("SecretClient.setSecret",a,async o=>{let G=await this.client.setSecret(e,{value:I,secretAttributes:{enabled:n,notBefore:c,expires:r},tags:s},o);return za(G)})}async beginDeleteSecret(e,I={}){let l=new h6(Object.assign(Object.assign({name:e,client:this.client},I),{operationOptions:I}));return await l.poll(),l}async updateSecretProperties(e,I,l={}){let{enabled:n,notBefore:c,expiresOn:r,tags:s}=l,a=IL(l,["enabled","notBefore","expiresOn","tags"]);return Do.withSpan("SecretClient.updateSecretProperties",a,async o=>{let G=await this.client.updateSecret(e,I,{secretAttributes:{enabled:n,notBefore:c,expires:r},tags:s},o);return za(G).properties})}getSecret(e,I={}){return Do.withSpan("SecretClient.getSecret",I,async l=>{let n=await this.client.getSecret(e,I&&I.version?I.version:"",l);return za(n)})}getDeletedSecret(e,I={}){return Do.withSpan("SecretClient.getDeletedSecret",I,async l=>{let n=await this.client.getDeletedSecret(e,l);return za(n)})}purgeDeletedSecret(e,I={}){return Do.withSpan("SecretClient.purgeDeletedSecret",I,async l=>{await this.client.purgeDeletedSecret(e,l)})}async beginRecoverDeletedSecret(e,I={}){let l=new u6(Object.assign(Object.assign({name:e,client:this.client},I),{operationOptions:I}));return await l.poll(),l}backupSecret(e,I={}){return Do.withSpan("SecretClient.backupSecret",I,async l=>(await this.client.backupSecret(e,l)).value)}restoreSecretBackup(e,I={}){return Do.withSpan("SecretClient.restoreSecretBackup",I,async l=>{let n=await this.client.restoreSecret({secretBundleBackup:e},l);return za(n).properties})}listPropertiesOfSecretVersions(e,I={}){return d6(l=>this.client.getSecretVersions(e,l),I,l=>za(l).properties)}listPropertiesOfSecrets(e={}){return d6(this.client.getSecrets.bind(this.client),e,I=>za(I).properties)}listDeletedSecrets(e={}){return d6(this.client.getDeletedSecrets.bind(this.client),e,za)}};var gbe=class{client;logger;constructor(e,I){if(this.logger=I,e){this.logger.debug(`Using Azure Key Vault at ${e}`);let l=new nh;this.client=new Z6(e,l)}else this.logger.debug("No Azure Key Vault URI provided, secret provider disabled")}async getSecret(e){if(this.client)try{return(await this.client.getSecret(e)).value}catch(I){if(this.logger.warning(`Error fetching secret ${e}: ${I}`),I?.code==="SecretNotFound")return;throw I}}};function nUe(t,e){let I=t.api?.copilot?.azureKeyVaultUri;return Fbe(I,e)}function Fbe(t,e){return new gbe(t,e)}import{createHmac as lkI}from"crypto";var W6=class t{static encode(e){let I=t.hmacGetBytes(e),r=(Math.floor(Date.now()/1e3)+30).toString(),s=Buffer.from(r,"ascii"),G=lkI("sha256",I).update(s).digest().toString("hex").toUpperCase();return`${r}.${G}`}static hmacGetBytes(e){return Buffer.from(e,"ascii")}};var nkI="X-GitHub-Api-Version",ckI="2025-05-01",N6=class t extends JI{constructor(I,l,n,c){super({baseURL:I,apiKey:"",logLevel:_v()?"debug":"info"});this.headers=l;this.runnerLogger=n;this.hmacKey=c}static baseHeaders={"Content-Type":"application/json",Accept:"application/json","X-Interaction-Type":"conversation-agent","Openai-Intent":"conversation-agent","X-Initiator":"user",[nkI]:ckI};hmacKey;additionalHeaders={};static createWithOAuthToken(I,l,n,c,r,s){let a={...this.defaultHeaders(n,r),Authorization:`Bearer ${c}`,...s??{}};return I.debug(`Creating copilot-client for integration ID ${n} with token authentication. User-agent: ${a["User-Agent"]}`),new t(l,a,I)}static createWithHmac(I,l,n,c,r,s,a){let o={...this.defaultHeaders(n,r),Authorization:"",...a??{}};return s&&(o["X-GitHub-User"]=s),I.debug(`Creating copilot-client for integration ID ${n} with key authentication. User-agent: ${o["User-Agent"]}`),new t(l,o,I,c)}static defaultHeaders(I,l){let n=Ibe();return{...t.baseHeaders,"Copilot-Integration-Id":I,"User-Agent":`${n.nameNoScope}/${n.version} (${process.platform} ${process.version}) OpenAI/${Nh}`,"X-Interaction-Id":l}}async prepareOptions(I){this.hmacKey&&(this.headers["Request-HMAC"]=W6.encode(this.hmacKey)),I.headers={...this.headers,...this.additionalHeaders,...I.headers},await super.prepareOptions(I)}setInitiatorHeader(I){this.headers["X-Initiator"]=I}setAdditionalHeaders(I){this.additionalHeaders=I}async listModels(){let I={method:"get",path:""};await this.prepareOptions(I);let l={};if(I.headers)for(let[s,a]of Object.entries(I.headers))typeof a=="string"&&(l[s]=a);let n=`${this.baseURL}/models`,c=await fetch(n,{method:I.method,headers:l});if(!c.ok)return this.runnerLogger.error(`Failed to list models: ${c.status} ${c.statusText}: ${await c.text()}`),c.status===421&&this.runnerLogger.error(`Verify the authenticated user against subscription-based Copilot API endpoint used: ${this.baseURL}`),[];let r=await c.json();return this.runnerLogger.debug(`Successfully listed ${r.data.length} models`),r.data}},OX=class{async createClient(e,I,l){I.startGroup("configured settings:",8),I.debug(JSON.stringify(e,null,2)),I.endGroup(8);let n=e.api?.copilot?.token,c=e.api?.copilot?.hmacKey,r=!!(c||n);if(!r){I.debug("No Copilot HMAC key or GitHub OAuth token provided, trying secret provider");let i=nUe(e,I);try{c=await i.getSecret("capi-hmac-key")}catch(d){I.debug(`Failed to get Copilot HMAC key from secret provider:
|
|
607
607
|
${d}`)}try{n=await i.getSecret("capi-token")}catch(d){I.debug(`Failed to get Copilot GitHub OAuth token from secret provider:
|
|
608
|
-
${d}`)}r=!!(c||n)}let s,a=x2e(e),o=$v(e),G=e.api?.copilot?.sessionId??Dp(e);if(I.debug(`Using Copilot API at ${a} with integration ID ${o}`),n&&(I.debug("Using GitHub OAuth token for Copilot API"),s=N6.createWithOAuthToken(I,a,o,n,G,l?.requestHeaders)),c){I.debug("Using Copilot HMAC key for Copilot API");let i=process.env.GITHUB_USER_ID;i?I.debug(`Using user ID ${i} for Copilot HMAC key`):I.debug("No user ID provided for Copilot HMAC key"),s=N6.createWithHmac(I,a,o,c,G,i,l?.requestHeaders)}if(s===void 0)throw new Error("No GitHub OAuth token or Copilot HMAC key provided");return s}},MX=class t extends dc{request_id;constructor(e){super(e.status,e.error,e.message,e.headers),this.name="CAPIError",this.cause=e.cause,this.ghRequestId=e.headers?.get("x-github-request-id")||this.requestID,this.request_id=this.requestID}ghRequestId;static fromAPIError(e){if(!(!e||!(e instanceof dc)))return new t(e)}};var Abe={type:"ephemeral"},CY=class t{constructor(e,I,l,n){this.settings=I;this.logger=l;this.clientOptions=t.initDefaultOptions(n),l.info(" "),l.debug(`Using model: ${this.model}`),this.clientPromise=e.createClient(I,l,n),this.modelPromise=this.clientPromise.then(async()=>{let c=await this.getModel();return l.debug(`Got model info: ${JSON.stringify(c,null,2)}`),c})}clientOptions;clientPromise;modelPromise;get model(){return this.clientOptions.model}static initDefaultOptions(e){return{model:e?.model||kde.model,toolTokenBudgetProportion:e?.toolTokenBudgetProportion??.25,retryPolicy:{maxRetries:e?.retryPolicy?.maxRetries??5,errorCodesToRetry:e?.retryPolicy?.errorCodesToRetry??[],rateLimitRetryPolicy:{defaultRetryAfterSeconds:e?.retryPolicy?.rateLimitRetryPolicy?.defaultRetryAfterSeconds??5,initialRetryBackoffExtraSeconds:e?.retryPolicy?.rateLimitRetryPolicy?.initialRetryBackoffExtraSeconds??1,retryBackoffExtraGrowth:e?.retryPolicy?.rateLimitRetryPolicy?.retryBackoffExtraGrowth??2,maxRetryAfterSeconds:e?.retryPolicy?.rateLimitRetryPolicy?.maxRetryAfterSeconds??180}},thinkingMode:e?.thinkingMode??!1,requestHeaders:e?.requestHeaders??{}}}getCompletionOptions(e,I){let l={snippy:{enabled:!1}};return{temperature:0,top_p:.95,frequency_penalty:0,presence_penalty:0,tool_choice:I?.toolChoice,...l}}makeRequest(e,I,l,n,c,r,s){return e.chat.completions.create({model:I,messages:[...l],...n,tools:c},{maxRetries:r,headers:s?.requestHeaders,signal:s?.abortSignal}).withResponse()}makeRequestStreaming(e,I,l,n,c,r,s){return e.chat.completions.create({model:I,messages:[...l],...n,tools:c,stream:!0,stream_options:{include_usage:!0}},{maxRetries:r,headers:s?.requestHeaders,signal:s?.abortSignal}).withResponse()}async*getCompletionWithTools(e,I,l,n){let c=this.model,r=await this.clientPromise,s=await this.modelPromise,a=ZN(l),o=[{role:"system",content:e,copilot_cache_control:Abe},...I.map(h=>zf(h))],G=l.map((h,u)=>({type:"function",function:{name:h.name,description:h.description,parameters:h.input_schema},copilot_cache_control:u===l.length-1?Abe:void 0}));this.logger.startGroup("Completion request configuration: ",8),this.logger.debug("Client options: "),this.logger.debug(JSON.stringify(this.clientOptions,null,2)),this.logger.debug("Request options: "),this.logger.debug(JSON.stringify(n??{},null,2)),this.logger.debug("Tools: "),this.logger.debug(JSON.stringify(G,null,2)),this.logger.endGroup(8);let i=this.getCompletionOptions(l,n),d=n?.initialTurnCount!==void 0?n.initialTurnCount+1:0,b=!1,m=!1;for(;!b&&!m;){let h=Date.now();yield{kind:"turn_started",model:c,modelInfo:s,turn:d,timestampMs:h};let u=0,Z=0,N=0,g=[429,503,500,400],y=this.clientOptions.retryPolicy.maxRetries,F=this.clientOptions.retryPolicy.rateLimitRetryPolicy.initialRetryBackoffExtraSeconds,f=0,v=this.clientOptions.retryPolicy.rateLimitRetryPolicy.maxRetryAfterSeconds,X,C;try{let L=[],U;do{N>0&&(yield{kind:"turn_retry",model:c,modelInfo:s,turn:d,timestampMs:Date.now()});try{let Ie={};for(let Ae of n?.processors?.preRequest||[]){let pe=Ae.preRequest({turn:d,retry:N,messages:o,toolDefinitions:G,modelInfo:s,additionalRequestHeaders:Ie,getCompletionWithToolsOptions:n});for await(let Fe of pe)yield Fe}if(this.logger.startGroup("Sending request to the AI model",8),hl(this.settings,"copilot_swe_agent_request_logging")){let Ae=JSON.stringify(o,null,2),pe=JSON.stringify(i,null,2);this.logger.debug(`Request messages: ${Ae}`),this.logger.debug(`Request options: ${pe}`)}L=o.map((Ae,pe)=>pe===o.length-1?{...Ae,copilot_cache_control:Abe}:Ae),u=Date.now(),r.setAdditionalHeaders(Ie);let Ge;if(n?.stream){let Ae=await this.makeRequestStreaming(r,c,L,i,G,y,n);Ge=await skI(Ae,r,n)}else Ge=await this.makeRequest(r,c,L,i,G,y,n);Z=Date.now()-u,X=Ge.data,U={model:c,api_id:X.id,request_id:Ge.response.headers.get("x-github-request-id")||void 0,initiator:n?.requestHeaders?.["X-Initiator"]||Ie["X-Initiator"]};let Qe={};Ge.response.headers.forEach((Ae,pe)=>{if(pe.toLowerCase().startsWith(xde)){let Fe=cze(Ae);Fe&&(Qe[pe.replace(xde,"")]=Fe)}}),yield{kind:"model_call_success",turn:d,callId:n?.callId,modelCallDurationMs:Z,modelCall:U,responseChunk:tze(X),responseUsage:X.usage,requestMessages:JSON.stringify(L),quotaSnapshots:Qe},this.logger.debug(`response (Request-ID ${Ge.request_id}):`),this.logger.debug("data:"),this.logger.debug(JSON.stringify(Ge.data,null,2))}catch(Ie){Z=Date.now()-u;let Ge=MX.fromAPIError(Ie),Qe=Ge?.error;if(Ge){yield{kind:"model_call_failure",turn:d,modelCallDurationMs:Z,requestMessages:JSON.stringify(L),modelCall:{model:c,status:Ge.status,error:JSON.stringify(Ge?.error||Ge?.message||"unknown error"),api_id:Ge.requestID||void 0,request_id:Ge.headers?.get("x-github-request-id")||""}},C=Ge;let pe=Ge.ghRequestId||Ge.headers?.get("x-github-request-id")||Ge.requestID;this.logger.error(`error (Request-ID ${pe})`),this.logger.error(JSON.stringify(Ge,Object.getOwnPropertyNames(Ge),2)),this.logger.debug(`Failed to get response from the AI model: ${Ge}`),Qe&&this.logger.debug(`Inner error: ${JSON.stringify(Qe,null,2)}`);let Fe;for(let _e of n?.processors?.onRequestError||[])Fe=await _e.onRequestError({turn:d,retry:N,maxRetries:y,error:Qe,modelInfo:s,getCompletionWithToolsOptions:n})||Fe;let me=Ge.status,uI=me?this.clientOptions.retryPolicy.errorCodesToRetry.some(_e=>Array.isArray(_e)?me>=_e[0]&&(_e[1]===void 0||me<=_e[1]):me===_e):!1,ve;if(Fe)ve=Fe.retryAfter;else if(Ge.status!==402){if(Ge.status===413){this.logger.debug("Request is too large, trying to remove images from the request");let _e=0;for(let Nl=o.length-1;Nl>=0;Nl--)l0(o[Nl])&&(o.splice(Nl,1),_e++,yield{kind:"images_removed",turn:d,imagesRemoved:1,largeImagesRemoved:1});_e>0?(this.logger.info(`Images have been removed from the request due to size constraints. Please resize images to be smaller than ${zm(s.capabilities.limits.vision?.max_prompt_image_size||0)}.`),this.logger.debug(`Removed ${_e} image messages from the request`),ve=1):this.logger.debug("No image messages found in the request - unsure why the request is too large - will fail")}else if((typeof Ge.status=="number"&&g.includes(Ge.status)||uI)&&(ve=parseInt(Ge.headers?.get("retry-after")||`${this.clientOptions.retryPolicy.rateLimitRetryPolicy.defaultRetryAfterSeconds}`,10)+F,F*=this.clientOptions.retryPolicy.rateLimitRetryPolicy.retryBackoffExtraGrowth,N==y-1))for(let _e=o.length-1;_e>=0;_e--)l0(o[_e])&&(this.logger.debug(`Removing image message at index ${_e} to avoid failure`),o.splice(_e,1),yield{kind:"images_removed",turn:d,imagesRemoved:1})}if(ve!==void 0&&ve<=v){let _e=.8+Math.random()*.4,Nl=ve*_e;this.logger.debug(`Retrying after ${Nl} seconds...`),await new Promise(xI=>setTimeout(xI,Nl*1e3)),f+=Nl,this.logger.debug(`Retrying after ${ve} seconds... Will try again now!`);continue}else ve?this.logger.error(`Retry after ${ve} seconds is too long. Giving up.`):this.logger.error("Retry after is not set. Giving up.")}let Ae=Ge||Ie;for(let pe of n?.processors?.onRequestError||[])await pe.preErrorThrow(Ie);throw this.logger.error("error"),this.logger.error(JSON.stringify(Ae,null,2)),Ae}finally{r.setAdditionalHeaders({}),this.logger.endGroup(8)}}while(!X&&N++<y);if(!X){this.logger.debug("Recent messages prior to failure:");for(let Ge=Math.max(0,o.length-6);Ge<o.length;Ge++)this.logger.debug(`${Ge}: ${JSON.stringify(o[Ge],null,2)}`);let Ie=new Error(`Failed to get response from the AI model; retried ${N-1} times (total retry wait time: ${f} seconds)`,{cause:C});throw this.isRateLimitExceededError(Ie)&&(this.logger.info(`Rate limit exceeded after ${N-1} retries, will fail job but skip Sentry reporting`),Ie.skipReport=!0),Ie}for(let Ie of X.choices.map(Ge=>Ge.message))rkI(Ie.tool_calls||[]),o.push(Ie),yield{kind:"message",turn:d,callId:n?.callId,modelCall:U,message:zf(mX(Ie))};if(this.isToolCallResponse(X)){let Ge=(s.capabilities.limits.max_prompt_tokens||s.capabilities.limits.max_context_window_tokens)*this.clientOptions.toolTokenBudgetProportion,Qe=dve(c,Ge,this,this.settings),pe=X.choices.filter(ve=>ve.message.tool_calls!==void 0).flatMap(ve=>ve.message.tool_calls||[]).filter(AG),Fe=new Map;for(let ve of n?.processors?.preToolsExecution||[]){let _e=await ve.preToolsExecution({turn:d,toolCalls:pe,modelInfo:s});if(_e)for(let[Nl,xI]of _e)Fe.set(Nl,xI)}let me=pe.filter(ve=>!Fe.has(ve.id)),uI=this.mergeToolResults(Fe,pe,me,a,Qe,n?.executeToolsInParallel);for await(let ve of uI){ve.toolResult.resultType==="rejected"&&(m=!0);let _e={role:"tool",tool_call_id:ve.originalCall.id,content:ve.toolResult.textResultForLlm};o.push(_e),yield{kind:"message",turn:d,callId:n?.callId,modelCall:U,message:zf(_e)},yield{kind:"tool_execution",turn:d,callId:n?.callId,toolCallId:ve.originalCall.id,toolResult:ve.toolResult,durationMs:ve.durationMs};for(let Nl of n?.processors?.postToolExecution||[])await Nl.postToolExecution({toolCall:ve.originalCall,toolResult:ve.toolResult,turn:d,modelInfo:s})}}else for(let Ie of X.choices.map(Ge=>Ge.message))yield{kind:"response",turn:d,callId:n?.callId,modelCall:{model:c,api_id:X.id},response:zf(mX(Ie))},b=!0}catch(L){let U;throw L instanceof Error&&L.cause&&L.cause instanceof MX?U=`${L} (Cause: ${L.cause})`:U=`${L}`,yield{kind:"turn_failed",model:c,modelInfo:s,turn:d,error:U,timestampMs:Date.now()},L}finally{let L=Date.now();yield{kind:"turn_ended",model:c,modelInfo:s,turn:d,timestampMs:L},d++}}}async*mergeToolResults(e,I,l,n,c,r=!1){for(let[s,a]of e){let o=I.find(G=>G.id===s);o&&(yield{durationMs:0,originalCall:o,toolResult:a})}l.length>0&&(yield*this.callTools(l,n,c,r))}async*callTools(e,I,l,n=!1){if(e.length===0)throw new Error("Tool call is missing");this.logger.debug(`Tool calls count: ${e.length}`);let c=e.some(s=>{let a=I[s.function.name];return dX(a)}),r=n&&!c;if(c&&n&&this.logger.debug("Custom agent detected in tool calls, forcing sequential execution"),r)this.logger.debug("Running tool calls in parallel"),yield*rve(e.map(s=>()=>this.callTool(s,I,l)));else{this.logger.debug("Running tool calls sequentially");for(let s of e)yield await this.callTool(s,I,l)}}async callTool(e,I,l){let n=0,c=e?.function.name;if(!c)throw new Error("Tool name is missing");let r=e?.function.arguments;if(r==null)throw new Error("Tool call arguments are missing");let s=e?.id;if(!s)throw new Error("Tool call id is missing");let a,o=I[c];try{let G=bX(r);if(!o||!o.callback)a={textResultForLlm:`Tool '${c}' does not exist. Available tools that can be called are ${Object.keys(I).join(", ")}.`,resultType:"failure",error:`Tool '${c}' does not exist.`,sessionLog:`<error>Tool '${c}' does not exist.</error>`,toolTelemetry:{}};else{let i=o.callback,d=Date.now(),b={...l,toolCallId:s,toolOptions:this.settings.service?.tools?.[c]},m=await i({...G},b);n=Date.now()-d,a=typeof m=="string"?{textResultForLlm:m,resultType:"success",toolTelemetry:{}}:m}}catch(G){G instanceof SyntaxError?(a={textResultForLlm:`The arguments for the tool call '${c}' were not valid JSON. The arguments have been cleared. Arguments: ${r}. JSON parse error: ${G.message}`,resultType:"failure",error:`${G.message}`,sessionLog:`<error>Failed to execute \`${c}\` tool with arguments: ${r} due to syntax error: ${G.message}</error>`,toolTelemetry:{properties:{wasSyntaxError:"true"}}},e.function.arguments="{}"):a={textResultForLlm:`Failed to execute \`${c}\` tool with arguments: ${r} due to error: ${G}`,resultType:"failure",error:G instanceof Error?G.message:`${G}`,sessionLog:`<error>Failed to execute \`${c}\` tool with arguments: ${r}</error>`,toolTelemetry:{}}}return{durationMs:n,originalCall:e,toolResult:a}}isToolCallResponse(e){return e.choices.find(I=>I.message.tool_calls!==void 0)!==void 0}isRateLimitExceededError(e){if(e instanceof Error){if(e.message?.includes("exceeded maximum number of retries")&&e.message?.includes("rate-limited requests"))return!0;if(e.message?.includes("Failed to get response from the AI model")&&e.cause instanceof MX)return e.cause.status===429}return!1}async getModel(){let e=this.clientOptions.model,I={id:e,name:e,capabilities:{supports:{vision:!1},limits:{max_prompt_tokens:9e4,max_context_window_tokens:128e3,vision:{max_prompt_image_size:3145728,max_prompt_images:1,supported_media_types:["image/jpeg","image/png","image/webp"]}}}};return(await(await this.clientPromise).listModels()).filter(r=>r.id===e).at(0)||I}};function rkI(t){for(let e of t)e.function.name=e.function.name.replace(/[^a-zA-Z0-9_-]+/g,"_")}async function skI(t,e,I){let l=akI(t.data,e).toReadableStream(),n=iZ.fromReadableStream(l),c=I?.processors?.onStreamingChunk;if(c?.length)for await(let r of n){I?.abortSignal?.throwIfAborted();let s={chunk:r};for(let a of c)a.onStreamingChunk(s)}return{data:await n.finalChatCompletion(),response:t.response,request_id:t.request_id}}function akI(t,e){let I=new Map;return new dd(async function*(){for await(let l of t)l.choices?.forEach(n=>{if(n.delta.role??="assistant",!!n.delta?.tool_calls?.length){n.finish_reason??="tool_calls";let r=I.get(n.index);r||(r={nextSequenceNumber:0,mappings:new Map},I.set(n.index,r)),n.delta.tool_calls?.forEach(s=>{let a=r.mappings.get(s.index);if(a!==void 0)s.id&&a.callId!==s.id&&(a.sequenceNumber=r.nextSequenceNumber++,a.callId=s.id),s.index=a.sequenceNumber;else{let o={callId:s.id,sequenceNumber:r.nextSequenceNumber++};r.mappings.set(s.index,o),s.index=o.sequenceNumber}})}}),yield l},t.controller,e)}var Y6=class extends CY{constructor(e,I,l){let n=new OX;super(n,e,I,l)}};var V6=class t{constructor(e,I,l,n){this.settings=I;this.logger=l;this.clientOptions=t.initDefaultOptions(n),this.logger.info(`Using responses with model: ${this.model}`),this.clientPromise=e.createClient(I,l,this.clientOptions)}clientOptions;clientPromise;get model(){return this.clientOptions.model}static initDefaultOptions(e){return{model:e?.model||"o4-mini",toolTokenBudgetProportion:e?.toolTokenBudgetProportion??.25,retryPolicy:{maxRetries:e?.retryPolicy?.maxRetries??5,errorCodesToRetry:e?.retryPolicy?.errorCodesToRetry??[],rateLimitRetryPolicy:{defaultRetryAfterSeconds:e?.retryPolicy?.rateLimitRetryPolicy?.defaultRetryAfterSeconds??5,initialRetryBackoffExtraSeconds:e?.retryPolicy?.rateLimitRetryPolicy?.initialRetryBackoffExtraSeconds??1,retryBackoffExtraGrowth:e?.retryPolicy?.rateLimitRetryPolicy?.retryBackoffExtraGrowth??2,maxRetryAfterSeconds:e?.retryPolicy?.rateLimitRetryPolicy?.maxRetryAfterSeconds??60}},thinkingMode:e?.thinkingMode??!0,requestHeaders:e?.requestHeaders??{}}}makeRequest(e,I,l,n,c,r,s,a){return e.responses.create({model:I,previous_response_id:r,instructions:l,input:n,parallel_tool_calls:c.length>0?!0:void 0,tools:c,reasoning:{summary:"auto",effort:"medium"},store:!1,include:["reasoning.encrypted_content"]},{maxRetries:s||this.clientOptions.retryPolicy.maxRetries,headers:a?.requestHeaders,signal:a?.abortSignal}).withResponse()}async*getCompletionWithTools(e,I,l,n){let c=await this.clientPromise,r=ZN(l),s=l.map(u=>({name:u.name,description:u.description,parameters:u.input_schema,strict:!1,type:"function"})),a=0,o=this.clientOptions.retryPolicy.maxRetries,G=this.clientOptions.retryPolicy.rateLimitRetryPolicy.initialRetryBackoffExtraSeconds,i=0,d=this.clientOptions.retryPolicy.rateLimitRetryPolicy.maxRetryAfterSeconds,b=I.flatMap(wbe),m,h=!1;for(;!h;){let u;do{u=void 0;try{let Z=await this.makeRequest(c,this.model,e,b,s,void 0,o,n);m=Z.data,b.push(...m.output),this.logger.debug(`response (Request-ID ${Z.request_id}):`),this.logger.debug("data:"),this.logger.debug(JSON.stringify(Z.data,null,2))}catch(Z){let N=Z,g=N.error;if(N){u=N,this.logger.error(`error (Request-ID ${N.requestID})`),this.logger.error(JSON.stringify(N,null,2)),this.logger.debug(`Failed to get response from the AI model: ${N}`),g&&this.logger.debug(`Inner error: ${JSON.stringify(g,null,2)}`);let y=N.status,F=y?this.clientOptions.retryPolicy.errorCodesToRetry.some(v=>Array.isArray(v)?y>=v[0]&&(v[1]===void 0||y<=v[1]):y===v):!1,f;if((N.status===429||F)&&(f=parseInt(N.headers?.get("retry-after")||`${this.clientOptions.retryPolicy.rateLimitRetryPolicy.defaultRetryAfterSeconds}`,10)+G,G*=this.clientOptions.retryPolicy.rateLimitRetryPolicy.retryBackoffExtraGrowth),f!==void 0&&f<=d){this.logger.debug(`Retrying after ${f} seconds...`),await new Promise(v=>setTimeout(v,f*1e3)),i+=f,this.logger.debug(`Retrying after ${f} seconds... Will try again now!`);continue}else f?this.logger.error(`Retry after ${f} seconds is too long. Giving up.`):this.logger.error("Retry after is not set. Giving up.")}throw this.logger.error("error"),this.logger.error(JSON.stringify(Z,null,2)),Z}finally{this.logger.endGroup(8)}}while(u&&a++<o);if(!m||u){this.logger.debug("Recent messages prior to failure:");for(let Z=Math.max(0,b.length-6);Z<b.length;Z++)this.logger.debug(`${Z}: ${JSON.stringify(b[Z],null,2)}`);throw new Error(`Failed to get response from the AI model; retried ${a-1} times (total retry wait time: ${i} seconds)`,{cause:u})}for(let Z of m.output)yield{kind:"message",message:Qbe(Z)};if(this.requiresToolOutput(m)){let N=(await this.runTool(m,r)).map(g=>({type:"function_call_output",call_id:g.toolCallId,output:g.textResultForLlm}));b.push(...N);for(let g of N)yield{kind:"message",message:Qbe(g)}}else yield{kind:"response",response:{content:m.output_text,refusal:null,role:"assistant"}},h=!0}}async runTool(e,I,l){let n=e.output.filter(r=>r.type==="function_call");if(!n||n.length===0)throw new Error("Tool calls in response are missing");let c=[];for(let r of n){let s=r.name;if(!s)throw new Error("Tool name is missing");let a=r.arguments;if(!a)throw new Error("Tool call arguments are missing");let o=r.call_id;if(!o)throw new Error("Tool call id is missing");let G,i=I[s];try{let d=bX(a);if(!i||!i.callback)G={textResultForLlm:`Tool '${s}' does not exist. Available tools that can be called are ${Object.keys(I).join(", ")}.`,resultType:"failure",error:`Tool '${s}' does not exist.`,sessionLog:`<error>Tool '${s}' does not exist.</error>`,toolTelemetry:{}};else{let b=i.callback,m={...l,toolCallId:o,toolOptions:this.settings.service?.tools?.[s],settings:this.settings},h=await b({...d},m);G=typeof h=="string"?{textResultForLlm:h,resultType:"success",toolTelemetry:{}}:h}}catch(d){G={textResultForLlm:`Failed to execute \`${s}\` tool with arguments: ${a} due to error: ${d}`,resultType:"failure",error:d instanceof Error?d.message:`${d}`,sessionLog:`<error>Failed to execute \`${s}\` tool with arguments: ${a}</error>`,toolTelemetry:{properties:{wasSyntaxError:d instanceof SyntaxError?"true":"false"}}}}c.push({toolCallId:o,textResultForLlm:G.textResultForLlm,sessionLog:G.resultType=="success"?G.sessionLog:G.error?`<error>${G.error}</error>`:void 0})}return c}requiresToolOutput(e){return e.output.filter(I=>I.type==="function_call").length>0}};function wbe(t){if(t.role==="function")throw new Error("Function role is not supported");let e=[];if(t.reasoning_opaque&&e.push({id:t.reasoning_opaque,type:"reasoning",summary:t.reasoning_text?[{text:t.reasoning_text,type:"summary_text"}]:[],encrypted_content:t.encrypted_content}),t.role==="assistant"&&t.tool_calls&&t.tool_calls.length>0&&AG(t.tool_calls[0])){let I=t.tool_calls[0];return[...e,{type:"function_call",id:t.id,name:I.function.name,arguments:I.function.arguments,call_id:I.id}]}if(t.role==="tool")return[...e,{type:"function_call_output",id:`fc_${t.tool_call_id}`,call_id:t.tool_call_id,output:typeof t.content=="string"?t.content:t.content.map(I=>I.text).join(" ")??""}];if(!t.content)return e;if(t.role==="assistant"){let I=t.id||crypto.randomUUID();return I.startsWith("msg_")||(I=`msg_${I}`),[...e,{type:"message",id:I,role:t.role,content:[{annotations:[],type:"output_text",text:typeof t.content=="string"?t.content:t.content?.map(l=>l.type==="text"?l.text:"").join(" ")??""}],status:"completed"}]}return[...e,{role:t.role,content:typeof t.content=="string"?[{type:"input_text",text:t.content}]:t.content.map(I=>{if(I.type==="text")return{type:"input_text",text:I.text};if(I.type==="image_url")return{type:"input_image",detail:I.image_url.detail||"auto",image_url:I.image_url.url}}).filter(I=>I!==void 0),type:"message"}]}function Qbe(t){if(t.type==="reasoning")return{role:"assistant",reasoning_opaque:t.id,reasoning_text:t.summary?t.summary.map(e=>e.text).join(" "):void 0,content:"",encrypted_content:t.encrypted_content};if(t.type==="function_call")return{role:"assistant",id:t.id,tool_calls:[{id:t.call_id,type:"function",function:{name:t.name,arguments:t.arguments}}],content:""};if(t.type==="function_call_output")return{role:"tool",content:t.output,tool_call_id:t.call_id};if(t.type==="message")return{id:"id"in t?t.id:void 0,role:t.role,content:typeof t.content=="string"?t.content:t.content?.map(e=>e.type==="input_text"||e.type==="output_text"?e.text:"").join(" ")??""};throw new Error(`Unknown item type: ${t.type}`)}function okI(t){let e;t.incomplete_details?.reason==="content_filter"?e="content_filter":t.incomplete_details?.reason==="max_output_tokens"?e="length":e=t.output.some(n=>n.type==="function_call")?"tool_calls":"stop";let l=t.output.filter(n=>n.type==="message"||n.type==="reasoning"||n.type==="function_call").map(n=>Qbe(n)).filter(n=>n.role==="assistant").map((n,c)=>({message:{content:Array.isArray(n.content)?n.content.map(r=>typeof r=="string"?r:"text"in r?r.text:"").join(" "):n.content||null,refusal:n.refusal||null,role:n.role||null,tool_calls:n.tool_calls?.filter(r=>r.type==="function"),reasoning_opaque:n.reasoning_opaque,reasoning_text:n.reasoning_text,encrypted_content:n.encrypted_content},index:c,finish_reason:e,logprobs:null}));return{id:t.id,choices:l,created:t.created_at,model:t.model,object:"chat.completion",usage:{completion_tokens:t.usage?.output_tokens||0,prompt_tokens:t.usage?.input_tokens||0,total_tokens:t.usage?.total_tokens||0}}}function cUe(t){return{request_id:t.request_id,data:okI(t.data),response:t.response}}var R6=class extends CY{makeResponsesRequest(e,I,l,n,c,r,s){let a=l.find(b=>b.role==="system")?.content||"",o=Array.isArray(a)?a.join(`
|
|
608
|
+
${d}`)}r=!!(c||n)}let s,a=x2e(e),o=$v(e),G=e.api?.copilot?.sessionId??Dp(e);if(I.debug(`Using Copilot API at ${a} with integration ID ${o}`),n&&(I.debug("Using GitHub OAuth token for Copilot API"),s=N6.createWithOAuthToken(I,a,o,n,G,l?.requestHeaders)),c){I.debug("Using Copilot HMAC key for Copilot API");let i=process.env.GITHUB_USER_ID;i?I.debug(`Using user ID ${i} for Copilot HMAC key`):I.debug("No user ID provided for Copilot HMAC key"),s=N6.createWithHmac(I,a,o,c,G,i,l?.requestHeaders)}if(s===void 0)throw new Error("No GitHub OAuth token or Copilot HMAC key provided");return s}},MX=class t extends dc{request_id;constructor(e){super(e.status,e.error,e.message,e.headers),this.name="CAPIError",this.cause=e.cause,this.ghRequestId=e.headers?.get("x-github-request-id")||this.requestID,this.request_id=this.requestID}ghRequestId;static fromAPIError(e){if(!(!e||!(e instanceof dc)))return new t(e)}};var Abe={type:"ephemeral"},CY=class t{constructor(e,I,l,n){this.settings=I;this.logger=l;this.clientOptions=t.initDefaultOptions(n),l.info(" "),l.debug(`Using model: ${this.model}`),this.clientPromise=e.createClient(I,l,n),this.modelPromise=this.clientPromise.then(async()=>{let c=await this.getModel();return l.debug(`Got model info: ${JSON.stringify(c,null,2)}`),c})}clientOptions;clientPromise;modelPromise;get model(){return this.clientOptions.model}static initDefaultOptions(e){return{model:e?.model||kde.model,toolTokenBudgetProportion:e?.toolTokenBudgetProportion??.25,retryPolicy:{maxRetries:e?.retryPolicy?.maxRetries??5,errorCodesToRetry:e?.retryPolicy?.errorCodesToRetry??[],rateLimitRetryPolicy:{defaultRetryAfterSeconds:e?.retryPolicy?.rateLimitRetryPolicy?.defaultRetryAfterSeconds??5,initialRetryBackoffExtraSeconds:e?.retryPolicy?.rateLimitRetryPolicy?.initialRetryBackoffExtraSeconds??1,retryBackoffExtraGrowth:e?.retryPolicy?.rateLimitRetryPolicy?.retryBackoffExtraGrowth??2,maxRetryAfterSeconds:e?.retryPolicy?.rateLimitRetryPolicy?.maxRetryAfterSeconds??180}},thinkingMode:e?.thinkingMode??!1,requestHeaders:e?.requestHeaders??{}}}getCompletionOptions(e,I){let l={snippy:{enabled:!1}};return{temperature:0,top_p:.95,frequency_penalty:0,presence_penalty:0,tool_choice:I?.toolChoice,...l}}makeRequest(e,I,l,n,c,r,s){return e.chat.completions.create({model:I,messages:[...l],...n,tools:c},{maxRetries:r,headers:s?.requestHeaders,signal:s?.abortSignal}).withResponse()}makeRequestStreaming(e,I,l,n,c,r,s){return e.chat.completions.create({model:I,messages:[...l],...n,tools:c,stream:!0,stream_options:{include_usage:!0}},{maxRetries:r,headers:s?.requestHeaders,signal:s?.abortSignal}).withResponse()}async*getCompletionWithTools(e,I,l,n){let c=this.model,r=await this.clientPromise,s=await this.modelPromise,a=ZN(l),o=[{role:"system",content:e,copilot_cache_control:Abe},...I.map(h=>zf(h))],G=l.map((h,u)=>({type:"function",function:{name:h.name,description:h.description,parameters:h.input_schema},copilot_cache_control:u===l.length-1?Abe:void 0}));this.logger.startGroup("Completion request configuration: ",8),this.logger.debug("Client options: "),this.logger.debug(JSON.stringify(this.clientOptions,null,2)),this.logger.debug("Request options: "),this.logger.debug(JSON.stringify(n??{},null,2)),this.logger.debug("Tools: "),this.logger.debug(JSON.stringify(G,null,2)),this.logger.endGroup(8);let i=this.getCompletionOptions(l,n),d=n?.initialTurnCount!==void 0?n.initialTurnCount+1:0,b=!1,m=!1;for(;!b&&!m;){let h=Date.now();yield{kind:"turn_started",model:c,modelInfo:s,turn:d,timestampMs:h};let u=0,Z=0,N=0,g=[429,503,500,400],y=this.clientOptions.retryPolicy.maxRetries,F=this.clientOptions.retryPolicy.rateLimitRetryPolicy.initialRetryBackoffExtraSeconds,f=0,v=this.clientOptions.retryPolicy.rateLimitRetryPolicy.maxRetryAfterSeconds,X,C;try{let L=[],U;do{N>0&&(yield{kind:"turn_retry",model:c,modelInfo:s,turn:d,timestampMs:Date.now()});try{let Ie={};for(let Ae of n?.processors?.preRequest||[]){let pe=Ae.preRequest({turn:d,retry:N,messages:o,toolDefinitions:G,modelInfo:s,additionalRequestHeaders:Ie,getCompletionWithToolsOptions:n});for await(let Fe of pe)yield Fe}if(this.logger.startGroup("Sending request to the AI model",8),hl(this.settings,"copilot_swe_agent_request_logging")){let Ae=JSON.stringify(o,null,2),pe=JSON.stringify(i,null,2);this.logger.debug(`Request messages: ${Ae}`),this.logger.debug(`Request options: ${pe}`)}L=o.map((Ae,pe)=>pe===o.length-1?{...Ae,copilot_cache_control:Abe}:Ae),u=Date.now(),r.setAdditionalHeaders(Ie);let Ge;if(n?.stream){let Ae=await this.makeRequestStreaming(r,c,L,i,G,y,n);Ge=await skI(Ae,r,n)}else Ge=await this.makeRequest(r,c,L,i,G,y,n);Z=Date.now()-u,X=Ge.data,U={model:c,api_id:X.id,request_id:Ge.response.headers.get("x-github-request-id")||void 0,initiator:n?.requestHeaders?.["X-Initiator"]||Ie["X-Initiator"]};let Qe={};Ge.response.headers.forEach((Ae,pe)=>{if(pe.toLowerCase().startsWith(xde)){let Fe=cze(Ae);Fe&&(Qe[pe.replace(xde,"")]=Fe)}}),yield{kind:"model_call_success",turn:d,callId:n?.callId,modelCallDurationMs:Z,modelCall:U,responseChunk:tze(X),responseUsage:X.usage,requestMessages:JSON.stringify(L),quotaSnapshots:Qe},this.logger.debug(`response (Request-ID ${Ge.request_id}):`),this.logger.debug("data:"),this.logger.debug(JSON.stringify(Ge.data,null,2))}catch(Ie){Z=Date.now()-u;let Ge=MX.fromAPIError(Ie),Qe=Ge?.error;if(Ge){yield{kind:"model_call_failure",turn:d,callId:n?.callId,modelCallDurationMs:Z,requestMessages:JSON.stringify(L),modelCall:{model:c,status:Ge.status,error:JSON.stringify(Ge?.error||Ge?.message||"unknown error"),api_id:Ge.requestID||void 0,request_id:Ge.headers?.get("x-github-request-id")||""}},C=Ge;let pe=Ge.ghRequestId||Ge.headers?.get("x-github-request-id")||Ge.requestID;this.logger.error(`error (Request-ID ${pe})`),this.logger.error(JSON.stringify(Ge,Object.getOwnPropertyNames(Ge),2)),this.logger.debug(`Failed to get response from the AI model: ${Ge}`),Qe&&this.logger.debug(`Inner error: ${JSON.stringify(Qe,null,2)}`);let Fe;for(let _e of n?.processors?.onRequestError||[])Fe=await _e.onRequestError({turn:d,retry:N,maxRetries:y,error:Qe,modelInfo:s,getCompletionWithToolsOptions:n})||Fe;let me=Ge.status,uI=me?this.clientOptions.retryPolicy.errorCodesToRetry.some(_e=>Array.isArray(_e)?me>=_e[0]&&(_e[1]===void 0||me<=_e[1]):me===_e):!1,ve;if(Fe)ve=Fe.retryAfter;else if(Ge.status!==402){if(Ge.status===413){this.logger.debug("Request is too large, trying to remove images from the request");let _e=0;for(let Nl=o.length-1;Nl>=0;Nl--)l0(o[Nl])&&(o.splice(Nl,1),_e++,yield{kind:"images_removed",turn:d,imagesRemoved:1,largeImagesRemoved:1});_e>0?(this.logger.info(`Images have been removed from the request due to size constraints. Please resize images to be smaller than ${zm(s.capabilities.limits.vision?.max_prompt_image_size||0)}.`),this.logger.debug(`Removed ${_e} image messages from the request`),ve=1):this.logger.debug("No image messages found in the request - unsure why the request is too large - will fail")}else if((typeof Ge.status=="number"&&g.includes(Ge.status)||uI)&&(ve=parseInt(Ge.headers?.get("retry-after")||`${this.clientOptions.retryPolicy.rateLimitRetryPolicy.defaultRetryAfterSeconds}`,10)+F,F*=this.clientOptions.retryPolicy.rateLimitRetryPolicy.retryBackoffExtraGrowth,N==y-1))for(let _e=o.length-1;_e>=0;_e--)l0(o[_e])&&(this.logger.debug(`Removing image message at index ${_e} to avoid failure`),o.splice(_e,1),yield{kind:"images_removed",turn:d,imagesRemoved:1})}if(ve!==void 0&&ve<=v){let _e=.8+Math.random()*.4,Nl=ve*_e;this.logger.debug(`Retrying after ${Nl} seconds...`),await new Promise(xI=>setTimeout(xI,Nl*1e3)),f+=Nl,this.logger.debug(`Retrying after ${ve} seconds... Will try again now!`);continue}else ve?this.logger.error(`Retry after ${ve} seconds is too long. Giving up.`):this.logger.error("Retry after is not set. Giving up.")}let Ae=Ge||Ie;for(let pe of n?.processors?.onRequestError||[])await pe.preErrorThrow(Ie);throw this.logger.error("error"),this.logger.error(JSON.stringify(Ae,null,2)),Ae}finally{r.setAdditionalHeaders({}),this.logger.endGroup(8)}}while(!X&&N++<y);if(!X){this.logger.debug("Recent messages prior to failure:");for(let Ge=Math.max(0,o.length-6);Ge<o.length;Ge++)this.logger.debug(`${Ge}: ${JSON.stringify(o[Ge],null,2)}`);let Ie=new Error(`Failed to get response from the AI model; retried ${N-1} times (total retry wait time: ${f} seconds)`,{cause:C});throw this.isRateLimitExceededError(Ie)&&(this.logger.info(`Rate limit exceeded after ${N-1} retries, will fail job but skip Sentry reporting`),Ie.skipReport=!0),Ie}for(let Ie of X.choices.map(Ge=>Ge.message))rkI(Ie.tool_calls||[]),o.push(Ie),yield{kind:"message",turn:d,callId:n?.callId,modelCall:U,message:zf(mX(Ie))};if(this.isToolCallResponse(X)){let Ge=(s.capabilities.limits.max_prompt_tokens||s.capabilities.limits.max_context_window_tokens)*this.clientOptions.toolTokenBudgetProportion,Qe=dve(c,Ge,this,this.settings),pe=X.choices.filter(ve=>ve.message.tool_calls!==void 0).flatMap(ve=>ve.message.tool_calls||[]).filter(AG),Fe=new Map;for(let ve of n?.processors?.preToolsExecution||[]){let _e=await ve.preToolsExecution({turn:d,toolCalls:pe,modelInfo:s});if(_e)for(let[Nl,xI]of _e)Fe.set(Nl,xI)}let me=pe.filter(ve=>!Fe.has(ve.id)),uI=this.mergeToolResults(Fe,pe,me,a,Qe,n?.executeToolsInParallel);for await(let ve of uI){ve.toolResult.resultType==="rejected"&&(m=!0);let _e={role:"tool",tool_call_id:ve.originalCall.id,content:ve.toolResult.textResultForLlm};o.push(_e),yield{kind:"message",turn:d,callId:n?.callId,modelCall:U,message:zf(_e)},yield{kind:"tool_execution",turn:d,callId:n?.callId,toolCallId:ve.originalCall.id,toolResult:ve.toolResult,durationMs:ve.durationMs};for(let Nl of n?.processors?.postToolExecution||[])await Nl.postToolExecution({toolCall:ve.originalCall,toolResult:ve.toolResult,turn:d,modelInfo:s})}}else for(let Ie of X.choices.map(Ge=>Ge.message))yield{kind:"response",turn:d,callId:n?.callId,modelCall:{model:c,api_id:X.id},response:zf(mX(Ie))},b=!0}catch(L){let U;throw L instanceof Error&&L.cause&&L.cause instanceof MX?U=`${L} (Cause: ${L.cause})`:U=`${L}`,yield{kind:"turn_failed",model:c,modelInfo:s,turn:d,error:U,timestampMs:Date.now()},L}finally{let L=Date.now();yield{kind:"turn_ended",model:c,modelInfo:s,turn:d,timestampMs:L},d++}}}async*mergeToolResults(e,I,l,n,c,r=!1){for(let[s,a]of e){let o=I.find(G=>G.id===s);o&&(yield{durationMs:0,originalCall:o,toolResult:a})}l.length>0&&(yield*this.callTools(l,n,c,r))}async*callTools(e,I,l,n=!1){if(e.length===0)throw new Error("Tool call is missing");this.logger.debug(`Tool calls count: ${e.length}`);let c=e.some(s=>{let a=I[s.function.name];return dX(a)}),r=n&&!c;if(c&&n&&this.logger.debug("Custom agent detected in tool calls, forcing sequential execution"),r)this.logger.debug("Running tool calls in parallel"),yield*rve(e.map(s=>()=>this.callTool(s,I,l)));else{this.logger.debug("Running tool calls sequentially");for(let s of e)yield await this.callTool(s,I,l)}}async callTool(e,I,l){let n=0,c=e?.function.name;if(!c)throw new Error("Tool name is missing");let r=e?.function.arguments;if(r==null)throw new Error("Tool call arguments are missing");let s=e?.id;if(!s)throw new Error("Tool call id is missing");let a,o=I[c];try{let G=bX(r);if(!o||!o.callback)a={textResultForLlm:`Tool '${c}' does not exist. Available tools that can be called are ${Object.keys(I).join(", ")}.`,resultType:"failure",error:`Tool '${c}' does not exist.`,sessionLog:`<error>Tool '${c}' does not exist.</error>`,toolTelemetry:{}};else{let i=o.callback,d=Date.now(),b={...l,toolCallId:s,toolOptions:this.settings.service?.tools?.[c]},m=await i({...G},b);n=Date.now()-d,a=typeof m=="string"?{textResultForLlm:m,resultType:"success",toolTelemetry:{}}:m}}catch(G){G instanceof SyntaxError?(a={textResultForLlm:`The arguments for the tool call '${c}' were not valid JSON. The arguments have been cleared. Arguments: ${r}. JSON parse error: ${G.message}`,resultType:"failure",error:`${G.message}`,sessionLog:`<error>Failed to execute \`${c}\` tool with arguments: ${r} due to syntax error: ${G.message}</error>`,toolTelemetry:{properties:{wasSyntaxError:"true"}}},e.function.arguments="{}"):a={textResultForLlm:`Failed to execute \`${c}\` tool with arguments: ${r} due to error: ${G}`,resultType:"failure",error:G instanceof Error?G.message:`${G}`,sessionLog:`<error>Failed to execute \`${c}\` tool with arguments: ${r}</error>`,toolTelemetry:{}}}return{durationMs:n,originalCall:e,toolResult:a}}isToolCallResponse(e){return e.choices.find(I=>I.message.tool_calls!==void 0)!==void 0}isRateLimitExceededError(e){if(e instanceof Error){if(e.message?.includes("exceeded maximum number of retries")&&e.message?.includes("rate-limited requests"))return!0;if(e.message?.includes("Failed to get response from the AI model")&&e.cause instanceof MX)return e.cause.status===429}return!1}async getModel(){let e=this.clientOptions.model,I={id:e,name:e,capabilities:{supports:{vision:!1},limits:{max_prompt_tokens:9e4,max_context_window_tokens:128e3,vision:{max_prompt_image_size:3145728,max_prompt_images:1,supported_media_types:["image/jpeg","image/png","image/webp"]}}}};return(await(await this.clientPromise).listModels()).filter(r=>r.id===e).at(0)||I}};function rkI(t){for(let e of t)e.function.name=e.function.name.replace(/[^a-zA-Z0-9_-]+/g,"_")}async function skI(t,e,I){let l=akI(t.data,e).toReadableStream(),n=iZ.fromReadableStream(l),c=I?.processors?.onStreamingChunk;if(c?.length)for await(let r of n){I?.abortSignal?.throwIfAborted();let s={chunk:r};for(let a of c)a.onStreamingChunk(s)}return{data:await n.finalChatCompletion(),response:t.response,request_id:t.request_id}}function akI(t,e){let I=new Map;return new dd(async function*(){for await(let l of t)l.choices?.forEach(n=>{if(n.delta.role??="assistant",!!n.delta?.tool_calls?.length){n.finish_reason??="tool_calls";let r=I.get(n.index);r||(r={nextSequenceNumber:0,mappings:new Map},I.set(n.index,r)),n.delta.tool_calls?.forEach(s=>{let a=r.mappings.get(s.index);if(a!==void 0)s.id&&a.callId!==s.id&&(a.sequenceNumber=r.nextSequenceNumber++,a.callId=s.id),s.index=a.sequenceNumber;else{let o={callId:s.id,sequenceNumber:r.nextSequenceNumber++};r.mappings.set(s.index,o),s.index=o.sequenceNumber}})}}),yield l},t.controller,e)}var Y6=class extends CY{constructor(e,I,l){let n=new OX;super(n,e,I,l)}};var V6=class t{constructor(e,I,l,n){this.settings=I;this.logger=l;this.clientOptions=t.initDefaultOptions(n),this.logger.info(`Using responses with model: ${this.model}`),this.clientPromise=e.createClient(I,l,this.clientOptions)}clientOptions;clientPromise;get model(){return this.clientOptions.model}static initDefaultOptions(e){return{model:e?.model||"o4-mini",toolTokenBudgetProportion:e?.toolTokenBudgetProportion??.25,retryPolicy:{maxRetries:e?.retryPolicy?.maxRetries??5,errorCodesToRetry:e?.retryPolicy?.errorCodesToRetry??[],rateLimitRetryPolicy:{defaultRetryAfterSeconds:e?.retryPolicy?.rateLimitRetryPolicy?.defaultRetryAfterSeconds??5,initialRetryBackoffExtraSeconds:e?.retryPolicy?.rateLimitRetryPolicy?.initialRetryBackoffExtraSeconds??1,retryBackoffExtraGrowth:e?.retryPolicy?.rateLimitRetryPolicy?.retryBackoffExtraGrowth??2,maxRetryAfterSeconds:e?.retryPolicy?.rateLimitRetryPolicy?.maxRetryAfterSeconds??60}},thinkingMode:e?.thinkingMode??!0,requestHeaders:e?.requestHeaders??{}}}makeRequest(e,I,l,n,c,r,s,a){return e.responses.create({model:I,previous_response_id:r,instructions:l,input:n,parallel_tool_calls:c.length>0?!0:void 0,tools:c,reasoning:{summary:"auto",effort:"medium"},store:!1,include:["reasoning.encrypted_content"]},{maxRetries:s||this.clientOptions.retryPolicy.maxRetries,headers:a?.requestHeaders,signal:a?.abortSignal}).withResponse()}async*getCompletionWithTools(e,I,l,n){let c=await this.clientPromise,r=ZN(l),s=l.map(u=>({name:u.name,description:u.description,parameters:u.input_schema,strict:!1,type:"function"})),a=0,o=this.clientOptions.retryPolicy.maxRetries,G=this.clientOptions.retryPolicy.rateLimitRetryPolicy.initialRetryBackoffExtraSeconds,i=0,d=this.clientOptions.retryPolicy.rateLimitRetryPolicy.maxRetryAfterSeconds,b=I.flatMap(wbe),m,h=!1;for(;!h;){let u;do{u=void 0;try{let Z=await this.makeRequest(c,this.model,e,b,s,void 0,o,n);m=Z.data,b.push(...m.output),this.logger.debug(`response (Request-ID ${Z.request_id}):`),this.logger.debug("data:"),this.logger.debug(JSON.stringify(Z.data,null,2))}catch(Z){let N=Z,g=N.error;if(N){u=N,this.logger.error(`error (Request-ID ${N.requestID})`),this.logger.error(JSON.stringify(N,null,2)),this.logger.debug(`Failed to get response from the AI model: ${N}`),g&&this.logger.debug(`Inner error: ${JSON.stringify(g,null,2)}`);let y=N.status,F=y?this.clientOptions.retryPolicy.errorCodesToRetry.some(v=>Array.isArray(v)?y>=v[0]&&(v[1]===void 0||y<=v[1]):y===v):!1,f;if((N.status===429||F)&&(f=parseInt(N.headers?.get("retry-after")||`${this.clientOptions.retryPolicy.rateLimitRetryPolicy.defaultRetryAfterSeconds}`,10)+G,G*=this.clientOptions.retryPolicy.rateLimitRetryPolicy.retryBackoffExtraGrowth),f!==void 0&&f<=d){this.logger.debug(`Retrying after ${f} seconds...`),await new Promise(v=>setTimeout(v,f*1e3)),i+=f,this.logger.debug(`Retrying after ${f} seconds... Will try again now!`);continue}else f?this.logger.error(`Retry after ${f} seconds is too long. Giving up.`):this.logger.error("Retry after is not set. Giving up.")}throw this.logger.error("error"),this.logger.error(JSON.stringify(Z,null,2)),Z}finally{this.logger.endGroup(8)}}while(u&&a++<o);if(!m||u){this.logger.debug("Recent messages prior to failure:");for(let Z=Math.max(0,b.length-6);Z<b.length;Z++)this.logger.debug(`${Z}: ${JSON.stringify(b[Z],null,2)}`);throw new Error(`Failed to get response from the AI model; retried ${a-1} times (total retry wait time: ${i} seconds)`,{cause:u})}for(let Z of m.output)yield{kind:"message",message:Qbe(Z)};if(this.requiresToolOutput(m)){let N=(await this.runTool(m,r)).map(g=>({type:"function_call_output",call_id:g.toolCallId,output:g.textResultForLlm}));b.push(...N);for(let g of N)yield{kind:"message",message:Qbe(g)}}else yield{kind:"response",response:{content:m.output_text,refusal:null,role:"assistant"}},h=!0}}async runTool(e,I,l){let n=e.output.filter(r=>r.type==="function_call");if(!n||n.length===0)throw new Error("Tool calls in response are missing");let c=[];for(let r of n){let s=r.name;if(!s)throw new Error("Tool name is missing");let a=r.arguments;if(!a)throw new Error("Tool call arguments are missing");let o=r.call_id;if(!o)throw new Error("Tool call id is missing");let G,i=I[s];try{let d=bX(a);if(!i||!i.callback)G={textResultForLlm:`Tool '${s}' does not exist. Available tools that can be called are ${Object.keys(I).join(", ")}.`,resultType:"failure",error:`Tool '${s}' does not exist.`,sessionLog:`<error>Tool '${s}' does not exist.</error>`,toolTelemetry:{}};else{let b=i.callback,m={...l,toolCallId:o,toolOptions:this.settings.service?.tools?.[s],settings:this.settings},h=await b({...d},m);G=typeof h=="string"?{textResultForLlm:h,resultType:"success",toolTelemetry:{}}:h}}catch(d){G={textResultForLlm:`Failed to execute \`${s}\` tool with arguments: ${a} due to error: ${d}`,resultType:"failure",error:d instanceof Error?d.message:`${d}`,sessionLog:`<error>Failed to execute \`${s}\` tool with arguments: ${a}</error>`,toolTelemetry:{properties:{wasSyntaxError:d instanceof SyntaxError?"true":"false"}}}}c.push({toolCallId:o,textResultForLlm:G.textResultForLlm,sessionLog:G.resultType=="success"?G.sessionLog:G.error?`<error>${G.error}</error>`:void 0})}return c}requiresToolOutput(e){return e.output.filter(I=>I.type==="function_call").length>0}};function wbe(t){if(t.role==="function")throw new Error("Function role is not supported");let e=[];if(t.reasoning_opaque&&e.push({id:t.reasoning_opaque,type:"reasoning",summary:t.reasoning_text?[{text:t.reasoning_text,type:"summary_text"}]:[],encrypted_content:t.encrypted_content}),t.role==="assistant"&&t.tool_calls&&t.tool_calls.length>0&&AG(t.tool_calls[0])){let I=t.tool_calls[0];return[...e,{type:"function_call",id:t.id,name:I.function.name,arguments:I.function.arguments,call_id:I.id}]}if(t.role==="tool")return[...e,{type:"function_call_output",id:`fc_${t.tool_call_id}`,call_id:t.tool_call_id,output:typeof t.content=="string"?t.content:t.content.map(I=>I.text).join(" ")??""}];if(!t.content)return e;if(t.role==="assistant"){let I=t.id||crypto.randomUUID();return I.startsWith("msg_")||(I=`msg_${I}`),[...e,{type:"message",id:I,role:t.role,content:[{annotations:[],type:"output_text",text:typeof t.content=="string"?t.content:t.content?.map(l=>l.type==="text"?l.text:"").join(" ")??""}],status:"completed"}]}return[...e,{role:t.role,content:typeof t.content=="string"?[{type:"input_text",text:t.content}]:t.content.map(I=>{if(I.type==="text")return{type:"input_text",text:I.text};if(I.type==="image_url")return{type:"input_image",detail:I.image_url.detail||"auto",image_url:I.image_url.url}}).filter(I=>I!==void 0),type:"message"}]}function Qbe(t){if(t.type==="reasoning")return{role:"assistant",reasoning_opaque:t.id,reasoning_text:t.summary?t.summary.map(e=>e.text).join(" "):void 0,content:"",encrypted_content:t.encrypted_content};if(t.type==="function_call")return{role:"assistant",id:t.id,tool_calls:[{id:t.call_id,type:"function",function:{name:t.name,arguments:t.arguments}}],content:""};if(t.type==="function_call_output")return{role:"tool",content:t.output,tool_call_id:t.call_id};if(t.type==="message")return{id:"id"in t?t.id:void 0,role:t.role,content:typeof t.content=="string"?t.content:t.content?.map(e=>e.type==="input_text"||e.type==="output_text"?e.text:"").join(" ")??""};throw new Error(`Unknown item type: ${t.type}`)}function okI(t){let e;t.incomplete_details?.reason==="content_filter"?e="content_filter":t.incomplete_details?.reason==="max_output_tokens"?e="length":e=t.output.some(n=>n.type==="function_call")?"tool_calls":"stop";let l=t.output.filter(n=>n.type==="message"||n.type==="reasoning"||n.type==="function_call").map(n=>Qbe(n)).filter(n=>n.role==="assistant").map((n,c)=>({message:{content:Array.isArray(n.content)?n.content.map(r=>typeof r=="string"?r:"text"in r?r.text:"").join(" "):n.content||null,refusal:n.refusal||null,role:n.role||null,tool_calls:n.tool_calls?.filter(r=>r.type==="function"),reasoning_opaque:n.reasoning_opaque,reasoning_text:n.reasoning_text,encrypted_content:n.encrypted_content},index:c,finish_reason:e,logprobs:null}));return{id:t.id,choices:l,created:t.created_at,model:t.model,object:"chat.completion",usage:{completion_tokens:t.usage?.output_tokens||0,prompt_tokens:t.usage?.input_tokens||0,total_tokens:t.usage?.total_tokens||0}}}function cUe(t){return{request_id:t.request_id,data:okI(t.data),response:t.response}}var R6=class extends CY{makeResponsesRequest(e,I,l,n,c,r,s){let a=l.find(b=>b.role==="system")?.content||"",o=Array.isArray(a)?a.join(`
|
|
609
609
|
`):a,i=l.filter(b=>b.role!=="system").flatMap(wbe),d=c.filter(b=>b.type==="function").map(b=>({name:b.function.name,description:b.function.description,parameters:b.function.parameters||null,strict:!1,type:"function"}));return this.logger.debug(`Making responses request with input: ${JSON.stringify(i,null,2)}`),e.responses.create({model:I,previous_response_id:void 0,instructions:o,input:i,parallel_tool_calls:c.length>0?!0:void 0,tools:d,reasoning:{summary:"auto",effort:"medium"},store:!1,include:["reasoning.encrypted_content"]},{maxRetries:r||this.clientOptions.retryPolicy.maxRetries,headers:s?.requestHeaders,signal:s?.abortSignal}).withResponse()}makeRequest(e,I,l,n,c,r,s){return this.makeResponsesRequest(e,I,l,n,c,r,s).then(cUe)}};var y6=class extends R6{constructor(e,I,l){let n=new OX;super(n,e,I,l)}};var $f=class{constructor(e,I,l){this.settings=e;this.logger=I;this.clientOptions=l;this.chatClient=new Y6(e,I,l)}chatClient;get model(){return this.chatClient.model}async*getCompletionWithTools(e,I,l,n){let c=await this.chatClient.modelPromise;(this.clientOptions?.thinkingMode||hl(this.settings,"copilot_swe_agent_enable_responses_api"))&&c&&c.supported_endpoints?.includes("/responses")?yield*new y6(this.settings,this.logger,{model:this.chatClient.model,...this.clientOptions}).getCompletionWithTools(e,I,l,n):yield*this.chatClient.getCompletionWithTools(e,I,l,n)}};var g6=class extends CY{constructor(e,I,l,n){super(e,I,l,n)}getCompletionOptions(e,I){return{...this.model.startsWith("gpt-4")?{temperature:0,top_p:.95,frequency_penalty:0,presence_penalty:0,parallel_tool_calls:e?!1:void 0}:{},tool_choice:I?.toolChoice}}async*getCompletionWithTools(e,I,l,n){let c=await super.getCompletionWithTools(e,I,l,n);for await(let r of c)r.kind==="message"?yield{...r,message:mX({...r.message,reasoning_text:r.message?.cot_summary})}:yield r}};var F6=class extends V6{constructor(e,I,l,n){super(e,I,l,n)}};var Xbe=class extends Tf{constructor(e){super(e)}setInitiatorHeader(e){}setAdditionalHeaders(e){}listModels(){return Promise.resolve([])}},A6=class{async createClient(e,I,l){I.startGroup("configured settings:",8),I.debug(JSON.stringify(e,null,2)),I.endGroup(8);let n=e.api?.openai?.apiKey,c=e.api?.openai?.azureKeyVaultUri,r=e.api?.openai?.azureSecretName;if(!n&&c){I.debug("No API_KEY provided, trying secret provider");let G=Fbe(c,I);try{n=await G.getSecret(r||"azure-openai-api-key")}catch(i){I.debug(`Failed to get API Key from secret provider:
|
|
610
610
|
${i}`)}}let s=k2e(e);I.debug(`Using Azure Open API at ${s}`);let o={baseURL:`${new URL(s).origin}/openai`,apiVersion:e.api?.openai?.azure?.apiVersion||"2024-10-21",deployment:l?.model,defaultHeaders:l?.requestHeaders};if(n)o={...o,apiKey:n},I.debug("Using Azure OpenAI API Key");else{let G=new nh,d=EGe(G,"https://cognitiveservices.azure.com/.default");o={...o,azureADTokenProvider:d},I.debug("Using Azure Managed Identity")}return new Xbe(o)}};var Ebe=class extends JI{constructor(e){super(e)}setInitiatorHeader(e){}setAdditionalHeaders(e){}listModels(){return Promise.resolve([])}},Q6=class{async createClient(e,I,l){I.startGroup("configured settings:",8),I.debug(JSON.stringify(e,null,2)),I.endGroup(8);let n=f2e(e),c=e.api?.openai?.baseUrl,r=l?.requestHeaders;return new Ebe({baseURL:c,apiKey:n,defaultHeaders:r})}};function Hbe(t,e,I,l){switch(I){case"sweagent-aip":return new oK(t,e,l);case"sweagent-anthropic":return new EP(t,e,l);case"sweagent-capi":return new $f(t,e,l);case"sweagent-openai":return l?.thinkingMode?new F6(rUe(t),t,e,l):new g6(rUe(t),t,e,l);default:return new $f(t,e,l)}}function rUe(t){return t.api?.openai?.azure?.url?new A6:new Q6}import{randomUUID as l9I}from"crypto";import{tmpdir as n9I}from"os";import c9I from"path";var YUe=Ll(ZUe(),1);import{exec as _kI,spawn as $kI}from"child_process";function Bbe({onlyFirst:t=!1}={}){let I=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");return new RegExp(I,t?void 0:"g")}var qkI=Bbe();function zbe(t){if(typeof t!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof t}\``);return t.replace(qkI,"")}import{promisify as e9I}from"util";var Rb="___BEGIN___COMMAND_OUTPUT_MARKER___",WUe=`
|
|
611
611
|
${Rb}`,V0="___BEGIN___COMMAND_DONE_MARKER___",I9I=new RegExp(`${V0}(\\d+)`),NUe=5e3,l3=100*1024,qX=class t{constructor(e,I,l={}){this.config=e;this.createdAtMs=Date.now(),this.lastUsedAtMs=Date.now();let n=this.config.shellType==="powershell",c=n?"pwsh.exe":"bash",r=n?["-nop","-nol"]:["--norc","--noprofile"],s=n?!1:void 0;this.process=(0,YUe.spawn)(c,r,{name:"xterm-color",cols:120,rows:80,cwd:I,env:l,useConpty:s}),this.process.onData(a=>{let G=zbe(a).replaceAll("\r","");if(this.outputBuffer.length+G.length>l3){this.wasTruncated=!0;let i=this.outputBuffer.lastIndexOf(Rb);if(i!==-1){let d=this.outputBuffer.substring(0,i+Rb.length),b=this.outputBuffer.substring(i+Rb.length),m=l3-G.length-d.length;if(m>0){let h=Dn(b,"output",m,"start");this.outputBuffer=d+h}else{this.outputBuffer=d+Dn(G,"output",l3-d.length,"start");return}}else{let d=l3-G.length;if(d>0)this.outputBuffer=Dn(this.outputBuffer,"output",d,"start");else{this.outputBuffer=Dn(G,"output",l3,"start");return}}}this.outputBuffer+=G}),this.process.onExit(a=>this.shutdown())}process;outputBuffer="";isCommandInProgress=!1;wasTruncated=!1;createdAtMs;lastUsedAtMs;onPartialOutputChanged;static shellIsSupportedCache=new Map;writeDelay=Promise.resolve();static async create(e,I,l={}){await t.ensureShellIsSupported(e.shellType);let n=new t(e,I,l);return await n.initializeShellEnvironment(),n}setPartialOutputChangedCallback(e){this.onPartialOutputChanged=e}async executeCommand(e,I){if(this.updateLastUsedTime(),!this.process)throw new Error(`Failed to start ${this.config.shellType} process`);if(this.tryStartCommand(e))return await(I?this.waitForCommandCompletionOrTimeout(I):this.waitForCommandCompletion())}async cwd(){try{let e=this.config.shellType==="powershell"?"(pwd).Path":"pwd",I=await this.executeCommand(e,NUe);return I?.exitCode===0?I.output:void 0}catch{return}}async tryExecuteAsyncCommand(e){return this.updateLastUsedTime(),this.tryStartCommand(e)?(this.waitForCommandCompletion().catch(I=>{}),this.config.shellType==="powershell"&&await new Promise(I=>setTimeout(I,250)),!0):!1}async tryExecuteDetachedCommand(e,I){return this.updateLastUsedTime(),this.isCommandInProgress?!1:process.platform==="win32"?this.tryExecuteDetachedCommandWindows(e,I):this.tryExecuteDetachedCommandUnix(e,I)}async tryExecuteDetachedCommandWindows(e,I){if(!(this.config.shellType==="powershell"))throw new Error("Only PowerShell is supported for detached commands on Windows");try{let n=e.replace(/"/g,'""'),c=I.replace(/\\/g,"\\\\"),r=`Start-Process -FilePath "pwsh.exe" -ArgumentList "-NoProfile","-Command","${n} *>> '${c}' 2>&1" -WindowStyle Hidden`;return $kI("pwsh.exe",["-NoProfile","-Command",r],{stdio:"ignore",cwd:await this.cwd(),windowsHide:!0}).unref(),this.isCommandInProgress=!0,this.outputBuffer=`${Rb}
|
|
@@ -1345,7 +1345,7 @@ ${t}
|
|
|
1345
1345
|
|
|
1346
1346
|
<reminder>
|
|
1347
1347
|
The user may have mentioned images, if so these will have been attached to this message, in the order they were mentioned
|
|
1348
|
-
</reminder>`),l.trim()},D8={completeAsSoonAsPossible:"You will soon run out of iterations. Begin making your final code changes. Complete any code changes that are still pending instead of performing validations.",commitNow:"You are imminently out of iterations. Call **report_progress** detailing your current progress. After doing so, provide a final answer as soon as possible.",finalAnswerNeeded:"You have reached the maximum number of iterations. Consider your work completed. I no longer need more changes. Please provide a final answer."},u8e=t=>`<reminder>You haven't committed any changes yet. Any code changes not meant to be temporary must be made in ${Wue(t)}. Commit changes by using the **report_progress** tool.</reminder>`;var IZe="/tmp/playwright-logs",D7I="0.0.40",tZe=[`@playwright/mcp@${D7I}`,"--viewport-size","1280, 720","--output-dir",IZe],Ixl=[...tZe,"--isolated"];var lZe=class t extends Error{constructor(e){super(e),this.name="ImageSizeError",Object.setPrototypeOf(this,t.prototype)}},HB=2e3;async function P7I(t,e,I,l){let n={"Content-Type":"application/octet-stream",Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",Authorization:"Bearer "+e},c=`${z2e(l)}/${t}`;I.info(`Downloading image from ${c}`);try{let r=await fetch(c,{method:"GET",headers:n});if(I.info(`Response status: ${r.status} ${r.statusText}`),I.debug(`Download Response URL: ${r.url}`),!r.ok){I.info(`Failed to download image, status: ${r.status}, statusText: ${r.statusText}`);try{let d=await r.text();I.info(`Error response body: ${d}`)}catch(d){I.info(`Could not read error response body: ${d}`)}return{size:0}}let a=(await r.json()).url;if(!a)return I.error(`No asset URL found in response for image GUID: ${t}`),{size:0};let o=await fetch(a,{method:"GET"});if(!o.ok)return I.error(`Failed to download image: ${o.status} ${o.statusText}`),{size:0};let G=await o.arrayBuffer(),i=G.byteLength;return I.info(`Downloaded content size: ${zm(i)}`),{size:i,buffer:Buffer.from(G),mimeType:o.headers.get("content-type")||void 0}}catch(r){return I.error("Network error downloading image"),r instanceof Error&&(I.info(`Error message: ${r.message}`),I.info(`Error stack: ${r.stack}`)),{size:0}}}function nZe(t,e,I,l){let n=/<img\b[^>]*\bsrc="([^"]+)"[^>]*>/g,c=/!\[.*?\]\((.*?)\)/g,r=[];return r.push(...Z8e(t,e,n,I,l)),r.push(...Z8e(t,e,c,I,l)),r}function Z8e(t,e,I,l,n){let c=t.matchAll(I),r=[],s=/\/([a-f0-9-]+)$/;for(let a of c){let o=e_I(a[1],e),G=I_I(a[1],e,n);if(o||G){let i=a[1].match(s),d={url:a[1],guid:"",kind:G?"legacy_attachment":"attachment"};i&&i.length>1&&(d.guid=i[1]),r.push(d)}else if(l){let i={url:a[1],guid:"",kind:"committed_attachment"};r.push(i)}}return r}function q7I(t){return!t.startsWith("http://")&&!t.startsWith("https://")&&sZe(t)}function sZe(t){return/\.(png|jpe?g|gif|svg|webp|bmp|tiff?|ico|heic|avif)$/i.test(t)}function _7I(t){try{let e=/Here are relevant code snippets from the repository that might help with this task:\s*(\[[\s\S]*?\])(?=\n|$)/,I=t.match(e);if(!I?.[1]||I[1].length<=1)return null;let l=I[1].trim();return JSON.parse(l)}catch{return null}}function $7I(t,e,I){if(!t?.url||!t?.ref||!t?.path)throw new Error("Invalid repository insight: missing required fields");if(!e||e.trim()==="")throw new Error("Invalid image path: path cannot be empty");let l=t.url.split("/").slice(3,5).join("/"),n=t.ref.split("/")[2],c;if(e.startsWith("/"))c=e.slice(1);else{let s=t.path,a=vB.dirname(s);c=vB.resolve("/",a,e).slice(1)}return`${I}/${l}/blob/${n}/${c}`}function e_I(t,e){return e?!!t.startsWith(`${e}/user-attachments/assets`):!1}function I_I(t,e,I){return e&&new RegExp(`^${e}/[\\w.-]+/[\\w.-]+/assets/\\d+/[^.]+$`).test(t)?(I.debug(`Legacy GitHub asset URL detected: ${t}`),!0):!1}async function aZe(t){let{width:e,height:I}=QPe(t);if(e===void 0||I===void 0)throw new Error("Unable to determine image dimensions.");return{width:e,height:I}}async function K8(t,e,I,l,n,c){t.debug(`Checking if image is valid size and dimensions. Max size: ${I}, Max dimension: ${l}`);let{exceedsSizeLimit:r,exceedsDimensionLimit:s}=await CB(I,l,c);if(!s&&!r)return t.debug("Image is within size and dimension limits."),c;if(s){t.debug(`Image x or y dimension exceeds the maximum limit of ${l}, attempting to resize`);let[a,o]=await n_I(t,c,l,I,n);if(!a){t.debug("Failed to resize image to fit within the maximum dimensions limits, skipping"),e.imagesRemovedDueToDimensions++,e.imagesFailedToResize++,o==="unsupported_mime_type"?e.resizeErrorsUnsupportedMimeType++:e.resizeErrorsUnknown++;return}let{exceedsDimensionLimit:G}=await CB(I,l,a);if(G){e.imagesRemovedDueToDimensions++,t.debug("Image dimensions exceed the maximum dimensions limits, skipping");return}return e.imagesResized++,t.debug("Image resized successfully."),a}if(r){t.debug(`Image size ${zm(c.length)} is larger than the maximum size of ${zm(I)}, attempting to reduce image quality`);let a=await c_I(t,c,l,I,n);if(!a){t.debug("Failed to reduce image quality to fit within the maximum size, skipping"),e.imagesFailedToReduceQuality++,e.imagesRemovedDueToSize++;return}return e.imagesWithLoweredQuality++,t.debug("Image quality successfully reduced."),a}}async function CB(t,e,I){let l=await aZe(I),n=I.length;return!l.width||!l.height?{exceedsSizeLimit:n>t,exceedsDimensionLimit:!1}:{exceedsSizeLimit:await l_I(t,I),exceedsDimensionLimit:await t_I(e,I)}}async function t_I(t,e){let I=await aZe(e);return!I.width||!I.height?!1:I.width>t||I.height>t}async function l_I(t,e){return e.length>t}async function n_I(t,e,I,l,n){try{if(!W8e(t,n))return[void 0,"unsupported_mime_type"];let c=await aZe(e);if(!c.width||!c.height)return t.error("Failed to determine size of uploaded image"),[void 0,"determine_dimensions_failed"];let r=async(u,Z)=>{let N=(0,rZe.default)(e).resize(u,Z,{fit:"inside",withoutEnlargement:!0});return cZe(t,await N.toBuffer(),void 0,n)},s=Math.min(I,c.width),a=Math.min(I,c.height),o=await r(s,a);if(o&&o.length<=l)return[o,void 0];let G=Math.max(s,a),i=1,d=G-1,b,m=0,h=10;for(;i<=d&&m<h;){let u=Math.floor((i+d)/2),Z=await r(u,u);if(!Z)break;let{exceedsSizeLimit:N,exceedsDimensionLimit:g}=await CB(l,I,Z);!N&&!g?(b=Z,i=u+1):d=u-1,m++}return[b,void 0]}catch(c){return t.error(`Failed to resize image for upload: ${c instanceof Error?c.message:String(c)}`),[void 0,"unknown"]}}async function c_I(t,e,I,l,n){try{let c=n==="image/png"?80:100,r=n==="image/png"?Math.floor(c*.4):20,s=await cZe(t,e,r,n);if(!s||s.length>l)return;let a=r,o=c,G,i=0,d=10,b=a,m=o-1;for(;b<=m&&i<d;){let h=Math.floor((b+m)/2),u=await cZe(t,e,h,n);if(!u)return G;let{exceedsSizeLimit:Z,exceedsDimensionLimit:N}=await CB(l,I,u);!Z&&!N?(G=u,b=h+1):m=h-1,i++}return G}catch(c){t.error(`Failed to reduce image quality: ${c instanceof Error?c.message:String(c)}`);return}}async function cZe(t,e,I,l){let n=(0,rZe.default)(e);switch(l){case"image/png":return I?n.png({quality:I}).toBuffer():n.png().toBuffer();case"image/jpeg":return I?n.jpeg({quality:I}).toBuffer():n.jpeg().toBuffer();default:t.debug(`Unsupported image format: ${l}`);return}}var JB=class{imagesRemovedDueToSize=0;imagesRemovedDueToDimensions=0;imagesResized=0;imagesWithLoweredQuality=0;imagesFailedToResize=0;imagesFailedToReduceQuality=0;base64ImagesSize=[];resizedBase64ImagesSize=[];extractedImagesSize=[];imagesResolvedFromGitHubMCPSize=[];resizeErrorsUnsupportedMimeType=0;resizeErrorsUnknown=0};function r_I(t,e,I,l){if(e<=0)return[];let n=[];for(let c of t){if(c.role!=="user"||n.length>=e)continue;let r=typeof c.content=="string"?c.content:JSON.stringify(c.content),s=_7I(r);if(s)for(let a in s){if(n.length>=e)break;let o=s[a].contents,G=nZe(o,I,!0,l);for(let i of G){if(n.length>=e)break;let d=i.url,b="",m=!1;if(i.kind==="attachment"||i.kind==="legacy_attachment"?n.push(i):q7I(d)?(m=!0,b=$7I(s[a],d,I),n.push({url:b,guid:i.guid,kind:"committed_attachment"})):sZe(d)&&d.startsWith(I)&&(m=!0,n.push({...i,kind:"committed_attachment"})),m){let h=n[n.length-1],u=new RegExp(`^${I}/([^/]+)/([^/]+)/blob/([^/]+)/(.+)$`),Z=h.url.match(u);if(l.info(`Blob match for ${h.url}: ${JSON.stringify(Z)}`),Z&&Z.length===5){let[,N,g,y,F]=Z;h.owner=N,h.repo=g,h.branch=y,h.path=F,l.info(`Repository metadata extracted: owner=${N}, repo=${g}, branch=${y}, path=${F}`)}else l.info(`Failed to extract repository metadata from URL: ${h.url}`)}}}}return n}function s_I(t,e){let I=e.flatMap(n=>l0(n)?n.content.flatMap(c=>c.type==="image_url"?c.image_url.url:[]):[]),l=new Set(I);return t.filter(n=>!l.has(n.url))}var P8=class{async resolveRepositoryImages(e,I,l,n,c,r){if(I<=0)return[];let s=r_I(e,I,l,n);this.logger.debug(`Found ${s.length} repository image URLs to process`);let a=s_I(s,e),o=await this.processImageReferences(a,c,r);return this.logger.debug(`Processed ${o.addedImages.length} repository image URLs`),o.addedImages}async*preRequest(e){let I=e.modelInfo;if(!I.capabilities?.limits){this.logger.debug("Model limits not defined, skipping image processing");return}if(!I.capabilities?.supports?.vision||!this.settings.featureFlags?.copilot_swe_agent_vision){this.logger.debug("Vision not supported or enabled, skipping image processing");return}if(!this.gitHubServerUrl){this.logger.debug("GitHub server URL is not set, skipping image processing");return}for(let i of this.messagesToInsertOnNextPreRequest)e.messages.push(i),yield{kind:"message",turn:e.turn,callId:e.callId,message:i};this.messagesToInsertOnNextPreRequest.splice(0);let l=[],n=I.capabilities.limits.vision?.max_prompt_images??1,c=I.capabilities.limits.vision?.max_prompt_image_size??3145728,r=0,s=[],a=new JB,o=new Map;for(let i of e.messages)if(i.role=="user")if(typeof i.content=="string"){let d=nZe(i.content,this.gitHubServerUrl,!1,this.logger).filter(m=>!this.processedImageUrls.has(m.url)),b=await this.processImageReferences(d,c,a);s.push(...b.addedImages)}else{let d=[];for(let[b,m]of i.content.entries()){if(m.type==="text"){let h=nZe(m.text,this.gitHubServerUrl,!1,this.logger).filter(Z=>!this.processedImageUrls.has(Z.url)),u=await this.processImageReferences(h,c,a);s.push(...u.addedImages)}else if(m.type==="image_url"){if(m.image_url.url.startsWith("data:")){let[h,u]=await this.extractAndUploadImageData(m,c,a);if(h===""){this.logger.debug("Skipping image upload for empty image data");continue}if(s.push(h),b>=1&&d.length>0){let Z=d.at(-1);Z&&Z.type==="text"&&Z.text&&Z.text.includes("screenshot")&&o.set(h,p8e(h))}d.pop();continue}r++}d.push(m)}i.content=d}for(this.logger.debug(`Found ${s.length} image urls in the messages`),this.logger.debug(`Allowed number of images: ${n}`);r<n&&s.length>0;){let i=s.shift();if(!i){this.logger.debug("Skipping empty image url");continue}if(this.processedImageUrls.has(i)){this.logger.debug(`Skipping already processed image url: ${i}`);continue}this.processedImageUrls.add(i);let d=`Here is the image url: ${i}`;o.has(i)&&(d=o.get(i)||d),this.logger.debug(`Adding image url: ${i}`),l.push({role:"user",content:[{type:"text",text:d},{type:"image_url",image_url:{url:i}}]}),r++}if(this.settings.featureFlags?.copilot_swe_agent_resolve_repo_images&&(this.logger.debug("Resolving repository images..."),r<n)){let i=await this.resolveRepositoryImages(e.messages,n-r,this.settings.github?.serverUrl||"",this.logger,c,a);this.logger.debug(`Resolved ${i.length} repository image URLs`);for(let d of i){if(r>=n)break;if(this.processedImageUrls.has(d)){this.logger.debug(`Skipping already processed repository image url: ${d}`);continue}l.push({role:"user",content:[{type:"text",text:"Here is the image url:"},{type:"image_url",image_url:{url:d}}]}),this.processedImageUrls.add(d),r++}}let G={imagesExtractedCount:a.extractedImagesSize.length,base64ImagesCount:a.base64ImagesSize.length,imagesRemovedDueToSize:a.imagesRemovedDueToSize,imagesRemovedDueToDimensions:a.imagesRemovedDueToDimensions,imagesResized:a.imagesResized,imagesResolvedFromGitHubMCPCount:a.imagesResolvedFromGitHubMCPSize.length};for(let i=0;i<a.base64ImagesSize.length;i++)G[`base64ImageSize_${i}`]=a.base64ImagesSize[i];for(let i=0;i<a.resizedBase64ImagesSize.length;i++)G[`resizedBase64ImageSize_${i}`]=a.resizedBase64ImagesSize[i];for(let i=0;i<a.extractedImagesSize.length;i++)G[`extractedImageSize_${i}`]=a.extractedImagesSize[i];for(let i=0;i<a.imagesResolvedFromGitHubMCPSize.length;i++)G[`imagesResolvedFromGitHubMCPSize_${i}`]=a.imagesResolvedFromGitHubMCPSize[i];l.length>0&&this.logger.debug(`Using ${l.length} image messages`);for(let i of l)yield{kind:"message",turn:e.turn,callId:e.callId,message:i},e.messages.push(i);G.allImagesSendToLlm=e.messages.filter(l0).length,yield{kind:"image_processing",turn:e.turn,imageProcessingMetrics:G},e.messages.some(i=>l0(i))&&(e.additionalRequestHeaders["Copilot-Vision-Request"]="true")}async extractAndUploadImageData(e,I,l){let n=eC(this.settings);if(!n)return this.logger.debug("No user token available, skipping image upload"),[""];this.logger.debug("Found base64 image data, uploading...");let c=e.image_url.url.match(/^data:(.*?);base64,(.*)$/);if(!c||c.length<3)return this.logger.debug("Invalid base64 image data format, skipping"),[""];let r=c[1];if(!W8e(this.logger,r))return[""];let s=c[2];if(s.length===0)return this.logger.debug("Empty base64 image data, skipping"),[""];let a=Buffer.from(s,"base64");if(l.base64ImagesSize.push(a.length),a=await K8(this.logger,l,I,HB,r,a),l.resizedBase64ImagesSize.push(a?.length??-1),!a)return["",new lZe(`Image size exceeds maximum size of ${zm(I)}`)];s=a.toString("base64");try{let o=await this.uploadBase64ImageData(s,r,n);return o?(this.logger.debug(`Uploaded image url: ${o}`),e.image_url.url=o,[o]):(this.logger.debug("Failed to upload image, skipping"),[""])}catch(o){let G=o instanceof Error?o.message:String(o);return this.logger.debug(`Error during image upload: ${G}`),[""]}}async uploadBase64ImageData(e,I,l){try{let n=B2e(this.settings),c=I.split("/").at(1),r=`image-${Date.now()}.${c}`;if(!e||e.trim()==="")return this.logger.error("Empty image data provided for upload"),null;let s=Buffer.from(e,"base64");if(s.length===0)return this.logger.error("Converted image data has zero length"),null;let a=this.settings.github?.repo?.id;if(!a)return this.logger.error("GitHub repository ID is not configured, cannot upload image"),null;let o=`${n}?name=${encodeURIComponent(r)}&content_type=${encodeURIComponent(I)}&repository_id=${a}`;this.logger.debug(`Uploading image data (${zm(s.length)}) to ${n} with name ${encodeURIComponent(r)} and content type ${encodeURIComponent(I)}`);let G={"Content-Type":"application/octet-stream",Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",Authorization:"Bearer "+l},i=await fetch(o,{method:"POST",headers:G,body:s}).catch(b=>{throw b instanceof Error?(this.logger.error(`Failed to upload image: ${b.message}`),b.code==="ECONNREFUSED"?this.logger.error("Connection refused. The server might be down or blocked."):b.code==="ETIMEDOUT"?this.logger.error("Connection timed out. Check network conditions or server load."):(b.message.includes("request entity too large")||b.message.includes("payload too large"))&&this.logger.error("Request payload too large. Try reducing the image size.")):typeof b=="object"&&b!==null&&"code"in b&&"message"in b?(this.logger.error(`Failed to upload image: ${b.message}`),b.code==="ECONNREFUSED"?this.logger.error("Connection refused. The server might be down or blocked."):b.code==="ETIMEDOUT"?this.logger.error("Connection timed out. Check network conditions or server load."):(b.message.includes("request entity too large")||b.message.includes("payload too large"))&&this.logger.error("Request payload too large. Try reducing the image size.")):this.logger.error(`Failed to upload image: ${String(b)}`),this.logger.debug(`Complete error details: ${JSON.stringify({code:b?.code,message:b?.message,stack:b?.stack,name:b?.name,cause:b?.cause},null,2)}`),b});if(!i.ok){let b=await i.text().catch(()=>"Unable to read error response");return this.logger.error(`Failed to upload image: ${i.status} ${i.statusText} - ${b}`),null}let d=await i.json();return this.logger.debug(`Upload result: ${JSON.stringify(d,null,2)}`),d.url||null}catch(n){return this.logger.error(`Error handling image upload: ${n instanceof Error?n.message:String(n)}`),n instanceof Error&&n.stack&&this.logger.debug(`Stack trace: ${n.stack}`),null}}async getRepositoryImageViaTools(e){if(this.logger.debug(`Attempting to retrieve repository image: ${e.owner}/${e.repo}/${e.path}@${e.branch}`),this.githubGetFileContentsTool){this.logger.debug(`GitHub MCP tool found, calling with image reference: ${JSON.stringify(e)}`);try{let I=await this.githubGetFileContentsTool.callback({owner:e.owner,repo:e.repo,path:e.path,branch:e.branch},{toolCallId:crypto.randomUUID(),settings:this.settings});if(this.logger.debug(`GitHub tool call completed. Result type: ${typeof I}`),this.logger.debug(`GitHub tool call result structure: ${typeof I=="object"&&I!==null?Object.keys(I).join(", "):typeof I}`),typeof I=="object"&&I!==null&&"binaryResultForLlm"in I&&Array.isArray(I.binaryResultForLlm)){this.logger.debug(`Tool result has binaryResultForLlm array with ${I.binaryResultForLlm.length} items`);try{for(let l of I.binaryResultForLlm)if(l.data&&l.mimeType){let n=Buffer.from(l.data,"base64"),c=l.mimeType;return{buffer:n,mimeType:c}}}catch(l){this.logger.error(`Failed to parse GitHub tool response: ${l}`),this.logger.debug(`binaryResultForLlm length: ${I.binaryResultForLlm?.length||0}`)}}else typeof I=="string"?this.logger.debug(`GitHub tool returned string result: ${I}`):this.logger.debug(`GitHub tool call failed or returned unexpected format. Result structure: ${typeof I=="object"&&I!==null?Object.keys(I).join(", "):typeof I}`)}catch(I){this.logger.error(`Error calling GitHub MCP tool: ${I}`)}}else this.logger.debug("GitHub MCP tool 'github-mcp-server-get_file_contents' not available");return this.logger.debug("Failed to retrieve repository image, returning null"),null}async getImgRefsSmallerThanMaxSize(e,I,l){let n=[],c=await Promise.all(e);for(let{imgRef:r,attachment:s}of c)if(this.logger.debug(`Processing attachment for ${r.url}, has buffer: ${!!s.buffer}, buffer size: ${s.buffer?.length||0}`),s.buffer)if(I.extractedImagesSize.push(s.buffer.length),hl(this.settings,"copilot_swe_agent_resize_image_references")){if(!await K8(this.logger,I,l,HB,s.mimeType,s.buffer)){this.logger.info("Unable to resize image to be within limits, skipping");continue}n.push(r.url)}else{let a=await CB(l,HB,s.buffer);if(this.logger.debug(`Image size check for ${r.url}: size=${s.buffer.length}, maxSize=${l}, exceedsSize=${a.exceedsSizeLimit}, exceedsDimensions=${a.exceedsDimensionLimit}`),a.exceedsSizeLimit?(I.imagesRemovedDueToSize++,this.logger.debug(`Image ${r.url} removed due to size (${s.buffer.length} > ${l})`)):a.exceedsDimensionLimit&&(I.imagesRemovedDueToDimensions++,this.logger.debug(`Image ${r.url} removed due to dimensions`)),a.exceedsSizeLimit||a.exceedsDimensionLimit){this.processedImageUrls.add(r.url),this.logger.info(`Image has been removed from the request due to size constraints. Please resize images to be smaller than ${zm(l)}.`);continue}n.push(r.url),this.logger.debug(`Image ${r.url} passed size checks and added to results`)}else this.processedImageUrls.add(r.url),this.logger.debug(`Skipping image ${r.url} - could not fetch image data`);return n}async processImageReferences(e,I,l){let n=this.settings.github?.serverUrl||"";this.logger.debug(`Processing ${e.length} image references`),this.logger.debug(`GitHub server URL: ${n}`),this.logger.debug(`Image references: ${e.map(s=>s.url).join(", ")}`);let c=e.filter(s=>!this.processedImageUrls.has(s.url)).map(async s=>{if(this.logger.debug(`Processing image reference: ${JSON.stringify(s,null,2)}`),s.kind==="committed_attachment"){this.logger.debug(`Detected repository image - Owner: ${s.owner}, Repo: ${s.repo}, Branch: ${s.branch}, Path: ${s.path}`);let a=await this.getRepositoryImageViaTools(s);return a?.buffer?(this.logger.debug(`Successfully fetched repository image buffer, size: ${a.buffer.length} bytes`),l.imagesResolvedFromGitHubMCPSize.push(a.buffer.length)):this.logger.debug("Failed to fetch repository image buffer"),{imgRef:s,attachment:{size:a?.buffer?.length||0,mimeType:a?.mimeType||"",buffer:a?.buffer||null}}}else return this.logger.debug(`Non-repository image, using getAttachmentFromGuid for: ${s.url}`),{imgRef:s,attachment:await P7I(s.guid,eC(this.settings),this.logger,this.settings)}}),r=await this.getImgRefsSmallerThanMaxSize(c,l,I);return this.logger.debug(`Processed image references, found ${r.length} attachments smaller than max size of ${zm(I)}`),{addedImages:r}}logger;settings;gitHubServerUrl;processedImageUrls;messagesToInsertOnNextPreRequest;githubGetFileContentsTool;constructor(e,I,l){this.logger=e,this.settings=I,this.gitHubServerUrl=I.github?.serverUrl,this.githubGetFileContentsTool=l,this.processedImageUrls=new Set,this.messagesToInsertOnNextPreRequest=[]}toJSON(){return"CAPIImageProcessor"}async onRequestError(e){}async preErrorThrow(e){this.processedImageUrls.size>0&&(e.isVisionFlow=!0)}async postToolExecution(e){let I=e.modelInfo,l=e.toolCall.function.name,n=e.toolResult;if(I?.capabilities?.supports?.vision){let c=Array.from(a_I(n,l));if(c.length===0){let r=await i_I(e.toolCall,this.logger);r&&c.push(r)}this.insertImageUrlMessages(c)}}insertImageUrlMessages(e){this.logger.info(`Inserted ${e.length} image URLs from tools into chat history.`);for(let I of e)this.messagesToInsertOnNextPreRequest.push({role:"user",content:[{type:"text",text:I.isScreenshot?"Here is a screenshot:":"Here is an image:"},{type:"image_url",image_url:{url:I.url}}]})}};function*a_I(t,e){for(let I of t.binaryResultForLlm??[])I.type==="image"&&(yield{url:`data:${I.mimeType};base64,${I.data}`,isScreenshot:e.toLowerCase().includes("screenshot")})}var o_I="playwright-browser_take_screenshot";function G_I(t){return typeof t=="object"&&t!==null&&typeof t.filename=="string"}async function i_I(t,e){if(t.function.name!==o_I)return;e.debug("Adding images using Playwright params fallback strategy");let I=JSON.parse(t.function.arguments);if(G_I(I)){let l=vB.isAbsolute(I.filename)?I.filename:vB.join(IZe,I.filename);e.debug(`Image from Playwright params: ${I.filename}. Updated to ${l}.`);let n=await b_I(l,e);if(n){let c=n.buffer.toString("base64");return{url:`data:${n.mimeType};base64,${c}`,isScreenshot:!0}}}}function d_I(t){switch(vB.extname(t).toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";default:return null}}function W8e(t,e){return e!=="image/png"&&e!=="image/jpeg"?(t.debug(`Unsupported content type: ${e}, only image / png and image / jpeg are supported`),!1):!0}async function b_I(t,e){try{if(!sZe(t))return e.debug(`Image ${t} does not have a valid image extension, skipping read`),null;let I=d_I(t);return I?{buffer:await K7I.readFile(t),mimeType:I}:(e.debug(`Image ${t} is not a mime type supported for file -> data URI flow`),null)}catch(I){return e.error(`Failed to read image from disk: ${I instanceof Error?I.message:String(I)}`),null}}var av=class t{static DEFAULT_TOKEN_LIMIT=128e3;static DEFAULT_TOKEN_LIMIT_BUFFER=0;static MAX_TOKEN_LIMIT_BUFFER=.5;latestUserPromptMessage;logger;modelToTokenLimit;constructor(e,I){this.latestUserPromptMessage=e,this.logger=I,this.modelToTokenLimit=new Map}toJSON(){return"BasicTruncator"}async*preRequest(e){this.initializeStateForModelOnFirstRequest(e);let I=this.modelToTokenLimit.get(e.modelInfo.name),l=I?.tokenLimit??t.DEFAULT_TOKEN_LIMIT;e.getCompletionWithToolsOptions?.failIfInitialInputsTooLong&&this.throwIfOverTokenLimitOnFirstTurn(e,l);let n=I?.tokenLimitBuffer??t.DEFAULT_TOKEN_LIMIT_BUFFER,c=l*(1-n),r=this.latestUserPromptMessage?lze(this.latestUserPromptMessage,e.messages):-1,s=[()=>p_I(e.messages,e.toolDefinitions,e.modelInfo.name,c),r===-1?void 0:()=>u_I(e.messages,e.toolDefinitions,e.modelInfo.name,c,r)].filter(G=>G!==void 0),a=0,o;for(;(!o||o.postTruncationTokensInMessages>c)&&a<s.length;){let G=s[a]();o=h_I(o,G),a++}return o=o??Z_I(e.messages,e.toolDefinitions,e.modelInfo.name,c),o.tokensRemovedDuringTruncation>0&&this.logger.debug(`BasicTruncator truncated: ${JSON.stringify(o)}`),yield{kind:"history_truncated",turn:e.turn,performedBy:"BasicTruncator",truncateResult:o},o}async preErrorThrow(){}async onRequestError(e){let I=this.modelToTokenLimit.get(e.modelInfo.name);if(I===void 0){this.logger.warning("Unable to determine if error relates to token limits due to missing information.");return}let{tokenLimit:l,tokenLimitBuffer:n}=I,c=m_I(e.error,l);if(c!==void 0){if(c<l)this.modelToTokenLimit.set(e.modelInfo.name,{tokenLimit:c,tokenLimitBuffer:t.DEFAULT_TOKEN_LIMIT_BUFFER}),this.logger.debug(`Adjusted model token limit to ${c}`);else{let r=Math.min(n+t.MAX_TOKEN_LIMIT_BUFFER/e.maxRetries,t.MAX_TOKEN_LIMIT_BUFFER);this.modelToTokenLimit.set(e.modelInfo.name,{tokenLimit:l,tokenLimitBuffer:r}),this.logger.debug(`Adjusted model token limit to ${l}, token limit retry buffer to ${r}`)}return{retryAfter:1}}}getTokenLimitForModel(e){let I=this.modelToTokenLimit.get(e),l=I?I.tokenLimit*(1-I.tokenLimitBuffer):void 0;return{tokenLimit:I?.tokenLimit,tokenLimitBuffer:I?.tokenLimitBuffer,effectiveTokenLimit:l}}initializeStateForModelOnFirstRequest(e){e.turn===0&&e.retry===0&&this.modelToTokenLimit.set(e.modelInfo.name,{tokenLimit:e.modelInfo.capabilities?.limits?.max_prompt_tokens||e.modelInfo.capabilities?.limits?.max_context_window_tokens||t.DEFAULT_TOKEN_LIMIT,tokenLimitBuffer:t.DEFAULT_TOKEN_LIMIT_BUFFER})}throwIfOverTokenLimitOnFirstTurn(e,I){if(e.turn===0){let l=o2e(e.messages,e.modelInfo.name),n=G2e(e.toolDefinitions,e.modelInfo.name);if(l+n>I){if(e.getCompletionWithToolsOptions?.failIfInitialInputsTooLong)throw new Error(`Initial inputs exceed the model token limit of ${I} tokens.`);this.logger.warning(`Initial inputs exceed the model token limit of ${I} tokens. The model may not be able to process the inputs correctly.`)}}}};function m_I(t,e){if(t&&typeof t=="object"){let I="message"in t&&typeof t.message=="string"?t.message.match(/prompt token count of (\d+) exceeds the limit of (\d+)/):null;if(I){let r=parseInt(I[2],10);return isNaN(r)?e:r}if("code"in t&&t.code==="model_max_prompt_tokens_exceeded")return e;let n=[JSON.stringify(t)];t instanceof Error&&(n.push(t.message),t.cause instanceof Error?n.push(t.cause.message):t.cause&&n.push(JSON.stringify(t.cause)));let c="Input length and `max_tokens` exceed context limit";if(n.some(r=>r.includes(c)))return e}}function h_I(t,e){return t?{preTruncationMessagesLength:t.preTruncationMessagesLength,preTruncationTokensInMessages:t.preTruncationTokensInMessages,tokensRemovedDuringTruncation:t.tokensRemovedDuringTruncation+e.tokensRemovedDuringTruncation,messagesRemovedDuringTruncation:t.messagesRemovedDuringTruncation+e.messagesRemovedDuringTruncation,tokenLimit:t.tokenLimit,postTruncationMessagesLength:e.postTruncationMessagesLength,postTruncationTokensInMessages:e.postTruncationTokensInMessages}:e}var N8e=.95;function p_I(t,e,I,l,n){let c=t.length;if(c===0)return{tokenLimit:l,preTruncationTokensInMessages:0,preTruncationMessagesLength:c,postTruncationTokensInMessages:0,postTruncationMessagesLength:c,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let r=t.map(b=>BF(b,I)),s=Td(JSON.stringify(e),I),a=l*N8e,o=r.reduce((b,m)=>b+m,0)+s;if(o<=a)return{tokenLimit:l,preTruncationTokensInMessages:o,preTruncationMessagesLength:c,postTruncationTokensInMessages:o,postTruncationMessagesLength:c,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let G=new Set,i=0,d=Math.min(n??t.length,t.length);for(let b=0;b<d;b++){let m=t[b];if(m.role!=="system"&&m.role!=="tool"&&m.role!=="user"){if(m.role==="assistant"){let h=m.tool_calls||[],u=h.filter(AG).filter(y=>y.function.name===rJ),Z=h.filter(AG).filter(y=>y.function.name!==rJ),N=u.length===0,g=new Set(Z.map(y=>y.id));if(Z.length>0&&(m.tool_calls=u,r[b]=BF(m,I)),N&&(G.add(b),i+=r[b]),g.size>0)for(let y=b+1;y<t.length;y++){let F=t[y];if(F.role==="tool"&&g.has(F.tool_call_id)&&(G.add(y),i+=r[y],g.delete(F.tool_call_id),g.size===0))break}}if(o-i<a)break}}for(let b=t.length-1;b>=0;b--)G.has(b)&&t.splice(b,1);return{tokenLimit:l,preTruncationTokensInMessages:o,preTruncationMessagesLength:c,postTruncationTokensInMessages:o-i,postTruncationMessagesLength:t.length,tokensRemovedDuringTruncation:i,messagesRemovedDuringTruncation:c-t.length}}function u_I(t,e,I,l,n){let c=t.length;if(c===0)return{tokenLimit:l,preTruncationTokensInMessages:0,preTruncationMessagesLength:c,postTruncationTokensInMessages:0,postTruncationMessagesLength:c,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let r=t.map(b=>BF(b,I)),s=Td(JSON.stringify(e),I),a=l*N8e,o=r.reduce((b,m)=>b+m,0)+s;if(o<=a)return{tokenLimit:l,preTruncationTokensInMessages:o,preTruncationMessagesLength:c,postTruncationTokensInMessages:o,postTruncationMessagesLength:c,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let G=new Set,i=0,d=Math.min(n??t.length,t.length);for(let b=0;b<d;b++){let m=t[b];if(m.role!=="system"&&m.role!=="tool"){if(m.role==="user")G.add(b),i+=r[b];else if(m.role==="assistant"){let h=m.tool_calls||[],u=new Set(h.map(Z=>Z.id));if(G.add(b),i+=r[b],u.size>0)for(let Z=b+1;Z<t.length;Z++){let N=t[Z];if(N.role==="tool"&&u.has(N.tool_call_id)&&(G.add(Z),i+=r[Z],u.delete(N.tool_call_id),u.size===0))break}}if(o-i<a)break}}for(let b=t.length-1;b>=0;b--)G.has(b)&&t.splice(b,1);return{tokenLimit:l,preTruncationTokensInMessages:o,preTruncationMessagesLength:c,postTruncationTokensInMessages:o-i,postTruncationMessagesLength:t.length,tokensRemovedDuringTruncation:i,messagesRemovedDuringTruncation:c-t.length}}function Z_I(t,e,I,l){let n=t.length;if(n===0)return{tokenLimit:l,preTruncationTokensInMessages:0,preTruncationMessagesLength:n,postTruncationTokensInMessages:0,postTruncationMessagesLength:n,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let c=t.map(a=>BF(a,I)),r=Td(JSON.stringify(e),I),s=c.reduce((a,o)=>a+o,0)+r;return{tokenLimit:l,preTruncationTokensInMessages:s,preTruncationMessagesLength:n,postTruncationTokensInMessages:s,postTruncationMessagesLength:n,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0}}var dW=class extends Mp{constructor(){super()}debug(e){}log(e){}info(e){}notice(e){}warning(e){}error(e){}startGroup(e,I){}endGroup(e){}};var Y8e={fetch:{tools:[{toolName:"fetch"}]},time:{tools:[{toolName:"get_current_time"},{toolName:"convert_time"}]},sequentialthinking:{tools:[{toolName:"sequentialthinking"}]},"github-mcp-server":{tools:[{toolName:"get_code_scanning_alert"},{toolName:"get_commit"},{toolName:"get_file_contents"},{toolName:"get_issue"},{toolName:"get_issue_comments"},{toolName:"get_me"},{toolName:"get_copilot_space"},{toolName:"get_pull_request"},{toolName:"get_pull_request_comments"},{toolName:"get_pull_request_files"},{toolName:"get_pull_request_reviews"},{toolName:"get_pull_request_status"},{toolName:"get_secret_scanning_alert"},{toolName:"get_tag"},{toolName:"list_branches"},{toolName:"list_code_scanning_alerts"},{toolName:"list_commits"},{toolName:"list_issues"},{toolName:"list_pull_requests"},{toolName:"list_secret_scanning_alerts"},{toolName:"list_tags"},{toolName:"search_code"},{toolName:"search_issues"},{toolName:"search_repositories"},{toolName:"search_users"},{toolName:"get_job_logs"},{toolName:"get_workflow_run"},{toolName:"get_workflow_run_logs"},{toolName:"list_workflow_jobs"},{toolName:"list_workflow_runs"},{toolName:"list_workflow_run_artifacts"},{toolName:"list_workflows"},{toolName:"summarize_job_log_failures"}]},playwright:{tools:[{toolName:"browser_close"},{toolName:"browser_resize"},{toolName:"browser_console_messages"},{toolName:"browser_handle_dialog"},{toolName:"browser_file_upload"},{toolName:"browser_install"},{toolName:"browser_press_key"},{toolName:"browser_navigate"},{toolName:"browser_navigate_back"},{toolName:"browser_navigate_forward"},{toolName:"browser_network_requests"},{toolName:"browser_pdf_save"},{toolName:"browser_take_screenshot"},{toolName:"browser_snapshot"},{toolName:"browser_click"},{toolName:"browser_drag"},{toolName:"browser_hover"},{toolName:"browser_type"},{toolName:"browser_select_option"},{toolName:"browser_tab_list"},{toolName:"browser_tab_new"},{toolName:"browser_tab_select"},{toolName:"browser_tab_close"},{toolName:"browser_generate_playwright_test"},{toolName:"browser_wait_for"}]},primer:{tools:[{toolName:"init"},{toolName:"list_components"},{toolName:"get_component"},{toolName:"get_component_examples"},{toolName:"get_component_usage_guidelines"},{toolName:"get_component_accessibility_guidelines"},{toolName:"list_patterns"},{toolName:"get_pattern"},{toolName:"list_tokens"},{toolName:"get_color_usage"},{toolName:"get_typography_usage"},{toolName:"list_icons"},{toolName:"get_icon"},{toolName:"review_alt_text"}]},azure:"azure-mcp-server","azure-azmcp":"azure-mcp-server","azure-mcp-server-azmcp":"azure-mcp-server","azure-mcp-server":{tools:[{toolName:"aks"},{toolName:"appconfig"},{toolName:"azureterraformbestpractices"},{toolName:"bestpractices"},{toolName:"bicepschema"},{toolName:"cosmos"},{toolName:"datadog"},{toolName:"documentation"},{toolName:"extension_az"},{toolName:"extension_azd"},{toolName:"extension_azqr"},{toolName:"foundry"},{toolName:"grafana"},{toolName:"group"},{toolName:"keyvault"},{toolName:"kusto"},{toolName:"loadtesting"},{toolName:"marketplace"},{toolName:"monitor"},{toolName:"postgres"},{toolName:"redis"},{toolName:"role"},{toolName:"search"},{toolName:"servicebus"},{toolName:"sql"},{toolName:"storage"},{toolName:"subscription"},{toolName:"workbooks"}]}};function q8(t,e,I){let l=(I||Y8e)[t.toLowerCase()],n=new Set;for(;typeof l=="string";){if(n.has(l))return!1;n.add(l),l=Y8e[l]}if(!l)return!1;let c=e.toLowerCase();return l.tools.some(r=>r.toolName===c)}var W_I="image";var N_I="resource",Y_I=180*1e3,V_I={timeout:Y_I};var oZe=class{constructor(e,I,l){this.settings=e;this.logger=I;this.cacheProviderTools=l}cachedTools=new Map;async invokeTool(e,I,l="hidden_characters"){let n=await this.doInvokeTool(e,I);return this.invokeToolResponseToToolResult(n,l)}invokeToolResponseToToolResult(e,I){let l=e.content||[],n="",c=[];for(let o of l)if(o.type==="text")n+=o.text||"";else if(o.type==="resource"){let G=o.resource;G&&G.blob?c.push({type:N_I,data:G.blob,mimeType:G.mimeType||"application/octet-stream"}):G&&G.text&&(n+=G.text)}else o.type==="image"&&c.push({type:W_I,data:o.data,mimeType:o.mimeType});let r=n;if(n==="")this.logger.debug("Tool invocation result is empty or undefined, skipping content filtering."),r=n;else try{let o=JSON.parse(n),G=Jpe(o,I);r=JSON.stringify(G)}catch(o){this.logger.debug(`Unable to parse tool invocation as JSON. Treating it as a string for filtering: ${o}`),r=vpe(n,I)}this.logger.debug(`Tool invocation result: ${r}`);let s={},a=r?Dn(r,"output"):"";return e.isToolError?{textResultForLlm:r,resultType:"failure",error:r,sessionLog:a,toolTelemetry:s}:{textResultForLlm:r,binaryResultForLlm:c,resultType:"success",sessionLog:a,toolTelemetry:s}}async loadTools(e,I={requestRequired:!1}){let l=this.getProviderCacheKey(e),n=this.cachedTools.get(l),c=n??await this.loadToolsFromProvider(e);this.cacheProviderTools&&!n&&this.cachedTools.set(l,c);let r={};for(let[s,a]of Object.entries(c)){let o=a.filterMode||"hidden_characters";r[s]={name:a.name,namespacedName:a.namespacedName,title:a.title||a.name,description:a.description,input_schema:a.input_schema,callback:async G=>{let i=c[s].serverName,d=c[s].name,b=c[s].title;if(!I.requestRequired)return this.invokeTool(s,G,o);let m=await I.request({kind:"mcp",serverName:i,toolName:d,toolTitle:b,args:G,readOnly:!!a.readOnly});switch(m.kind){case"approved":return this.invokeTool(s,G,o);case"denied-by-rules":return JT(m.rules);case"denied-no-approval-rule-and-could-not-request-from-user":return LT;case"denied-interactively-by-user":return CT;default:dm(m,`Unhandled permission result kind: ${m}`)}},safeForTelemetry:a.safeForTelemetry}}return Object.values(r)}};var LB=class t extends oZe{toolIdToClientInfo=new Map;constructor(e,I,l=!1){super(e,I,l)}async doInvokeTool(e,I){let l=this.toolIdToClientInfo.get(e);if(!l)throw new Error(`No MCP client found for tool ID: ${e}`);let n=l.mcpClient,c=t.getToolNameFromIdAndClientName(e,l.clientName),r=await n.callTool({name:c,arguments:I},void 0,{...V_I,onprogress:s=>{this.logger.info(`Tool ${e} progress: ${JSON.stringify(s)}`)},resetTimeoutOnProgress:!0});if(!Array.isArray(r.content))throw new Error("Expected array of results");return{content:r.content,isToolError:r.error!==void 0&&r.error!==null||r.isError===!0}}getProviderCacheKey(e){return[e.clientName,...e.tools,JSON.stringify(e.filterMapping)].join("+")}async loadToolsFromProvider(e){let I={};this.logger.debug(`Loading tools for client: ${e.clientName}`);for(let l of(await e.mcpClient.listTools()).tools){if(!e.tools.includes("*")&&!e.tools.includes(l.name)){this.logger.debug(`Skipping tool ${l.name} for client ${e.clientName}`);continue}let n=t.getToolIdFromClientAndToolName(e.clientName,l.name);this.toolIdToClientInfo.set(n,e);let c;e.safeForTelemetry===!0?c={name:!0,inputsNames:!0}:e.safeForTelemetry&&typeof e.safeForTelemetry=="object"?c=e.safeForTelemetry:c={name:q8(e.clientName,l.name),inputsNames:!1},this.logger.debug(`Adding tool: ${n}`);let r;e.filterMapping===void 0?r="hidden_characters":typeof e.filterMapping=="object"?r=e.filterMapping[l.name]||"hidden_characters":r=e.filterMapping,I[n]={serverName:e.clientName,name:n,namespacedName:`${e.clientName}/${l.name}`,title:l.title||l.annotations?.title||l.name,description:l.description||"",input_schema:l.inputSchema,readOnly:l.annotations?.readOnlyHint,safeForTelemetry:c,filterMode:r}}return I}static getToolIdFromClientAndToolName(e,I){return`${e}-${I}`}static getToolNameFromIdAndClientName(e,I){return e.substring(I.length+1)}};var _8=class{settings;logger;gitHandler;location;commitPriorToCompletionWithTools;jitInstructions;emittedJitInstructions;constructor(e,I,l,n,c,r){this.settings=e,this.logger=I,this.gitHandler=l,this.location=n,this.commitPriorToCompletionWithTools=c,this.jitInstructions=r||{},this.emittedJitInstructions=new Set}toJSON(){return"JitInstructionsProcessor"}async*preRequest(e){if(this.jitInstructions&&Object.keys(this.jitInstructions).length>0){let I,l=async()=>{if(I===void 0)try{I=(await this.gitHandler.getChangedPaths(this.location,"HEAD",this.commitPriorToCompletionWithTools)).length}catch(r){this.logger.error(`Failed to get changed paths, err: ${r}`),I=1}return I},n;for(let[r,s]of Object.entries(this.jitInstructions)){let a=e2e(this.settings,s.percentRemainingOfTimeout);a.isWithin&&(!s.whenNoPathsChanged||await l()===0)&&(!n||a.withinMs<n[0])&&(n=[a.withinMs,s.instruction])}let c=n?.[1];if(typeof c=="function"&&(c=c(this.location)),c&&!this.emittedJitInstructions.has(c)){this.logger.debug(`Adding JIT instructions to the history: ${c}`),this.emittedJitInstructions.add(c);let r={role:"user",content:c};e.messages.push(r),yield{kind:"message",turn:e.turn,callId:e.callId,message:r,source:"jit-instruction"}}}}},iZe={remindWhereToDoWork:{instruction:u8e,percentRemainingOfTimeout:1/2,whenNoPathsChanged:!0},completeAsSoonAsPossible:{instruction:D8.completeAsSoonAsPossible,percentRemainingOfTimeout:1/6},commitNow:{instruction:D8.commitNow,percentRemainingOfTimeout:2/15},finalAnswerNeeded:{instruction:D8.finalAnswerNeeded,percentRemainingOfTimeout:1/10}};function $8(t){if(!t)return nze;let[e,...I]=t?.split(":")??[t,void 0],l=I.join(":")||void 0;return{agent:e||void 0,model:l||void 0}}var fB=class{logger;forcePremiumRequest=!1;constructor(e){this.logger=e}async*preRequest(e){e.turn===0||this.forcePremiumRequest?(e.additionalRequestHeaders["X-Initiator"]="user",this.logger.debug("InitiatorHeaderProcessor: Setting X-Initiator to 'user'")):(e.additionalRequestHeaders["X-Initiator"]="agent",this.logger.debug("InitiatorHeaderProcessor: Setting X-Initiator to 'agent'")),this.resetPremiumRequest(),yield*[]}setForcePremiumRequest(){this.forcePremiumRequest=!0}toJSON(){return JSON.stringify({type:"InitiatorHeaderProcessor"})}resetPremiumRequest(){this.forcePremiumRequest=!1}},kB=class{logger;constructor(e){this.logger=e}async*preRequest(e){e.additionalRequestHeaders["X-Initiator"]="agent",this.logger.debug("FreeRequestProcessor: Setting X-Initiator to 'agent'"),yield*[]}setForcePremiumRequest(){}toJSON(){return JSON.stringify({type:"FreeRequestProcessor"})}};function e7(t){return t.kind==="message"&&t.message.role==="assistant"}function V8e(t){return t.kind==="message"&&t.message.role==="user"}function R8e(t){return t.kind==="message"&&t.message.role==="assistant"&&!!t.message.tool_calls}function y8e(t){return t.kind==="message"&&t.message.role==="tool"}function R_I(t,e){return t.toolCalls.find(I=>I.toolCallId===e)}function y_I(t,e,I){let l=I.function.name;try{let n=JSON.parse(I.function.arguments||"{}"),c=e.find(o=>o.name===l),r=c?.safeForTelemetry||{name:!1,inputsNames:!1},s=dX(c),a;if(s&&t.customAgents&&t.settings){let o=t.customAgents.find(G=>G.name===l);if(o){let G=t.settings.github?.repo?.name??"",i=G.split("/"),d=i.length===2?i[0]:"",b=i.length===2?i[1]:G,m=o.mcpServers?Object.keys(o.mcpServers).join(","):"",h=o.mcpServers?Object.keys(o.mcpServers).length:0;a={repoOwner:d,repoName:b,displayName:o.name,mcpServerNames:m,mcpServerCount:h}}}return{toolCallId:I.id,toolName:l,arguments:I.function.arguments,safeForTelemetryToolName:r===!0||r.name?l:wR(l),safeForTelemetryArguments:r===!0||r.inputsNames?eze(n):"",isCustomAgent:s,customAgentInfo:a}}catch{return{toolCallId:I.id,toolName:l,arguments:I.function.arguments,safeForTelemetryToolName:wR(l),safeForTelemetryArguments:"",isCustomAgent:!1,customAgentInfo:void 0}}}var I7=class{constructor(e,I,l){this.runtimeContext=e;this.forAgent=I;this.toolsInUse=l}turnDataCache=new Map;emittedTurns=new Set;getTurnData(){return this.turnDataCache}async ingestEvent(e){let I,l;if("turn"in e&&typeof e.turn=="number"){if(I=e.turn+1,this.emittedTurns.has(I))return;this.turnDataCache.has(I)||this.turnDataCache.set(I,{featureFlagsAsString:m$(this.runtimeContext.settings),toolCalls:[],toolCallExecutions:[],turn:I}),l=this.turnDataCache.get(I)}else return;e.kind==="tool_execution"?await this.ingestToolExecutionEventAndEmitToolCallExecutedTelemetry(l,e):e.kind==="turn_started"||e.kind==="turn_failed"||e.kind==="turn_retry"||e.kind==="turn_ended"?(l={...l,model:e.model,modelInfo:JSON.stringify(e.modelInfo)},e.kind==="turn_started"?l={...l,startTimeMs:e.timestampMs}:e.kind==="turn_retry"?l={...l,endTimeMs:e.timestampMs,retriesUsed:(l.retriesUsed??0)+1}:e.kind==="turn_failed"?l={...l,endTimeMs:e.timestampMs,error:e.error}:e.kind==="turn_ended"&&(l={...l,endTimeMs:e.timestampMs})):e.kind==="history_truncated"?l={...l,truncateEvent:e}:e.kind==="image_processing"?l={...l,imageProcessingMetrics:e.imageProcessingMetrics}:e.kind==="images_removed"?l={...l,largeImagesRemoved:(l.largeImagesRemoved??0)+(e.largeImagesRemoved?1:0),imagesRemoved:(l.imagesRemoved??0)+(e.imagesRemoved?1:0)}:e.kind==="model_call_success"||e.kind==="model_call_failure"?(l={...l,modelCallDurationMs:e.modelCallDurationMs,api_call_id:e.modelCall.api_id,provider_call_id:e.modelCall.request_id,conversationStructureSummary:Ize(e.requestMessages)},e.kind==="model_call_success"&&(l={...l,responsePromptTokens:e.responseUsage?.prompt_tokens,responseCompletionTokens:e.responseUsage?.completion_tokens,responseTotalTokens:e.responseUsage?.total_tokens})):V8e(e)&&e.source==="jit-instruction"?l={...l,jitInstructionsAdded:(l?.jitInstructionsAdded??0)+1}:e7(e)&&e.message.tool_calls?l={...l,toolCalls:l.toolCalls.concat(e.message.tool_calls.map(n=>({...y_I(this.runtimeContext,this.toolsInUse,n)})))}:y8e(e)&&(l={...l,toolCallExecutions:l.toolCallExecutions.concat([e.message.tool_call_id])}),this.turnDataCache.set(I,l),e.kind==="turn_ended"&&(await this.emitTurnTelemetry(I),this.emittedTurns.add(I),this.turnDataCache.delete(I))}async emitTurnTelemetry(e){let I=this.turnDataCache.get(e);if(I){let l={kind:"telemetry",telemetry:{event:"get_completion_with_tools_turn",properties:{model:I.model||"default",modelInfo:I.modelInfo||"{}",api_call_id:I.api_call_id,provider_call_id:I.provider_call_id,agent:this.forAgent,toolCalls:JSON.stringify(I.toolCalls.map(n=>({toolCallId:n.toolCallId,toolName:n.safeForTelemetryToolName}))),toolCallExecutions:JSON.stringify(I.toolCallExecutions),error:I.error,featureFlags:m$(this.runtimeContext.settings),conversationStructureSummary:I.conversationStructureSummary,truncationPerformedBy:I.truncateEvent?.performedBy},metrics:{turn:e,turnDurationMs:I.endTimeMs!==void 0&&I.startTimeMs!==void 0?I.endTimeMs-I.startTimeMs:0,modelCallDurationMs:I.modelCallDurationMs,retriesUsed:I.retriesUsed??0,numToolCalls:I.toolCalls.length,numToolExecutions:I.toolCallExecutions.length,largeImagesRemoved:I.largeImagesRemoved,imagesRemoved:I.imagesRemoved,responsePromptTokens:I.responsePromptTokens,responseCompletionTokens:I.responseCompletionTokens,responseTotalTokens:I.responseTotalTokens,jitInstructionsAdded:I.jitInstructionsAdded,...I.truncateEvent?.truncateResult,...I.imageProcessingMetrics},restrictedProperties:{}}};await this.runtimeContext.callback?.progress(l)}}async ingestToolExecutionEventAndEmitToolCallExecutedTelemetry(e,I){let l=I.toolCallId,n=R_I(e,l);if(n){let c=I.toolResult,r={kind:"telemetry",telemetry:{event:"tool_call_executed",properties:{...c.toolTelemetry.properties,resultType:c.resultType,toolCallId:l,arguments:n.safeForTelemetryArguments,toolName:n.safeForTelemetryToolName,api_call_id:e.api_call_id,isCustomAgent:n.isCustomAgent?"true":"false"},restrictedProperties:{...c.toolTelemetry.restrictedProperties,arguments:n.arguments,result:c.textResultForLlm,toolName:n.toolName,error:c.error,customAgent:n.customAgentInfo?JSON.stringify({repoOwner:n.customAgentInfo.repoOwner,repoName:n.customAgentInfo.repoName,displayName:n.customAgentInfo.displayName,mcpServerNames:n.customAgentInfo.mcpServerNames}):void 0},metrics:{...c.toolTelemetry.metrics,durationMs:I.durationMs,customAgentMcpServerCount:n.customAgentInfo?.mcpServerCount}}};await this.runtimeContext.callback?.progress(r)}}};var xB=class{async*preRequest(e){yield*[]}handleCallbackResponse(e){}getUserMessages(){return[]}clearUserMessages(){}canProcessUserMessages(){return!1}toJSON(){return JSON.stringify({type:"NoopUserMessageProcessor"})}};var g_I=void 0,t7=class{constructor(e,I=g_I){this.runtimeContext=e;this.agentId=I;this.gitHandlers={silent:new No(new dW,this.runtimeContext.exec),logging:new No(this.runtimeContext.logger,this.runtimeContext.exec)}}gitHandlers;async agent(e,I,l,n,c,r,s,a=new xB,o){let G=async(m,h,u)=>{let Z={role:"user",content:m};return await this.runtimeContext.callback?.progress({kind:"message",turn:0,callId:this.agentId,message:Z}),await this.runCompletionWithTools(e,I,[...h??[],Z],r,s,c,{executeToolsInParallel:hl(this.runtimeContext.settings,"copilot_swe_agent_parallel_tool_execution"),initialTurnCount:u},o,a)},i=n,d=l??[],b;for(;i;){let m=await G(i,d,b);b=m.finalTurnCount,d=m.messages,i=await o?.onResult(m.postCompletionWithToolsCommitHash)}for(let m of r)if(m.shutdown){let h=await m.shutdown();h&&await this.runtimeContext.callback?.progress(h)}return{finalTurnCount:b||0,messages:d}}async runCompletionWithTools(e,I,l,n,c,r,s,a,o=new xB){let G=this.runtimeContext.callback?new I7(this.runtimeContext,"sweagent-capi",n):void 0,i=this.gitHandlers.logging,d=await i.getCurrentCommitHash(e),b=l.filter(y=>y.role==="user").at(-1),m=this.createCompletionWithToolsProcessors(e,d,n,c,o,r,a,b),h=this.runtimeContext.client.getCompletionWithTools(I,l,n,{...s,callId:this.agentId,processors:m}),u=0,Z=[...l],N=[];for await(let y of h){if(hl(this.runtimeContext.settings,"copilot_swe_agent_progress_commands")){let F=await this.runtimeContext.callback?.progress(y,{accepts_user_messages:o.canProcessUserMessages()});o.handleCallbackResponse(F)}else await this.runtimeContext.callback?.progress(y);G&&await G.ingestEvent(y),(y.kind==="message"||y.kind==="response")&&(y.kind==="message"&&Z.push(y.message),y.kind==="response"&&N.push(y.response),u=Math.max(u,y.turn??0))}let g=await i.getCurrentCommitHash(e);return{finalTurnCount:u,messages:Z,resultMessages:N,preCompletionWithToolsCommitHash:d,postCompletionWithToolsCommitHash:g}}createCompletionWithToolsProcessors(e,I,l,n,c,r,s,a){let o=new P8(this.runtimeContext.logger,this.runtimeContext.settings,l.find(b=>b.name==="github-mcp-server-get_file_contents")),G=new _8(this.runtimeContext.settings,this.runtimeContext.logger,this.gitHandlers.silent,e,I,r),i=new av(a,this.runtimeContext.logger),d=[G,o,i];return hl(this.runtimeContext.settings,"copilot_swe_agent_progress_commands")&&d.push(c),d.push(n),{preRequest:d.filter(b=>b!==void 0),preToolsExecution:[s].filter(b=>b!==void 0),postToolExecution:[o,s].filter(b=>b!==void 0),onRequestError:[o,i].filter(b=>b!==void 0)}}};async function dZe(t,e,I,l,n){try{return(await l.invokeTool("blackbird-mcp-server/search_repository_with_agent",{task:t,depth:2,owner:e,repo:I,numSnippets:10},"hidden_characters")).textResultForLlm}catch(c){return n.error(`Error during Blackbird search: ${c}`),""}}var F8e=t=>hl(t,"copilot_swe_agent_search")||$Ye(t,"SearchAgentExperiment")==="enabled",g8e="search";function bZe(t){return t!==null&&typeof t=="object"&&"question"in t&&"reason"in t&&"searchCommand"in t}var F_I=(t,e,I)=>`
|
|
1348
|
+
</reminder>`),l.trim()},D8={completeAsSoonAsPossible:"You will soon run out of iterations. Begin making your final code changes. Complete any code changes that are still pending instead of performing validations.",commitNow:"You are imminently out of iterations. Call **report_progress** detailing your current progress. After doing so, provide a final answer as soon as possible.",finalAnswerNeeded:"You have reached the maximum number of iterations. Consider your work completed. I no longer need more changes. Please provide a final answer."},u8e=t=>`<reminder>You haven't committed any changes yet. Any code changes not meant to be temporary must be made in ${Wue(t)}. Commit changes by using the **report_progress** tool.</reminder>`;var IZe="/tmp/playwright-logs",D7I="0.0.40",tZe=[`@playwright/mcp@${D7I}`,"--viewport-size","1280, 720","--output-dir",IZe],Ixl=[...tZe,"--isolated"];var lZe=class t extends Error{constructor(e){super(e),this.name="ImageSizeError",Object.setPrototypeOf(this,t.prototype)}},HB=2e3;async function P7I(t,e,I,l){let n={"Content-Type":"application/octet-stream",Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",Authorization:"Bearer "+e},c=`${z2e(l)}/${t}`;I.info(`Downloading image from ${c}`);try{let r=await fetch(c,{method:"GET",headers:n});if(I.info(`Response status: ${r.status} ${r.statusText}`),I.debug(`Download Response URL: ${r.url}`),!r.ok){I.info(`Failed to download image, status: ${r.status}, statusText: ${r.statusText}`);try{let d=await r.text();I.info(`Error response body: ${d}`)}catch(d){I.info(`Could not read error response body: ${d}`)}return{size:0}}let a=(await r.json()).url;if(!a)return I.error(`No asset URL found in response for image GUID: ${t}`),{size:0};let o=await fetch(a,{method:"GET"});if(!o.ok)return I.error(`Failed to download image: ${o.status} ${o.statusText}`),{size:0};let G=await o.arrayBuffer(),i=G.byteLength;return I.info(`Downloaded content size: ${zm(i)}`),{size:i,buffer:Buffer.from(G),mimeType:o.headers.get("content-type")||void 0}}catch(r){return I.error("Network error downloading image"),r instanceof Error&&(I.info(`Error message: ${r.message}`),I.info(`Error stack: ${r.stack}`)),{size:0}}}function nZe(t,e,I,l){let n=/<img\b[^>]*\bsrc="([^"]+)"[^>]*>/g,c=/!\[.*?\]\((.*?)\)/g,r=[];return r.push(...Z8e(t,e,n,I,l)),r.push(...Z8e(t,e,c,I,l)),r}function Z8e(t,e,I,l,n){let c=t.matchAll(I),r=[],s=/\/([a-f0-9-]+)$/;for(let a of c){let o=e_I(a[1],e),G=I_I(a[1],e,n);if(o||G){let i=a[1].match(s),d={url:a[1],guid:"",kind:G?"legacy_attachment":"attachment"};i&&i.length>1&&(d.guid=i[1]),r.push(d)}else if(l){let i={url:a[1],guid:"",kind:"committed_attachment"};r.push(i)}}return r}function q7I(t){return!t.startsWith("http://")&&!t.startsWith("https://")&&sZe(t)}function sZe(t){return/\.(png|jpe?g|gif|svg|webp|bmp|tiff?|ico|heic|avif)$/i.test(t)}function _7I(t){try{let e=/Here are relevant code snippets from the repository that might help with this task:\s*(\[[\s\S]*?\])(?=\n|$)/,I=t.match(e);if(!I?.[1]||I[1].length<=1)return null;let l=I[1].trim();return JSON.parse(l)}catch{return null}}function $7I(t,e,I){if(!t?.url||!t?.ref||!t?.path)throw new Error("Invalid repository insight: missing required fields");if(!e||e.trim()==="")throw new Error("Invalid image path: path cannot be empty");let l=t.url.split("/").slice(3,5).join("/"),n=t.ref.split("/")[2],c;if(e.startsWith("/"))c=e.slice(1);else{let s=t.path,a=vB.dirname(s);c=vB.resolve("/",a,e).slice(1)}return`${I}/${l}/blob/${n}/${c}`}function e_I(t,e){return e?!!t.startsWith(`${e}/user-attachments/assets`):!1}function I_I(t,e,I){return e&&new RegExp(`^${e}/[\\w.-]+/[\\w.-]+/assets/\\d+/[^.]+$`).test(t)?(I.debug(`Legacy GitHub asset URL detected: ${t}`),!0):!1}async function aZe(t){let{width:e,height:I}=QPe(t);if(e===void 0||I===void 0)throw new Error("Unable to determine image dimensions.");return{width:e,height:I}}async function K8(t,e,I,l,n,c){t.debug(`Checking if image is valid size and dimensions. Max size: ${I}, Max dimension: ${l}`);let{exceedsSizeLimit:r,exceedsDimensionLimit:s}=await CB(I,l,c);if(!s&&!r)return t.debug("Image is within size and dimension limits."),c;if(s){t.debug(`Image x or y dimension exceeds the maximum limit of ${l}, attempting to resize`);let[a,o]=await n_I(t,c,l,I,n);if(!a){t.debug("Failed to resize image to fit within the maximum dimensions limits, skipping"),e.imagesRemovedDueToDimensions++,e.imagesFailedToResize++,o==="unsupported_mime_type"?e.resizeErrorsUnsupportedMimeType++:e.resizeErrorsUnknown++;return}let{exceedsDimensionLimit:G}=await CB(I,l,a);if(G){e.imagesRemovedDueToDimensions++,t.debug("Image dimensions exceed the maximum dimensions limits, skipping");return}return e.imagesResized++,t.debug("Image resized successfully."),a}if(r){t.debug(`Image size ${zm(c.length)} is larger than the maximum size of ${zm(I)}, attempting to reduce image quality`);let a=await c_I(t,c,l,I,n);if(!a){t.debug("Failed to reduce image quality to fit within the maximum size, skipping"),e.imagesFailedToReduceQuality++,e.imagesRemovedDueToSize++;return}return e.imagesWithLoweredQuality++,t.debug("Image quality successfully reduced."),a}}async function CB(t,e,I){let l=await aZe(I),n=I.length;return!l.width||!l.height?{exceedsSizeLimit:n>t,exceedsDimensionLimit:!1}:{exceedsSizeLimit:await l_I(t,I),exceedsDimensionLimit:await t_I(e,I)}}async function t_I(t,e){let I=await aZe(e);return!I.width||!I.height?!1:I.width>t||I.height>t}async function l_I(t,e){return e.length>t}async function n_I(t,e,I,l,n){try{if(!W8e(t,n))return[void 0,"unsupported_mime_type"];let c=await aZe(e);if(!c.width||!c.height)return t.error("Failed to determine size of uploaded image"),[void 0,"determine_dimensions_failed"];let r=async(u,Z)=>{let N=(0,rZe.default)(e).resize(u,Z,{fit:"inside",withoutEnlargement:!0});return cZe(t,await N.toBuffer(),void 0,n)},s=Math.min(I,c.width),a=Math.min(I,c.height),o=await r(s,a);if(o&&o.length<=l)return[o,void 0];let G=Math.max(s,a),i=1,d=G-1,b,m=0,h=10;for(;i<=d&&m<h;){let u=Math.floor((i+d)/2),Z=await r(u,u);if(!Z)break;let{exceedsSizeLimit:N,exceedsDimensionLimit:g}=await CB(l,I,Z);!N&&!g?(b=Z,i=u+1):d=u-1,m++}return[b,void 0]}catch(c){return t.error(`Failed to resize image for upload: ${c instanceof Error?c.message:String(c)}`),[void 0,"unknown"]}}async function c_I(t,e,I,l,n){try{let c=n==="image/png"?80:100,r=n==="image/png"?Math.floor(c*.4):20,s=await cZe(t,e,r,n);if(!s||s.length>l)return;let a=r,o=c,G,i=0,d=10,b=a,m=o-1;for(;b<=m&&i<d;){let h=Math.floor((b+m)/2),u=await cZe(t,e,h,n);if(!u)return G;let{exceedsSizeLimit:Z,exceedsDimensionLimit:N}=await CB(l,I,u);!Z&&!N?(G=u,b=h+1):m=h-1,i++}return G}catch(c){t.error(`Failed to reduce image quality: ${c instanceof Error?c.message:String(c)}`);return}}async function cZe(t,e,I,l){let n=(0,rZe.default)(e);switch(l){case"image/png":return I?n.png({quality:I}).toBuffer():n.png().toBuffer();case"image/jpeg":return I?n.jpeg({quality:I}).toBuffer():n.jpeg().toBuffer();default:t.debug(`Unsupported image format: ${l}`);return}}var JB=class{imagesRemovedDueToSize=0;imagesRemovedDueToDimensions=0;imagesResized=0;imagesWithLoweredQuality=0;imagesFailedToResize=0;imagesFailedToReduceQuality=0;base64ImagesSize=[];resizedBase64ImagesSize=[];extractedImagesSize=[];imagesResolvedFromGitHubMCPSize=[];resizeErrorsUnsupportedMimeType=0;resizeErrorsUnknown=0};function r_I(t,e,I,l){if(e<=0)return[];let n=[];for(let c of t){if(c.role!=="user"||n.length>=e)continue;let r=typeof c.content=="string"?c.content:JSON.stringify(c.content),s=_7I(r);if(s)for(let a in s){if(n.length>=e)break;let o=s[a].contents,G=nZe(o,I,!0,l);for(let i of G){if(n.length>=e)break;let d=i.url,b="",m=!1;if(i.kind==="attachment"||i.kind==="legacy_attachment"?n.push(i):q7I(d)?(m=!0,b=$7I(s[a],d,I),n.push({url:b,guid:i.guid,kind:"committed_attachment"})):sZe(d)&&d.startsWith(I)&&(m=!0,n.push({...i,kind:"committed_attachment"})),m){let h=n[n.length-1],u=new RegExp(`^${I}/([^/]+)/([^/]+)/blob/([^/]+)/(.+)$`),Z=h.url.match(u);if(l.info(`Blob match for ${h.url}: ${JSON.stringify(Z)}`),Z&&Z.length===5){let[,N,g,y,F]=Z;h.owner=N,h.repo=g,h.branch=y,h.path=F,l.info(`Repository metadata extracted: owner=${N}, repo=${g}, branch=${y}, path=${F}`)}else l.info(`Failed to extract repository metadata from URL: ${h.url}`)}}}}return n}function s_I(t,e){let I=e.flatMap(n=>l0(n)?n.content.flatMap(c=>c.type==="image_url"?c.image_url.url:[]):[]),l=new Set(I);return t.filter(n=>!l.has(n.url))}var P8=class{async resolveRepositoryImages(e,I,l,n,c,r){if(I<=0)return[];let s=r_I(e,I,l,n);this.logger.debug(`Found ${s.length} repository image URLs to process`);let a=s_I(s,e),o=await this.processImageReferences(a,c,r);return this.logger.debug(`Processed ${o.addedImages.length} repository image URLs`),o.addedImages}async*preRequest(e){let I=e.modelInfo;if(!I.capabilities?.limits){this.logger.debug("Model limits not defined, skipping image processing");return}if(!I.capabilities?.supports?.vision||!this.settings.featureFlags?.copilot_swe_agent_vision){this.logger.debug("Vision not supported or enabled, skipping image processing");return}if(!this.gitHubServerUrl){this.logger.debug("GitHub server URL is not set, skipping image processing");return}for(let i of this.messagesToInsertOnNextPreRequest)e.messages.push(i),yield{kind:"message",turn:e.turn,callId:e.callId,message:i};this.messagesToInsertOnNextPreRequest.splice(0);let l=[],n=I.capabilities.limits.vision?.max_prompt_images??1,c=I.capabilities.limits.vision?.max_prompt_image_size??3145728,r=0,s=[],a=new JB,o=new Map;for(let i of e.messages)if(i.role=="user")if(typeof i.content=="string"){let d=nZe(i.content,this.gitHubServerUrl,!1,this.logger).filter(m=>!this.processedImageUrls.has(m.url)),b=await this.processImageReferences(d,c,a);s.push(...b.addedImages)}else{let d=[];for(let[b,m]of i.content.entries()){if(m.type==="text"){let h=nZe(m.text,this.gitHubServerUrl,!1,this.logger).filter(Z=>!this.processedImageUrls.has(Z.url)),u=await this.processImageReferences(h,c,a);s.push(...u.addedImages)}else if(m.type==="image_url"){if(m.image_url.url.startsWith("data:")){let[h,u]=await this.extractAndUploadImageData(m,c,a);if(h===""){this.logger.debug("Skipping image upload for empty image data");continue}if(s.push(h),b>=1&&d.length>0){let Z=d.at(-1);Z&&Z.type==="text"&&Z.text&&Z.text.includes("screenshot")&&o.set(h,p8e(h))}d.pop();continue}r++}d.push(m)}i.content=d}for(this.logger.debug(`Found ${s.length} image urls in the messages`),this.logger.debug(`Allowed number of images: ${n}`);r<n&&s.length>0;){let i=s.shift();if(!i){this.logger.debug("Skipping empty image url");continue}if(this.processedImageUrls.has(i)){this.logger.debug(`Skipping already processed image url: ${i}`);continue}this.processedImageUrls.add(i);let d=`Here is the image url: ${i}`;o.has(i)&&(d=o.get(i)||d),this.logger.debug(`Adding image url: ${i}`),l.push({role:"user",content:[{type:"text",text:d},{type:"image_url",image_url:{url:i}}]}),r++}if(this.settings.featureFlags?.copilot_swe_agent_resolve_repo_images&&(this.logger.debug("Resolving repository images..."),r<n)){let i=await this.resolveRepositoryImages(e.messages,n-r,this.settings.github?.serverUrl||"",this.logger,c,a);this.logger.debug(`Resolved ${i.length} repository image URLs`);for(let d of i){if(r>=n)break;if(this.processedImageUrls.has(d)){this.logger.debug(`Skipping already processed repository image url: ${d}`);continue}l.push({role:"user",content:[{type:"text",text:"Here is the image url:"},{type:"image_url",image_url:{url:d}}]}),this.processedImageUrls.add(d),r++}}let G={imagesExtractedCount:a.extractedImagesSize.length,base64ImagesCount:a.base64ImagesSize.length,imagesRemovedDueToSize:a.imagesRemovedDueToSize,imagesRemovedDueToDimensions:a.imagesRemovedDueToDimensions,imagesResized:a.imagesResized,imagesResolvedFromGitHubMCPCount:a.imagesResolvedFromGitHubMCPSize.length};for(let i=0;i<a.base64ImagesSize.length;i++)G[`base64ImageSize_${i}`]=a.base64ImagesSize[i];for(let i=0;i<a.resizedBase64ImagesSize.length;i++)G[`resizedBase64ImageSize_${i}`]=a.resizedBase64ImagesSize[i];for(let i=0;i<a.extractedImagesSize.length;i++)G[`extractedImageSize_${i}`]=a.extractedImagesSize[i];for(let i=0;i<a.imagesResolvedFromGitHubMCPSize.length;i++)G[`imagesResolvedFromGitHubMCPSize_${i}`]=a.imagesResolvedFromGitHubMCPSize[i];l.length>0&&this.logger.debug(`Using ${l.length} image messages`);for(let i of l)yield{kind:"message",turn:e.turn,callId:e.callId,message:i},e.messages.push(i);G.allImagesSendToLlm=e.messages.filter(l0).length,yield{kind:"image_processing",turn:e.turn,imageProcessingMetrics:G},e.messages.some(i=>l0(i))&&(e.additionalRequestHeaders["Copilot-Vision-Request"]="true")}async extractAndUploadImageData(e,I,l){let n=eC(this.settings);if(!n)return this.logger.debug("No user token available, skipping image upload"),[""];this.logger.debug("Found base64 image data, uploading...");let c=e.image_url.url.match(/^data:(.*?);base64,(.*)$/);if(!c||c.length<3)return this.logger.debug("Invalid base64 image data format, skipping"),[""];let r=c[1];if(!W8e(this.logger,r))return[""];let s=c[2];if(s.length===0)return this.logger.debug("Empty base64 image data, skipping"),[""];let a=Buffer.from(s,"base64");if(l.base64ImagesSize.push(a.length),a=await K8(this.logger,l,I,HB,r,a),l.resizedBase64ImagesSize.push(a?.length??-1),!a)return["",new lZe(`Image size exceeds maximum size of ${zm(I)}`)];s=a.toString("base64");try{let o=await this.uploadBase64ImageData(s,r,n);return o?(this.logger.debug(`Uploaded image url: ${o}`),e.image_url.url=o,[o]):(this.logger.debug("Failed to upload image, skipping"),[""])}catch(o){let G=o instanceof Error?o.message:String(o);return this.logger.debug(`Error during image upload: ${G}`),[""]}}async uploadBase64ImageData(e,I,l){try{let n=B2e(this.settings),c=I.split("/").at(1),r=`image-${Date.now()}.${c}`;if(!e||e.trim()==="")return this.logger.error("Empty image data provided for upload"),null;let s=Buffer.from(e,"base64");if(s.length===0)return this.logger.error("Converted image data has zero length"),null;let a=this.settings.github?.repo?.id;if(!a)return this.logger.error("GitHub repository ID is not configured, cannot upload image"),null;let o=`${n}?name=${encodeURIComponent(r)}&content_type=${encodeURIComponent(I)}&repository_id=${a}`;this.logger.debug(`Uploading image data (${zm(s.length)}) to ${n} with name ${encodeURIComponent(r)} and content type ${encodeURIComponent(I)}`);let G={"Content-Type":"application/octet-stream",Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",Authorization:"Bearer "+l},i=await fetch(o,{method:"POST",headers:G,body:s}).catch(b=>{throw b instanceof Error?(this.logger.error(`Failed to upload image: ${b.message}`),b.code==="ECONNREFUSED"?this.logger.error("Connection refused. The server might be down or blocked."):b.code==="ETIMEDOUT"?this.logger.error("Connection timed out. Check network conditions or server load."):(b.message.includes("request entity too large")||b.message.includes("payload too large"))&&this.logger.error("Request payload too large. Try reducing the image size.")):typeof b=="object"&&b!==null&&"code"in b&&"message"in b?(this.logger.error(`Failed to upload image: ${b.message}`),b.code==="ECONNREFUSED"?this.logger.error("Connection refused. The server might be down or blocked."):b.code==="ETIMEDOUT"?this.logger.error("Connection timed out. Check network conditions or server load."):(b.message.includes("request entity too large")||b.message.includes("payload too large"))&&this.logger.error("Request payload too large. Try reducing the image size.")):this.logger.error(`Failed to upload image: ${String(b)}`),this.logger.debug(`Complete error details: ${JSON.stringify({code:b?.code,message:b?.message,stack:b?.stack,name:b?.name,cause:b?.cause},null,2)}`),b});if(!i.ok){let b=await i.text().catch(()=>"Unable to read error response");return this.logger.error(`Failed to upload image: ${i.status} ${i.statusText} - ${b}`),null}let d=await i.json();return this.logger.debug(`Upload result: ${JSON.stringify(d,null,2)}`),d.url||null}catch(n){return this.logger.error(`Error handling image upload: ${n instanceof Error?n.message:String(n)}`),n instanceof Error&&n.stack&&this.logger.debug(`Stack trace: ${n.stack}`),null}}async getRepositoryImageViaTools(e){if(this.logger.debug(`Attempting to retrieve repository image: ${e.owner}/${e.repo}/${e.path}@${e.branch}`),this.githubGetFileContentsTool){this.logger.debug(`GitHub MCP tool found, calling with image reference: ${JSON.stringify(e)}`);try{let I=await this.githubGetFileContentsTool.callback({owner:e.owner,repo:e.repo,path:e.path,branch:e.branch},{toolCallId:crypto.randomUUID(),settings:this.settings});if(this.logger.debug(`GitHub tool call completed. Result type: ${typeof I}`),this.logger.debug(`GitHub tool call result structure: ${typeof I=="object"&&I!==null?Object.keys(I).join(", "):typeof I}`),typeof I=="object"&&I!==null&&"binaryResultForLlm"in I&&Array.isArray(I.binaryResultForLlm)){this.logger.debug(`Tool result has binaryResultForLlm array with ${I.binaryResultForLlm.length} items`);try{for(let l of I.binaryResultForLlm)if(l.data&&l.mimeType){let n=Buffer.from(l.data,"base64"),c=l.mimeType;return{buffer:n,mimeType:c}}}catch(l){this.logger.error(`Failed to parse GitHub tool response: ${l}`),this.logger.debug(`binaryResultForLlm length: ${I.binaryResultForLlm?.length||0}`)}}else typeof I=="string"?this.logger.debug(`GitHub tool returned string result: ${I}`):this.logger.debug(`GitHub tool call failed or returned unexpected format. Result structure: ${typeof I=="object"&&I!==null?Object.keys(I).join(", "):typeof I}`)}catch(I){this.logger.error(`Error calling GitHub MCP tool: ${I}`)}}else this.logger.debug("GitHub MCP tool 'github-mcp-server-get_file_contents' not available");return this.logger.debug("Failed to retrieve repository image, returning null"),null}async getImgRefsSmallerThanMaxSize(e,I,l){let n=[],c=await Promise.all(e);for(let{imgRef:r,attachment:s}of c)if(this.logger.debug(`Processing attachment for ${r.url}, has buffer: ${!!s.buffer}, buffer size: ${s.buffer?.length||0}`),s.buffer)if(I.extractedImagesSize.push(s.buffer.length),hl(this.settings,"copilot_swe_agent_resize_image_references")){if(!await K8(this.logger,I,l,HB,s.mimeType,s.buffer)){this.logger.info("Unable to resize image to be within limits, skipping");continue}n.push(r.url)}else{let a=await CB(l,HB,s.buffer);if(this.logger.debug(`Image size check for ${r.url}: size=${s.buffer.length}, maxSize=${l}, exceedsSize=${a.exceedsSizeLimit}, exceedsDimensions=${a.exceedsDimensionLimit}`),a.exceedsSizeLimit?(I.imagesRemovedDueToSize++,this.logger.debug(`Image ${r.url} removed due to size (${s.buffer.length} > ${l})`)):a.exceedsDimensionLimit&&(I.imagesRemovedDueToDimensions++,this.logger.debug(`Image ${r.url} removed due to dimensions`)),a.exceedsSizeLimit||a.exceedsDimensionLimit){this.processedImageUrls.add(r.url),this.logger.info(`Image has been removed from the request due to size constraints. Please resize images to be smaller than ${zm(l)}.`);continue}n.push(r.url),this.logger.debug(`Image ${r.url} passed size checks and added to results`)}else this.processedImageUrls.add(r.url),this.logger.debug(`Skipping image ${r.url} - could not fetch image data`);return n}async processImageReferences(e,I,l){let n=this.settings.github?.serverUrl||"";this.logger.debug(`Processing ${e.length} image references`),this.logger.debug(`GitHub server URL: ${n}`),this.logger.debug(`Image references: ${e.map(s=>s.url).join(", ")}`);let c=e.filter(s=>!this.processedImageUrls.has(s.url)).map(async s=>{if(this.logger.debug(`Processing image reference: ${JSON.stringify(s,null,2)}`),s.kind==="committed_attachment"){this.logger.debug(`Detected repository image - Owner: ${s.owner}, Repo: ${s.repo}, Branch: ${s.branch}, Path: ${s.path}`);let a=await this.getRepositoryImageViaTools(s);return a?.buffer?(this.logger.debug(`Successfully fetched repository image buffer, size: ${a.buffer.length} bytes`),l.imagesResolvedFromGitHubMCPSize.push(a.buffer.length)):this.logger.debug("Failed to fetch repository image buffer"),{imgRef:s,attachment:{size:a?.buffer?.length||0,mimeType:a?.mimeType||"",buffer:a?.buffer||null}}}else return this.logger.debug(`Non-repository image, using getAttachmentFromGuid for: ${s.url}`),{imgRef:s,attachment:await P7I(s.guid,eC(this.settings),this.logger,this.settings)}}),r=await this.getImgRefsSmallerThanMaxSize(c,l,I);return this.logger.debug(`Processed image references, found ${r.length} attachments smaller than max size of ${zm(I)}`),{addedImages:r}}logger;settings;gitHubServerUrl;processedImageUrls;messagesToInsertOnNextPreRequest;githubGetFileContentsTool;constructor(e,I,l){this.logger=e,this.settings=I,this.gitHubServerUrl=I.github?.serverUrl,this.githubGetFileContentsTool=l,this.processedImageUrls=new Set,this.messagesToInsertOnNextPreRequest=[]}toJSON(){return"CAPIImageProcessor"}async onRequestError(e){}async preErrorThrow(e){this.processedImageUrls.size>0&&(e.isVisionFlow=!0)}async postToolExecution(e){let I=e.modelInfo,l=e.toolCall.function.name,n=e.toolResult;if(I?.capabilities?.supports?.vision){let c=Array.from(a_I(n,l));if(c.length===0){let r=await i_I(e.toolCall,this.logger);r&&c.push(r)}this.insertImageUrlMessages(c)}}insertImageUrlMessages(e){this.logger.info(`Inserted ${e.length} image URLs from tools into chat history.`);for(let I of e)this.messagesToInsertOnNextPreRequest.push({role:"user",content:[{type:"text",text:I.isScreenshot?"Here is a screenshot:":"Here is an image:"},{type:"image_url",image_url:{url:I.url}}]})}};function*a_I(t,e){for(let I of t.binaryResultForLlm??[])I.type==="image"&&(yield{url:`data:${I.mimeType};base64,${I.data}`,isScreenshot:e.toLowerCase().includes("screenshot")})}var o_I="playwright-browser_take_screenshot";function G_I(t){return typeof t=="object"&&t!==null&&typeof t.filename=="string"}async function i_I(t,e){if(t.function.name!==o_I)return;e.debug("Adding images using Playwright params fallback strategy");let I=JSON.parse(t.function.arguments);if(G_I(I)){let l=vB.isAbsolute(I.filename)?I.filename:vB.join(IZe,I.filename);e.debug(`Image from Playwright params: ${I.filename}. Updated to ${l}.`);let n=await b_I(l,e);if(n){let c=n.buffer.toString("base64");return{url:`data:${n.mimeType};base64,${c}`,isScreenshot:!0}}}}function d_I(t){switch(vB.extname(t).toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";default:return null}}function W8e(t,e){return e!=="image/png"&&e!=="image/jpeg"?(t.debug(`Unsupported content type: ${e}, only image / png and image / jpeg are supported`),!1):!0}async function b_I(t,e){try{if(!sZe(t))return e.debug(`Image ${t} does not have a valid image extension, skipping read`),null;let I=d_I(t);return I?{buffer:await K7I.readFile(t),mimeType:I}:(e.debug(`Image ${t} is not a mime type supported for file -> data URI flow`),null)}catch(I){return e.error(`Failed to read image from disk: ${I instanceof Error?I.message:String(I)}`),null}}var av=class t{static DEFAULT_TOKEN_LIMIT=128e3;static DEFAULT_TOKEN_LIMIT_BUFFER=0;static MAX_TOKEN_LIMIT_BUFFER=.5;latestUserPromptMessage;logger;modelToTokenLimit;constructor(e,I){this.latestUserPromptMessage=e,this.logger=I,this.modelToTokenLimit=new Map}toJSON(){return"BasicTruncator"}async*preRequest(e){this.initializeStateForModelOnFirstRequest(e);let I=this.modelToTokenLimit.get(e.modelInfo.name),l=I?.tokenLimit??t.DEFAULT_TOKEN_LIMIT;e.getCompletionWithToolsOptions?.failIfInitialInputsTooLong&&this.throwIfOverTokenLimitOnFirstTurn(e,l);let n=I?.tokenLimitBuffer??t.DEFAULT_TOKEN_LIMIT_BUFFER,c=l*(1-n),r=this.latestUserPromptMessage?lze(this.latestUserPromptMessage,e.messages):-1,s=[()=>p_I(e.messages,e.toolDefinitions,e.modelInfo.name,c),r===-1?void 0:()=>u_I(e.messages,e.toolDefinitions,e.modelInfo.name,c,r)].filter(G=>G!==void 0),a=0,o;for(;(!o||o.postTruncationTokensInMessages>c)&&a<s.length;){let G=s[a]();o=h_I(o,G),a++}return o=o??Z_I(e.messages,e.toolDefinitions,e.modelInfo.name,c),o.tokensRemovedDuringTruncation>0&&this.logger.debug(`BasicTruncator truncated: ${JSON.stringify(o)}`),yield{kind:"history_truncated",turn:e.turn,performedBy:"BasicTruncator",truncateResult:o},o}async preErrorThrow(){}async onRequestError(e){let I=this.modelToTokenLimit.get(e.modelInfo.name);if(I===void 0){this.logger.warning("Unable to determine if error relates to token limits due to missing information.");return}let{tokenLimit:l,tokenLimitBuffer:n}=I,c=m_I(e.error,l);if(c!==void 0){if(c<l)this.modelToTokenLimit.set(e.modelInfo.name,{tokenLimit:c,tokenLimitBuffer:t.DEFAULT_TOKEN_LIMIT_BUFFER}),this.logger.debug(`Adjusted model token limit to ${c}`);else{let r=Math.min(n+t.MAX_TOKEN_LIMIT_BUFFER/e.maxRetries,t.MAX_TOKEN_LIMIT_BUFFER);this.modelToTokenLimit.set(e.modelInfo.name,{tokenLimit:l,tokenLimitBuffer:r}),this.logger.debug(`Adjusted model token limit to ${l}, token limit retry buffer to ${r}`)}return{retryAfter:1}}}getTokenLimitForModel(e){let I=this.modelToTokenLimit.get(e),l=I?I.tokenLimit*(1-I.tokenLimitBuffer):void 0;return{tokenLimit:I?.tokenLimit,tokenLimitBuffer:I?.tokenLimitBuffer,effectiveTokenLimit:l}}initializeStateForModelOnFirstRequest(e){e.turn===0&&e.retry===0&&this.modelToTokenLimit.set(e.modelInfo.name,{tokenLimit:e.modelInfo.capabilities?.limits?.max_prompt_tokens||e.modelInfo.capabilities?.limits?.max_context_window_tokens||t.DEFAULT_TOKEN_LIMIT,tokenLimitBuffer:t.DEFAULT_TOKEN_LIMIT_BUFFER})}throwIfOverTokenLimitOnFirstTurn(e,I){if(e.turn===0){let l=o2e(e.messages,e.modelInfo.name),n=G2e(e.toolDefinitions,e.modelInfo.name);if(l+n>I){if(e.getCompletionWithToolsOptions?.failIfInitialInputsTooLong)throw new Error(`Initial inputs exceed the model token limit of ${I} tokens.`);this.logger.warning(`Initial inputs exceed the model token limit of ${I} tokens. The model may not be able to process the inputs correctly.`)}}}};function m_I(t,e){if(t&&typeof t=="object"){let I="message"in t&&typeof t.message=="string"?t.message.match(/prompt token count of (\d+) exceeds the limit of (\d+)/):null;if(I){let r=parseInt(I[2],10);return isNaN(r)?e:r}if("code"in t&&t.code==="model_max_prompt_tokens_exceeded")return e;let n=[JSON.stringify(t)];t instanceof Error&&(n.push(t.message),t.cause instanceof Error?n.push(t.cause.message):t.cause&&n.push(JSON.stringify(t.cause)));let c="Input length and `max_tokens` exceed context limit";if(n.some(r=>r.includes(c)))return e}}function h_I(t,e){return t?{preTruncationMessagesLength:t.preTruncationMessagesLength,preTruncationTokensInMessages:t.preTruncationTokensInMessages,tokensRemovedDuringTruncation:t.tokensRemovedDuringTruncation+e.tokensRemovedDuringTruncation,messagesRemovedDuringTruncation:t.messagesRemovedDuringTruncation+e.messagesRemovedDuringTruncation,tokenLimit:t.tokenLimit,postTruncationMessagesLength:e.postTruncationMessagesLength,postTruncationTokensInMessages:e.postTruncationTokensInMessages}:e}var N8e=.95;function p_I(t,e,I,l,n){let c=t.length;if(c===0)return{tokenLimit:l,preTruncationTokensInMessages:0,preTruncationMessagesLength:c,postTruncationTokensInMessages:0,postTruncationMessagesLength:c,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let r=t.map(b=>BF(b,I)),s=Td(JSON.stringify(e),I),a=l*N8e,o=r.reduce((b,m)=>b+m,0)+s;if(o<=a)return{tokenLimit:l,preTruncationTokensInMessages:o,preTruncationMessagesLength:c,postTruncationTokensInMessages:o,postTruncationMessagesLength:c,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let G=new Set,i=0,d=Math.min(n??t.length,t.length);for(let b=0;b<d;b++){let m=t[b];if(m.role!=="system"&&m.role!=="tool"&&m.role!=="user"){if(m.role==="assistant"){let h=m.tool_calls||[],u=h.filter(AG).filter(y=>y.function.name===rJ),Z=h.filter(AG).filter(y=>y.function.name!==rJ),N=u.length===0,g=new Set(Z.map(y=>y.id));if(Z.length>0&&(m.tool_calls=u,r[b]=BF(m,I)),N&&(G.add(b),i+=r[b]),g.size>0)for(let y=b+1;y<t.length;y++){let F=t[y];if(F.role==="tool"&&g.has(F.tool_call_id)&&(G.add(y),i+=r[y],g.delete(F.tool_call_id),g.size===0))break}}if(o-i<a)break}}for(let b=t.length-1;b>=0;b--)G.has(b)&&t.splice(b,1);return{tokenLimit:l,preTruncationTokensInMessages:o,preTruncationMessagesLength:c,postTruncationTokensInMessages:o-i,postTruncationMessagesLength:t.length,tokensRemovedDuringTruncation:i,messagesRemovedDuringTruncation:c-t.length}}function u_I(t,e,I,l,n){let c=t.length;if(c===0)return{tokenLimit:l,preTruncationTokensInMessages:0,preTruncationMessagesLength:c,postTruncationTokensInMessages:0,postTruncationMessagesLength:c,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let r=t.map(b=>BF(b,I)),s=Td(JSON.stringify(e),I),a=l*N8e,o=r.reduce((b,m)=>b+m,0)+s;if(o<=a)return{tokenLimit:l,preTruncationTokensInMessages:o,preTruncationMessagesLength:c,postTruncationTokensInMessages:o,postTruncationMessagesLength:c,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let G=new Set,i=0,d=Math.min(n??t.length,t.length);for(let b=0;b<d;b++){let m=t[b];if(m.role!=="system"&&m.role!=="tool"){if(m.role==="user")G.add(b),i+=r[b];else if(m.role==="assistant"){let h=m.tool_calls||[],u=new Set(h.map(Z=>Z.id));if(G.add(b),i+=r[b],u.size>0)for(let Z=b+1;Z<t.length;Z++){let N=t[Z];if(N.role==="tool"&&u.has(N.tool_call_id)&&(G.add(Z),i+=r[Z],u.delete(N.tool_call_id),u.size===0))break}}if(o-i<a)break}}for(let b=t.length-1;b>=0;b--)G.has(b)&&t.splice(b,1);return{tokenLimit:l,preTruncationTokensInMessages:o,preTruncationMessagesLength:c,postTruncationTokensInMessages:o-i,postTruncationMessagesLength:t.length,tokensRemovedDuringTruncation:i,messagesRemovedDuringTruncation:c-t.length}}function Z_I(t,e,I,l){let n=t.length;if(n===0)return{tokenLimit:l,preTruncationTokensInMessages:0,preTruncationMessagesLength:n,postTruncationTokensInMessages:0,postTruncationMessagesLength:n,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let c=t.map(a=>BF(a,I)),r=Td(JSON.stringify(e),I),s=c.reduce((a,o)=>a+o,0)+r;return{tokenLimit:l,preTruncationTokensInMessages:s,preTruncationMessagesLength:n,postTruncationTokensInMessages:s,postTruncationMessagesLength:n,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0}}var dW=class extends Mp{constructor(){super()}debug(e){}log(e){}info(e){}notice(e){}warning(e){}error(e){}startGroup(e,I){}endGroup(e){}};var Y8e={fetch:{tools:[{toolName:"fetch"}]},time:{tools:[{toolName:"get_current_time"},{toolName:"convert_time"}]},sequentialthinking:{tools:[{toolName:"sequentialthinking"}]},"github-mcp-server":{tools:[{toolName:"get_code_scanning_alert"},{toolName:"get_commit"},{toolName:"get_file_contents"},{toolName:"get_issue"},{toolName:"get_issue_comments"},{toolName:"get_me"},{toolName:"get_copilot_space"},{toolName:"get_pull_request"},{toolName:"get_pull_request_comments"},{toolName:"get_pull_request_files"},{toolName:"get_pull_request_reviews"},{toolName:"get_pull_request_status"},{toolName:"get_secret_scanning_alert"},{toolName:"get_tag"},{toolName:"list_branches"},{toolName:"list_code_scanning_alerts"},{toolName:"list_commits"},{toolName:"list_issues"},{toolName:"list_pull_requests"},{toolName:"list_secret_scanning_alerts"},{toolName:"list_tags"},{toolName:"search_code"},{toolName:"search_issues"},{toolName:"search_repositories"},{toolName:"search_users"},{toolName:"get_job_logs"},{toolName:"get_workflow_run"},{toolName:"get_workflow_run_logs"},{toolName:"list_workflow_jobs"},{toolName:"list_workflow_runs"},{toolName:"list_workflow_run_artifacts"},{toolName:"list_workflows"},{toolName:"summarize_job_log_failures"}]},playwright:{tools:[{toolName:"browser_close"},{toolName:"browser_resize"},{toolName:"browser_console_messages"},{toolName:"browser_handle_dialog"},{toolName:"browser_file_upload"},{toolName:"browser_install"},{toolName:"browser_press_key"},{toolName:"browser_navigate"},{toolName:"browser_navigate_back"},{toolName:"browser_navigate_forward"},{toolName:"browser_network_requests"},{toolName:"browser_pdf_save"},{toolName:"browser_take_screenshot"},{toolName:"browser_snapshot"},{toolName:"browser_click"},{toolName:"browser_drag"},{toolName:"browser_hover"},{toolName:"browser_type"},{toolName:"browser_select_option"},{toolName:"browser_tab_list"},{toolName:"browser_tab_new"},{toolName:"browser_tab_select"},{toolName:"browser_tab_close"},{toolName:"browser_generate_playwright_test"},{toolName:"browser_wait_for"}]},primer:{tools:[{toolName:"init"},{toolName:"list_components"},{toolName:"get_component"},{toolName:"get_component_examples"},{toolName:"get_component_usage_guidelines"},{toolName:"get_component_accessibility_guidelines"},{toolName:"list_patterns"},{toolName:"get_pattern"},{toolName:"list_tokens"},{toolName:"get_color_usage"},{toolName:"get_typography_usage"},{toolName:"list_icons"},{toolName:"get_icon"},{toolName:"review_alt_text"}]},azure:"azure-mcp-server","azure-azmcp":"azure-mcp-server","azure-mcp-server-azmcp":"azure-mcp-server","azure-mcp-server":{tools:[{toolName:"aks"},{toolName:"appconfig"},{toolName:"azureterraformbestpractices"},{toolName:"bestpractices"},{toolName:"bicepschema"},{toolName:"cosmos"},{toolName:"datadog"},{toolName:"documentation"},{toolName:"extension_az"},{toolName:"extension_azd"},{toolName:"extension_azqr"},{toolName:"foundry"},{toolName:"grafana"},{toolName:"group"},{toolName:"keyvault"},{toolName:"kusto"},{toolName:"loadtesting"},{toolName:"marketplace"},{toolName:"monitor"},{toolName:"postgres"},{toolName:"redis"},{toolName:"role"},{toolName:"search"},{toolName:"servicebus"},{toolName:"sql"},{toolName:"storage"},{toolName:"subscription"},{toolName:"workbooks"}]}};function q8(t,e,I){let l=(I||Y8e)[t.toLowerCase()],n=new Set;for(;typeof l=="string";){if(n.has(l))return!1;n.add(l),l=Y8e[l]}if(!l)return!1;let c=e.toLowerCase();return l.tools.some(r=>r.toolName===c)}var W_I="image";var N_I="resource",Y_I=180*1e3,V_I={timeout:Y_I};var oZe=class{constructor(e,I,l){this.settings=e;this.logger=I;this.cacheProviderTools=l}cachedTools=new Map;async invokeTool(e,I,l="hidden_characters"){let n=await this.doInvokeTool(e,I);return this.invokeToolResponseToToolResult(n,l)}invokeToolResponseToToolResult(e,I){let l=e.content||[],n="",c=[];for(let o of l)if(o.type==="text")n+=o.text||"";else if(o.type==="resource"){let G=o.resource;G&&G.blob?c.push({type:N_I,data:G.blob,mimeType:G.mimeType||"application/octet-stream"}):G&&G.text&&(n+=G.text)}else o.type==="image"&&c.push({type:W_I,data:o.data,mimeType:o.mimeType});let r=n;if(n==="")this.logger.debug("Tool invocation result is empty or undefined, skipping content filtering."),r=n;else try{let o=JSON.parse(n),G=Jpe(o,I);r=JSON.stringify(G)}catch(o){this.logger.debug(`Unable to parse tool invocation as JSON. Treating it as a string for filtering: ${o}`),r=vpe(n,I)}this.logger.debug(`Tool invocation result: ${r}`);let s={},a=r?Dn(r,"output"):"";return e.isToolError?{textResultForLlm:r,resultType:"failure",error:r,sessionLog:a,toolTelemetry:s}:{textResultForLlm:r,binaryResultForLlm:c,resultType:"success",sessionLog:a,toolTelemetry:s}}async loadTools(e,I={requestRequired:!1}){let l=this.getProviderCacheKey(e),n=this.cachedTools.get(l),c=n??await this.loadToolsFromProvider(e);this.cacheProviderTools&&!n&&this.cachedTools.set(l,c);let r={};for(let[s,a]of Object.entries(c)){let o=a.filterMode||"hidden_characters";r[s]={name:a.name,namespacedName:a.namespacedName,title:a.title||a.name,description:a.description,input_schema:a.input_schema,callback:async G=>{let i=c[s].serverName,d=c[s].name,b=c[s].title;if(!I.requestRequired)return this.invokeTool(s,G,o);let m=await I.request({kind:"mcp",serverName:i,toolName:d,toolTitle:b,args:G,readOnly:!!a.readOnly});switch(m.kind){case"approved":return this.invokeTool(s,G,o);case"denied-by-rules":return JT(m.rules);case"denied-no-approval-rule-and-could-not-request-from-user":return LT;case"denied-interactively-by-user":return CT;default:dm(m,`Unhandled permission result kind: ${m}`)}},safeForTelemetry:a.safeForTelemetry}}return Object.values(r)}};var LB=class t extends oZe{toolIdToClientInfo=new Map;constructor(e,I,l=!1){super(e,I,l)}async doInvokeTool(e,I){let l=this.toolIdToClientInfo.get(e);if(!l)throw new Error(`No MCP client found for tool ID: ${e}`);let n=l.mcpClient,c=t.getToolNameFromIdAndClientName(e,l.clientName),r=await n.callTool({name:c,arguments:I},void 0,{...V_I,onprogress:s=>{this.logger.info(`Tool ${e} progress: ${JSON.stringify(s)}`)},resetTimeoutOnProgress:!0});if(!Array.isArray(r.content))throw new Error("Expected array of results");return{content:r.content,isToolError:r.error!==void 0&&r.error!==null||r.isError===!0}}getProviderCacheKey(e){return[e.clientName,...e.tools,JSON.stringify(e.filterMapping)].join("+")}async loadToolsFromProvider(e){let I={};this.logger.debug(`Loading tools for client: ${e.clientName}`);for(let l of(await e.mcpClient.listTools()).tools){if(!e.tools.includes("*")&&!e.tools.includes(l.name)){this.logger.debug(`Skipping tool ${l.name} for client ${e.clientName}`);continue}let n=t.getToolIdFromClientAndToolName(e.clientName,l.name);this.toolIdToClientInfo.set(n,e);let c;e.safeForTelemetry===!0?c={name:!0,inputsNames:!0}:e.safeForTelemetry&&typeof e.safeForTelemetry=="object"?c=e.safeForTelemetry:c={name:q8(e.clientName,l.name),inputsNames:!1},this.logger.debug(`Adding tool: ${n}`);let r;e.filterMapping===void 0?r="hidden_characters":typeof e.filterMapping=="object"?r=e.filterMapping[l.name]||"hidden_characters":r=e.filterMapping,I[n]={serverName:e.clientName,name:n,namespacedName:`${e.clientName}/${l.name}`,title:l.title||l.annotations?.title||l.name,description:l.description||"",input_schema:l.inputSchema,readOnly:l.annotations?.readOnlyHint,safeForTelemetry:c,filterMode:r}}return I}static getToolIdFromClientAndToolName(e,I){return`${e}-${I}`}static getToolNameFromIdAndClientName(e,I){return e.substring(I.length+1)}};var _8=class{settings;logger;gitHandler;location;commitPriorToCompletionWithTools;jitInstructions;emittedJitInstructions;constructor(e,I,l,n,c,r){this.settings=e,this.logger=I,this.gitHandler=l,this.location=n,this.commitPriorToCompletionWithTools=c,this.jitInstructions=r||{},this.emittedJitInstructions=new Set}toJSON(){return"JitInstructionsProcessor"}async*preRequest(e){if(this.jitInstructions&&Object.keys(this.jitInstructions).length>0){let I,l=async()=>{if(I===void 0)try{I=(await this.gitHandler.getChangedPaths(this.location,"HEAD",this.commitPriorToCompletionWithTools)).length}catch(r){this.logger.error(`Failed to get changed paths, err: ${r}`),I=1}return I},n;for(let[r,s]of Object.entries(this.jitInstructions)){let a=e2e(this.settings,s.percentRemainingOfTimeout);a.isWithin&&(!s.whenNoPathsChanged||await l()===0)&&(!n||a.withinMs<n[0])&&(n=[a.withinMs,s.instruction])}let c=n?.[1];if(typeof c=="function"&&(c=c(this.location)),c&&!this.emittedJitInstructions.has(c)){this.logger.debug(`Adding JIT instructions to the history: ${c}`),this.emittedJitInstructions.add(c);let r={role:"user",content:c};e.messages.push(r),yield{kind:"message",turn:e.turn,callId:e.callId,message:r,source:"jit-instruction"}}}}},iZe={remindWhereToDoWork:{instruction:u8e,percentRemainingOfTimeout:1/2,whenNoPathsChanged:!0},completeAsSoonAsPossible:{instruction:D8.completeAsSoonAsPossible,percentRemainingOfTimeout:1/6},commitNow:{instruction:D8.commitNow,percentRemainingOfTimeout:2/15},finalAnswerNeeded:{instruction:D8.finalAnswerNeeded,percentRemainingOfTimeout:1/10}};function $8(t){if(!t)return nze;let[e,...I]=t?.split(":")??[t,void 0],l=I.join(":")||void 0;return{agent:e||void 0,model:l||void 0}}var fB=class{logger;forcePremiumRequest=!1;constructor(e){this.logger=e}async*preRequest(e){e.turn===0||this.forcePremiumRequest?(e.additionalRequestHeaders["X-Initiator"]="user",this.logger.debug("InitiatorHeaderProcessor: Setting X-Initiator to 'user'")):(e.additionalRequestHeaders["X-Initiator"]="agent",this.logger.debug("InitiatorHeaderProcessor: Setting X-Initiator to 'agent'")),this.resetPremiumRequest(),yield*[]}setForcePremiumRequest(){this.forcePremiumRequest=!0}toJSON(){return JSON.stringify({type:"InitiatorHeaderProcessor"})}resetPremiumRequest(){this.forcePremiumRequest=!1}},kB=class{logger;constructor(e){this.logger=e}async*preRequest(e){e.additionalRequestHeaders["X-Initiator"]="agent",this.logger.debug("FreeRequestProcessor: Setting X-Initiator to 'agent'"),yield*[]}setForcePremiumRequest(){}toJSON(){return JSON.stringify({type:"FreeRequestProcessor"})}};function e7(t){return t.kind==="message"&&t.message.role==="assistant"}function V8e(t){return t.kind==="message"&&t.message.role==="user"}function R8e(t){return t.kind==="message"&&t.message.role==="assistant"&&!!t.message.tool_calls}function y8e(t){return t.kind==="message"&&t.message.role==="tool"}function R_I(t,e){return t.toolCalls.find(I=>I.toolCallId===e)}function y_I(t,e,I){let l=I.function.name;try{let n=JSON.parse(I.function.arguments||"{}"),c=e.find(o=>o.name===l),r=c?.safeForTelemetry||{name:!1,inputsNames:!1},s=dX(c),a;if(s&&t.customAgents&&t.settings){let o=t.customAgents.find(G=>G.name===l);if(o){let G=t.settings.github?.repo?.name??"",i=G.split("/"),d=i.length===2?i[0]:"",b=i.length===2?i[1]:G,m=o.mcpServers?Object.keys(o.mcpServers).join(","):"",h=o.mcpServers?Object.keys(o.mcpServers).length:0;a={repoOwner:d,repoName:b,displayName:o.name,mcpServerNames:m,mcpServerCount:h}}}return{toolCallId:I.id,toolName:l,arguments:I.function.arguments,safeForTelemetryToolName:r===!0||r.name?l:wR(l),safeForTelemetryArguments:r===!0||r.inputsNames?eze(n):"",isCustomAgent:s,customAgentInfo:a}}catch{return{toolCallId:I.id,toolName:l,arguments:I.function.arguments,safeForTelemetryToolName:wR(l),safeForTelemetryArguments:"",isCustomAgent:!1,customAgentInfo:void 0}}}var I7=class{constructor(e,I,l){this.runtimeContext=e;this.forAgent=I;this.toolsInUse=l}turnDataCache=new Map;emittedTurns=new Set;getTurnData(){return this.turnDataCache}async ingestEvent(e){let I,l;if("turn"in e&&typeof e.turn=="number"){if(I=e.turn+1,this.emittedTurns.has(I))return;this.turnDataCache.has(I)||this.turnDataCache.set(I,{featureFlagsAsString:m$(this.runtimeContext.settings),toolCalls:[],toolCallExecutions:[],turn:I}),l=this.turnDataCache.get(I)}else return;e.kind==="tool_execution"?await this.ingestToolExecutionEventAndEmitToolCallExecutedTelemetry(l,e):e.kind==="turn_started"||e.kind==="turn_failed"||e.kind==="turn_retry"||e.kind==="turn_ended"?(l={...l,model:e.model,modelInfo:JSON.stringify(e.modelInfo)},e.kind==="turn_started"?l={...l,startTimeMs:e.timestampMs}:e.kind==="turn_retry"?l={...l,endTimeMs:e.timestampMs,retriesUsed:(l.retriesUsed??0)+1}:e.kind==="turn_failed"?l={...l,endTimeMs:e.timestampMs,error:e.error}:e.kind==="turn_ended"&&(l={...l,endTimeMs:e.timestampMs})):e.kind==="history_truncated"?l={...l,truncateEvent:e}:e.kind==="image_processing"?l={...l,imageProcessingMetrics:e.imageProcessingMetrics}:e.kind==="images_removed"?l={...l,largeImagesRemoved:(l.largeImagesRemoved??0)+(e.largeImagesRemoved?1:0),imagesRemoved:(l.imagesRemoved??0)+(e.imagesRemoved?1:0)}:e.kind==="model_call_success"||e.kind==="model_call_failure"?(l={...l,callId:e.callId,modelCallDurationMs:e.modelCallDurationMs,api_call_id:e.modelCall.api_id,provider_call_id:e.modelCall.request_id,conversationStructureSummary:Ize(e.requestMessages)},e.kind==="model_call_success"&&(l={...l,responsePromptTokens:e.responseUsage?.prompt_tokens,responseCompletionTokens:e.responseUsage?.completion_tokens,responseTotalTokens:e.responseUsage?.total_tokens})):V8e(e)&&e.source==="jit-instruction"?l={...l,jitInstructionsAdded:(l?.jitInstructionsAdded??0)+1}:e7(e)&&e.message.tool_calls?l={...l,toolCalls:l.toolCalls.concat(e.message.tool_calls.map(n=>({...y_I(this.runtimeContext,this.toolsInUse,n)})))}:y8e(e)&&(l={...l,toolCallExecutions:l.toolCallExecutions.concat([e.message.tool_call_id])}),this.turnDataCache.set(I,l),e.kind==="turn_ended"&&(await this.emitTurnTelemetry(I),this.emittedTurns.add(I),this.turnDataCache.delete(I))}async emitTurnTelemetry(e){let I=this.turnDataCache.get(e);if(I){let l={kind:"telemetry",telemetry:{event:"get_completion_with_tools_turn",properties:{callId:I.callId,model:I.model||"default",modelInfo:I.modelInfo||"{}",api_call_id:I.api_call_id,provider_call_id:I.provider_call_id,agent:this.forAgent,toolCalls:JSON.stringify(I.toolCalls.map(n=>({toolCallId:n.toolCallId,toolName:n.safeForTelemetryToolName}))),toolCallExecutions:JSON.stringify(I.toolCallExecutions),error:I.error,featureFlags:m$(this.runtimeContext.settings),conversationStructureSummary:I.conversationStructureSummary,truncationPerformedBy:I.truncateEvent?.performedBy},metrics:{turn:e,turnDurationMs:I.endTimeMs!==void 0&&I.startTimeMs!==void 0?I.endTimeMs-I.startTimeMs:0,modelCallDurationMs:I.modelCallDurationMs,retriesUsed:I.retriesUsed??0,numToolCalls:I.toolCalls.length,numToolExecutions:I.toolCallExecutions.length,largeImagesRemoved:I.largeImagesRemoved,imagesRemoved:I.imagesRemoved,responsePromptTokens:I.responsePromptTokens,responseCompletionTokens:I.responseCompletionTokens,responseTotalTokens:I.responseTotalTokens,jitInstructionsAdded:I.jitInstructionsAdded,...I.truncateEvent?.truncateResult,...I.imageProcessingMetrics},restrictedProperties:{}}};await this.runtimeContext.callback?.progress(l)}}async ingestToolExecutionEventAndEmitToolCallExecutedTelemetry(e,I){let l=I.toolCallId,n=R_I(e,l);if(n){let c=I.toolResult,r={kind:"telemetry",telemetry:{event:"tool_call_executed",properties:{...c.toolTelemetry.properties,completionWithToolsCallId:I.callId,resultType:c.resultType,toolCallId:l,arguments:n.safeForTelemetryArguments,toolName:n.safeForTelemetryToolName,api_call_id:e.api_call_id,isCustomAgent:n.isCustomAgent?"true":"false"},restrictedProperties:{...c.toolTelemetry.restrictedProperties,arguments:n.arguments,result:c.textResultForLlm,toolName:n.toolName,error:c.error,customAgent:n.customAgentInfo?JSON.stringify({repoOwner:n.customAgentInfo.repoOwner,repoName:n.customAgentInfo.repoName,displayName:n.customAgentInfo.displayName,mcpServerNames:n.customAgentInfo.mcpServerNames}):void 0},metrics:{...c.toolTelemetry.metrics,durationMs:I.durationMs,customAgentMcpServerCount:n.customAgentInfo?.mcpServerCount}}};await this.runtimeContext.callback?.progress(r)}}};var xB=class{async*preRequest(e){yield*[]}handleCallbackResponse(e){}getUserMessages(){return[]}clearUserMessages(){}canProcessUserMessages(){return!1}toJSON(){return JSON.stringify({type:"NoopUserMessageProcessor"})}};var g_I=void 0,t7=class{constructor(e,I=g_I){this.runtimeContext=e;this.agentId=I;this.gitHandlers={silent:new No(new dW,this.runtimeContext.exec),logging:new No(this.runtimeContext.logger,this.runtimeContext.exec)}}gitHandlers;async agent(e,I,l,n,c,r,s,a=new xB,o){let G=async(m,h,u)=>{let Z={role:"user",content:m};return await this.runtimeContext.callback?.progress({kind:"message",turn:0,callId:this.agentId,message:Z}),await this.runCompletionWithTools(e,I,[...h??[],Z],r,s,c,{executeToolsInParallel:hl(this.runtimeContext.settings,"copilot_swe_agent_parallel_tool_execution"),initialTurnCount:u},o,a)},i=n,d=l??[],b;for(;i;){let m=await G(i,d,b);b=m.finalTurnCount,d=m.messages,i=await o?.onResult(m.postCompletionWithToolsCommitHash)}for(let m of r)if(m.shutdown){let h=await m.shutdown();h&&await this.runtimeContext.callback?.progress(h)}return{finalTurnCount:b||0,messages:d}}async runCompletionWithTools(e,I,l,n,c,r,s,a,o=new xB){let G=this.runtimeContext.callback?new I7(this.runtimeContext,"sweagent-capi",n):void 0,i=this.gitHandlers.logging,d=await i.getCurrentCommitHash(e),b=l.filter(y=>y.role==="user").at(-1),m=this.createCompletionWithToolsProcessors(e,d,n,c,o,r,a,b),h=this.runtimeContext.client.getCompletionWithTools(I,l,n,{...s,callId:this.agentId,processors:m}),u=0,Z=[...l],N=[];for await(let y of h){if(hl(this.runtimeContext.settings,"copilot_swe_agent_progress_commands")){let F=await this.runtimeContext.callback?.progress(y,{accepts_user_messages:o.canProcessUserMessages()});o.handleCallbackResponse(F)}else await this.runtimeContext.callback?.progress(y);G&&await G.ingestEvent(y),(y.kind==="message"||y.kind==="response")&&(y.kind==="message"&&Z.push(y.message),y.kind==="response"&&N.push(y.response),u=Math.max(u,y.turn??0))}let g=await i.getCurrentCommitHash(e);return{finalTurnCount:u,messages:Z,resultMessages:N,preCompletionWithToolsCommitHash:d,postCompletionWithToolsCommitHash:g}}createCompletionWithToolsProcessors(e,I,l,n,c,r,s,a){let o=new P8(this.runtimeContext.logger,this.runtimeContext.settings,l.find(b=>b.name==="github-mcp-server-get_file_contents")),G=new _8(this.runtimeContext.settings,this.runtimeContext.logger,this.gitHandlers.silent,e,I,r),i=new av(a,this.runtimeContext.logger),d=[G,o,i];return hl(this.runtimeContext.settings,"copilot_swe_agent_progress_commands")&&d.push(c),d.push(n),{preRequest:d.filter(b=>b!==void 0),preToolsExecution:[s].filter(b=>b!==void 0),postToolExecution:[o,s].filter(b=>b!==void 0),onRequestError:[o,i].filter(b=>b!==void 0)}}};async function dZe(t,e,I,l,n){try{return(await l.invokeTool("blackbird-mcp-server/search_repository_with_agent",{task:t,depth:2,owner:e,repo:I,numSnippets:10},"hidden_characters")).textResultForLlm}catch(c){return n.error(`Error during Blackbird search: ${c}`),""}}var F8e=t=>hl(t,"copilot_swe_agent_search")||$Ye(t,"SearchAgentExperiment")==="enabled",g8e="search";function bZe(t){return t!==null&&typeof t=="object"&&"question"in t&&"reason"in t&&"searchCommand"in t}var F_I=(t,e,I)=>`
|
|
1349
1349
|
You are a question answering agent that is a component of GitHub Copilot coding agent. Your task is to take the given question
|
|
1350
1350
|
and answer it using the given facts.
|
|
1351
1351
|
|