@github/copilot 0.0.378-2 → 0.0.378

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 CHANGED
@@ -1732,11 +1732,7 @@ Files (in files/):`;let I=10,c=r.slice(0,I);for(let d of c)s+=`
1732
1732
 
1733
1733
  For multi-step tasks, create plan.md to track progress.`),s+=`
1734
1734
 
1735
- files/ persists across checkpoints for artifacts that shouldn't be committed (e.g., architecture diagrams, task breakdowns, user preferences).`,t.showPlanReminder&&n&&(s+=`
1736
-
1737
- <reminder>
1738
- Consider updating plan.md to reflect current progress and next steps.
1739
- </reminder>`),s+=`
1735
+ files/ persists across checkpoints for artifacts that shouldn't be committed (e.g., architecture diagrams, task breakdowns, user preferences).`,s+=`
1740
1736
  </session_context>`,s}var D6n=W(()=>{"use strict"});function OQt(t,e,n){return{kind:"telemetry",telemetry:{event:"workspace_checkpoint_read",properties:{sessionId:t,checkpointNumber:String(e)},restrictedProperties:{},metrics:{contentSizeBytes:n}}}}function _Qt(t,e,n){return{kind:"telemetry",telemetry:{event:"workspace_plan_write",properties:{sessionId:t,operation:e},restrictedProperties:{},metrics:{contentSizeBytes:n}}}}function UQt(t,e){return{kind:"telemetry",telemetry:{event:"workspace_plan_read",properties:{sessionId:t},restrictedProperties:{},metrics:{contentSizeBytes:e}}}}function MQt(t,e,n,r){return{kind:"telemetry",telemetry:{event:"workspace_file_write",properties:{sessionId:t,relativePath:e,operation:n},restrictedProperties:{},metrics:{contentSizeBytes:r}}}}function DQt(t,e,n){return{kind:"telemetry",telemetry:{event:"workspace_file_read",properties:{sessionId:t,relativePath:e},restrictedProperties:{},metrics:{contentSizeBytes:n}}}}var zQt=W(()=>{"use strict"});var qDe=W(()=>{"use strict";LQt();M6n();D6n();zQt()});import{promises as e6l}from"fs";import t6l from"os";import{sep as n6l}from"path";function c6l(t,e,n,r){let l=t6l.type(),a=e===""?"":w6(e);return i6l.override({details:`You are working in the following environment. You do not need to make additional tool calls to verify this.
1741
1737
  * Current working directory: ${t}
1742
1738
  * Git repository root: ${a!==""?a:"Not a git repository"}
@@ -1999,11 +1995,12 @@ ${this.escapeXml(this.secretFilter.filterSecrets(n.trim()))}
1999
1995
  CRITICAL: The following tools have been REMOVED and will FAIL if called: ${t.join(", ")}
2000
1996
 
2001
1997
  You MUST NOT attempt to call any of these tools. They no longer exist and any calls to them will result in an error. If you need functionality from these tools, explain to the user that the capability is no longer available.
2002
- </removed_tools_warning>`,Y8n=({customAgentPrompt:t,problemStatement:e,capabilities:n,hasImages:r,handoffContext:l,removedTools:a})=>{let s=(n.vision&&r?bye(`
1998
+ </removed_tools_warning>`,Y8n=({customAgentPrompt:t,problemStatement:e,capabilities:n,hasImages:r,handoffContext:l,removedTools:a,planReminder:o})=>{let c=[(n.vision&&r?bye(`
2003
1999
  The user mentioned images and they have been attached to this message in the order they were mentioned. You can view them with the ${Ize}
2004
- `):"").trim()||void 0;return d9e.renderAs({repository_context:"raw",problem_statement:"raw"}).with({agent_instructions:t?`
2000
+ `):"").trim(),o?.trim()].filter(Boolean).join(`
2001
+ `)||void 0;return d9e.renderAs({repository_context:"raw",problem_statement:"raw"}).with({agent_instructions:t?`
2005
2002
  ${t}
2006
- `:"",problem_statement:e,repository_context:l,removed_tools_warning:a?.length?QKl(a):void 0,current_datetime:new Date().toISOString(),additional_instructions:s}).asXML().trim()},v8n=(t,e)=>d9e.with({problem_statement:"",agent_instructions:`
2003
+ `:"",problem_statement:e,repository_context:l,removed_tools_warning:a?.length?QKl(a):void 0,current_datetime:new Date().toISOString(),additional_instructions:c}).asXML().trim()},v8n=(t,e)=>d9e.with({problem_statement:"",agent_instructions:`
2007
2004
  ${t}
2008
2005
  `,current_datetime:new Date().toISOString(),additional_instructions:`In the <prompt> tag below, you will find the task you need to complete.
2009
2006
  When you have completed the task your response must include the following:
@@ -2129,18 +2126,9 @@ The summary should include the following parts:
2129
2126
  3. <work_done> - changes made, current state, and any issues encountered
2130
2127
  4. <technical_details> - key concepts, decisions, and quirks discovered
2131
2128
  5. <important_files> - files central to the work and why they matter
2132
- 6. <next_steps> - pending tasks and planned actions
2133
- ${t?`
2134
-
2135
- At the very end of your response, include a short descriptive title for this checkpoint:
2136
- CHECKPOINT_TITLE: [2-6 word description of the main work done in this segment]
2129
+ 6. <next_steps> - pending tasks and planned actions${t?`
2130
+ 7. <checkpoint_title> - 2-6 word description of the main work done`:""}
2137
2131
 
2138
- The title should be concise and descriptive, capturing the essence of what was accomplished in this specific work segment. Examples:
2139
- - "Implementing user authentication"
2140
- - "Fixing database connection bugs"
2141
- - "Refactoring payment module"
2142
- - "Adding unit tests for API"
2143
- `:""}
2144
2132
  ---
2145
2133
 
2146
2134
  ## Section Guidelines
@@ -2189,7 +2177,15 @@ List the files most central to the task, prioritizing those you've actively work
2189
2177
 
2190
2178
  If there's pending work, describe what you were actively working on when compaction occurred. List remaining tasks, outline your planned approach, and flag any blockers or open questions.
2191
2179
  If you've finished all requested work, you can simply note that no next steps are needed.
2180
+ ${t?`
2181
+ ### Checkpoint Title
2192
2182
 
2183
+ Provide a concise 2-6 word title capturing the essence of what was accomplished in this work segment. This title will be used to identify this checkpoint when reviewing session history. Examples:
2184
+ - "Implementing user authentication"
2185
+ - "Fixing database connection bugs"
2186
+ - "Refactoring payment module"
2187
+ - "Adding unit tests for API"
2188
+ `:""}
2193
2189
  ---
2194
2190
 
2195
2191
  ## Example
@@ -2249,7 +2245,7 @@ Immediate next steps:
2249
2245
 
2250
2246
  ---
2251
2247
 
2252
- Please write the summary now, following the structure and guidelines above. Be concise where possible, but don't sacrifice important context for brevity.${t?" Remember to include the <checkpoint_title> section at the very end.":""}`});function xKl(t,e,n=`
2248
+ Please write the summary now, following the structure and guidelines above. Be concise where possible, but don't sacrifice important context for brevity.`});function xKl(t,e,n=`
2253
2249
  ...<truncated>...
2254
2250
  `){if(t.length<=e)return t;let r=e-n.length;if(r<=0)return n;let l=Math.floor(r/2),a=r-l,o=t.slice(0,l),s=t.slice(t.length-a);return o+n+s}function LKl(t,e){if(t.length===0)return"";let r=`<user_message>
2255
2251
  ${t.join(`
@@ -2276,12 +2272,12 @@ Here is a summary of the prior context:
2276
2272
  <summary>
2277
2273
  ${e}
2278
2274
  </summary>
2279
- ${s}`},c=t.find(d=>d.role==="system");return c?[c,I]:[I]}function Tze(t,e){if(e.length===0||e[0].role!=="tool")return{adjustedCheckpoint:t,adjustedNew:e};let n=-1;for(let o=t.length-1;o>=0;o--){let s=t[o];if(s.role==="assistant"&&"tool_calls"in s&&s.tool_calls&&s.tool_calls.length>0){n=o;break}if(s.role!=="tool"&&s.role!=="assistant")break}if(n===-1)return{adjustedCheckpoint:t,adjustedNew:e};let r=t.slice(0,n),a=[...t.slice(n),...e];return{adjustedCheckpoint:r,adjustedNew:a}}function X8n(t,e){let n=W1e(t);return Sf(n,e)}async function Oze(t,e,n,r,l){let a="",o=0,s=0,I=0,c=t.getCompletionWithTools(e,n,r,{stream:!1,processors:{preRequest:[new FX(l)]},...r.length>0?{toolChoice:"none"}:{}});for await(let d of c)d.kind==="response"&&d.response.content&&(a=typeof d.response.content=="string"?d.response.content:""),d.kind==="model_call_success"&&d.responseUsage&&(o=d.responseUsage.prompt_tokens||0,s=d.responseUsage.completion_tokens||0,I=d.responseUsage.prompt_tokens_details?.cached_tokens||0);if(!a)throw new Error("Compaction failed: received empty response from model");return{content:a,inputTokens:o,outputTokens:s,cachedInputTokens:I}}var kKl,uHt=W(()=>{"use strict";mIe();dHt();qB();kKl=3e4});var _ze,k8n=W(()=>{"use strict";qB();uHt();Wye();_ze=class t{constructor(e,n){this.logger=e;this.backgroundThreshold=n.backgroundThreshold??Eoe(),this.bufferExhaustionThreshold=n.bufferExhaustionThreshold??nkn(),this.minMessagesForCompaction=n.minMessagesForCompaction??t.DEFAULT_MIN_MESSAGES,this.getOriginalUserMessages=n.getOriginalUserMessages,this.getPlanContent=n.getPlanContent,this.getTodoContent=n.getTodoContent,this.shouldShowPlanReminder=n.shouldShowPlanReminder,this.onCompactionComplete=n.onCompactionComplete}static DEFAULT_BACKGROUND_THRESHOLD=.8;static DEFAULT_BUFFER_EXHAUSTION_THRESHOLD=.95;static DEFAULT_MIN_MESSAGES=6;static PLAN_REMINDER_THRESHOLD=.75;backgroundThreshold;bufferExhaustionThreshold;minMessagesForCompaction;getOriginalUserMessages;getPlanContent;getTodoContent;shouldShowPlanReminder;onCompactionComplete;pendingCompaction=null;lastCompactionStartTurn=null;planReminderShownAtTurn=null;toJSON(){return"CompactionProcessor"}async*preRequest(e){let{messages:n,modelInfo:r,toolDefinitions:l}=e,a=r.capabilities?.limits?.max_prompt_tokens||r.capabilities?.limits?.max_context_window_tokens||128e3,o=Sf(n,r.name),s=XAe(l,r.name),I=o+s,c=I/a;if(this.pendingCompaction){let d=this.checkCompactionCompleted();if(this.logger.debug(`CompactionProcessor: Checking pending compaction - completed: ${d}, has error: ${!!this.pendingCompaction.error}, has result: ${!!this.pendingCompaction.result}`),d){yield*this.applyCompactionResult(e);return}if(c>=this.bufferExhaustionThreshold){this.logger.info(`CompactionProcessor: Buffer exhausted at ${(c*100).toFixed(1)}% - waiting for compaction to complete...`),yield*this.waitForCompactionAndApply(e);return}this.logger.debug(`CompactionProcessor: Compaction in progress, utilization at ${(c*100).toFixed(1)}% - continuing with buffer space`);return}if(c<this.backgroundThreshold){this.logger.info(`CompactionProcessor: Utilization ${(c*100).toFixed(1)}% (${I}/${a} tokens) below threshold ${(this.backgroundThreshold*100).toFixed(0)}%`);return}if(this.lastCompactionStartTurn===e.turn){this.logger.debug("CompactionProcessor: Skipping - already started compaction this turn");return}if(n.length<this.minMessagesForCompaction){this.logger.info(`CompactionProcessor: Skipping - only ${n.length} messages (need at least ${this.minMessagesForCompaction}) at ${(c*100).toFixed(1)}% utilization`);return}this.logger.info(`CompactionProcessor: Context at ${(c*100).toFixed(1)}% utilization - starting background compaction...`),yield{kind:"compaction_started",turn:e.turn,performedBy:"CompactionProcessor"},this.startBackgroundCompaction(e,I),this.lastCompactionStartTurn=e.turn}checkCompactionCompleted(){return this.pendingCompaction?this.pendingCompaction.completed:!1}startBackgroundCompaction(e,n){let{messages:r,modelInfo:l}=e,a=[...r],o=this.getTodoContent?.()??null,s=r.find(b=>b.role==="system")?.content,I=typeof s=="string"?s:"";this.logger.debug(`CompactionProcessor: Sending ${r.length} messages for background compaction`);let c=!!this.getPlanContent,d=(async()=>{let b=W1e(r,c),G=await(this.getPlanContent?.()??Promise.resolve(null)),A=X8n(r,l.name);return{...await Oze(e.client,I,b,e.tools,this.logger),estimatedInputTokens:A,planContent:G}})(),p={promise:d.then(b=>({content:b.content,inputTokens:b.inputTokens,outputTokens:b.outputTokens,cachedInputTokens:b.cachedInputTokens})).catch(()=>new Promise(()=>{})),checkpointMessages:a,startTurn:e.turn,checkpointTokens:n,estimatedInputTokens:0,completed:!1,originalUserMessages:this.getOriginalUserMessages?.(),todoContent:o??void 0};d.then(b=>{this.logger.info("CompactionProcessor: Background compaction completed successfully"),p.completed=!0,p.result={content:b.content,inputTokens:b.inputTokens,outputTokens:b.outputTokens,cachedInputTokens:b.cachedInputTokens},p.estimatedInputTokens=b.estimatedInputTokens,p.planContent=b.planContent??void 0,this.onCompactionComplete({success:!0,startTurn:p.startTurn,summaryContent:b.content,checkpointMessagesLength:p.checkpointMessages.length,checkpointTokens:p.checkpointTokens,compactionTokensUsed:{input:b.inputTokens||b.estimatedInputTokens,output:b.outputTokens||0,cachedInput:b.cachedInputTokens||0}})}).catch(b=>{this.logger.error(`CompactionProcessor: Background compaction failed: ${b instanceof Error?b.message:String(b)}`),p.completed=!0,p.error=b,this.onCompactionComplete({success:!1,startTurn:p.startTurn,checkpointMessagesLength:p.checkpointMessages.length,checkpointTokens:p.checkpointTokens,error:b instanceof Error?b.message:String(b)})}),this.pendingCompaction=p}async*waitForCompactionAndApply(e){if(this.pendingCompaction){for(;!this.pendingCompaction.completed;)await new Promise(n=>setTimeout(n,50));yield*this.applyCompactionResult(e)}}async*applyCompactionResult(e){if(!this.pendingCompaction)return;let{messages:n,modelInfo:r}=e,l=this.pendingCompaction;if(l.error){this.handleCompactionFailure(e,l.error);return}let a=l.result;if(!a){this.handleCompactionFailure(e,new Error("Compaction completed but no result available"));return}let o=l.checkpointMessages.length,s=l.checkpointMessages,I=n.slice(o),c=Tze(s,I);s=c.adjustedCheckpoint,I=c.adjustedNew,this.logger.debug(`CompactionProcessor: Applying compaction - ${s.length} checkpoint messages (adjusted from ${o}), ${I.length} new messages`);let u=[...wIe(s,a.content,l.originalUserMessages,{planContent:l.planContent,todoContent:l.todoContent}),...I],p=Sf(u,r.name);n.splice(0,n.length,...u);let b=l.checkpointTokens-p;this.logger.info(`CompactionProcessor: Compaction complete - replaced ${l.checkpointMessages.length} messages with summary + ${I.length} new messages, saved ~${b} tokens`),this.pendingCompaction=null}handleCompactionFailure(e,n){this.logger.error(`CompactionProcessor: Compaction failed: ${n instanceof Error?n.message:String(n)}`);let r=n instanceof Error?n.cause:void 0;if(r&&typeof r=="object"){let l=r,a=l.ghRequestId||l.headers?.get?.("x-github-request-id")||l.requestID;this.logger.debug(`CompactionProcessor: API error details - status: ${l.status}, requestId: ${a}, message: ${l.message}`)}this.pendingCompaction=null}isCompacting(){return this.pendingCompaction!==null}getCompactionStartTurn(){return this.pendingCompaction?.startTurn??null}clearCompletedCompaction(){this.pendingCompaction?.completed&&(this.logger.debug("CompactionProcessor: Clearing completed compaction state at loop boundary"),this.pendingCompaction=null)}}});var Uze,x8n=W(()=>{"use strict";Uze=class{async exec(){return 0}async execReturn(){return{exitCode:0,stdout:"",stderr:""}}}});var uqn=V((E1e,YIe)=>{var BKl=200,D8n="__lodash_hash_undefined__",TKl=800,OKl=16,z8n=9007199254740991,P8n="[object Arguments]",_Kl="[object Array]",UKl="[object AsyncFunction]",MKl="[object Boolean]",DKl="[object Date]",zKl="[object Error]",j8n="[object Function]",PKl="[object GeneratorFunction]",jKl="[object Map]",KKl="[object Number]",qKl="[object Null]",K8n="[object Object]",$Kl="[object Proxy]",e8l="[object RegExp]",t8l="[object Set]",n8l="[object String]",r8l="[object Undefined]",l8l="[object WeakMap]",a8l="[object ArrayBuffer]",o8l="[object DataView]",s8l="[object Float32Array]",i8l="[object Float64Array]",I8l="[object Int8Array]",c8l="[object Int16Array]",d8l="[object Int32Array]",u8l="[object Uint8Array]",m8l="[object Uint8ClampedArray]",p8l="[object Uint16Array]",b8l="[object Uint32Array]",h8l=/[\\^$.*+?()[\]{}|]/g,G8l=/^\[object .+?Constructor\]$/,g8l=/^(?:0|[1-9]\d*)$/,pm={};pm[s8l]=pm[i8l]=pm[I8l]=pm[c8l]=pm[d8l]=pm[u8l]=pm[m8l]=pm[p8l]=pm[b8l]=!0;pm[P8n]=pm[_Kl]=pm[a8l]=pm[MKl]=pm[o8l]=pm[DKl]=pm[zKl]=pm[j8n]=pm[jKl]=pm[KKl]=pm[K8n]=pm[e8l]=pm[t8l]=pm[n8l]=pm[l8l]=!1;var q8n=typeof global=="object"&&global&&global.Object===Object&&global,A8l=typeof self=="object"&&self&&self.Object===Object&&self,w1e=q8n||A8l||Function("return this")(),$8n=typeof E1e=="object"&&E1e&&!E1e.nodeType&&E1e,f1e=$8n&&typeof YIe=="object"&&YIe&&!YIe.nodeType&&YIe,eqn=f1e&&f1e.exports===$8n,mHt=eqn&&q8n.process,L8n=(function(){try{var t=f1e&&f1e.require&&f1e.require("util").types;return t||mHt&&mHt.binding&&mHt.binding("util")}catch{}})(),S8n=L8n&&L8n.isTypedArray;function Z8l(t,e,n){switch(n.length){case 0:return t.call(e);case 1:return t.call(e,n[0]);case 2:return t.call(e,n[0],n[1]);case 3:return t.call(e,n[0],n[1],n[2])}return t.apply(e,n)}function N8l(t,e){for(var n=-1,r=Array(t);++n<t;)r[n]=e(n);return r}function y8l(t){return function(e){return t(e)}}function W8l(t,e){return t?.[e]}function E8l(t,e){return function(n){return t(e(n))}}var f8l=Array.prototype,R8l=Function.prototype,zze=Object.prototype,pHt=w1e["__core-js_shared__"],Pze=R8l.toString,_L=zze.hasOwnProperty,J8n=(function(){var t=/[^.]+$/.exec(pHt&&pHt.keys&&pHt.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""})(),tqn=zze.toString,w8l=Pze.call(Object),Y8l=RegExp("^"+Pze.call(_L).replace(h8l,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Mze=eqn?w1e.Buffer:void 0,B8n=w1e.Symbol,T8n=w1e.Uint8Array,O8n=Mze?Mze.allocUnsafe:void 0,nqn=E8l(Object.getPrototypeOf,Object),_8n=Object.create,v8l=zze.propertyIsEnumerable,V8l=f8l.splice,$K=B8n?B8n.toStringTag:void 0,Dze=(function(){try{var t=ZHt(Object,"defineProperty");return t({},"",{}),t}catch{}})(),C8l=Mze?Mze.isBuffer:void 0,U8n=Math.max,Q8l=Date.now,rqn=ZHt(w1e,"Map"),R1e=ZHt(Object,"create"),F8l=(function(){function t(){}return function(e){if(!t8(e))return{};if(_8n)return _8n(e);t.prototype=e;var n=new t;return t.prototype=void 0,n}})();function e8(t){var e=-1,n=t==null?0:t.length;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}function H8l(){this.__data__=R1e?R1e(null):{},this.size=0}function X8l(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}function k8l(t){var e=this.__data__;if(R1e){var n=e[t];return n===D8n?void 0:n}return _L.call(e,t)?e[t]:void 0}function x8l(t){var e=this.__data__;return R1e?e[t]!==void 0:_L.call(e,t)}function L8l(t,e){var n=this.__data__;return this.size+=this.has(t)?0:1,n[t]=R1e&&e===void 0?D8n:e,this}e8.prototype.clear=H8l;e8.prototype.delete=X8l;e8.prototype.get=k8l;e8.prototype.has=x8l;e8.prototype.set=L8l;function UL(t){var e=-1,n=t==null?0:t.length;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}function S8l(){this.__data__=[],this.size=0}function J8l(t){var e=this.__data__,n=jze(e,t);if(n<0)return!1;var r=e.length-1;return n==r?e.pop():V8l.call(e,n,1),--this.size,!0}function B8l(t){var e=this.__data__,n=jze(e,t);return n<0?void 0:e[n][1]}function T8l(t){return jze(this.__data__,t)>-1}function O8l(t,e){var n=this.__data__,r=jze(n,t);return r<0?(++this.size,n.push([t,e])):n[r][1]=e,this}UL.prototype.clear=S8l;UL.prototype.delete=J8l;UL.prototype.get=B8l;UL.prototype.has=T8l;UL.prototype.set=O8l;function vIe(t){var e=-1,n=t==null?0:t.length;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}function _8l(){this.size=0,this.__data__={hash:new e8,map:new(rqn||UL),string:new e8}}function U8l(t){var e=qze(this,t).delete(t);return this.size-=e?1:0,e}function M8l(t){return qze(this,t).get(t)}function D8l(t){return qze(this,t).has(t)}function z8l(t,e){var n=qze(this,t),r=n.size;return n.set(t,e),this.size+=n.size==r?0:1,this}vIe.prototype.clear=_8l;vIe.prototype.delete=U8l;vIe.prototype.get=M8l;vIe.prototype.has=D8l;vIe.prototype.set=z8l;function VIe(t){var e=this.__data__=new UL(t);this.size=e.size}function P8l(){this.__data__=new UL,this.size=0}function j8l(t){var e=this.__data__,n=e.delete(t);return this.size=e.size,n}function K8l(t){return this.__data__.get(t)}function q8l(t){return this.__data__.has(t)}function $8l(t,e){var n=this.__data__;if(n instanceof UL){var r=n.__data__;if(!rqn||r.length<BKl-1)return r.push([t,e]),this.size=++n.size,this;n=this.__data__=new vIe(r)}return n.set(t,e),this.size=n.size,this}VIe.prototype.clear=P8l;VIe.prototype.delete=j8l;VIe.prototype.get=K8l;VIe.prototype.has=q8l;VIe.prototype.set=$8l;function eql(t,e){var n=gHt(t),r=!n&&GHt(t),l=!n&&!r&&sqn(t),a=!n&&!r&&!l&&Iqn(t),o=n||r||l||a,s=o?N8l(t.length,String):[],I=s.length;for(var c in t)(e||_L.call(t,c))&&!(o&&(c=="length"||l&&(c=="offset"||c=="parent")||a&&(c=="buffer"||c=="byteLength"||c=="byteOffset")||aqn(c,I)))&&s.push(c);return s}function bHt(t,e,n){(n!==void 0&&!$ze(t[e],n)||n===void 0&&!(e in t))&&AHt(t,e,n)}function tql(t,e,n){var r=t[e];(!(_L.call(t,e)&&$ze(r,n))||n===void 0&&!(e in t))&&AHt(t,e,n)}function jze(t,e){for(var n=t.length;n--;)if($ze(t[n][0],e))return n;return-1}function AHt(t,e,n){e=="__proto__"&&Dze?Dze(t,e,{configurable:!0,enumerable:!0,value:n,writable:!0}):t[e]=n}var nql=bql();function Kze(t){return t==null?t===void 0?r8l:qKl:$K&&$K in Object(t)?hql(t):yql(t)}function M8n(t){return Y1e(t)&&Kze(t)==P8n}function rql(t){if(!t8(t)||Zql(t))return!1;var e=yHt(t)?Y8l:G8l;return e.test(Rql(t))}function lql(t){return Y1e(t)&&iqn(t.length)&&!!pm[Kze(t)]}function aql(t){if(!t8(t))return Nql(t);var e=oqn(t),n=[];for(var r in t)r=="constructor"&&(e||!_L.call(t,r))||n.push(r);return n}function lqn(t,e,n,r,l){t!==e&&nql(e,function(a,o){if(l||(l=new VIe),t8(a))oql(t,e,o,n,lqn,r,l);else{var s=r?r(hHt(t,o),a,o+"",t,e,l):void 0;s===void 0&&(s=a),bHt(t,o,s)}},cqn)}function oql(t,e,n,r,l,a,o){var s=hHt(t,n),I=hHt(e,n),c=o.get(I);if(c){bHt(t,n,c);return}var d=a?a(s,I,n+"",t,e,o):void 0,u=d===void 0;if(u){var p=gHt(I),b=!p&&sqn(I),G=!p&&!b&&Iqn(I);d=I,p||b||G?gHt(s)?d=s:wql(s)?d=uql(s):b?(u=!1,d=Iql(I,!0)):G?(u=!1,d=dql(I,!0)):d=[]:Yql(I)||GHt(I)?(d=s,GHt(s)?d=vql(s):(!t8(s)||yHt(s))&&(d=Gql(I))):u=!1}u&&(o.set(I,d),l(d,I,r,a,o),o.delete(I)),bHt(t,n,d)}function sql(t,e){return Eql(Wql(t,e,dqn),t+"")}var iql=Dze?function(t,e){return Dze(t,"toString",{configurable:!0,enumerable:!1,value:Cql(e),writable:!0})}:dqn;function Iql(t,e){if(e)return t.slice();var n=t.length,r=O8n?O8n(n):new t.constructor(n);return t.copy(r),r}function cql(t){var e=new t.constructor(t.byteLength);return new T8n(e).set(new T8n(t)),e}function dql(t,e){var n=e?cql(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.length)}function uql(t,e){var n=-1,r=t.length;for(e||(e=Array(r));++n<r;)e[n]=t[n];return e}function mql(t,e,n,r){var l=!n;n||(n={});for(var a=-1,o=e.length;++a<o;){var s=e[a],I=r?r(n[s],t[s],s,n,t):void 0;I===void 0&&(I=t[s]),l?AHt(n,s,I):tql(n,s,I)}return n}function pql(t){return sql(function(e,n){var r=-1,l=n.length,a=l>1?n[l-1]:void 0,o=l>2?n[2]:void 0;for(a=t.length>3&&typeof a=="function"?(l--,a):void 0,o&&gql(n[0],n[1],o)&&(a=l<3?void 0:a,l=1),e=Object(e);++r<l;){var s=n[r];s&&t(e,s,r,a)}return e})}function bql(t){return function(e,n,r){for(var l=-1,a=Object(e),o=r(e),s=o.length;s--;){var I=o[t?s:++l];if(n(a[I],I,a)===!1)break}return e}}function qze(t,e){var n=t.__data__;return Aql(e)?n[typeof e=="string"?"string":"hash"]:n.map}function ZHt(t,e){var n=W8l(t,e);return rql(n)?n:void 0}function hql(t){var e=_L.call(t,$K),n=t[$K];try{t[$K]=void 0;var r=!0}catch{}var l=tqn.call(t);return r&&(e?t[$K]=n:delete t[$K]),l}function Gql(t){return typeof t.constructor=="function"&&!oqn(t)?F8l(nqn(t)):{}}function aqn(t,e){var n=typeof t;return e=e??z8n,!!e&&(n=="number"||n!="symbol"&&g8l.test(t))&&t>-1&&t%1==0&&t<e}function gql(t,e,n){if(!t8(n))return!1;var r=typeof e;return(r=="number"?NHt(n)&&aqn(e,n.length):r=="string"&&e in n)?$ze(n[e],t):!1}function Aql(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}function Zql(t){return!!J8n&&J8n in t}function oqn(t){var e=t&&t.constructor,n=typeof e=="function"&&e.prototype||zze;return t===n}function Nql(t){var e=[];if(t!=null)for(var n in Object(t))e.push(n);return e}function yql(t){return tqn.call(t)}function Wql(t,e,n){return e=U8n(e===void 0?t.length-1:e,0),function(){for(var r=arguments,l=-1,a=U8n(r.length-e,0),o=Array(a);++l<a;)o[l]=r[e+l];l=-1;for(var s=Array(e+1);++l<e;)s[l]=r[l];return s[e]=n(o),Z8l(t,this,s)}}function hHt(t,e){if(!(e==="constructor"&&typeof t[e]=="function")&&e!="__proto__")return t[e]}var Eql=fql(iql);function fql(t){var e=0,n=0;return function(){var r=Q8l(),l=OKl-(r-n);if(n=r,l>0){if(++e>=TKl)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}function Rql(t){if(t!=null){try{return Pze.call(t)}catch{}try{return t+""}catch{}}return""}function $ze(t,e){return t===e||t!==t&&e!==e}var GHt=M8n((function(){return arguments})())?M8n:function(t){return Y1e(t)&&_L.call(t,"callee")&&!v8l.call(t,"callee")},gHt=Array.isArray;function NHt(t){return t!=null&&iqn(t.length)&&!yHt(t)}function wql(t){return Y1e(t)&&NHt(t)}var sqn=C8l||Qql;function yHt(t){if(!t8(t))return!1;var e=Kze(t);return e==j8n||e==PKl||e==UKl||e==$Kl}function iqn(t){return typeof t=="number"&&t>-1&&t%1==0&&t<=z8n}function t8(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}function Y1e(t){return t!=null&&typeof t=="object"}function Yql(t){if(!Y1e(t)||Kze(t)!=K8n)return!1;var e=nqn(t);if(e===null)return!0;var n=_L.call(e,"constructor")&&e.constructor;return typeof n=="function"&&n instanceof n&&Pze.call(n)==w8l}var Iqn=S8n?y8l(S8n):lql;function vql(t){return mql(t,cqn(t))}function cqn(t){return NHt(t)?eql(t,!0):aql(t)}var Vql=pql(function(t,e,n){lqn(t,e,n)});function Cql(t){return function(){return t}}function dqn(t){return t}function Qql(){return!1}YIe.exports=Vql});async function Fql(t={}){let e=await Eon();return won((0,mqn.default)({},e,t))}async function WHt(t={}){if(HHe())throw new Error("Settings have already been initialized");return Fql(t)}var mqn,pqn=W(()=>{"use strict";mqn=ze(uqn(),1);XHe();$pe()});import{readdir as Hql,stat as Xql}from"fs/promises";async function kql(t,e){try{let n=await Xql(t);if(n.isDirectory()){let r=await Hql(t);return{path:t,type:"directory",lines:r.length}}else{let r=n.size/1048576;if(n.size>bqn){let a=(bqn/1048576).toFixed(0);return e.debug(`File ${t} is too large (${r.toFixed(1)}MB). Maximum file size is ${a}MB. Skipping line count.`),{path:t,type:"file",sizeMB:r}}let{totalLineCount:l}=await F4e(t,1,void 0);return{path:t,type:"file",lines:l}}}catch(n){return e.debug(`Error getting file info for ${t}: ${gt(n)}`),{path:t,type:"file",error:gt(n)}}}async function hqn(t,e){let n=t.filter(a=>!e1(a.path));if(n.length===0)return"";let r=await Promise.all(n.map(a=>kql(a.path,e))),l=["<tagged_files>"];for(let a of r)a.error?l.push(`* ${a.path} (error: ${a.error})`):a.sizeMB!==void 0?l.push(`* ${a.path} (large file: ${a.sizeMB.toFixed(1)}MB)`):a.type==="directory"?l.push(`* ${a.path} (${a.lines} entries)`):l.push(`* ${a.path} (${a.lines} lines)`);return l.push("</tagged_files>"),l.join(`
2275
+ ${s}`},c=t.find(d=>d.role==="system");return c?[c,I]:[I]}function Tze(t,e){if(e.length===0||e[0].role!=="tool")return{adjustedCheckpoint:t,adjustedNew:e};let n=-1;for(let o=t.length-1;o>=0;o--){let s=t[o];if(s.role==="assistant"&&"tool_calls"in s&&s.tool_calls&&s.tool_calls.length>0){n=o;break}if(s.role!=="tool"&&s.role!=="assistant")break}if(n===-1)return{adjustedCheckpoint:t,adjustedNew:e};let r=t.slice(0,n),a=[...t.slice(n),...e];return{adjustedCheckpoint:r,adjustedNew:a}}function X8n(t,e){let n=W1e(t);return Sf(n,e)}async function Oze(t,e,n,r,l){let a="",o=0,s=0,I=0,c=t.getCompletionWithTools(e,n,r,{stream:!1,processors:{preRequest:[new FX(l)]},...r.length>0?{toolChoice:"none"}:{}});for await(let d of c)d.kind==="response"&&d.response.content&&(a=typeof d.response.content=="string"?d.response.content:""),d.kind==="model_call_success"&&d.responseUsage&&(o=d.responseUsage.prompt_tokens||0,s=d.responseUsage.completion_tokens||0,I=d.responseUsage.prompt_tokens_details?.cached_tokens||0);if(!a)throw new Error("Compaction failed: received empty response from model");return{content:a,inputTokens:o,outputTokens:s,cachedInputTokens:I}}var kKl,uHt=W(()=>{"use strict";mIe();dHt();qB();kKl=3e4});var _ze,k8n=W(()=>{"use strict";qB();uHt();Wye();_ze=class t{constructor(e,n){this.logger=e;this.backgroundThreshold=n.backgroundThreshold??Eoe(),this.bufferExhaustionThreshold=n.bufferExhaustionThreshold??nkn(),this.minMessagesForCompaction=n.minMessagesForCompaction??t.DEFAULT_MIN_MESSAGES,this.getOriginalUserMessages=n.getOriginalUserMessages,this.getPlanContent=n.getPlanContent,this.getTodoContent=n.getTodoContent,this.onCompactionComplete=n.onCompactionComplete}static DEFAULT_BACKGROUND_THRESHOLD=.8;static DEFAULT_BUFFER_EXHAUSTION_THRESHOLD=.95;static DEFAULT_MIN_MESSAGES=6;backgroundThreshold;bufferExhaustionThreshold;minMessagesForCompaction;getOriginalUserMessages;getPlanContent;getTodoContent;onCompactionComplete;pendingCompaction=null;lastCompactionStartTurn=null;toJSON(){return"CompactionProcessor"}async*preRequest(e){let{messages:n,modelInfo:r,toolDefinitions:l}=e,a=r.capabilities?.limits?.max_prompt_tokens||r.capabilities?.limits?.max_context_window_tokens||128e3,o=Sf(n,r.name),s=XAe(l,r.name),I=o+s,c=I/a;if(this.pendingCompaction){let d=this.checkCompactionCompleted();if(this.logger.debug(`CompactionProcessor: Checking pending compaction - completed: ${d}, has error: ${!!this.pendingCompaction.error}, has result: ${!!this.pendingCompaction.result}`),d){yield*this.applyCompactionResult(e);return}if(c>=this.bufferExhaustionThreshold){this.logger.info(`CompactionProcessor: Buffer exhausted at ${(c*100).toFixed(1)}% - waiting for compaction to complete...`),yield*this.waitForCompactionAndApply(e);return}this.logger.debug(`CompactionProcessor: Compaction in progress, utilization at ${(c*100).toFixed(1)}% - continuing with buffer space`);return}if(c<this.backgroundThreshold){this.logger.info(`CompactionProcessor: Utilization ${(c*100).toFixed(1)}% (${I}/${a} tokens) below threshold ${(this.backgroundThreshold*100).toFixed(0)}%`);return}if(this.lastCompactionStartTurn===e.turn){this.logger.debug("CompactionProcessor: Skipping - already started compaction this turn");return}if(n.length<this.minMessagesForCompaction){this.logger.info(`CompactionProcessor: Skipping - only ${n.length} messages (need at least ${this.minMessagesForCompaction}) at ${(c*100).toFixed(1)}% utilization`);return}this.logger.info(`CompactionProcessor: Context at ${(c*100).toFixed(1)}% utilization - starting background compaction...`),yield{kind:"compaction_started",turn:e.turn,performedBy:"CompactionProcessor"},this.startBackgroundCompaction(e,I),this.lastCompactionStartTurn=e.turn}checkCompactionCompleted(){return this.pendingCompaction?this.pendingCompaction.completed:!1}startBackgroundCompaction(e,n){let{messages:r,modelInfo:l}=e,a=[...r],o=this.getTodoContent?.()??null,s=r.find(b=>b.role==="system")?.content,I=typeof s=="string"?s:"";this.logger.debug(`CompactionProcessor: Sending ${r.length} messages for background compaction`);let c=!!this.getPlanContent,d=(async()=>{let b=W1e(r,c),G=await(this.getPlanContent?.()??Promise.resolve(null)),A=X8n(r,l.name);return{...await Oze(e.client,I,b,e.tools,this.logger),estimatedInputTokens:A,planContent:G}})(),p={promise:d.then(b=>({content:b.content,inputTokens:b.inputTokens,outputTokens:b.outputTokens,cachedInputTokens:b.cachedInputTokens})).catch(()=>new Promise(()=>{})),checkpointMessages:a,startTurn:e.turn,checkpointTokens:n,estimatedInputTokens:0,completed:!1,originalUserMessages:this.getOriginalUserMessages?.(),todoContent:o??void 0};d.then(b=>{this.logger.info("CompactionProcessor: Background compaction completed successfully"),p.completed=!0,p.result={content:b.content,inputTokens:b.inputTokens,outputTokens:b.outputTokens,cachedInputTokens:b.cachedInputTokens},p.estimatedInputTokens=b.estimatedInputTokens,p.planContent=b.planContent??void 0,this.onCompactionComplete({success:!0,startTurn:p.startTurn,summaryContent:b.content,checkpointMessagesLength:p.checkpointMessages.length,checkpointTokens:p.checkpointTokens,compactionTokensUsed:{input:b.inputTokens||b.estimatedInputTokens,output:b.outputTokens||0,cachedInput:b.cachedInputTokens||0}})}).catch(b=>{this.logger.error(`CompactionProcessor: Background compaction failed: ${b instanceof Error?b.message:String(b)}`),p.completed=!0,p.error=b,this.onCompactionComplete({success:!1,startTurn:p.startTurn,checkpointMessagesLength:p.checkpointMessages.length,checkpointTokens:p.checkpointTokens,error:b instanceof Error?b.message:String(b)})}),this.pendingCompaction=p}async*waitForCompactionAndApply(e){if(this.pendingCompaction){for(;!this.pendingCompaction.completed;)await new Promise(n=>setTimeout(n,50));yield*this.applyCompactionResult(e)}}async*applyCompactionResult(e){if(!this.pendingCompaction)return;let{messages:n,modelInfo:r}=e,l=this.pendingCompaction;if(l.error){this.handleCompactionFailure(e,l.error);return}let a=l.result;if(!a){this.handleCompactionFailure(e,new Error("Compaction completed but no result available"));return}let o=l.checkpointMessages.length,s=l.checkpointMessages,I=n.slice(o),c=Tze(s,I);s=c.adjustedCheckpoint,I=c.adjustedNew,this.logger.debug(`CompactionProcessor: Applying compaction - ${s.length} checkpoint messages (adjusted from ${o}), ${I.length} new messages`);let u=[...wIe(s,a.content,l.originalUserMessages,{planContent:l.planContent,todoContent:l.todoContent}),...I],p=Sf(u,r.name);n.splice(0,n.length,...u);let b=l.checkpointTokens-p;this.logger.info(`CompactionProcessor: Compaction complete - replaced ${l.checkpointMessages.length} messages with summary + ${I.length} new messages, saved ~${b} tokens`),this.pendingCompaction=null}handleCompactionFailure(e,n){this.logger.error(`CompactionProcessor: Compaction failed: ${n instanceof Error?n.message:String(n)}`);let r=n instanceof Error?n.cause:void 0;if(r&&typeof r=="object"){let l=r,a=l.ghRequestId||l.headers?.get?.("x-github-request-id")||l.requestID;this.logger.debug(`CompactionProcessor: API error details - status: ${l.status}, requestId: ${a}, message: ${l.message}`)}this.pendingCompaction=null}isCompacting(){return this.pendingCompaction!==null}getCompactionStartTurn(){return this.pendingCompaction?.startTurn??null}clearCompletedCompaction(){this.pendingCompaction?.completed&&(this.logger.debug("CompactionProcessor: Clearing completed compaction state at loop boundary"),this.pendingCompaction=null)}}});var Uze,x8n=W(()=>{"use strict";Uze=class{async exec(){return 0}async execReturn(){return{exitCode:0,stdout:"",stderr:""}}}});var uqn=V((E1e,YIe)=>{var BKl=200,D8n="__lodash_hash_undefined__",TKl=800,OKl=16,z8n=9007199254740991,P8n="[object Arguments]",_Kl="[object Array]",UKl="[object AsyncFunction]",MKl="[object Boolean]",DKl="[object Date]",zKl="[object Error]",j8n="[object Function]",PKl="[object GeneratorFunction]",jKl="[object Map]",KKl="[object Number]",qKl="[object Null]",K8n="[object Object]",$Kl="[object Proxy]",e8l="[object RegExp]",t8l="[object Set]",n8l="[object String]",r8l="[object Undefined]",l8l="[object WeakMap]",a8l="[object ArrayBuffer]",o8l="[object DataView]",s8l="[object Float32Array]",i8l="[object Float64Array]",I8l="[object Int8Array]",c8l="[object Int16Array]",d8l="[object Int32Array]",u8l="[object Uint8Array]",m8l="[object Uint8ClampedArray]",p8l="[object Uint16Array]",b8l="[object Uint32Array]",h8l=/[\\^$.*+?()[\]{}|]/g,G8l=/^\[object .+?Constructor\]$/,g8l=/^(?:0|[1-9]\d*)$/,pm={};pm[s8l]=pm[i8l]=pm[I8l]=pm[c8l]=pm[d8l]=pm[u8l]=pm[m8l]=pm[p8l]=pm[b8l]=!0;pm[P8n]=pm[_Kl]=pm[a8l]=pm[MKl]=pm[o8l]=pm[DKl]=pm[zKl]=pm[j8n]=pm[jKl]=pm[KKl]=pm[K8n]=pm[e8l]=pm[t8l]=pm[n8l]=pm[l8l]=!1;var q8n=typeof global=="object"&&global&&global.Object===Object&&global,A8l=typeof self=="object"&&self&&self.Object===Object&&self,w1e=q8n||A8l||Function("return this")(),$8n=typeof E1e=="object"&&E1e&&!E1e.nodeType&&E1e,f1e=$8n&&typeof YIe=="object"&&YIe&&!YIe.nodeType&&YIe,eqn=f1e&&f1e.exports===$8n,mHt=eqn&&q8n.process,L8n=(function(){try{var t=f1e&&f1e.require&&f1e.require("util").types;return t||mHt&&mHt.binding&&mHt.binding("util")}catch{}})(),S8n=L8n&&L8n.isTypedArray;function Z8l(t,e,n){switch(n.length){case 0:return t.call(e);case 1:return t.call(e,n[0]);case 2:return t.call(e,n[0],n[1]);case 3:return t.call(e,n[0],n[1],n[2])}return t.apply(e,n)}function N8l(t,e){for(var n=-1,r=Array(t);++n<t;)r[n]=e(n);return r}function y8l(t){return function(e){return t(e)}}function W8l(t,e){return t?.[e]}function E8l(t,e){return function(n){return t(e(n))}}var f8l=Array.prototype,R8l=Function.prototype,zze=Object.prototype,pHt=w1e["__core-js_shared__"],Pze=R8l.toString,_L=zze.hasOwnProperty,J8n=(function(){var t=/[^.]+$/.exec(pHt&&pHt.keys&&pHt.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""})(),tqn=zze.toString,w8l=Pze.call(Object),Y8l=RegExp("^"+Pze.call(_L).replace(h8l,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Mze=eqn?w1e.Buffer:void 0,B8n=w1e.Symbol,T8n=w1e.Uint8Array,O8n=Mze?Mze.allocUnsafe:void 0,nqn=E8l(Object.getPrototypeOf,Object),_8n=Object.create,v8l=zze.propertyIsEnumerable,V8l=f8l.splice,$K=B8n?B8n.toStringTag:void 0,Dze=(function(){try{var t=ZHt(Object,"defineProperty");return t({},"",{}),t}catch{}})(),C8l=Mze?Mze.isBuffer:void 0,U8n=Math.max,Q8l=Date.now,rqn=ZHt(w1e,"Map"),R1e=ZHt(Object,"create"),F8l=(function(){function t(){}return function(e){if(!t8(e))return{};if(_8n)return _8n(e);t.prototype=e;var n=new t;return t.prototype=void 0,n}})();function e8(t){var e=-1,n=t==null?0:t.length;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}function H8l(){this.__data__=R1e?R1e(null):{},this.size=0}function X8l(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}function k8l(t){var e=this.__data__;if(R1e){var n=e[t];return n===D8n?void 0:n}return _L.call(e,t)?e[t]:void 0}function x8l(t){var e=this.__data__;return R1e?e[t]!==void 0:_L.call(e,t)}function L8l(t,e){var n=this.__data__;return this.size+=this.has(t)?0:1,n[t]=R1e&&e===void 0?D8n:e,this}e8.prototype.clear=H8l;e8.prototype.delete=X8l;e8.prototype.get=k8l;e8.prototype.has=x8l;e8.prototype.set=L8l;function UL(t){var e=-1,n=t==null?0:t.length;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}function S8l(){this.__data__=[],this.size=0}function J8l(t){var e=this.__data__,n=jze(e,t);if(n<0)return!1;var r=e.length-1;return n==r?e.pop():V8l.call(e,n,1),--this.size,!0}function B8l(t){var e=this.__data__,n=jze(e,t);return n<0?void 0:e[n][1]}function T8l(t){return jze(this.__data__,t)>-1}function O8l(t,e){var n=this.__data__,r=jze(n,t);return r<0?(++this.size,n.push([t,e])):n[r][1]=e,this}UL.prototype.clear=S8l;UL.prototype.delete=J8l;UL.prototype.get=B8l;UL.prototype.has=T8l;UL.prototype.set=O8l;function vIe(t){var e=-1,n=t==null?0:t.length;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}function _8l(){this.size=0,this.__data__={hash:new e8,map:new(rqn||UL),string:new e8}}function U8l(t){var e=qze(this,t).delete(t);return this.size-=e?1:0,e}function M8l(t){return qze(this,t).get(t)}function D8l(t){return qze(this,t).has(t)}function z8l(t,e){var n=qze(this,t),r=n.size;return n.set(t,e),this.size+=n.size==r?0:1,this}vIe.prototype.clear=_8l;vIe.prototype.delete=U8l;vIe.prototype.get=M8l;vIe.prototype.has=D8l;vIe.prototype.set=z8l;function VIe(t){var e=this.__data__=new UL(t);this.size=e.size}function P8l(){this.__data__=new UL,this.size=0}function j8l(t){var e=this.__data__,n=e.delete(t);return this.size=e.size,n}function K8l(t){return this.__data__.get(t)}function q8l(t){return this.__data__.has(t)}function $8l(t,e){var n=this.__data__;if(n instanceof UL){var r=n.__data__;if(!rqn||r.length<BKl-1)return r.push([t,e]),this.size=++n.size,this;n=this.__data__=new vIe(r)}return n.set(t,e),this.size=n.size,this}VIe.prototype.clear=P8l;VIe.prototype.delete=j8l;VIe.prototype.get=K8l;VIe.prototype.has=q8l;VIe.prototype.set=$8l;function eql(t,e){var n=gHt(t),r=!n&&GHt(t),l=!n&&!r&&sqn(t),a=!n&&!r&&!l&&Iqn(t),o=n||r||l||a,s=o?N8l(t.length,String):[],I=s.length;for(var c in t)(e||_L.call(t,c))&&!(o&&(c=="length"||l&&(c=="offset"||c=="parent")||a&&(c=="buffer"||c=="byteLength"||c=="byteOffset")||aqn(c,I)))&&s.push(c);return s}function bHt(t,e,n){(n!==void 0&&!$ze(t[e],n)||n===void 0&&!(e in t))&&AHt(t,e,n)}function tql(t,e,n){var r=t[e];(!(_L.call(t,e)&&$ze(r,n))||n===void 0&&!(e in t))&&AHt(t,e,n)}function jze(t,e){for(var n=t.length;n--;)if($ze(t[n][0],e))return n;return-1}function AHt(t,e,n){e=="__proto__"&&Dze?Dze(t,e,{configurable:!0,enumerable:!0,value:n,writable:!0}):t[e]=n}var nql=bql();function Kze(t){return t==null?t===void 0?r8l:qKl:$K&&$K in Object(t)?hql(t):yql(t)}function M8n(t){return Y1e(t)&&Kze(t)==P8n}function rql(t){if(!t8(t)||Zql(t))return!1;var e=yHt(t)?Y8l:G8l;return e.test(Rql(t))}function lql(t){return Y1e(t)&&iqn(t.length)&&!!pm[Kze(t)]}function aql(t){if(!t8(t))return Nql(t);var e=oqn(t),n=[];for(var r in t)r=="constructor"&&(e||!_L.call(t,r))||n.push(r);return n}function lqn(t,e,n,r,l){t!==e&&nql(e,function(a,o){if(l||(l=new VIe),t8(a))oql(t,e,o,n,lqn,r,l);else{var s=r?r(hHt(t,o),a,o+"",t,e,l):void 0;s===void 0&&(s=a),bHt(t,o,s)}},cqn)}function oql(t,e,n,r,l,a,o){var s=hHt(t,n),I=hHt(e,n),c=o.get(I);if(c){bHt(t,n,c);return}var d=a?a(s,I,n+"",t,e,o):void 0,u=d===void 0;if(u){var p=gHt(I),b=!p&&sqn(I),G=!p&&!b&&Iqn(I);d=I,p||b||G?gHt(s)?d=s:wql(s)?d=uql(s):b?(u=!1,d=Iql(I,!0)):G?(u=!1,d=dql(I,!0)):d=[]:Yql(I)||GHt(I)?(d=s,GHt(s)?d=vql(s):(!t8(s)||yHt(s))&&(d=Gql(I))):u=!1}u&&(o.set(I,d),l(d,I,r,a,o),o.delete(I)),bHt(t,n,d)}function sql(t,e){return Eql(Wql(t,e,dqn),t+"")}var iql=Dze?function(t,e){return Dze(t,"toString",{configurable:!0,enumerable:!1,value:Cql(e),writable:!0})}:dqn;function Iql(t,e){if(e)return t.slice();var n=t.length,r=O8n?O8n(n):new t.constructor(n);return t.copy(r),r}function cql(t){var e=new t.constructor(t.byteLength);return new T8n(e).set(new T8n(t)),e}function dql(t,e){var n=e?cql(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.length)}function uql(t,e){var n=-1,r=t.length;for(e||(e=Array(r));++n<r;)e[n]=t[n];return e}function mql(t,e,n,r){var l=!n;n||(n={});for(var a=-1,o=e.length;++a<o;){var s=e[a],I=r?r(n[s],t[s],s,n,t):void 0;I===void 0&&(I=t[s]),l?AHt(n,s,I):tql(n,s,I)}return n}function pql(t){return sql(function(e,n){var r=-1,l=n.length,a=l>1?n[l-1]:void 0,o=l>2?n[2]:void 0;for(a=t.length>3&&typeof a=="function"?(l--,a):void 0,o&&gql(n[0],n[1],o)&&(a=l<3?void 0:a,l=1),e=Object(e);++r<l;){var s=n[r];s&&t(e,s,r,a)}return e})}function bql(t){return function(e,n,r){for(var l=-1,a=Object(e),o=r(e),s=o.length;s--;){var I=o[t?s:++l];if(n(a[I],I,a)===!1)break}return e}}function qze(t,e){var n=t.__data__;return Aql(e)?n[typeof e=="string"?"string":"hash"]:n.map}function ZHt(t,e){var n=W8l(t,e);return rql(n)?n:void 0}function hql(t){var e=_L.call(t,$K),n=t[$K];try{t[$K]=void 0;var r=!0}catch{}var l=tqn.call(t);return r&&(e?t[$K]=n:delete t[$K]),l}function Gql(t){return typeof t.constructor=="function"&&!oqn(t)?F8l(nqn(t)):{}}function aqn(t,e){var n=typeof t;return e=e??z8n,!!e&&(n=="number"||n!="symbol"&&g8l.test(t))&&t>-1&&t%1==0&&t<e}function gql(t,e,n){if(!t8(n))return!1;var r=typeof e;return(r=="number"?NHt(n)&&aqn(e,n.length):r=="string"&&e in n)?$ze(n[e],t):!1}function Aql(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}function Zql(t){return!!J8n&&J8n in t}function oqn(t){var e=t&&t.constructor,n=typeof e=="function"&&e.prototype||zze;return t===n}function Nql(t){var e=[];if(t!=null)for(var n in Object(t))e.push(n);return e}function yql(t){return tqn.call(t)}function Wql(t,e,n){return e=U8n(e===void 0?t.length-1:e,0),function(){for(var r=arguments,l=-1,a=U8n(r.length-e,0),o=Array(a);++l<a;)o[l]=r[e+l];l=-1;for(var s=Array(e+1);++l<e;)s[l]=r[l];return s[e]=n(o),Z8l(t,this,s)}}function hHt(t,e){if(!(e==="constructor"&&typeof t[e]=="function")&&e!="__proto__")return t[e]}var Eql=fql(iql);function fql(t){var e=0,n=0;return function(){var r=Q8l(),l=OKl-(r-n);if(n=r,l>0){if(++e>=TKl)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}function Rql(t){if(t!=null){try{return Pze.call(t)}catch{}try{return t+""}catch{}}return""}function $ze(t,e){return t===e||t!==t&&e!==e}var GHt=M8n((function(){return arguments})())?M8n:function(t){return Y1e(t)&&_L.call(t,"callee")&&!v8l.call(t,"callee")},gHt=Array.isArray;function NHt(t){return t!=null&&iqn(t.length)&&!yHt(t)}function wql(t){return Y1e(t)&&NHt(t)}var sqn=C8l||Qql;function yHt(t){if(!t8(t))return!1;var e=Kze(t);return e==j8n||e==PKl||e==UKl||e==$Kl}function iqn(t){return typeof t=="number"&&t>-1&&t%1==0&&t<=z8n}function t8(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}function Y1e(t){return t!=null&&typeof t=="object"}function Yql(t){if(!Y1e(t)||Kze(t)!=K8n)return!1;var e=nqn(t);if(e===null)return!0;var n=_L.call(e,"constructor")&&e.constructor;return typeof n=="function"&&n instanceof n&&Pze.call(n)==w8l}var Iqn=S8n?y8l(S8n):lql;function vql(t){return mql(t,cqn(t))}function cqn(t){return NHt(t)?eql(t,!0):aql(t)}var Vql=pql(function(t,e,n){lqn(t,e,n)});function Cql(t){return function(){return t}}function dqn(t){return t}function Qql(){return!1}YIe.exports=Vql});async function Fql(t={}){let e=await Eon();return won((0,mqn.default)({},e,t))}async function WHt(t={}){if(HHe())throw new Error("Settings have already been initialized");return Fql(t)}var mqn,pqn=W(()=>{"use strict";mqn=ze(uqn(),1);XHe();$pe()});import{readdir as Hql,stat as Xql}from"fs/promises";async function kql(t,e){try{let n=await Xql(t);if(n.isDirectory()){let r=await Hql(t);return{path:t,type:"directory",lines:r.length}}else{let r=n.size/1048576;if(n.size>bqn){let a=(bqn/1048576).toFixed(0);return e.debug(`File ${t} is too large (${r.toFixed(1)}MB). Maximum file size is ${a}MB. Skipping line count.`),{path:t,type:"file",sizeMB:r}}let{totalLineCount:l}=await F4e(t,1,void 0);return{path:t,type:"file",lines:l}}}catch(n){return e.debug(`Error getting file info for ${t}: ${gt(n)}`),{path:t,type:"file",error:gt(n)}}}async function hqn(t,e){let n=t.filter(a=>!e1(a.path));if(n.length===0)return"";let r=await Promise.all(n.map(a=>kql(a.path,e))),l=["<tagged_files>"];for(let a of r)a.error?l.push(`* ${a.path} (error: ${a.error})`):a.sizeMB!==void 0?l.push(`* ${a.path} (large file: ${a.sizeMB.toFixed(1)}MB)`):a.type==="directory"?l.push(`* ${a.path} (${a.lines} entries)`):l.push(`* ${a.path} (${a.lines} lines)`);return l.push("</tagged_files>"),l.join(`
2280
2276
  `)}async function Gqn(t,e){let n=t.filter(l=>l.type==="file"&&e1(l.path));return(await Promise.all(n.map(async l=>{try{let a=await i9e(l.path,e);return a?[{type:"text",text:`Image file at path ${l.path}`},{type:"image_url",image_url:{url:`data:${a.mimeType};base64,${a.base64Data}`}}]:void 0}catch(a){e.error(`Failed to process image ${l.path}: ${a instanceof Error?a.message:String(a)}`);return}}))).filter(l=>l!==void 0).flat()}var bqn,gqn=W(()=>{"use strict";ma();FE();sT();bqn=10*1024*1024});async function qO(t,e,n){if(!t||t.length===0)return;let r=!1,l={};for(let a of t)try{let o=await a(e);o&&(r=!0,l={...l,...o})}catch(o){n.error(`Hook execution failed: ${gt(o)}`)}return r?l:void 0}var EHt=W(()=>{"use strict";ma()});function Aqn(t){return t.filter(e=>MO(e.id)&&ZC(e.id,t)).sort((e,n)=>hW.indexOf(e.id)-hW.indexOf(n.id))}async function ePe(t,e,n,r,l){if(XX())return{models:[],copilotUrl:e};if(t.type==="hmac"){if(GN&&t.type===GN.authInfo.type&&t.hmac===GN.authInfo.hmac)return{models:GN.models,copilotUrl:GN.copilotUrl};let u=e||mD(),b=await SO.createWithHmac(l,u,n,t.hmac,r).listModels();return GN={models:Aqn(b.models),authInfo:t,copilotUrl:b.copilotUrl},{models:GN.models,copilotUrl:b.copilotUrl}}let a=await EG(t);if(!a)throw new Error("Failed to get token for auth info");if(GN&&GN.models.length>0&&GN.authInfo.type!=="hmac"&&a===await EG(GN.authInfo))return{models:GN.models,copilotUrl:GN.copilotUrl};let s=await eN(t.host,a),c=await SO.createWithOAuthToken(l,s,n,a,r).listModels();return c.models.length===0?{models:[],copilotUrl:c.copilotUrl}:(GN={models:Aqn(c.models),authInfo:t,copilotUrl:c.copilotUrl},{models:GN.models,copilotUrl:c.copilotUrl})}async function Zqn(t,e,n,r,l){if(r??=Ni(),n??=v1e,l??=new Q0,t.type==="hmac")return{success:!1,canBeEnabled:!1,error:"Model enablement is not available with HMAC authentication. Only Copilot for Individuals users can enable models."};let a=await EG(t);if(!a)return{success:!1,error:"Failed to get authentication token"};let s=await eN(t.host,a),c=await SO.createWithOAuthToken(l,s,n,a,r).enableModelPolicy(e);return c.success&&(GN=null),c}var GN,fHt=W(()=>{"use strict";Nf();vw();iY();yC();$fe();Mg();Fze();ML();GN=null});function Nqn(t){return t?.trim().length??0}function yqn(t,e){if(t&&e){let n=Nqn(t),r=Nqn(e);return n===r?e:n>r?t:e}return t??e??null}function tPe(t){let{streamingReasoningId:e,streamingReasoningContent:n,messageReasoningId:r,messageReasoningText:l,fallbackReasoningIdFactory:a=Ni}=t,o=yqn(n,l),s=e??r??null;return!s&&o&&(s=a()),{reasoningId:s,reasoningContent:o}}var Wqn=W(()=>{"use strict";Nf()});var Eqn=W(()=>{"use strict";Wqn()});function xql(t){if(!t)return"Unknown error occurred";try{let e=JSON.parse(t);if(typeof e=="object"&&e!==null){let n=e;if(typeof n.message=="string")return n.message;if(typeof n.error=="string")return n.error;if(typeof n.error=="object"&&n.error!==null){let r=n.error;if(typeof r.message=="string")return r.message}}}catch{}return t}function Lql(t){return hW.filter(e=>ZC(e,t)).map(e=>{let n=t.find(o=>o.id===e),r=n?.name??e,l=n?.billing?.multiplier??1,a=l<=.5?"fast/cheap":l>=2?"premium":"standard";return{id:e,label:r,description:a}})}function RHt(t){return t.map(e=>({name:e.name,namespacedName:e.namespacedName,description:e.description,title:e.title,input_schema:e.input_schema,instructions:e.instructions}))}function Rqn(t){return t===void 0||t.type==="object"}function Sql(t){if(t.length===0)return t;let e=[],n=new Set,r=!1;for(let o=t.length-1;o>=0;o--){let s=t[o];if(s.role==="assistant"&&(r=!0),s.role==="assistant"&&"tool_calls"in s&&s.tool_calls&&s.tool_calls.length>0)for(let I of s.tool_calls)n.has(I.id)||e.push(I.id);else{if(r)break;s.role==="tool"&&s.tool_call_id&&n.add(s.tool_call_id)}}if(e.length===0)return t;let l="The execution of this tool, or a previous tool was interrupted.";Qe.info(`Completing ${e.length} orphaned tool calls.`);let a=e.map(o=>({role:"tool",tool_call_id:o,content:l}));return[...t,...a]}var CIe,v1e,fqn,wHt,nPe,T0,DL,ML=W(()=>{"use strict";m8n();Nf();hIe();t1e();bIe();mIe();CNe();b8n();y8n();zO();vw();iY();WC();E8n();f8n();qK();w8n();yC();jQt();V8n();C8n();uH();ma();TP();sT();Afe();JL();Yv();TG();Bze();uHt();k8n();c9e();$Wt();Ty();Boe();qB();TO();dHt();x8n();Lv();XHe();Mg();pqn();Rst();au();K9e();qDe();zQt();IHt();YHt();gqn();EHt();fHt();Eqn();CIe="copilot-developer-cli",v1e=process.env.GITHUB_COPILOT_INTEGRATION_ID||CIe,fqn=u8n(eN);wHt=class{constructor(e,n){this.premiumRequestProcessor=e;this.session=n}messageQueue=[];async*preRequest(e){if(this.messageQueue.length===0)return;Qe.debug("ImmediatePromptProcessor: Injecting immediate prompts"),this.premiumRequestProcessor.setForcePremiumRequest();let r=(await this.session.getChatMessages()).length;for(;this.messageQueue.length>0;){let o=this.messageQueue.shift();this.session.emitEphemeral("pending_messages.modified",{}),this.session.emit("user.message",{content:o.prompt,attachments:o.attachments})}let a=(await this.session.getChatMessages()).slice(r);for(let o of a)e.messages.push(o),yield{kind:"message",message:o,turn:e.turn,source:"immediate-prompt"}}addMessage(e){this.messageQueue.push(e)}getQueue(){return this.messageQueue}clearQueue(){this.messageQueue.length=0}popMessage(){return this.messageQueue.shift()}toJSON(){return"ImmediatePromptProcessor"}},nPe=class{sessionId;startTime;modifiedTime;summary;events=[];_chatMessages=[];_selectedModel;originalUserMessages=[];eventProcessingQueue=Promise.resolve();eventHandlers={};wildcardEventHandlers=[];integrationId;availableTools;excludedTools;executeToolsInParallel;shellConfig;requestPermission;mcpServers;mcpHost;hooks;customAgents;selectedCustomAgent;organizationCustomInstructions;skipCustomInstructions;systemMessageConfig;workingDir;featureFlags;skillDirectories;disabledSkills;trajectoryFile;eventsLogDirectory;authInfo;copilotUrl;provider;onToolsUpdate;enableStreaming=!1;handoffContext;externalToolDefinitions;externalToolDispatcher;clientName;largeOutputConfig;workspaceContext;currentSystemMessage;currentToolMetadata;currentTools;async initializeAndValidateTools(){}constructor(e={}){this.sessionId=e.sessionId||Ni(),this.startTime=e.startTime||new Date,this.modifiedTime=e.modifiedTime||this.startTime,this.summary=e.summary,this.integrationId=e.integrationId||v1e,this.skipCustomInstructions=e.skipCustomInstructions??!1,this.workingDir=e.workingDirectory||process.cwd(),this.updateOptions(e)}static async fromEvents(e,n){if(e.length===0)throw new Error("Cannot create session from empty events array");let r=e[0];if(r.type!=="session.start")throw new Error("First event must be session.start");let l=new this({...n,sessionId:r.data.sessionId,startTime:new Date(r.data.startTime)});l._selectedModel=r.data.selectedModel,l.events.push(r);for(let a=1;a<e.length;a++){let o=e[a];l.events.push(o),await l.processEventForState(o)}return l}setAuthInfo(e){this.updateOptions({authInfo:e})}updateOptions(e){e.clientName!==void 0&&(this.clientName=e.clientName),e.model!==void 0&&(this._selectedModel=e.model),e.integrationId!==void 0&&(this.integrationId=e.integrationId),e.availableTools!==void 0&&(this.availableTools=e.availableTools),e.excludedTools!==void 0&&(this.excludedTools=e.excludedTools),e.executeToolsInParallel!==void 0&&(this.executeToolsInParallel=e.executeToolsInParallel),e.shellConfig!==void 0&&(this.shellConfig=e.shellConfig),e.requestPermission!==void 0&&(this.requestPermission=e.requestPermission),e.featureFlags!==void 0&&(this.featureFlags=e.featureFlags),e.skillDirectories!==void 0&&(this.skillDirectories=e.skillDirectories),e.disabledSkills!==void 0&&(this.disabledSkills=e.disabledSkills),e.mcpServers!==void 0&&(this.mcpServers=e.mcpServers),e.mcpHost!==void 0&&(this.mcpHost=e.mcpHost),e.customAgents!==void 0?this.customAgents=e.customAgents:this.loadCustomAgents().catch(n=>Qe.error(`Failed to load custom agents: ${gt(n)}`)),"selectedCustomAgent"in e&&(this.selectedCustomAgent=e.selectedCustomAgent),e.organizationCustomInstructions!==void 0&&(this.organizationCustomInstructions=e.organizationCustomInstructions),e.skipCustomInstructions!==void 0&&(this.skipCustomInstructions=e.skipCustomInstructions),e.systemMessage!==void 0&&(this.systemMessageConfig=e.systemMessage),e.hooks!==void 0&&(this.hooks=e.hooks),e.externalToolDefinitions!==void 0&&(this.externalToolDefinitions=e.externalToolDefinitions),e.externalToolDispatcher!==void 0&&(this.externalToolDispatcher=e.externalToolDispatcher),e.trajectoryFile!==void 0&&(this.trajectoryFile=e.trajectoryFile),e.eventsLogDirectory!==void 0&&(this.eventsLogDirectory=e.eventsLogDirectory),e.workingDirectory!==void 0&&(this.workingDir=e.workingDirectory),e.authInfo!==void 0&&(this.authInfo=e.authInfo),e.copilotUrl!==void 0&&(this.copilotUrl=e.copilotUrl),e.provider!==void 0&&(this.provider=e.provider),e.enableStreaming!==void 0&&(this.enableStreaming=e.enableStreaming),e.largeOutput!==void 0&&(this.largeOutputConfig=e.largeOutput)}setOnToolsUpdate(e){this.onToolsUpdate=e}getAvailableCustomAgents(){return this.customAgents||[]}async selectCustomAgent(e){let n=this.customAgents?.find(r=>r.name===e);if(!n)throw new Error(`Custom agent '${e}' not found`);this.selectedCustomAgent=n,this.emit("custom_agent.selected",{agentName:n.name,agentDisplayName:n.displayName,tools:n.tools})}clearCustomAgent(){this.selectedCustomAgent=void 0}on(e,n){return e==="*"?(this.wildcardEventHandlers.push(n),()=>{let r=this.wildcardEventHandlers.indexOf(n);r!==-1&&this.wildcardEventHandlers.splice(r,1)}):(this.eventHandlers[e]||(this.eventHandlers[e]=[]),this.eventHandlers[e].push(n),()=>{let r=this.eventHandlers[e];if(r){let l=r.indexOf(n);l!==-1&&r.splice(l,1)}})}emitInternal(e,n,r=!1){let l=Ni(),a=new Date().toISOString(),o=this.getLastEventId(),s={type:e,data:n,id:l,timestamp:a,parentId:o,...r&&{ephemeral:r}};this.events.push(s),this.enqueueEventProcessing(()=>this.processEventForState(s)).catch(I=>{Qe.error(`Error emitting event: ${I instanceof Error?I.message:String(I)}`)}).catch(I=>{Qe.error(`Error emitting event ${I instanceof Error?I.message:String(I)}`)}),[...this.eventHandlers[s.type]||[],...this.wildcardEventHandlers].forEach(I=>{try{I(s)}catch(c){Qe.error(`Error in event handler for event type ${s.type}: ${c instanceof Error?c.message:String(c)}`)}})}emit(e,n){this.emitInternal(e,n)}emitEphemeral(e,n){this.emitInternal(e,n,!0)}getEvents(){return this.events}async getChatMessages(){return this.enqueueEventProcessing(()=>this._chatMessages)}async getChatContextMessages(){return(await this.getChatMessages()).filter(n=>n.role!=="system")}async getSystemContextMessages(){return(await this.getChatMessages()).filter(n=>n.role==="system")}getCurrentSystemMessage(){return this.currentSystemMessage}getCurrentToolMetadata(){return this.currentToolMetadata}async getSelectedModel(){return this.enqueueEventProcessing(()=>this._selectedModel)}getOrganizationCustomInstructions(){return this.organizationCustomInstructions}getSkipCustomInstructions(){return this.skipCustomInstructions}getSystemMessageConfig(){return this.systemMessageConfig}setWorkspaceContext(e){this.workspaceContext=e}getWorkspaceContext(){return this.workspaceContext}getWorkspace(){return null}isWorkspaceEnabled(){return!1}getWorkspacePath(){return null}getCheckpointCount(){return 0}async listCheckpointTitles(){return[]}hasPlan(){return!1}async ensureWorkspace(e,n){throw new Error("Workspace features are not available for this session type")}async setSelectedModel(e){let n=await this.getSelectedModel();this.emit("session.model_change",{previousModel:n,newModel:e})}getLastEventId(){return this.events.length===0?null:this.events[this.events.length-1].id}enqueueEventProcessing(e){let n=this.eventProcessingQueue.then(()=>e());return this.eventProcessingQueue=n,n}async processEventForState(e){switch(e.type){case"session.start":e.data.selectedModel&&(this._selectedModel=e.data.selectedModel);break;case"session.model_change":this._selectedModel=e.data.newModel;break;case"user.message":{this.originalUserMessages.push(e.data.content);let n=e.data.transformedContent??e.data.content,r=[];if(e.data.attachments&&e.data.attachments.length>0){let l=await Gqn(e.data.attachments,Qe);if(r.push(...l),e.data.attachments&&e.data.attachments.length>0){let a=await hqn(e.data.attachments,Qe);a&&(n=`${n}
2281
2277
 
2282
- ${a}`)}}r.length>0?this._chatMessages.push({role:"user",content:[{type:"text",text:n},...r]}):this._chatMessages.push({role:"user",content:n});break}case"assistant.message":{if(e.ephemeral||e.data.parentToolCallId)break;let n={role:"assistant",content:e.data.content||null};e.data.toolRequests&&e.data.toolRequests.length>0&&(n.tool_calls=e.data.toolRequests.map(r=>r.toolCallId.startsWith("custom_")?{id:r.toolCallId,type:"custom",custom:{name:r.name,input:typeof r.arguments=="string"?r.arguments:JSON.stringify(r.arguments)}}:{id:r.toolCallId,type:"function",function:{name:r.name,arguments:typeof r.arguments=="string"?r.arguments:JSON.stringify(r.arguments)}})),this._chatMessages.push(n);break}case"tool.execution_complete":{if(e.data.parentToolCallId)break;e.data.isUserRequested||this._chatMessages.push({role:"tool",tool_call_id:e.data.toolCallId,content:e.data.success?e.data.result?.content||"":e.data.error?.message||"Tool execution failed"});break}case"system.message":this._chatMessages.push({role:e.data.role,content:e.data.content,...e.data.name&&{name:e.data.name}});break;case"session.import_legacy":this._chatMessages=[...e.data.legacySession.chatMessages],e.data.legacySession.selectedModel&&(this._selectedModel=e.data.legacySession.selectedModel);break;case"abort":case"session.resume":this._chatMessages=Sql(this._chatMessages);break;case"session.handoff":e.data.context&&(this.handoffContext=e.data.context);break;case"session.compaction_complete":{if(e.data.success&&e.data.summaryContent){let n=e.data.preCompactionMessagesLength??this._chatMessages.length;this.applyCompactionToMessages(n,e.data.summaryContent)}break}case"session.compaction_start":case"assistant.intent":case"assistant.message_delta":case"assistant.reasoning_delta":case"session.idle":case"session.error":case"session.info":case"session.truncation":case"assistant.turn_start":case"assistant.turn_end":case"assistant.usage":case"assistant.reasoning":case"tool.user_requested":case"tool.execution_start":case"tool.execution_partial_result":case"custom_agent.started":case"custom_agent.completed":case"custom_agent.failed":case"custom_agent.selected":case"hook.start":case"hook.end":case"pending_messages.modified":break;default:{let n=e;Qe.error(`Unknown event type: ${n.type}`);break}}}async loadCustomAgents(){if(this.provider){Qe.debug("Using custom provider, skipping custom agents load");return}if(!this.authInfo){Qe.debug("No auth info available, skipping custom agents load");return}this.customAgents=await wqn(this.authInfo,this.workingDir,this.integrationId,Qe)}applyCompactionToMessages(e,n){if(e<this._chatMessages.length){let r=this._chatMessages.slice(0,e),l=this._chatMessages.slice(e),a=Tze(r,l);r=a.adjustedCheckpoint,l=a.adjustedNew;let o=wIe(r,n,this.originalUserMessages);for(;l.length>0&&l[0].role==="tool";)l.shift();return this._chatMessages=[...o,...l],{compacted:o,newMessages:l}}else{let r=wIe(this._chatMessages,n,this.originalUserMessages);return this._chatMessages=r,{compacted:r,newMessages:[]}}}},T0=class t extends nPe{callback=new cBe;isProcessing=!1;messageQueue=[];premiumRequestProcessor;immediatePromptProcessor;compactionProcessor;abortController;activeCustomAgents=new Map;mcpHostCache;modelListCache=void 0;warnedUnknownTools=new Set;sessionWorkspace=null;workspaceEnabled=!1;lastTodoContent=null;lastPlanUpdateTurn=0;currentTurn=0;static PLAN_REMINDER_TURN_THRESHOLD=10;constructor(e={}){super(e),this.premiumRequestProcessor=new n1e(Qe),this.immediatePromptProcessor=new wHt(this.premiumRequestProcessor,this),this.compactionProcessor=new _ze(Qe,{getOriginalUserMessages:()=>this.originalUserMessages,getPlanContent:this.workspaceEnabled?()=>this.getPlanContentForCompaction():void 0,getTodoContent:()=>this.lastTodoContent,onCompactionComplete:n=>{this.enqueueEventProcessing(()=>this.handleCompactionComplete(n))}}),this.mcpHostCache=new Jze(Qe),this.on("session.model_change",()=>{this.warnedUnknownTools.clear(),this.initializeAndValidateTools()}),e.featureFlags?.INFINITE_SESSIONS&&(this.workspaceEnabled=!0,this.initializeWorkspace(),this.on("session.compaction_complete",n=>{n.data.success&&n.data.summaryContent&&this.persistCompactionCheckpoint(n.data.summaryContent)}))}async initializeWorkspace(){let n=await B0().getOrCreateWorkspace(this.sessionId);this.sessionWorkspace=n,await this.updateWorkspaceContext(),Qe.debug(`Workspace initialized: ${this.sessionId} (checkpoints: ${n.summary_count})`)}async updateWorkspaceContext(){let e=this.getWorkspacePath();if(!e){this.setWorkspaceContext(void 0);return}let n=this.sessionWorkspace,r=n?n.name||`${n.owner||"_local"}/${n.repo||"workspace"}`:"_local/workspace",l=await this.listCheckpointTitles(),a=await B0().listFiles(this.sessionId);this.setWorkspaceContext({name:r,workspacePath:e,summaryCount:this.getCheckpointCount(),hasPlan:this.hasPlan(),checkpoints:l,filesInWorkspace:a,showPlanReminder:this.shouldShowPlanReminder()})}updateOptions(e){if(super.updateOptions(e),e.trajectoryFile!==void 0){let n=new xze(Qe,e.trajectoryFile);this.callback.addCallback(n)}if(e.eventsLogDirectory!==void 0){let n=new Hze(Qe,e.eventsLogDirectory);this.callback.addCallback(n)}}getMetadata(){return{sessionId:this.sessionId,startTime:this.startTime,modifiedTime:this.modifiedTime,summary:this.summary,isRemote:!1}}getWorkspace(){return this.sessionWorkspace}isWorkspaceEnabled(){return this.workspaceEnabled}getWorkspacePath(){return this.workspaceEnabled?B0().getWorkspacePath(this.sessionId):null}getCheckpointCount(){return this.sessionWorkspace?.summary_count??0}async listCheckpointTitles(){return this.workspaceEnabled?(await B0().listCheckpoints(this.sessionId)).map(n=>({number:n.number,title:n.title,filename:n.filename})):[]}hasPlan(){return B0().planExists(this.sessionId)}async getPlanContentForCompaction(){return this.workspaceEnabled?B0().readPlan(this.sessionId):null}setLastTodoContent(e){this.lastTodoContent=e}getLastTodoContent(){return this.lastTodoContent}shouldShowPlanReminder(){return this.workspaceEnabled?this.currentTurn-this.lastPlanUpdateTurn>=t.PLAN_REMINDER_TURN_THRESHOLD&&this.hasPlan():!1}getPlanReminderMessage(){return this.shouldShowPlanReminder()?`<reminder>
2278
+ ${a}`)}}r.length>0?this._chatMessages.push({role:"user",content:[{type:"text",text:n},...r]}):this._chatMessages.push({role:"user",content:n});break}case"assistant.message":{if(e.ephemeral||e.data.parentToolCallId)break;let n={role:"assistant",content:e.data.content||null};e.data.toolRequests&&e.data.toolRequests.length>0&&(n.tool_calls=e.data.toolRequests.map(r=>r.toolCallId.startsWith("custom_")?{id:r.toolCallId,type:"custom",custom:{name:r.name,input:typeof r.arguments=="string"?r.arguments:JSON.stringify(r.arguments)}}:{id:r.toolCallId,type:"function",function:{name:r.name,arguments:typeof r.arguments=="string"?r.arguments:JSON.stringify(r.arguments)}})),this._chatMessages.push(n);break}case"tool.execution_complete":{if(e.data.parentToolCallId)break;e.data.isUserRequested||this._chatMessages.push({role:"tool",tool_call_id:e.data.toolCallId,content:e.data.success?e.data.result?.content||"":e.data.error?.message||"Tool execution failed"});break}case"system.message":this._chatMessages.push({role:e.data.role,content:e.data.content,...e.data.name&&{name:e.data.name}});break;case"session.import_legacy":this._chatMessages=[...e.data.legacySession.chatMessages],e.data.legacySession.selectedModel&&(this._selectedModel=e.data.legacySession.selectedModel);break;case"abort":case"session.resume":this._chatMessages=Sql(this._chatMessages);break;case"session.handoff":e.data.context&&(this.handoffContext=e.data.context);break;case"session.compaction_complete":{if(e.data.success&&e.data.summaryContent){let n=e.data.preCompactionMessagesLength??this._chatMessages.length;this.applyCompactionToMessages(n,e.data.summaryContent)}break}case"session.compaction_start":case"assistant.intent":case"assistant.message_delta":case"assistant.reasoning_delta":case"session.idle":case"session.error":case"session.info":case"session.truncation":case"assistant.turn_start":case"assistant.turn_end":case"assistant.usage":case"assistant.reasoning":case"tool.user_requested":case"tool.execution_start":case"tool.execution_partial_result":case"custom_agent.started":case"custom_agent.completed":case"custom_agent.failed":case"custom_agent.selected":case"hook.start":case"hook.end":case"pending_messages.modified":break;default:{let n=e;Qe.error(`Unknown event type: ${n.type}`);break}}}async loadCustomAgents(){if(this.provider){Qe.debug("Using custom provider, skipping custom agents load");return}if(!this.authInfo){Qe.debug("No auth info available, skipping custom agents load");return}this.customAgents=await wqn(this.authInfo,this.workingDir,this.integrationId,Qe)}applyCompactionToMessages(e,n){if(e<this._chatMessages.length){let r=this._chatMessages.slice(0,e),l=this._chatMessages.slice(e),a=Tze(r,l);r=a.adjustedCheckpoint,l=a.adjustedNew;let o=wIe(r,n,this.originalUserMessages);for(;l.length>0&&l[0].role==="tool";)l.shift();return this._chatMessages=[...o,...l],{compacted:o,newMessages:l}}else{let r=wIe(this._chatMessages,n,this.originalUserMessages);return this._chatMessages=r,{compacted:r,newMessages:[]}}}},T0=class t extends nPe{callback=new cBe;isProcessing=!1;messageQueue=[];premiumRequestProcessor;immediatePromptProcessor;compactionProcessor;abortController;activeCustomAgents=new Map;mcpHostCache;modelListCache=void 0;warnedUnknownTools=new Set;sessionWorkspace=null;workspaceEnabled=!1;lastTodoContent=null;lastPlanUpdateTurn=0;currentTurn=0;static PLAN_REMINDER_TURN_THRESHOLD=10;constructor(e={}){super(e),this.premiumRequestProcessor=new n1e(Qe),this.immediatePromptProcessor=new wHt(this.premiumRequestProcessor,this),this.compactionProcessor=new _ze(Qe,{getOriginalUserMessages:()=>this.originalUserMessages,getPlanContent:this.workspaceEnabled?()=>this.getPlanContentForCompaction():void 0,getTodoContent:()=>this.lastTodoContent,onCompactionComplete:n=>{this.enqueueEventProcessing(()=>this.handleCompactionComplete(n))}}),this.mcpHostCache=new Jze(Qe),this.on("session.model_change",()=>{this.warnedUnknownTools.clear(),this.initializeAndValidateTools()}),e.featureFlags?.INFINITE_SESSIONS&&(this.workspaceEnabled=!0,this.initializeWorkspace(),this.on("session.compaction_complete",n=>{n.data.success&&n.data.summaryContent&&this.persistCompactionCheckpoint(n.data.summaryContent)}))}async initializeWorkspace(){let n=await B0().getOrCreateWorkspace(this.sessionId);this.sessionWorkspace=n,await this.updateWorkspaceContext(),Qe.debug(`Workspace initialized: ${this.sessionId} (checkpoints: ${n.summary_count})`)}async updateWorkspaceContext(){let e=this.getWorkspacePath();if(!e){this.setWorkspaceContext(void 0);return}let n=this.sessionWorkspace,r=n?n.name||`${n.owner||"_local"}/${n.repo||"workspace"}`:"_local/workspace",l=await this.listCheckpointTitles(),a=await B0().listFiles(this.sessionId);this.setWorkspaceContext({name:r,workspacePath:e,summaryCount:this.getCheckpointCount(),hasPlan:this.hasPlan(),checkpoints:l,filesInWorkspace:a})}updateOptions(e){if(super.updateOptions(e),e.trajectoryFile!==void 0){let n=new xze(Qe,e.trajectoryFile);this.callback.addCallback(n)}if(e.eventsLogDirectory!==void 0){let n=new Hze(Qe,e.eventsLogDirectory);this.callback.addCallback(n)}}getMetadata(){return{sessionId:this.sessionId,startTime:this.startTime,modifiedTime:this.modifiedTime,summary:this.summary,isRemote:!1}}getWorkspace(){return this.sessionWorkspace}isWorkspaceEnabled(){return this.workspaceEnabled}getWorkspacePath(){return this.workspaceEnabled?B0().getWorkspacePath(this.sessionId):null}getCheckpointCount(){return this.sessionWorkspace?.summary_count??0}async listCheckpointTitles(){return this.workspaceEnabled?(await B0().listCheckpoints(this.sessionId)).map(n=>({number:n.number,title:n.title,filename:n.filename})):[]}hasPlan(){return B0().planExists(this.sessionId)}async getPlanContentForCompaction(){return this.workspaceEnabled?B0().readPlan(this.sessionId):null}setLastTodoContent(e){this.lastTodoContent=e}getLastTodoContent(){return this.lastTodoContent}shouldShowPlanReminder(){return!this.workspaceEnabled||!this.hasPlan()?!1:this.currentTurn-this.lastPlanUpdateTurn>=t.PLAN_REMINDER_TURN_THRESHOLD}getPlanReminderMessage(){return this.shouldShowPlanReminder()?`<reminder>
2283
2279
  Consider updating plan.md to reflect current progress and next steps.
2284
- </reminder>`:null}markPlanUpdated(){this.lastPlanUpdateTurn=this.currentTurn}emitWorkspaceFileTelemetry(e,n){let r=this.getWorkspacePath();if(!r)return;if(e.endsWith("/plan.md")||e.endsWith("\\plan.md")){this.invokeCallbacks(_Qt(this.sessionId,n,0));return}let l=`${r}/files/`,a=`${r}\\files\\`;if(e.startsWith(l)||e.startsWith(a)){let o=e.startsWith(l)?e.slice(l.length):e.slice(a.length);this.invokeCallbacks(MQt(this.sessionId,o,n,0))}}emitWorkspaceFileReadTelemetry(e){let n=this.getWorkspacePath();if(!n)return;if(e.endsWith("/plan.md")||e.endsWith("\\plan.md")){this.invokeCallbacks(UQt(this.sessionId,0));return}let r=`${n}/checkpoints/`,l=`${n}\\checkpoints\\`;if(e.startsWith(r)||e.startsWith(l)){let I=(e.split(/[/\\]/).pop()||"").match(/^(\d+)-/),c=I?parseInt(I[1],10):0;this.invokeCallbacks(OQt(this.sessionId,c,0));return}let a=`${n}/files/`,o=`${n}\\files\\`;if(e.startsWith(a)||e.startsWith(o)){let s=e.startsWith(a)?e.slice(a.length):e.slice(o.length);this.invokeCallbacks(DQt(this.sessionId,s,0))}}async ensureWorkspace(e,n){if(!this.workspaceEnabled)throw new Error("Workspace features are not enabled for this session");let l=await B0().getOrCreateWorkspace(this.sessionId,e,n);return this.sessionWorkspace=l,l}async persistCompactionCheckpoint(e){if(!this.sessionWorkspace){Qe.debug("No workspace loaded, skipping checkpoint persistence");return}try{let n=B0(),r=JQt(e,this.sessionId),l=BQt(e),a=await n.addSummary(this.sessionId,l,r);Qe.info(`Persisted checkpoint #${a}: ${r}`);let o=await n.loadWorkspace(this.sessionId);o&&(this.sessionWorkspace=o,await this.updateWorkspaceContext())}catch(n){let r=n instanceof Error?n.message:String(n);Qe.error(`Failed to persist checkpoint: ${r}`)}}async send(e){if(e.mode==="immediate"&&this.isProcessing){this.immediatePromptProcessor.addMessage(e),this.emitEphemeral("pending_messages.modified",{});return}if(this.messageQueue.push(e),this.emitEphemeral("pending_messages.modified",{}),!this.isProcessing){for(this.isProcessing=!0,await this.initializeMcpHost();this.messageQueue.length>0;){let n=this.messageQueue.shift();this.emitEphemeral("pending_messages.modified",{}),this.abortController=n.abortController||new AbortController,await this.runAgenticLoop(n.prompt,n.attachments);let r=this.immediatePromptProcessor.popMessage();r&&(this.emitEphemeral("pending_messages.modified",{}),this.messageQueue.unshift(r))}this.isProcessing=!1,this.emitEphemeral("session.idle",{})}}async abort(){this.abortController?.abort()}getPendingSteeringMessages(){return this.immediatePromptProcessor.getQueue().map(e=>e.prompt)}getPendingQueuedMessages(){return this.messageQueue.map(e=>e.prompt)}clearPendingMessages(){this.immediatePromptProcessor.clearQueue(),this.messageQueue.length=0,this.emitEphemeral("pending_messages.modified",{})}async compactHistory(){this.emit("session.compaction_start",{});let e=await this.getChatMessages();if(e.length<2)throw new Error("Nothing to compact.");if(!this.authInfo)throw new Error("Authentication required for compaction. Please log in first.");if(this.currentSystemMessage===void 0)throw new Error("Cannot compact: no active agent context. Send a message first.");let{client:n,settings:r}=await this.getClient(),l=sY(r.service?.agent?.model).model,a=Sf(e,l),o=e.length,I=W1e(e,this.workspaceEnabled).filter(A=>A.role!=="system"),c=await Oze(n,this.currentSystemMessage,I,this.currentTools??[],Qe);if(!c.content)throw new Error("Compaction failed: No response from model");let d=this.workspaceEnabled?await this.getPlanContentForCompaction():null,u=wIe(e,c.content,this.originalUserMessages,{isManualCompaction:!0,planContent:d??void 0,todoContent:this.lastTodoContent??void 0}),p=Sf(u,l),b=a-p,G=o-u.length;return this._chatMessages=u,this.emit("session.compaction_complete",{success:!0,preCompactionTokens:a,postCompactionTokens:p,preCompactionMessagesLength:o,messagesRemoved:G,tokensRemoved:b,summaryContent:c.content,compactionTokensUsed:{input:c.inputTokens,output:c.outputTokens,cachedInput:c.cachedInputTokens}}),Qe.info(`Compacted ${G} messages, saved ~${b} tokens`),{success:!0,tokensRemoved:b,messagesRemoved:G,summaryContent:c.content}}handleCompactionComplete(e){if(e.success&&e.summaryContent){let n={success:!0,preCompactionTokens:e.checkpointTokens,preCompactionMessagesLength:e.checkpointMessagesLength,summaryContent:e.summaryContent,compactionTokensUsed:e.compactionTokensUsed};this.emit("session.compaction_complete",n);let r={kind:"compaction_completed",turn:e.startTurn,performedBy:"CompactionProcessor",success:!0,compactionResult:{tokenLimit:0,preCompactionTokens:e.checkpointTokens,preCompactionMessagesLength:e.checkpointMessagesLength,summaryContent:e.summaryContent}};this.invokeCallbacks(r)}else{this.emit("session.compaction_complete",{success:!1,error:e.error});let n={kind:"compaction_completed",turn:e.startTurn,performedBy:"CompactionProcessor",success:!1,error:e.error};this.invokeCallbacks(n)}}async initializeMcpHost(){if(!this.mcpHost&&this.mcpServers&&Object.keys(this.mcpServers).length>0)try{this.mcpHost=new KO(Qe,{mcpServers:this.mcpServers},this.excludedTools),await this.mcpHost.startServers()}catch(e){Qe.error(`Failed to initialize MCP host: ${gt(e)}`)}}async initializeAndValidateTools(){try{let e=await this.buildSettingsAndTools();if(!e){Qe.debug("Could not initialize tools: buildSettingsAndTools returned undefined");return}let{settings:n,builtInTools:r,mcpTools:l,config:a,toolConfig:o}=e,s=[];for(let E of this.externalToolDefinitions??[])Rqn(E.parameters)&&s.push({name:E.name,description:E.description,input_schema:E.parameters??{type:"object",properties:{}}});let I=new Set([...r.map(E=>E.name),...l.map(E=>E.name),...s.map(E=>E.name)]);this.validateToolFilters(I);let c=r.filter(E=>this.isToolEnabled(E.name)),d=l.filter(E=>this.isToolEnabled(E.name)),u=s.filter(E=>this.isToolEnabled(E.name)),p=await R1(this.workingDir),b={...a.supports,reasoning:!0},G,A=[...RHt(c),...RHt(d),...u];if(this.customAgents&&this.customAgents.length>0&&!Sk(n)){let Y=(this.selectedCustomAgent?[this.selectedCustomAgent]:this.customAgents).filter(J=>J.infer!==!1).map(Xjn),C=[...A,...Y];G=this.filterToolsForSelectedAgent(C)}else G=A,G=this.filterToolsForSelectedAgent(G);let N=await GIe({location:p.found?p.gitRoot:"",version:YQe(),currentWorkingDirectory:this.workingDir,parts:a.cli?.systemMessage||{},capabilities:b,tools:G,organizationCustomInstructions:this.organizationCustomInstructions,skipCustomInstructions:this.skipCustomInstructions,systemMessage:this.systemMessageConfig,toolConfigOverrides:o,workspaceContext:this.workspaceContext});this.currentSystemMessage=N,this.currentToolMetadata=G}catch(e){Qe.debug(`Failed to initialize tools for validation: ${gt(e)}`)}}async buildSettingsAndTools(e){if(!this.authInfo&&!this.provider)return;await this.initializeMcpHost();let n,r;if(!this.provider){if(!this.authInfo)return;n=await EG(this.authInfo),r=this.copilotUrl,!r&&n&&this.authInfo.type!=="hmac"&&(r=await fqn(this.authInfo.host,n||""))}let l=!!this.provider,a=l?[]:await this.getModelList(),o=await BL(this._selectedModel,this,a,Qe,l);if(!o)throw new Error("No model available. Check policy enablement under GitHub Settings > Copilot");let s=l?`capi:${o}`:await CFt(o),c=new dD().setProblemStatement(e??"").setAgentModel(s).setGithubRepoName("copilot-sdk-session").setGithubRepoCommit("copilot-sdk-commit").setGithubRepoReadWrite(!1).setCopilotIntegrationId(this.integrationId).setCopilotUrl(r).setCopilotHmacKey(this.authInfo?.type==="hmac"?this.authInfo.hmac:void 0).setGithubToken(n).setCopilotToken(n).setTrajectoryOutputFile(this.trajectoryFile).setEventsLogDirectory(this.eventsLogDirectory).setFeatureFlags(this.featureFlags).setClientName(this.clientName).build();vst();let d=await WHt(c),u=d.service?.agent?.model,p=sY(u),b=SL(p.agent,p.model),G=Lql(a),A={location:this.workingDir,timeout:3e4,availableModels:G,toolPartialResultCallback:(Y,C)=>{this.emitEphemeral("tool.execution_partial_result",{toolCallId:Y,partialOutput:C})},createSubAgentCallback:Y=>({progress:async C=>{if(await this.invokeCallbacks(C),EIe(C))switch(C.kind){case"message":if(Bw(C)){let J=Joe(C)?C.message.tool_calls.map(_=>({toolCallId:_.id,name:ZV(_),arguments:E4e(_,vL)})):[];this.emit("assistant.message",{parentToolCallId:Y,messageId:Ni(),content:typeof C.message.content=="string"?C.message.content:"",toolRequests:J});for(let _ of J)this.emit("tool.execution_start",{parentToolCallId:Y,toolCallId:_.toolCallId,toolName:_.name,arguments:_.arguments})}break;case"tool_execution":this.emit("tool.execution_complete",{parentToolCallId:Y,toolCallId:C.toolCallId,success:C.toolResult.resultType==="success",result:C.toolResult.resultType==="success"?{content:C.toolResult.textResultForLlm||C.toolResult.sessionLog||""}:void 0,error:C.toolResult.resultType!=="success"?{message:(C.toolResult.resultType==="failure"?C.toolResult.error:void 0)||C.toolResult.textResultForLlm||C.toolResult.sessionLog||"Tool execution failed",code:C.toolResult.resultType}:void 0});break;default:break}},partialResult:async()=>{},commentReply:async()=>{},result:async()=>{},error:async()=>{}}),permissions:this.requestPermission?{requestRequired:!0,request:this.requestPermission}:{requestRequired:!1},shellConfig:this.shellConfig??(process.platform==="win32"?fA.powerShell:fA.bash).withScriptSafetyAssessor(async function(Y){return{result:"completed",commands:[{identifier:Y,readOnly:!1}],possiblePaths:[],possibleUrls:[],hasWriteFileRedirection:!1,canOfferSessionApproval:!1}}),skillDirectories:this.skillDirectories,disabledSkills:this.disabledSkills,customAgents:this.customAgents,...b.toolConfigOverrides},N=[];if(this.mcpHost){try{N=await this.mcpHost.getTools(d,Qe,A.permissions)}catch(Y){Qe.error(`Failed to get MCP tools: ${gt(Y)}`)}EEt(b.supports,N)}A.mcpTools=N,A.getMcpServerProviderForAgent=this.mcpHost?async Y=>{let C=await this.mcpHostCache.getOrCreateHost(Y,{});if(C)return new I1e(C,d,A.permissions)}:void 0;let R=await(b.cli?.toolInit??Zd.cli.toolInit)(A,d,Qe,new Uze,this.callback,void 0);return{settings:d,builtInTools:R,mcpTools:N,config:b,toolConfig:A}}isToolEnabled(e){return this.availableTools?this.availableTools.includes(e):this.excludedTools?!this.excludedTools.includes(e):!0}validateToolFilters(e){let n=Array.from(e).filter(r=>!this.isToolEnabled(r));if(n.length>0&&!this.warnedUnknownTools.has("__disabled_tools_info__")){this.warnedUnknownTools.add("__disabled_tools_info__");let r=n.sort();this.emitEphemeral("session.info",{infoType:"configuration",message:`Disabled tools: ${r.join(", ")}`})}if(this.availableTools)for(let r of this.availableTools)!e.has(r)&&!this.warnedUnknownTools.has(r)&&(this.warnedUnknownTools.add(r),this.emitEphemeral("session.info",{infoType:"configuration",message:`Unknown tool name in the tool allowlist: "${r}"`}));if(this.excludedTools)for(let r of this.excludedTools)!e.has(r)&&!this.warnedUnknownTools.has(r)&&(this.warnedUnknownTools.add(r),this.emitEphemeral("session.info",{infoType:"configuration",message:`Unknown tool name in the tool denylist: "${r}"`}))}async buildCustomAgentTools(e,n,r,l,a,o,s){let I=async u=>await GIe({location:a,version:YQe(),currentWorkingDirectory:this.workingDir,parts:{},capabilities:{...o,customAgents:!1},tools:u,organizationCustomInstructions:this.organizationCustomInstructions,toolConfigOverrides:s}),d=(this.selectedCustomAgent?[this.selectedCustomAgent]:e).filter(u=>u.infer!==!1);return await Promise.all(d.map(async u=>{let p;if(u.mcpServers&&Object.keys(u.mcpServers).length>0){let b=await this.mcpHostCache.getOrCreateHost(u.name,u.mcpServers);b&&(p=new I1e(b,n,s.permissions))}return Hjn(I,v8n,u,this.workingDir,l,r,p)}))}filterToolsForSelectedAgent(e){return this.selectedCustomAgent?a1e(e,this.selectedCustomAgent,"top-level"):e}async invokeCallbacks(e){if(EIe(e))try{await this.callback.progress(e)}catch(n){Qe.error(`Error in callback: ${gt(n)}`)}}async getModelList(){if(this.provider)return[];if(!this.authInfo)return Promise.reject(new Error("Session was not created with authentication info or custom provider"));let e=await ePe(this.authInfo,this.copilotUrl||mD(),this.integrationId,this.sessionId,Qe);return e.copilotUrl&&(this.copilotUrl=e.copilotUrl),e.models}async getClient(){if(!this.authInfo&&!this.provider)throw new Error("Session was not created with authentication info or custom provider");let e,n;if(!this.provider){if(!this.authInfo)throw new Error("Session was not created with authentication info");e=await EG(this.authInfo),n=this.copilotUrl,!n&&e&&this.authInfo.type!=="hmac"&&(n=await fqn(this.authInfo.host,e||""))}let r=!!this.provider,l=r?[]:await this.getModelList(),a=await BL(this._selectedModel,this,l,Qe,r);if(!a)throw new Error("No model available. Check policy enablement under GitHub Settings > Copilot");let o=r?`capi:${a}`:await CFt(a),I=new dD().setProblemStatement("").setAgentModel(o).setGithubRepoName("copilot-sdk-session").setGithubRepoCommit("copilot-sdk-commit").setGithubRepoReadWrite(!1).setCopilotIntegrationId(this.integrationId).setCopilotUrl(n).setCopilotHmacKey(this.authInfo?.type==="hmac"?this.authInfo.hmac:void 0).setGithubToken(e).setCopilotToken(e).setTrajectoryOutputFile(this.trajectoryFile).setEventsLogDirectory(this.eventsLogDirectory).build();vst();let c=await WHt(I);this.largeOutputConfig&&(c.tools={...c.tools,largeOutput:this.largeOutputConfig});let d=c.service?.agent?.model,u=sY(d),p=SL(u.agent,u.model);return{client:OO(c,Qe,u.agent,{...p.clientOptions,...u.clientOptions,model:u.model},this.provider),settings:c}}async getContextSummary(){let e=await this.getChatMessages();if(e.length===0)return"";let{client:n}=await this.getClient(),r=Q8n(),l=2e4,a={role:"user",content:F8n()},o=new S6(a,Qe);try{let s="";for await(let I of n.getCompletionWithTools(r,[...e,a],[],{failIfInitialInputsTooLong:!1,processors:{preRequest:[o],onRequestError:[o]}}))I.kind==="message"&&I.message.role==="assistant"&&(s=typeof I.message.content=="string"?I.message.content:"");return s.length>l?s.slice(0,l):s}catch(s){return Qe.error(`Failed to summarize context: ${gt(s)}`),""}}async runAgenticLoop(e,n=[]){if(!this.authInfo&&!this.provider)throw new Error("Session was not created with authentication info or custom provider");this.compactionProcessor.clearCompletedCompaction();let r=new Map,l=new Map,a=[],o=!1;try{let I=(await qO(this.hooks?.userPromptSubmitted,{timestamp:Date.now(),cwd:this.workingDir,prompt:e},Qe))?.modifiedPrompt??e,c=await this.buildSettingsAndTools(I);if(!c)throw new Error("No model available. Check policy enablement under GitHub Settings > Copilot");let{settings:d,builtInTools:u,mcpTools:p,config:b,toolConfig:G}=c,A=d.service?.agent?.model,N=sY(A),E=OO(d,Qe,N.agent,{...b.clientOptions,...N.clientOptions,model:N.model},this.provider),R=[];if(this.externalToolDefinitions?.length){let me=this.externalToolDispatcher;if(!me)Qe.warning("External tool definitions provided without a dispatcher; ignoring");else for(let ht of this.externalToolDefinitions){if(!Rqn(ht.parameters)){Qe.warning(`External tool "${ht.name}" has invalid parameters schema (expected type object), ignoring tool`);continue}R.push({name:ht.name,description:ht.description,input_schema:ht.parameters??{type:"object",properties:{}},callback:async(zt,Oe)=>{if(!Oe?.toolCallId)throw new Error("External tool invocation missing toolCallId");return await me({sessionId:this.sessionId,toolCallId:Oe.toolCallId,toolName:ht.name,arguments:zt,abortSignal:Oe.abortSignal})}})}}let Y=new Set([...u,...p,...R].map(me=>me.name));this.validateToolFilters(Y);let C=[...u,...p,...R].filter(me=>this.isToolEnabled(me.name)),J=await R1(this.workingDir),_={...b.supports,reasoning:!0},U,D={progress:async me=>{if(me.kind==="message"&&me.turn===0){if(!me.callId)throw new Error("message on turn 0 event missing callId");U=me.callId}if(await this.invokeCallbacks(me),me.kind==="custom_agent_session_boundary"){let ht=me.agentId;if(ht)if(me.sessionBoundaryType==="start"){let zt=this.customAgents?.find(lt=>lt.name===me.agentName),Oe=zt?.displayName||me.agentDisplayName||me.agentName,Rt=zt?.description||me.agentDescription||"";this.activeCustomAgents.set(ht,{name:me.agentName,displayName:Oe}),this.emit("custom_agent.started",{toolCallId:ht,agentName:me.agentName,agentDisplayName:Oe,agentDescription:Rt})}else{let zt=this.activeCustomAgents.get(ht);zt&&this.emit("custom_agent.completed",{toolCallId:ht,agentName:zt.name}),this.activeCustomAgents.delete(ht)}return}if(EIe(me)){if(!U)throw new Error("Custom agent event received without parentToolCallId");switch(me.kind){case"message":if(Bw(me)){let{messageId:ht,reasoningId:zt,reasoningContent:Oe}=Se.endCurrentStreamingMessage(),Rt=Joe(me)?me.message.tool_calls.map(we=>({toolCallId:we.id,name:ZV(we),arguments:E4e(we,vL)})):[],lt=ht??Ni(),Lt=typeof me.message.reasoning_text=="string"?me.message.reasoning_text:void 0,qt=typeof me.message.reasoning_opaque=="string"?me.message.reasoning_opaque:null,{reasoningId:Sr,reasoningContent:Wn}=tPe({streamingReasoningId:zt,streamingReasoningContent:Oe,messageReasoningId:qt,messageReasoningText:Lt});this.emit("assistant.message",{parentToolCallId:U,messageId:lt,content:typeof me.message.content=="string"?me.message.content:"",toolRequests:Rt}),Sr&&Wn&&this.emit("assistant.reasoning",{reasoningId:Sr,content:Wn});for(let we of Rt)this.emit("tool.execution_start",{parentToolCallId:U,toolCallId:we.toolCallId,toolName:we.name,arguments:we.arguments})}break;case"tool_execution":this.emit("tool.execution_complete",{parentToolCallId:U,toolCallId:me.toolCallId,success:me.toolResult.resultType==="success",result:me.toolResult.resultType==="success"?{content:me.toolResult.textResultForLlm||me.toolResult.sessionLog||""}:void 0,error:me.toolResult.resultType!=="success"?{message:(me.toolResult.resultType==="failure"?me.toolResult.error:void 0)||me.toolResult.textResultForLlm||me.toolResult.sessionLog||"Tool execution failed",code:me.toolResult.resultType}:void 0,toolTelemetry:me.toolResult.toolTelemetry});break;case"model_call_failure":case"model_call_success":case"image_processing":case"images_removed":case"response":case"history_truncated":case"compaction_started":case"compaction_completed":case"turn_started":case"turn_ended":case"turn_failed":case"turn_retry":break;default:sm(me,`Unknown event kind: ${JSON.stringify(me)}`)}}},partialResult:async()=>{},commentReply:async()=>{},result:async()=>{},error:async()=>{}},B={client:E,settings:d,logger:Qe,exec:new jh(Qe),customAgents:this.customAgents||[],organizationCustomInstructions:this.organizationCustomInstructions,callback:D},M=C;if(this.customAgents&&this.customAgents.length>0&&!Sk(d)){let me=await this.buildCustomAgentTools(this.customAgents,d,C,B,J.found?J.gitRoot:"",_,G);M=[...C,...me]}a=this.filterToolsForSelectedAgent(M),this.onToolsUpdate&&this.onToolsUpdate(a);let j=await GIe({location:J.found?J.gitRoot:"",version:YQe(),currentWorkingDirectory:this.workingDir,parts:b.cli?.systemMessage||{},capabilities:_,tools:a,organizationCustomInstructions:this.organizationCustomInstructions,skipCustomInstructions:this.skipCustomInstructions,systemMessage:this.systemMessageConfig,toolConfigOverrides:G,workspaceContext:this.workspaceContext});this.currentSystemMessage=j;let oe=Yqn(this.currentTools??[],a);this.currentTools=a,this.currentToolMetadata=RHt(a);let Ze=n?.some(me=>me.type==="file"&&e1(me.path))??!1,O=await this.selectedCustomAgent?.prompt(),z=Y8n({customAgentPrompt:O,problemStatement:I,capabilities:_,hasImages:Ze,handoffContext:this.handoffContext,removedTools:oe});this.emit("user.message",{content:I,transformedContent:z,attachments:n});let be=await this.getChatMessages(),ie=be.findLastIndex(me=>me.role==="user"),ye=be[ie];this.handoffContext=void 0;let he=be.map((me,ht)=>ht===ie?ye:me);await qO(this.hooks?.sessionStart,{timestamp:Date.now(),cwd:this.workingDir,source:"new",initialPrompt:e},Qe);let Se=new Lze(this,()=>{},!1,Qe),Ee=new Sze(me=>{this.emitEphemeral("assistant.intent",{intent:me})}),pe=new S6(ye,Qe),Ie=F9e(Qe,d,M.find(me=>me.name==="github-mcp-server-get_file_contents")),Ge=E.getCompletionWithTools(j,he,a,{failIfInitialInputsTooLong:!1,processors:{preRequest:[this.compactionProcessor,pe,this.immediatePromptProcessor,this.premiumRequestProcessor,Ie],postToolExecution:[Ie],onRequestError:[Ie,pe],onStreamingChunk:[Se,Ee]},executeToolsInParallel:this.executeToolsInParallel??!0,abortSignal:this.abortController?.signal,stream:this.enableStreaming});for await(let me of Ge){if(this.abortController?.signal.aborted){this.emit("abort",{reason:"user initiated"}),this.emitEphemeral("session.info",{infoType:"cancellation",message:"Operation cancelled by user"});break}switch(await this.invokeCallbacks(me),me.kind){case"message":{if(Bw(me)){let{messageId:ht,reasoningId:zt,reasoningContent:Oe}=Se.endCurrentStreamingMessage(),Rt=ht??Ni(),lt=Joe(me)?await Promise.all(me.message.tool_calls.map(async we=>{let vt=ZV(we),mn=E4e(we,vL);r.set(we.id,vt),l.set(we.id,mn);let en=await qO(this.hooks?.preToolUse,{timestamp:Date.now(),cwd:this.workingDir,toolName:vt,toolArgs:mn},Qe);return{toolCallId:we.id,name:vt,arguments:en?.modifiedArgs??mn}})):[],Lt=typeof me.message.reasoning_text=="string"?me.message.reasoning_text:void 0,qt=typeof me.message.reasoning_opaque=="string"?me.message.reasoning_opaque:null,{reasoningId:Sr,reasoningContent:Wn}=tPe({streamingReasoningId:zt,streamingReasoningContent:Oe,messageReasoningId:qt,messageReasoningText:Lt});this.emit("assistant.message",{parentToolCallId:void 0,messageId:Rt,content:typeof me.message.content=="string"?me.message.content:"",toolRequests:lt}),Sr&&Wn&&this.emit("assistant.reasoning",{reasoningId:Sr,content:Wn});for(let we of lt)this.emit("tool.execution_start",{toolCallId:we.toolCallId,toolName:we.name,arguments:we.arguments})}else(me.message.role==="system"||me.message.role==="developer")&&this.emit("system.message",{role:me.message.role,content:typeof me.message.content=="string"?me.message.content:JSON.stringify(me.message.content),name:"name"in me.message?me.message.name:void 0});break}case"model_call_failure":{let ht=new Error(me.modelCall?.error||"Model call failed");if(await qO(this.hooks?.errorOccurred,{timestamp:Date.now(),cwd:this.workingDir,error:ht,errorContext:"model_call",recoverable:!0},Qe),cHt(me.modelCall?.error||""))return;let Oe=xql(me.modelCall?.error);me.modelCall.request_id&&(Oe+=` (Request ID: ${me.modelCall.request_id})`),this.emit("session.error",{errorType:"model_call",message:`Model call failed: ${Oe}`,stack:ht.stack});break}case"tool_execution":{let ht=r.get(me.toolCallId)||"unknown",zt=l.get(me.toolCallId)||{},Rt=(await qO(this.hooks?.postToolUse,{timestamp:Date.now(),cwd:this.workingDir,toolName:ht,toolArgs:zt,toolResult:me.toolResult},Qe))?.modifiedResult??me.toolResult;Rt.resultType==="rejected"&&(o=!0);let lt=(Rt.resultType==="failure"?Rt.error:void 0)||Rt.textResultForLlm||Rt.sessionLog||"";if(ht===MK&&Rt.resultType==="success"&&typeof zt=="object"&&zt!==null&&"todos"in zt&&this.setLastTodoContent(zt.todos),this.workspaceEnabled&&(ht==="edit"||ht==="create")&&Rt.resultType==="success"&&typeof zt=="object"&&zt!==null&&"path"in zt){let Lt=zt.path;(Lt.endsWith("/plan.md")||Lt.endsWith("\\plan.md"))&&(this.lastPlanUpdateTurn=this.currentTurn,this.emitWorkspaceFileTelemetry(Lt,ht==="create"?"create":"update"))}if(this.workspaceEnabled&&ht==="view"&&Rt.resultType==="success"&&typeof zt=="object"&&zt!==null&&"path"in zt){let Lt=zt.path;this.emitWorkspaceFileReadTelemetry(Lt)}this.emit("tool.execution_complete",{parentToolCallId:void 0,toolCallId:me.toolCallId,success:Rt.resultType==="success",result:Rt.resultType==="success"?{content:lt}:void 0,error:Rt.resultType!=="success"?{message:lt,code:Rt.resultType}:void 0,toolTelemetry:Rt.toolTelemetry});break}case"turn_started":{this.currentTurn=me.turn,this.emit("assistant.turn_start",{turnId:`${me.turn}`});break}case"turn_ended":{this.emit("assistant.turn_end",{turnId:`${me.turn}`});break}case"model_call_success":{let ht=me.modelCall.model||await this.getSelectedModel(),zt=me.modelCallDurationMs||0,Oe=me.responseUsage,Rt=await this.getModelList(),lt=ht?DK(ht,Rt):1;this.emitEphemeral("assistant.usage",{model:ht||"unknown",inputTokens:Oe?.prompt_tokens||0,outputTokens:Oe?.completion_tokens||0,cacheReadTokens:Oe?.prompt_tokens_details?.cached_tokens||0,cacheWriteTokens:0,cost:lt,duration:zt,initiator:me.modelCall?.initiator,apiCallId:me.modelCall?.api_id,providerCallId:me.modelCall?.request_id,quotaSnapshots:me.quotaSnapshots});break}case"history_truncated":{this.emit("session.truncation",{...me.truncateResult,performedBy:me.performedBy});break}case"compaction_started":{this.emit("session.compaction_start",{});break}case"compaction_completed":{me.success&&me.compactionResult?this.emit("session.compaction_complete",{success:!0,preCompactionTokens:me.compactionResult.preCompactionTokens,postCompactionTokens:me.compactionResult.postCompactionTokens,preCompactionMessagesLength:me.compactionResult.preCompactionMessagesLength,messagesRemoved:me.compactionResult.messagesRemoved,tokensRemoved:me.compactionResult.tokensRemoved,summaryContent:me.compactionResult.summaryContent,compactionTokensUsed:me.compactionResult.compactionTokensUsed}):this.emit("session.compaction_complete",{success:!1,error:me.error});break}case"response":case"images_removed":case"image_processing":case"turn_failed":case"turn_retry":Qe.debug(`Ignoring event of kind: ${me.kind}`);break;default:sm(me,"Unhandled event type")}}}catch(s){if(await qO(this.hooks?.sessionEnd,{timestamp:Date.now(),cwd:this.workingDir,reason:"error",error:s instanceof Error?s:new Error(String(s))},Qe),s&&typeof s=="object"&&"status"in s&&(s.status===401||s.status===403)){if("message"in s&&typeof s.message=="string"){let c=cHt(s.message);c&&this.emit("session.error",{errorType:"authentication",message:c.message})}this.emit("session.error",{errorType:"authorization",message:"Authorization error, you may need to run /login"})}s&&typeof s=="object"&&"status"in s&&s.status===402&&this.emit("session.error",{errorType:"quota",message:"Quota exceeded. Upgrade to increase your limit: https://github.com/features/copilot/plans"});let I=`Execution failed: ${gt(s)}`;this.emit("session.error",{errorType:"query",message:I,stack:s instanceof Error?s.stack:void 0})}finally{await qO(this.hooks?.sessionEnd,{timestamp:Date.now(),cwd:this.workingDir,reason:"complete"},Qe),o&&this.clearPendingMessages();try{for(let s of a)s.shutdown&&await s.shutdown()}catch(s){Qe.error(`Error during session shutdown: ${gt(s)}`)}}}},DL=class extends nPe{repository;remoteSessionIds;pullRequestNumber;constructor(e){super(e),this.repository=e.repository,this.remoteSessionIds=e.remoteSessionIds,this.pullRequestNumber=e.pullRequestNumber}async send(e){let{prompt:n}=e;if(!this.pullRequestNumber)throw new Error("Cannot send message: Pull request number is not available");if(!this.authInfo)throw new Error("Cannot send message: Authentication info is not available");let{owner:r,name:l}=this.repository,a=this.pullRequestNumber,o=`@copilot ${n}`;Qe.debug(`Posting user message to PR ${r}/${l}#${a}`);let s=GW(this.authInfo),I=new URL(`/repos/${r}/${l}/issues/${a}/comments`,zy(s)),c=await cY(I,this.authInfo,Qe,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({body:o})});if(!c.ok){let d=await c.text();throw new Error(`Failed to post comment to PR ${r}/${l}#${a}: ${c.status} ${c.statusText}
2280
+ </reminder>`:null}markPlanUpdated(){this.lastPlanUpdateTurn=this.currentTurn}emitWorkspaceFileTelemetry(e,n){let r=this.getWorkspacePath();if(!r)return;if(e.endsWith("/plan.md")||e.endsWith("\\plan.md")){this.invokeCallbacks(_Qt(this.sessionId,n,0));return}let l=`${r}/files/`,a=`${r}\\files\\`;if(e.startsWith(l)||e.startsWith(a)){let o=e.startsWith(l)?e.slice(l.length):e.slice(a.length);this.invokeCallbacks(MQt(this.sessionId,o,n,0))}}emitWorkspaceFileReadTelemetry(e){let n=this.getWorkspacePath();if(!n)return;if(e.endsWith("/plan.md")||e.endsWith("\\plan.md")){this.invokeCallbacks(UQt(this.sessionId,0));return}let r=`${n}/checkpoints/`,l=`${n}\\checkpoints\\`;if(e.startsWith(r)||e.startsWith(l)){let I=(e.split(/[/\\]/).pop()||"").match(/^(\d+)-/),c=I?parseInt(I[1],10):0;this.invokeCallbacks(OQt(this.sessionId,c,0));return}let a=`${n}/files/`,o=`${n}\\files\\`;if(e.startsWith(a)||e.startsWith(o)){let s=e.startsWith(a)?e.slice(a.length):e.slice(o.length);this.invokeCallbacks(DQt(this.sessionId,s,0))}}async ensureWorkspace(e,n){if(!this.workspaceEnabled)throw new Error("Workspace features are not enabled for this session");let l=await B0().getOrCreateWorkspace(this.sessionId,e,n);return this.sessionWorkspace=l,l}async persistCompactionCheckpoint(e){if(!this.sessionWorkspace){Qe.debug("No workspace loaded, skipping checkpoint persistence");return}try{let n=B0(),r=JQt(e,this.sessionId),l=BQt(e),a=await n.addSummary(this.sessionId,l,r);Qe.info(`Persisted checkpoint #${a}: ${r}`);let o=await n.loadWorkspace(this.sessionId);o&&(this.sessionWorkspace=o,await this.updateWorkspaceContext())}catch(n){let r=n instanceof Error?n.message:String(n);Qe.error(`Failed to persist checkpoint: ${r}`)}}async send(e){if(e.mode==="immediate"&&this.isProcessing){this.immediatePromptProcessor.addMessage(e),this.emitEphemeral("pending_messages.modified",{});return}if(this.messageQueue.push(e),this.emitEphemeral("pending_messages.modified",{}),!this.isProcessing){for(this.isProcessing=!0,await this.initializeMcpHost();this.messageQueue.length>0;){let n=this.messageQueue.shift();this.emitEphemeral("pending_messages.modified",{}),this.abortController=n.abortController||new AbortController,await this.runAgenticLoop(n.prompt,n.attachments);let r=this.immediatePromptProcessor.popMessage();r&&(this.emitEphemeral("pending_messages.modified",{}),this.messageQueue.unshift(r))}this.isProcessing=!1,this.emitEphemeral("session.idle",{})}}async abort(){this.abortController?.abort()}getPendingSteeringMessages(){return this.immediatePromptProcessor.getQueue().map(e=>e.prompt)}getPendingQueuedMessages(){return this.messageQueue.map(e=>e.prompt)}clearPendingMessages(){this.immediatePromptProcessor.clearQueue(),this.messageQueue.length=0,this.emitEphemeral("pending_messages.modified",{})}async compactHistory(){this.emit("session.compaction_start",{});let e=await this.getChatMessages();if(e.length<2)throw new Error("Nothing to compact.");if(!this.authInfo)throw new Error("Authentication required for compaction. Please log in first.");if(this.currentSystemMessage===void 0)throw new Error("Cannot compact: no active agent context. Send a message first.");let{client:n,settings:r}=await this.getClient(),l=sY(r.service?.agent?.model).model,a=Sf(e,l),o=e.length,I=W1e(e,this.workspaceEnabled).filter(A=>A.role!=="system"),c=await Oze(n,this.currentSystemMessage,I,this.currentTools??[],Qe);if(!c.content)throw new Error("Compaction failed: No response from model");let d=this.workspaceEnabled?await this.getPlanContentForCompaction():null,u=wIe(e,c.content,this.originalUserMessages,{isManualCompaction:!0,planContent:d??void 0,todoContent:this.lastTodoContent??void 0}),p=Sf(u,l),b=a-p,G=o-u.length;return this._chatMessages=u,this.emit("session.compaction_complete",{success:!0,preCompactionTokens:a,postCompactionTokens:p,preCompactionMessagesLength:o,messagesRemoved:G,tokensRemoved:b,summaryContent:c.content,compactionTokensUsed:{input:c.inputTokens,output:c.outputTokens,cachedInput:c.cachedInputTokens}}),Qe.info(`Compacted ${G} messages, saved ~${b} tokens`),{success:!0,tokensRemoved:b,messagesRemoved:G,summaryContent:c.content}}handleCompactionComplete(e){if(e.success&&e.summaryContent){let n={success:!0,preCompactionTokens:e.checkpointTokens,preCompactionMessagesLength:e.checkpointMessagesLength,summaryContent:e.summaryContent,compactionTokensUsed:e.compactionTokensUsed};this.emit("session.compaction_complete",n);let r={kind:"compaction_completed",turn:e.startTurn,performedBy:"CompactionProcessor",success:!0,compactionResult:{tokenLimit:0,preCompactionTokens:e.checkpointTokens,preCompactionMessagesLength:e.checkpointMessagesLength,summaryContent:e.summaryContent}};this.invokeCallbacks(r)}else{this.emit("session.compaction_complete",{success:!1,error:e.error});let n={kind:"compaction_completed",turn:e.startTurn,performedBy:"CompactionProcessor",success:!1,error:e.error};this.invokeCallbacks(n)}}async initializeMcpHost(){if(!this.mcpHost&&this.mcpServers&&Object.keys(this.mcpServers).length>0)try{this.mcpHost=new KO(Qe,{mcpServers:this.mcpServers},this.excludedTools),await this.mcpHost.startServers()}catch(e){Qe.error(`Failed to initialize MCP host: ${gt(e)}`)}}async initializeAndValidateTools(){try{let e=await this.buildSettingsAndTools();if(!e){Qe.debug("Could not initialize tools: buildSettingsAndTools returned undefined");return}let{settings:n,builtInTools:r,mcpTools:l,config:a,toolConfig:o}=e,s=[];for(let E of this.externalToolDefinitions??[])Rqn(E.parameters)&&s.push({name:E.name,description:E.description,input_schema:E.parameters??{type:"object",properties:{}}});let I=new Set([...r.map(E=>E.name),...l.map(E=>E.name),...s.map(E=>E.name)]);this.validateToolFilters(I);let c=r.filter(E=>this.isToolEnabled(E.name)),d=l.filter(E=>this.isToolEnabled(E.name)),u=s.filter(E=>this.isToolEnabled(E.name)),p=await R1(this.workingDir),b={...a.supports,reasoning:!0},G,A=[...RHt(c),...RHt(d),...u];if(this.customAgents&&this.customAgents.length>0&&!Sk(n)){let Y=(this.selectedCustomAgent?[this.selectedCustomAgent]:this.customAgents).filter(J=>J.infer!==!1).map(Xjn),C=[...A,...Y];G=this.filterToolsForSelectedAgent(C)}else G=A,G=this.filterToolsForSelectedAgent(G);let N=await GIe({location:p.found?p.gitRoot:"",version:YQe(),currentWorkingDirectory:this.workingDir,parts:a.cli?.systemMessage||{},capabilities:b,tools:G,organizationCustomInstructions:this.organizationCustomInstructions,skipCustomInstructions:this.skipCustomInstructions,systemMessage:this.systemMessageConfig,toolConfigOverrides:o,workspaceContext:this.workspaceContext});this.currentSystemMessage=N,this.currentToolMetadata=G}catch(e){Qe.debug(`Failed to initialize tools for validation: ${gt(e)}`)}}async buildSettingsAndTools(e){if(!this.authInfo&&!this.provider)return;await this.initializeMcpHost();let n,r;if(!this.provider){if(!this.authInfo)return;n=await EG(this.authInfo),r=this.copilotUrl,!r&&n&&this.authInfo.type!=="hmac"&&(r=await fqn(this.authInfo.host,n||""))}let l=!!this.provider,a=l?[]:await this.getModelList(),o=await BL(this._selectedModel,this,a,Qe,l);if(!o)throw new Error("No model available. Check policy enablement under GitHub Settings > Copilot");let s=l?`capi:${o}`:await CFt(o),c=new dD().setProblemStatement(e??"").setAgentModel(s).setGithubRepoName("copilot-sdk-session").setGithubRepoCommit("copilot-sdk-commit").setGithubRepoReadWrite(!1).setCopilotIntegrationId(this.integrationId).setCopilotUrl(r).setCopilotHmacKey(this.authInfo?.type==="hmac"?this.authInfo.hmac:void 0).setGithubToken(n).setCopilotToken(n).setTrajectoryOutputFile(this.trajectoryFile).setEventsLogDirectory(this.eventsLogDirectory).setFeatureFlags(this.featureFlags).setClientName(this.clientName).build();vst();let d=await WHt(c),u=d.service?.agent?.model,p=sY(u),b=SL(p.agent,p.model),G=Lql(a),A={location:this.workingDir,timeout:3e4,availableModels:G,toolPartialResultCallback:(Y,C)=>{this.emitEphemeral("tool.execution_partial_result",{toolCallId:Y,partialOutput:C})},createSubAgentCallback:Y=>({progress:async C=>{if(await this.invokeCallbacks(C),EIe(C))switch(C.kind){case"message":if(Bw(C)){let J=Joe(C)?C.message.tool_calls.map(_=>({toolCallId:_.id,name:ZV(_),arguments:E4e(_,vL)})):[];this.emit("assistant.message",{parentToolCallId:Y,messageId:Ni(),content:typeof C.message.content=="string"?C.message.content:"",toolRequests:J});for(let _ of J)this.emit("tool.execution_start",{parentToolCallId:Y,toolCallId:_.toolCallId,toolName:_.name,arguments:_.arguments})}break;case"tool_execution":this.emit("tool.execution_complete",{parentToolCallId:Y,toolCallId:C.toolCallId,success:C.toolResult.resultType==="success",result:C.toolResult.resultType==="success"?{content:C.toolResult.textResultForLlm||C.toolResult.sessionLog||""}:void 0,error:C.toolResult.resultType!=="success"?{message:(C.toolResult.resultType==="failure"?C.toolResult.error:void 0)||C.toolResult.textResultForLlm||C.toolResult.sessionLog||"Tool execution failed",code:C.toolResult.resultType}:void 0});break;default:break}},partialResult:async()=>{},commentReply:async()=>{},result:async()=>{},error:async()=>{}}),permissions:this.requestPermission?{requestRequired:!0,request:this.requestPermission}:{requestRequired:!1},shellConfig:this.shellConfig??(process.platform==="win32"?fA.powerShell:fA.bash).withScriptSafetyAssessor(async function(Y){return{result:"completed",commands:[{identifier:Y,readOnly:!1}],possiblePaths:[],possibleUrls:[],hasWriteFileRedirection:!1,canOfferSessionApproval:!1}}),skillDirectories:this.skillDirectories,disabledSkills:this.disabledSkills,customAgents:this.customAgents,...b.toolConfigOverrides},N=[];if(this.mcpHost){try{N=await this.mcpHost.getTools(d,Qe,A.permissions)}catch(Y){Qe.error(`Failed to get MCP tools: ${gt(Y)}`)}EEt(b.supports,N)}A.mcpTools=N,A.getMcpServerProviderForAgent=this.mcpHost?async Y=>{let C=await this.mcpHostCache.getOrCreateHost(Y,{});if(C)return new I1e(C,d,A.permissions)}:void 0;let R=await(b.cli?.toolInit??Zd.cli.toolInit)(A,d,Qe,new Uze,this.callback,void 0);return{settings:d,builtInTools:R,mcpTools:N,config:b,toolConfig:A}}isToolEnabled(e){return this.availableTools?this.availableTools.includes(e):this.excludedTools?!this.excludedTools.includes(e):!0}validateToolFilters(e){let n=Array.from(e).filter(r=>!this.isToolEnabled(r));if(n.length>0&&!this.warnedUnknownTools.has("__disabled_tools_info__")){this.warnedUnknownTools.add("__disabled_tools_info__");let r=n.sort();this.emitEphemeral("session.info",{infoType:"configuration",message:`Disabled tools: ${r.join(", ")}`})}if(this.availableTools)for(let r of this.availableTools)!e.has(r)&&!this.warnedUnknownTools.has(r)&&(this.warnedUnknownTools.add(r),this.emitEphemeral("session.info",{infoType:"configuration",message:`Unknown tool name in the tool allowlist: "${r}"`}));if(this.excludedTools)for(let r of this.excludedTools)!e.has(r)&&!this.warnedUnknownTools.has(r)&&(this.warnedUnknownTools.add(r),this.emitEphemeral("session.info",{infoType:"configuration",message:`Unknown tool name in the tool denylist: "${r}"`}))}async buildCustomAgentTools(e,n,r,l,a,o,s){let I=async u=>await GIe({location:a,version:YQe(),currentWorkingDirectory:this.workingDir,parts:{},capabilities:{...o,customAgents:!1},tools:u,organizationCustomInstructions:this.organizationCustomInstructions,toolConfigOverrides:s}),d=(this.selectedCustomAgent?[this.selectedCustomAgent]:e).filter(u=>u.infer!==!1);return await Promise.all(d.map(async u=>{let p;if(u.mcpServers&&Object.keys(u.mcpServers).length>0){let b=await this.mcpHostCache.getOrCreateHost(u.name,u.mcpServers);b&&(p=new I1e(b,n,s.permissions))}return Hjn(I,v8n,u,this.workingDir,l,r,p)}))}filterToolsForSelectedAgent(e){return this.selectedCustomAgent?a1e(e,this.selectedCustomAgent,"top-level"):e}async invokeCallbacks(e){if(EIe(e))try{await this.callback.progress(e)}catch(n){Qe.error(`Error in callback: ${gt(n)}`)}}async getModelList(){if(this.provider)return[];if(!this.authInfo)return Promise.reject(new Error("Session was not created with authentication info or custom provider"));let e=await ePe(this.authInfo,this.copilotUrl||mD(),this.integrationId,this.sessionId,Qe);return e.copilotUrl&&(this.copilotUrl=e.copilotUrl),e.models}async getClient(){if(!this.authInfo&&!this.provider)throw new Error("Session was not created with authentication info or custom provider");let e,n;if(!this.provider){if(!this.authInfo)throw new Error("Session was not created with authentication info");e=await EG(this.authInfo),n=this.copilotUrl,!n&&e&&this.authInfo.type!=="hmac"&&(n=await fqn(this.authInfo.host,e||""))}let r=!!this.provider,l=r?[]:await this.getModelList(),a=await BL(this._selectedModel,this,l,Qe,r);if(!a)throw new Error("No model available. Check policy enablement under GitHub Settings > Copilot");let o=r?`capi:${a}`:await CFt(a),I=new dD().setProblemStatement("").setAgentModel(o).setGithubRepoName("copilot-sdk-session").setGithubRepoCommit("copilot-sdk-commit").setGithubRepoReadWrite(!1).setCopilotIntegrationId(this.integrationId).setCopilotUrl(n).setCopilotHmacKey(this.authInfo?.type==="hmac"?this.authInfo.hmac:void 0).setGithubToken(e).setCopilotToken(e).setTrajectoryOutputFile(this.trajectoryFile).setEventsLogDirectory(this.eventsLogDirectory).build();vst();let c=await WHt(I);this.largeOutputConfig&&(c.tools={...c.tools,largeOutput:this.largeOutputConfig});let d=c.service?.agent?.model,u=sY(d),p=SL(u.agent,u.model);return{client:OO(c,Qe,u.agent,{...p.clientOptions,...u.clientOptions,model:u.model},this.provider),settings:c}}async getContextSummary(){let e=await this.getChatMessages();if(e.length===0)return"";let{client:n}=await this.getClient(),r=Q8n(),l=2e4,a={role:"user",content:F8n()},o=new S6(a,Qe);try{let s="";for await(let I of n.getCompletionWithTools(r,[...e,a],[],{failIfInitialInputsTooLong:!1,processors:{preRequest:[o],onRequestError:[o]}}))I.kind==="message"&&I.message.role==="assistant"&&(s=typeof I.message.content=="string"?I.message.content:"");return s.length>l?s.slice(0,l):s}catch(s){return Qe.error(`Failed to summarize context: ${gt(s)}`),""}}async runAgenticLoop(e,n=[]){if(!this.authInfo&&!this.provider)throw new Error("Session was not created with authentication info or custom provider");this.compactionProcessor.clearCompletedCompaction();let r=new Map,l=new Map,a=[],o=!1;try{let I=(await qO(this.hooks?.userPromptSubmitted,{timestamp:Date.now(),cwd:this.workingDir,prompt:e},Qe))?.modifiedPrompt??e,c=await this.buildSettingsAndTools(I);if(!c)throw new Error("No model available. Check policy enablement under GitHub Settings > Copilot");let{settings:d,builtInTools:u,mcpTools:p,config:b,toolConfig:G}=c,A=d.service?.agent?.model,N=sY(A),E=OO(d,Qe,N.agent,{...b.clientOptions,...N.clientOptions,model:N.model},this.provider),R=[];if(this.externalToolDefinitions?.length){let me=this.externalToolDispatcher;if(!me)Qe.warning("External tool definitions provided without a dispatcher; ignoring");else for(let ht of this.externalToolDefinitions){if(!Rqn(ht.parameters)){Qe.warning(`External tool "${ht.name}" has invalid parameters schema (expected type object), ignoring tool`);continue}R.push({name:ht.name,description:ht.description,input_schema:ht.parameters??{type:"object",properties:{}},callback:async(zt,Oe)=>{if(!Oe?.toolCallId)throw new Error("External tool invocation missing toolCallId");return await me({sessionId:this.sessionId,toolCallId:Oe.toolCallId,toolName:ht.name,arguments:zt,abortSignal:Oe.abortSignal})}})}}let Y=new Set([...u,...p,...R].map(me=>me.name));this.validateToolFilters(Y);let C=[...u,...p,...R].filter(me=>this.isToolEnabled(me.name)),J=await R1(this.workingDir),_={...b.supports,reasoning:!0},U,D={progress:async me=>{if(me.kind==="message"&&me.turn===0){if(!me.callId)throw new Error("message on turn 0 event missing callId");U=me.callId}if(await this.invokeCallbacks(me),me.kind==="custom_agent_session_boundary"){let ht=me.agentId;if(ht)if(me.sessionBoundaryType==="start"){let zt=this.customAgents?.find(lt=>lt.name===me.agentName),Oe=zt?.displayName||me.agentDisplayName||me.agentName,Rt=zt?.description||me.agentDescription||"";this.activeCustomAgents.set(ht,{name:me.agentName,displayName:Oe}),this.emit("custom_agent.started",{toolCallId:ht,agentName:me.agentName,agentDisplayName:Oe,agentDescription:Rt})}else{let zt=this.activeCustomAgents.get(ht);zt&&this.emit("custom_agent.completed",{toolCallId:ht,agentName:zt.name}),this.activeCustomAgents.delete(ht)}return}if(EIe(me)){if(!U)throw new Error("Custom agent event received without parentToolCallId");switch(me.kind){case"message":if(Bw(me)){let{messageId:ht,reasoningId:zt,reasoningContent:Oe}=Se.endCurrentStreamingMessage(),Rt=Joe(me)?me.message.tool_calls.map(we=>({toolCallId:we.id,name:ZV(we),arguments:E4e(we,vL)})):[],lt=ht??Ni(),Lt=typeof me.message.reasoning_text=="string"?me.message.reasoning_text:void 0,qt=typeof me.message.reasoning_opaque=="string"?me.message.reasoning_opaque:null,{reasoningId:Sr,reasoningContent:Wn}=tPe({streamingReasoningId:zt,streamingReasoningContent:Oe,messageReasoningId:qt,messageReasoningText:Lt});this.emit("assistant.message",{parentToolCallId:U,messageId:lt,content:typeof me.message.content=="string"?me.message.content:"",toolRequests:Rt}),Sr&&Wn&&this.emit("assistant.reasoning",{reasoningId:Sr,content:Wn});for(let we of Rt)this.emit("tool.execution_start",{parentToolCallId:U,toolCallId:we.toolCallId,toolName:we.name,arguments:we.arguments})}break;case"tool_execution":this.emit("tool.execution_complete",{parentToolCallId:U,toolCallId:me.toolCallId,success:me.toolResult.resultType==="success",result:me.toolResult.resultType==="success"?{content:me.toolResult.textResultForLlm||me.toolResult.sessionLog||""}:void 0,error:me.toolResult.resultType!=="success"?{message:(me.toolResult.resultType==="failure"?me.toolResult.error:void 0)||me.toolResult.textResultForLlm||me.toolResult.sessionLog||"Tool execution failed",code:me.toolResult.resultType}:void 0,toolTelemetry:me.toolResult.toolTelemetry});break;case"model_call_failure":case"model_call_success":case"image_processing":case"images_removed":case"response":case"history_truncated":case"compaction_started":case"compaction_completed":case"turn_started":case"turn_ended":case"turn_failed":case"turn_retry":break;default:sm(me,`Unknown event kind: ${JSON.stringify(me)}`)}}},partialResult:async()=>{},commentReply:async()=>{},result:async()=>{},error:async()=>{}},B={client:E,settings:d,logger:Qe,exec:new jh(Qe),customAgents:this.customAgents||[],organizationCustomInstructions:this.organizationCustomInstructions,callback:D},M=C;if(this.customAgents&&this.customAgents.length>0&&!Sk(d)){let me=await this.buildCustomAgentTools(this.customAgents,d,C,B,J.found?J.gitRoot:"",_,G);M=[...C,...me]}a=this.filterToolsForSelectedAgent(M),this.onToolsUpdate&&this.onToolsUpdate(a);let j=await GIe({location:J.found?J.gitRoot:"",version:YQe(),currentWorkingDirectory:this.workingDir,parts:b.cli?.systemMessage||{},capabilities:_,tools:a,organizationCustomInstructions:this.organizationCustomInstructions,skipCustomInstructions:this.skipCustomInstructions,systemMessage:this.systemMessageConfig,toolConfigOverrides:G,workspaceContext:this.workspaceContext});this.currentSystemMessage=j;let oe=Yqn(this.currentTools??[],a);this.currentTools=a,this.currentToolMetadata=RHt(a);let Ze=n?.some(me=>me.type==="file"&&e1(me.path))??!1,O=await this.selectedCustomAgent?.prompt(),z=Y8n({customAgentPrompt:O,problemStatement:I,capabilities:_,hasImages:Ze,handoffContext:this.handoffContext,removedTools:oe,planReminder:this.getPlanReminderMessage()??void 0});this.emit("user.message",{content:I,transformedContent:z,attachments:n});let be=await this.getChatMessages(),ie=be.findLastIndex(me=>me.role==="user"),ye=be[ie];this.handoffContext=void 0;let he=be.map((me,ht)=>ht===ie?ye:me);await qO(this.hooks?.sessionStart,{timestamp:Date.now(),cwd:this.workingDir,source:"new",initialPrompt:e},Qe);let Se=new Lze(this,()=>{},!1,Qe),Ee=new Sze(me=>{this.emitEphemeral("assistant.intent",{intent:me})}),pe=new S6(ye,Qe),Ie=F9e(Qe,d,M.find(me=>me.name==="github-mcp-server-get_file_contents")),Ge=E.getCompletionWithTools(j,he,a,{failIfInitialInputsTooLong:!1,processors:{preRequest:[this.compactionProcessor,pe,this.immediatePromptProcessor,this.premiumRequestProcessor,Ie],postToolExecution:[Ie],onRequestError:[Ie,pe],onStreamingChunk:[Se,Ee]},executeToolsInParallel:this.executeToolsInParallel??!0,abortSignal:this.abortController?.signal,stream:this.enableStreaming});for await(let me of Ge){if(this.abortController?.signal.aborted){this.emit("abort",{reason:"user initiated"}),this.emitEphemeral("session.info",{infoType:"cancellation",message:"Operation cancelled by user"});break}switch(await this.invokeCallbacks(me),me.kind){case"message":{if(Bw(me)){let{messageId:ht,reasoningId:zt,reasoningContent:Oe}=Se.endCurrentStreamingMessage(),Rt=ht??Ni(),lt=Joe(me)?await Promise.all(me.message.tool_calls.map(async we=>{let vt=ZV(we),mn=E4e(we,vL);r.set(we.id,vt),l.set(we.id,mn);let en=await qO(this.hooks?.preToolUse,{timestamp:Date.now(),cwd:this.workingDir,toolName:vt,toolArgs:mn},Qe);return{toolCallId:we.id,name:vt,arguments:en?.modifiedArgs??mn}})):[],Lt=typeof me.message.reasoning_text=="string"?me.message.reasoning_text:void 0,qt=typeof me.message.reasoning_opaque=="string"?me.message.reasoning_opaque:null,{reasoningId:Sr,reasoningContent:Wn}=tPe({streamingReasoningId:zt,streamingReasoningContent:Oe,messageReasoningId:qt,messageReasoningText:Lt});this.emit("assistant.message",{parentToolCallId:void 0,messageId:Rt,content:typeof me.message.content=="string"?me.message.content:"",toolRequests:lt}),Sr&&Wn&&this.emit("assistant.reasoning",{reasoningId:Sr,content:Wn});for(let we of lt)this.emit("tool.execution_start",{toolCallId:we.toolCallId,toolName:we.name,arguments:we.arguments})}else(me.message.role==="system"||me.message.role==="developer")&&this.emit("system.message",{role:me.message.role,content:typeof me.message.content=="string"?me.message.content:JSON.stringify(me.message.content),name:"name"in me.message?me.message.name:void 0});break}case"model_call_failure":{let ht=new Error(me.modelCall?.error||"Model call failed");if(await qO(this.hooks?.errorOccurred,{timestamp:Date.now(),cwd:this.workingDir,error:ht,errorContext:"model_call",recoverable:!0},Qe),cHt(me.modelCall?.error||""))return;let Oe=xql(me.modelCall?.error);me.modelCall.request_id&&(Oe+=` (Request ID: ${me.modelCall.request_id})`),this.emit("session.error",{errorType:"model_call",message:`Model call failed: ${Oe}`,stack:ht.stack});break}case"tool_execution":{let ht=r.get(me.toolCallId)||"unknown",zt=l.get(me.toolCallId)||{},Rt=(await qO(this.hooks?.postToolUse,{timestamp:Date.now(),cwd:this.workingDir,toolName:ht,toolArgs:zt,toolResult:me.toolResult},Qe))?.modifiedResult??me.toolResult;Rt.resultType==="rejected"&&(o=!0);let lt=(Rt.resultType==="failure"?Rt.error:void 0)||Rt.textResultForLlm||Rt.sessionLog||"";if(ht===MK&&Rt.resultType==="success"&&typeof zt=="object"&&zt!==null&&"todos"in zt&&this.setLastTodoContent(zt.todos),this.workspaceEnabled&&(ht==="edit"||ht==="create")&&Rt.resultType==="success"&&typeof zt=="object"&&zt!==null&&"path"in zt){let Lt=zt.path;(Lt.endsWith("/plan.md")||Lt.endsWith("\\plan.md"))&&(this.lastPlanUpdateTurn=this.currentTurn,this.emitWorkspaceFileTelemetry(Lt,ht==="create"?"create":"update"))}if(this.workspaceEnabled&&ht==="view"&&Rt.resultType==="success"&&typeof zt=="object"&&zt!==null&&"path"in zt){let Lt=zt.path;this.emitWorkspaceFileReadTelemetry(Lt)}this.emit("tool.execution_complete",{parentToolCallId:void 0,toolCallId:me.toolCallId,success:Rt.resultType==="success",result:Rt.resultType==="success"?{content:lt}:void 0,error:Rt.resultType!=="success"?{message:lt,code:Rt.resultType}:void 0,toolTelemetry:Rt.toolTelemetry});break}case"turn_started":{this.currentTurn=me.turn,this.emit("assistant.turn_start",{turnId:`${me.turn}`});break}case"turn_ended":{this.emit("assistant.turn_end",{turnId:`${me.turn}`});break}case"model_call_success":{let ht=me.modelCall.model||await this.getSelectedModel(),zt=me.modelCallDurationMs||0,Oe=me.responseUsage,Rt=await this.getModelList(),lt=ht?DK(ht,Rt):1;this.emitEphemeral("assistant.usage",{model:ht||"unknown",inputTokens:Oe?.prompt_tokens||0,outputTokens:Oe?.completion_tokens||0,cacheReadTokens:Oe?.prompt_tokens_details?.cached_tokens||0,cacheWriteTokens:0,cost:lt,duration:zt,initiator:me.modelCall?.initiator,apiCallId:me.modelCall?.api_id,providerCallId:me.modelCall?.request_id,quotaSnapshots:me.quotaSnapshots});break}case"history_truncated":{this.emit("session.truncation",{...me.truncateResult,performedBy:me.performedBy});break}case"compaction_started":{this.emit("session.compaction_start",{});break}case"compaction_completed":{me.success&&me.compactionResult?this.emit("session.compaction_complete",{success:!0,preCompactionTokens:me.compactionResult.preCompactionTokens,postCompactionTokens:me.compactionResult.postCompactionTokens,preCompactionMessagesLength:me.compactionResult.preCompactionMessagesLength,messagesRemoved:me.compactionResult.messagesRemoved,tokensRemoved:me.compactionResult.tokensRemoved,summaryContent:me.compactionResult.summaryContent,compactionTokensUsed:me.compactionResult.compactionTokensUsed}):this.emit("session.compaction_complete",{success:!1,error:me.error});break}case"response":case"images_removed":case"image_processing":case"turn_failed":case"turn_retry":Qe.debug(`Ignoring event of kind: ${me.kind}`);break;default:sm(me,"Unhandled event type")}}}catch(s){if(await qO(this.hooks?.sessionEnd,{timestamp:Date.now(),cwd:this.workingDir,reason:"error",error:s instanceof Error?s:new Error(String(s))},Qe),s&&typeof s=="object"&&"status"in s&&(s.status===401||s.status===403)){if("message"in s&&typeof s.message=="string"){let c=cHt(s.message);c&&this.emit("session.error",{errorType:"authentication",message:c.message})}this.emit("session.error",{errorType:"authorization",message:"Authorization error, you may need to run /login"})}s&&typeof s=="object"&&"status"in s&&s.status===402&&this.emit("session.error",{errorType:"quota",message:"Quota exceeded. Upgrade to increase your limit: https://github.com/features/copilot/plans"});let I=`Execution failed: ${gt(s)}`;this.emit("session.error",{errorType:"query",message:I,stack:s instanceof Error?s.stack:void 0})}finally{await qO(this.hooks?.sessionEnd,{timestamp:Date.now(),cwd:this.workingDir,reason:"complete"},Qe),o&&this.clearPendingMessages();try{for(let s of a)s.shutdown&&await s.shutdown()}catch(s){Qe.error(`Error during session shutdown: ${gt(s)}`)}}}},DL=class extends nPe{repository;remoteSessionIds;pullRequestNumber;constructor(e){super(e),this.repository=e.repository,this.remoteSessionIds=e.remoteSessionIds,this.pullRequestNumber=e.pullRequestNumber}async send(e){let{prompt:n}=e;if(!this.pullRequestNumber)throw new Error("Cannot send message: Pull request number is not available");if(!this.authInfo)throw new Error("Cannot send message: Authentication info is not available");let{owner:r,name:l}=this.repository,a=this.pullRequestNumber,o=`@copilot ${n}`;Qe.debug(`Posting user message to PR ${r}/${l}#${a}`);let s=GW(this.authInfo),I=new URL(`/repos/${r}/${l}/issues/${a}/comments`,zy(s)),c=await cY(I,this.authInfo,Qe,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({body:o})});if(!c.ok){let d=await c.text();throw new Error(`Failed to post comment to PR ${r}/${l}#${a}: ${c.status} ${c.statusText}
2285
2281
  ${d}
2286
2282
  ${I.toString()}`)}Qe.info(`Successfully posted user message to PR ${r}/${l}#${a}`),this.emit("user.message",{content:n})}async abort(){throw new Error("RemoteSession.abort() is not implemented yet.")}async compactHistory(){throw new Error("RemoteSession.compactHistory() is not implemented yet.")}getMetadata(){return{sessionId:this.sessionId,startTime:this.startTime,modifiedTime:this.modifiedTime,summary:this.summary,isRemote:!0,repository:this.repository,remoteSessionIds:this.remoteSessionIds,pullRequestNumber:this.pullRequestNumber}}}});import Jql from"node:path";async function wqn(t,e,n,r){n??=v1e,r??=new Q0;let l=await N1e(e),{agents:a}=await y1e(r,n,t,Jql.join(qf(),"agents"),l,!1);return a.map(o=>({name:o.id,displayName:o.displayName,description:o.description,tools:o.tools,prompt:o.prompt,mcpServers:o.mcpServers||{},infer:o.infer}))}var YHt=W(()=>{"use strict";Qze();Vze();$f();Fze();ML()});var V1e,Bql,Tql,Oql,_ql,Uql,Mql,Dql,zql,Pql,jql,Kql,qql,$ql,e7l,t7l,n7l,r7l,l7l,a7l,o7l,s7l,i7l,I7l,c7l,d7l,u7l,m7l,vHt,$O,VHt=W(()=>{"use strict";Ps();yC();RC();Qre();V1e=_n({type:el("text"),text:Gt()}),Bql=_n({type:el("refusal"),refusal:Gt()}),Tql=_n({type:el("image_url"),image_url:_n({url:Gt(),detail:JZ(["auto","low","high"]).optional()})}),Oql=_n({type:el("input_audio"),input_audio:_n({data:Gt(),format:el("wav").or(el("mp3"))})}),_ql=_n({type:el("file"),file:_n({file_date:Gt().optional(),file_id:Gt().optional(),filename:Gt().optional()})}),Uql=SZ([V1e,Tql,Oql,_ql]),Mql=_n({name:Gt(),arguments:Gt()}),Dql=_n({name:Gt(),input:Gt()}),zql=_n({id:Gt(),type:el("function"),function:Mql}),Pql=_n({id:Gt(),type:el("custom"),custom:Dql}),jql=SZ([zql,Pql]),Kql=_n({name:Gt(),arguments:Gt()}),qql=_n({id:Gt()}),$ql=_n({content:SZ([Gt(),Dc(V1e)]),role:el("developer"),name:Gt().optional()}),e7l=_n({content:SZ([Gt(),Dc(V1e)]),role:el("system"),name:Gt().optional()}),t7l=_n({content:SZ([Gt(),Dc(Uql)]),role:el("user"),name:Gt().optional()}),n7l=_n({content:SZ([Gt(),Dc(SZ([V1e,Bql]))]).nullable().optional(),role:el("assistant"),name:Gt().optional(),refusal:Gt().nullable().optional(),audio:qql.nullable().optional(),function_call:Kql.nullable().optional(),tool_calls:Dc(jql).optional()}),r7l=_n({content:SZ([Gt(),Dc(V1e)]),role:el("tool"),tool_call_id:Gt()}),l7l=_n({content:Gt().nullable(),role:el("function"),name:Gt()}),a7l=SZ([$ql,e7l,t7l,n7l,r7l,l7l]),o7l=_n({type:el("copilot"),text:Gt(),isStreaming:Is().optional()}),s7l=_n({type:el("error"),text:Gt()}),i7l=_n({type:el("info"),text:Gt()}),I7l=_n({type:el("user"),text:Gt()}),c7l=_n({type:el("tool_call_requested"),callId:Gt(),name:Gt(),toolTitle:Gt().optional(),intentionSummary:Gt().nullable(),arguments:PFt,partialOutput:Gt().optional(),isHidden:Is().optional(),isAlwaysExpanded:Is().optional(),showNoContent:Is().optional()}),d7l=_n({type:el("tool_call_completed"),callId:Gt(),name:Gt(),toolTitle:Gt().optional(),intentionSummary:Gt().nullable(),result:SZ([_n({type:el("success"),log:Gt(),markdown:Is().optional()}),_n({type:el("failure"),log:Gt(),markdown:Is().optional()}),_n({type:el("rejected"),markdown:Is().optional()}),_n({type:el("denied"),log:Gt(),markdown:Is().optional()})]),arguments:PFt,isHidden:Is().optional(),isAlwaysExpanded:Is().optional(),showNoContent:Is().optional()}),u7l=SZ([o7l,s7l,i7l,I7l,c7l,d7l]),m7l=u7l.and(_n({id:Gt(),timestamp:s4e.date()})),vHt=_n({sessionId:Gt(),startTime:s4e.date(),chatMessages:Dc(a7l),timeline:Dc(m7l),selectedModel:JZ(hW).optional()}),$O=G4e(vHt.parse,"history-session")});var MI,rPe,p7l,b7l,h7l,G7l,g7l,A7l,Z7l,N7l,y7l,W7l,E7l,f7l,R7l,w7l,Y7l,v7l,V7l,C7l,Q7l,F7l,H7l,X7l,k7l,x7l,L7l,S7l,J7l,B7l,T7l,O7l,_7l,U7l,M7l,D7l,Vqn,CHt=W(()=>{"use strict";Ps();VHt();MI=_n({id:Gt().uuid(),timestamp:Gt().datetime(),parentId:Gt().uuid().nullable(),ephemeral:Is().optional()}),rPe=_n({parentToolCallId:Gt().optional()}),p7l=MI.extend({type:el("session.start"),data:_n({sessionId:Gt(),version:ho(),producer:Gt(),copilotVersion:Gt(),startTime:Gt().datetime(),selectedModel:Gt().optional()})}),b7l=MI.extend({type:el("session.resume"),data:_n({resumeTime:Gt().datetime(),eventCount:ho()})}),h7l=MI.extend({type:el("session.error"),data:_n({errorType:Gt(),message:Gt(),stack:Gt().optional()})}),G7l=MI.extend({type:el("session.info"),data:_n({infoType:Gt(),message:Gt()})}),g7l=MI.extend({type:el("session.model_change"),data:_n({previousModel:Gt().optional(),newModel:Gt()})}),A7l=MI.extend({type:el("session.import_legacy"),data:_n({legacySession:vHt,importTime:Gt().datetime(),sourceFile:Gt()})}),Z7l=MI.extend({type:el("session.handoff"),data:_n({handoffTime:Gt().datetime(),sourceType:JZ(["remote","local"]),repository:_n({owner:Gt(),name:Gt(),branch:Gt().optional()}).optional(),context:Gt().optional(),summary:Gt().optional(),remoteSessionId:Gt().optional()})}),N7l=MI.extend({type:el("session.idle"),ephemeral:el(!0),data:_n({})}),y7l=MI.extend({type:el("session.truncation"),data:_n({tokenLimit:ho(),preTruncationTokensInMessages:ho(),preTruncationMessagesLength:ho(),postTruncationTokensInMessages:ho(),postTruncationMessagesLength:ho(),tokensRemovedDuringTruncation:ho(),messagesRemovedDuringTruncation:ho(),performedBy:Gt()})}),W7l=MI.extend({type:el("session.compaction_start"),data:_n({})}),E7l=MI.extend({type:el("session.compaction_complete"),data:_n({success:Is(),error:Gt().optional(),preCompactionTokens:ho().optional(),postCompactionTokens:ho().optional(),preCompactionMessagesLength:ho().optional(),messagesRemoved:ho().optional(),tokensRemoved:ho().optional(),summaryContent:Gt().optional(),compactionTokensUsed:_n({input:ho(),output:ho(),cachedInput:ho()}).optional()})}),f7l=_n({type:JZ(["file","directory"]),path:Gt(),displayName:Gt()}),R7l=MI.extend({type:el("user.message"),data:_n({content:Gt(),transformedContent:Gt().optional(),attachments:Dc(f7l).optional(),source:Gt().optional()})}),w7l=MI.extend({type:el("pending_messages.modified"),ephemeral:el(!0),data:_n({})}),Y7l=MI.extend({type:el("assistant.turn_start"),data:_n({turnId:Gt()})}),v7l=MI.extend({type:el("assistant.message"),data:_n({messageId:Gt(),content:Gt(),toolRequests:Dc(_n({toolCallId:Gt(),name:Gt(),arguments:AV()})).optional()}).merge(rPe)}),V7l=MI.extend({type:el("assistant.message_delta"),ephemeral:el(!0),data:_n({messageId:Gt(),deltaContent:Gt(),totalResponseSizeBytes:ho().optional()}).merge(rPe)}),C7l=MI.extend({type:el("assistant.intent"),ephemeral:el(!0),data:_n({intent:Gt()})}),Q7l=MI.extend({type:el("assistant.reasoning"),data:_n({reasoningId:Gt(),content:Gt()})}),F7l=MI.extend({type:el("assistant.reasoning_delta"),ephemeral:el(!0),data:_n({reasoningId:Gt(),deltaContent:Gt()})}),H7l=MI.extend({type:el("assistant.turn_end"),data:_n({turnId:Gt()})}),X7l=MI.extend({type:el("assistant.usage"),ephemeral:el(!0),data:_n({model:Gt().optional(),inputTokens:ho().optional(),outputTokens:ho().optional(),cacheReadTokens:ho().optional(),cacheWriteTokens:ho().optional(),cost:ho().optional(),duration:ho().optional(),initiator:Gt().optional(),apiCallId:Gt().optional(),providerCallId:Gt().optional(),quotaSnapshots:xf(Gt(),_n({isUnlimitedEntitlement:Is(),entitlementRequests:ho(),usedRequests:ho(),usageAllowedWithExhaustedQuota:Is(),overage:ho(),overageAllowedWithExhaustedQuota:Is(),remainingPercentage:ho(),resetDate:ipt().optional()})).optional()})}),k7l=MI.extend({type:el("abort"),data:_n({reason:Gt()})}),x7l=MI.extend({type:el("tool.user_requested"),data:_n({toolCallId:Gt(),toolName:Gt(),arguments:AV()})}),L7l=MI.extend({type:el("tool.execution_start"),data:_n({toolCallId:Gt(),toolName:Gt(),arguments:AV()}).merge(rPe)}),S7l=MI.extend({type:el("tool.execution_partial_result"),ephemeral:el(!0),data:_n({toolCallId:Gt(),partialOutput:Gt()})}),J7l=MI.extend({type:el("tool.execution_complete"),data:_n({toolCallId:Gt(),success:Is(),isUserRequested:Is().optional(),result:_n({content:Gt()}).optional(),error:_n({message:Gt(),code:Gt().optional()}).optional(),toolTelemetry:xf(AV()).optional()}).merge(rPe)}),B7l=MI.extend({type:el("custom_agent.started"),data:_n({toolCallId:Gt(),agentName:Gt(),agentDisplayName:Gt(),agentDescription:Gt()})}),T7l=MI.extend({type:el("custom_agent.completed"),data:_n({toolCallId:Gt(),agentName:Gt()})}),O7l=MI.extend({type:el("custom_agent.failed"),data:_n({toolCallId:Gt(),agentName:Gt(),error:Gt()})}),_7l=MI.extend({type:el("custom_agent.selected"),data:_n({agentName:Gt(),agentDisplayName:Gt(),tools:Dc(Gt()).nullable()})}),U7l=MI.extend({type:el("hook.start"),data:_n({hookInvocationId:Gt(),hookType:Gt(),input:AV()})}),M7l=MI.extend({type:el("hook.end"),data:_n({hookInvocationId:Gt(),hookType:Gt(),output:AV(),success:Is(),error:_n({message:Gt(),stack:Gt().optional()}).optional()})}),D7l=MI.extend({type:el("system.message"),data:_n({content:Gt(),role:JZ(["system","developer"]),name:Gt().optional(),metadata:_n({promptVersion:Gt().optional(),variables:xf(AV()).optional()}).optional()})}),Vqn=QAe("type",[p7l,b7l,h7l,N7l,G7l,g7l,A7l,Z7l,y7l,W7l,E7l,R7l,w7l,Y7l,C7l,Q7l,F7l,v7l,V7l,H7l,X7l,k7l,x7l,L7l,S7l,J7l,B7l,T7l,O7l,_7l,U7l,M7l,D7l])});var kX,QHt=W(()=>{"use strict";CHt();Qre();kX=Kbn(Vqn.parse,"session")});var Cqn,FHt,Qqn,Fqn,Hqn,Xqn,kqn=W(()=>{Cqn=t=>{t=1831565813+(t|=0)|0;let e=Math.imul(t^t>>>15,1|t);return e=e+Math.imul(e^e>>>7,61|e)^e,((e^e>>>14)>>>0)/4294967296},FHt=class{constructor(e){this.dictionaries=void 0,this.length=void 0,this.separator=void 0,this.style=void 0,this.seed=void 0;let{length:n,separator:r,dictionaries:l,style:a,seed:o}=e;this.dictionaries=l,this.separator=r,this.length=n,this.style=a,this.seed=o}generate(){if(!this.dictionaries)throw new Error('Cannot find any dictionary. Please provide at least one, or leave the "dictionary" field empty in the config object');if(this.length<=0)throw new Error("Invalid length provided");if(this.length>this.dictionaries.length)throw new Error(`The length cannot be bigger than the number of dictionaries.
2287
2283
  Length provided: ${this.length}. Number of dictionaries provided: ${this.dictionaries.length}`);let e=this.seed;return this.dictionaries.slice(0,this.length).reduce((n,r)=>{let l;e?(l=(o=>{if(typeof o=="string"){let s=o.split("").map(c=>c.charCodeAt(0)).reduce((c,d)=>c+d,1),I=Math.floor(Number(s));return Cqn(I)}return Cqn(o)})(e),e=4294967296*l):l=Math.random();let a=r[Math.floor(l*r.length)]||"";if(this.style==="lowerCase")a=a.toLowerCase();else if(this.style==="capital"){let[o,...s]=a.split("");a=o.toUpperCase()+s.join("")}else this.style==="upperCase"&&(a=a.toUpperCase());return n?`${n}${this.separator}${a}`:`${a}`},"")}},Qqn={separator:"_",dictionaries:[]},Fqn=t=>{let e=[...t&&t.dictionaries||Qqn.dictionaries],n={...Qqn,...t,length:t&&t.length||e.length,dictionaries:e};if(!t||!t.dictionaries||!t.dictionaries.length)throw new Error('A "dictionaries" array must be provided. This is a breaking change introduced starting from Unique Name Generator v4. Read more about the breaking change here: https://github.com/andreasonny83/unique-names-generator#migration-guide');return new FHt(n).generate()},Hqn=["able","above","absent","absolute","abstract","abundant","academic","acceptable","accepted","accessible","accurate","accused","active","actual","acute","added","additional","adequate","adjacent","administrative","adorable","advanced","adverse","advisory","aesthetic","afraid","aggregate","aggressive","agreeable","agreed","agricultural","alert","alive","alleged","allied","alone","alright","alternative","amateur","amazing","ambitious","amused","ancient","angry","annoyed","annual","anonymous","anxious","appalling","apparent","applicable","appropriate","arbitrary","architectural","armed","arrogant","artificial","artistic","ashamed","asleep","assistant","associated","atomic","attractive","automatic","autonomous","available","average","awake","aware","awful","awkward","back","bad","balanced","bare","basic","beautiful","beneficial","better","bewildered","big","binding","biological","bitter","bizarre","blank","blonde","blushing","boiling","bold","bored","boring","bottom","brainy","brave","breakable","breezy","brief","bright","brilliant","broad","broken","bumpy","burning","busy","calm","capable","careful","casual","causal","cautious","central","certain","changing","characteristic","charming","cheap","cheerful","chemical","chief","chilly","chosen","chronic","chubby","circular","civic","civil","classic","classical","clean","clear","clever","clinical","close","closed","cloudy","clumsy","coastal","cognitive","coherent","cold","collective","colorful","colossal","coloured","colourful","combined","comfortable","commercial","common","compact","comparable","comparative","compatible","competent","competitive","complete","complex","complicated","comprehensive","compulsory","conceptual","concerned","concrete","condemned","confident","confidential","confused","conscious","conservation","considerable","consistent","constant","constitutional","contemporary","content","continental","continued","continuing","continuous","controlled","controversial","convenient","conventional","convinced","convincing","cooing","cool","cooperative","corporate","correct","corresponding","costly","courageous","creative","creepy","criminal","critical","crooked","crowded","crucial","crude","cruel","cuddly","cultural","curious","curly","current","curved","cute","daily","damaged","damp","dangerous","dark","dead","deafening","dear","decent","decisive","deep","defeated","defensive","defiant","definite","deliberate","delicate","delicious","delighted","delightful","democratic","dependent","depressed","desirable","desperate","detailed","determined","developed","developing","devoted","different","difficult","digital","diplomatic","direct","dirty","disappointed","disastrous","disciplinary","disgusted","distant","distinct","distinctive","distinguished","disturbed","disturbing","diverse","divine","dizzy","domestic","dominant","double","doubtful","drab","dramatic","dreadful","driving","dry","dual","due","dull","dusty","dutch","dying","dynamic","eager","early","eastern","easy","economic","educational","eerie","effective","efficient","elaborate","elated","elderly","eldest","electoral","electric","electrical","electronic","elegant","eligible","embarrassed","embarrassing","emotional","empirical","empty","enchanting","encouraging","endless","energetic","enormous","enthusiastic","entire","entitled","envious","environmental","equal","equivalent","essential","established","estimated","ethical","eventual","everyday","evident","evil","evolutionary","exact","excellent","exceptional","excess","excessive","excited","exciting","exclusive","existing","exotic","expected","expensive","experienced","experimental","explicit","extended","extensive","external","extra","extraordinary","extreme","exuberant","faint","fair","faithful","familiar","famous","fancy","fantastic","far","fascinating","fashionable","fast","fatal","favourable","favourite","federal","fellow","few","fierce","final","financial","fine","firm","fiscal","fit","fixed","flaky","flat","flexible","fluffy","fluttering","flying","following","fond","foolish","foreign","formal","formidable","forthcoming","fortunate","forward","fragile","frail","frantic","free","frequent","fresh","friendly","frightened","front","frozen","full","fun","functional","fundamental","funny","furious","future","fuzzy","gastric","general","generous","genetic","gentle","genuine","geographical","giant","gigantic","given","glad","glamorous","gleaming","global","glorious","golden","good","gorgeous","gothic","governing","graceful","gradual","grand","grateful","greasy","great","grieving","grim","gross","grotesque","growing","grubby","grumpy","guilty","handsome","happy","hard","harsh","head","healthy","heavy","helpful","helpless","hidden","high","hilarious","hissing","historic","historical","hollow","holy","homely","hon","honest","horizontal","horrible","hostile","hot","huge","human","hungry","hurt","hushed","husky","icy","ideal","identical","ideological","ill","illegal","imaginative","immediate","immense","implicit","important","impossible","impressed","impressive","improved","inadequate","inc","inclined","increased","increasing","incredible","independent","indirect","individual","industrial","inevitable","influential","informal","inherent","initial","injured","inland","inner","innocent","innovative","inquisitive","instant","institutional","insufficient","intact","integral","integrated","intellectual","intelligent","intense","intensive","interested","interesting","interim","interior","intermediate","internal","international","invisible","involved","irrelevant","isolated","itchy","jealous","jittery","joint","jolly","joyous","judicial","juicy","junior","just","keen","key","kind","known","labour","large","late","latin","lazy","leading","left","legal","legislative","legitimate","lengthy","lesser","level","lexical","liable","light","like","likely","limited","linear","linguistic","liquid","literary","little","live","lively","living","local","logical","lonely","long","loose","lost","loud","lovely","low","loyal","ltd","lucky","mad","magic","magnetic","magnificent","main","major","mammoth","managerial","managing","manual","many","marginal","marine","marked","married","marvellous","mass","massive","mathematical","mature","maximum","mean","meaningful","mechanical","medical","medieval","melodic","melted","mental","mere","metropolitan","mid","middle","mighty","mild","military","miniature","minimal","minimum","ministerial","minor","miserable","misleading","missing","misty","mixed","moaning","mobile","moderate","modern","modest","molecular","monetary","monthly","moral","motionless","muddy","multiple","mushy","musical","mutual","mysterious","naked","narrow","nasty","national","natural","naughty","naval","near","nearby","neat","necessary","negative","neighbouring","nervous","net","neutral","new","nice","noble","noisy","normal","northern","nosy","notable","novel","nuclear","numerous","nursing","nutritious","nutty","obedient","objective","obliged","obnoxious","obvious","occasional","occupational","odd","official","ok","okay","old","only","open","operational","opposite","optimistic","ordinary","organic","organisational","original","orthodox","other","outdoor","outer","outrageous","outside","outstanding","overall","overseas","overwhelming","painful","pale","panicky","parallel","parental","parliamentary","partial","particular","passing","passive","past","patient","payable","peaceful","peculiar","perfect","permanent","persistent","personal","petite","philosophical","physical","plain","planned","plastic","pleasant","pleased","poised","polite","poor","popular","positive","possible","potential","powerful","practical","precious","precise","preferred","pregnant","preliminary","premier","prepared","present","presidential","pretty","previous","prickly","primary","prime","principal","printed","prior","private","probable","productive","professional","profitable","profound","progressive","prominent","promising","proper","proposed","prospective","protective","proud","provincial","psychiatric","psychological","public","puny","pure","purring","puzzled","quaint","qualified","quarrelsome","querulous","quick","quickest","quiet","quintessential","quixotic","racial","radical","rainy","random","rapid","rare","raspy","rational","ratty","raw","ready","real","realistic","rear","reasonable","recent","reduced","redundant","regional","registered","regular","regulatory","related","relative","relaxed","relevant","reliable","relieved","religious","reluctant","remaining","remarkable","remote","renewed","representative","repulsive","required","resident","residential","resonant","respectable","respective","responsible","resulting","retail","retired","revolutionary","rich","ridiculous","right","rigid","ripe","rising","rival","roasted","robust","rolling","romantic","rotten","rough","round","royal","rubber","rude","ruling","running","rural","sacred","sad","safe","salty","satisfactory","satisfied","scared","scary","scattered","scientific","scornful","scrawny","screeching","secondary","secret","secure","select","selected","selective","selfish","semantic","senior","sensible","sensitive","separate","serious","severe","shaggy","shaky","shallow","shared","sharp","sheer","shiny","shivering","shocked","short","shrill","shy","sick","significant","silent","silky","silly","similar","simple","single","skilled","skinny","sleepy","slight","slim","slimy","slippery","slow","small","smart","smiling","smoggy","smooth","social","soft","solar","sole","solid","sophisticated","sore","sorry","sound","sour","southern","spare","sparkling","spatial","special","specific","specified","spectacular","spicy","spiritual","splendid","spontaneous","sporting","spotless","spotty","square","squealing","stable","stale","standard","static","statistical","statutory","steady","steep","sticky","stiff","still","stingy","stormy","straight","straightforward","strange","strategic","strict","striking","striped","strong","structural","stuck","subjective","subsequent","substantial","subtle","successful","successive","sudden","sufficient","suitable","sunny","super","superb","superior","supporting","supposed","supreme","sure","surprised","surprising","surrounding","surviving","suspicious","sweet","swift","symbolic","sympathetic","systematic","tall","tame","tart","tasteless","tasty","technical","technological","teenage","temporary","tender","tense","terrible","territorial","testy","then","theoretical","thick","thin","thorough","thoughtful","thoughtless","thundering","tight","tiny","tired","top","total","tough","toxic","traditional","tragic","tremendous","tricky","tropical","troubled","typical","ugliest","ugly","ultimate","unable","unacceptable","unaware","uncertain","unchanged","uncomfortable","unconscious","underground","underlying","unemployed","uneven","unexpected","unfair","unfortunate","unhappy","uniform","uninterested","unique","united","universal","unknown","unlikely","unnecessary","unpleasant","unsightly","unusual","unwilling","upper","upset","uptight","urban","urgent","used","useful","useless","usual","vague","valid","valuable","variable","varied","various","varying","vast","verbal","vertical","very","vicarious","vicious","victorious","violent","visible","visiting","visual","vital","vitreous","vivacious","vivid","vocal","vocational","voiceless","voluminous","voluntary","vulnerable","wandering","warm","wasteful","watery","weak","wealthy","weary","wee","weekly","weird","welcome","well","western","wet","whispering","whole","wicked","wide","widespread","wild","wilful","willing","willowy","wily","wise","wispy","wittering","witty","wonderful","wooden","working","worldwide","worried","worrying","worthwhile","worthy","written","wrong","xenacious","xenial","xenogeneic","xeric","xerothermic","yabbering","yammering","yappiest","yappy","yawning","yearling","yearning","yeasty","yelling","yelping","yielding","yodelling","young","youngest","youthful","ytterbic","yucky","yummy","zany","zealous","zeroth","zestful","zesty","zippy","zonal","zoophagous","zygomorphic","zygotic"],Xqn=["aardvark","aardwolf","albatross","alligator","alpaca","amphibian","anaconda","angelfish","anglerfish","ant","anteater","antelope","antlion","ape","aphid","armadillo","asp","baboon","badger","bandicoot","barnacle","barracuda","basilisk","bass","bat","bear","beaver","bedbug","bee","beetle","bird","bison","blackbird","boa","boar","bobcat","bobolink","bonobo","bovid","bug","butterfly","buzzard","camel","canid","canidae","capybara","cardinal","caribou","carp","cat","caterpillar","catfish","catshark","cattle","centipede","cephalopod","chameleon","cheetah","chickadee","chicken","chimpanzee","chinchilla","chipmunk","cicada","clam","clownfish","cobra","cockroach","cod","condor","constrictor","coral","cougar","cow","coyote","crab","crane","crawdad","crayfish","cricket","crocodile","crow","cuckoo","damselfly","deer","dingo","dinosaur","dog","dolphin","donkey","dormouse","dove","dragon","dragonfly","duck","eagle","earthworm","earwig","echidna","eel","egret","elephant","elk","emu","ermine","falcon","felidae","ferret","finch","firefly","fish","flamingo","flea","fly","flyingfish","fowl","fox","frog","galliform","gamefowl","gayal","gazelle","gecko","gerbil","gibbon","giraffe","goat","goldfish","goose","gopher","gorilla","grasshopper","grouse","guan","guanaco","guineafowl","gull","guppy","haddock","halibut","hamster","hare","harrier","hawk","hedgehog","heron","herring","hippopotamus","hookworm","hornet","horse","hoverfly","hummingbird","hyena","iguana","impala","jackal","jaguar","jay","jellyfish","junglefowl","kangaroo","kingfisher","kite","kiwi","koala","koi","krill","ladybug","lamprey","landfowl","lark","leech","lemming","lemur","leopard","leopon","limpet","lion","lizard","llama","lobster","locust","loon","louse","lungfish","lynx","macaw","mackerel","magpie","mammal","manatee","mandrill","marlin","marmoset","marmot","marsupial","marten","mastodon","meadowlark","meerkat","mink","minnow","mite","mockingbird","mole","mollusk","mongoose","monkey","moose","mosquito","moth","mouse","mule","muskox","narwhal","newt","nightingale","ocelot","octopus","opossum","orangutan","orca","ostrich","otter","owl","ox","panda","panther","parakeet","parrot","parrotfish","partridge","peacock","peafowl","pelican","penguin","perch","pheasant","pig","pigeon","pike","pinniped","piranha","planarian","platypus","pony","porcupine","porpoise","possum","prawn","primate","ptarmigan","puffin","puma","python","quail","quelea","quokka","rabbit","raccoon","rat","rattlesnake","raven","reindeer","reptile","rhinoceros","roadrunner","rodent","rook","rooster","roundworm","sailfish","salamander","salmon","sawfish","scallop","scorpion","seahorse","shark","sheep","shrew","shrimp","silkworm","silverfish","skink","skunk","sloth","slug","smelt","snail","snake","snipe","sole","sparrow","spider","spoonbill","squid","squirrel","starfish","stingray","stoat","stork","sturgeon","swallow","swan","swift","swordfish","swordtail","tahr","takin","tapir","tarantula","tarsier","termite","tern","thrush","tick","tiger","tiglon","toad","tortoise","toucan","trout","tuna","turkey","turtle","tyrannosaurus","unicorn","urial","vicuna","viper","vole","vulture","wallaby","walrus","warbler","wasp","weasel","whale","whippet","whitefish","wildcat","wildebeest","wildfowl","wolf","wolverine","wombat","woodpecker","worm","wren","xerinae","yak","zebra"]});import{execFile as z7l}from"node:child_process";import{promisify as P7l}from"node:util";function QIe(t){let[e,n]=t.split("/");if(!e||!n)throw new Error(`Invalid repository format: ${t}. Expected format: owner/repo`);return{owner:e,repo:n}}async function lPe(t){try{let{stdout:e}=await u2("git",["status","--porcelain","--ignore-submodules"],{cwd:t,encoding:"utf8",timeout:5e3,maxBuffer:1048576}),n=e.split(`
@@ -2953,7 +2949,7 @@ Read about how to prevent this error on https://github.com/vadimdemedes/ink/#isr
2953
2949
  `;if(this.options.debug){l&&(this.fullStaticOutput+=r),this.options.stdout.write(this.fullStaticOutput+e);return}if(F8){l&&this.options.stdout.write(r),this.lastOutput=e,this.lastOutputHeight=n;return}if(this.isScreenReaderEnabled){if(l){let s=this.lastOutputHeight>0?XA.eraseLines(this.lastOutputHeight):"";this.options.stdout.write(s+r),this.lastOutputHeight=0}if(e===this.lastOutput&&!l)return;let a=this.options.stdout.columns||80,o=kC(e,a,{trim:!1,hard:!0});if(l)this.options.stdout.write(o);else{let s=this.lastOutputHeight>0?XA.eraseLines(this.lastOutputHeight):"";this.options.stdout.write(s+o)}this.lastOutput=e,this.lastOutputHeight=o===""?0:o.split(`
2954
2950
  `).length;return}if(l&&(this.fullStaticOutput+=r),this.lastOutputHeight>=this.options.stdout.rows){this.options.stdout.write(XA.clearTerminal+this.fullStaticOutput+e),this.lastOutput=e,this.lastOutputHeight=n,this.log.sync(e);return}l&&(this.log.clear(),this.options.stdout.write(r),this.log(e)),!l&&e!==this.lastOutput&&this.throttledLog(e),this.lastOutput=e,this.lastOutputHeight=n};render(e){let n=GJt.default.createElement(gS.Provider,{value:{isScreenReaderEnabled:this.isScreenReaderEnabled}},GJt.default.createElement(rYe,{stdin:this.options.stdin,stdout:this.options.stdout,stderr:this.options.stderr,writeToStdout:this.writeToStdout,writeToStderr:this.writeToStderr,exitOnCtrlC:this.options.exitOnCtrlC,onExit:this.unmount},e));GS.updateContainerSync(n,this.container,null,bcr),GS.flushSyncWork()}writeToStdout(e){if(!this.isUnmounted){if(this.options.debug){this.options.stdout.write(e+this.fullStaticOutput+this.lastOutput);return}if(F8){this.options.stdout.write(e);return}this.log.clear(),this.options.stdout.write(e),this.log(this.lastOutput)}}writeToStderr(e){if(!this.isUnmounted){if(this.options.debug){this.options.stderr.write(e),this.options.stdout.write(this.fullStaticOutput+this.lastOutput);return}if(F8){this.options.stderr.write(e);return}this.log.clear(),this.options.stderr.write(e),this.log(this.lastOutput)}}unmount(e){this.isUnmounted||(this.calculateLayout(),this.onRender(),this.unsubscribeExit(),typeof this.restoreConsole=="function"&&this.restoreConsole(),typeof this.unsubscribeResize=="function"&&this.unsubscribeResize(),F8?this.options.stdout.write(this.lastOutput+`
2955
2951
  `):this.options.debug||this.log.done(),this.isUnmounted=!0,GS.updateContainerSync(null,this.container,null,bcr),GS.flushSyncWork(),$ce.delete(this.options.stdout),e instanceof Error?this.rejectExitPromise(e):this.resolveExitPromise())}async waitUntilExit(){return this.exitPromise||=new Promise((e,n)=>{this.resolveExitPromise=e,this.rejectExitPromise=n}),this.exitPromise}clear(){!F8&&!this.options.debug&&this.log.clear()}patchConsole(){this.options.debug||(this.restoreConsole=YVe((e,n)=>{e==="stdout"&&this.writeToStdout(n),e==="stderr"&&(n.startsWith("The above error occurred")||this.writeToStderr(n))}))}};var Iba=(t,e)=>{let n={stdout:BKe.stdout,stdin:BKe.stdin,stderr:BKe.stderr,debug:!1,exitOnCtrlC:!0,patchConsole:!0,maxFps:30,...cba(e)},r=dba(n.stdout,()=>new lYe(n));return r.render(t),{rerender:r.render,unmount(){r.unmount()},waitUntilExit:r.waitUntilExit,cleanup:()=>$ce.delete(n.stdout),clear:r.clear}},aYe=Iba,cba=(t={})=>t instanceof iba?{stdout:t,stdin:BKe.stdin}:t,dba=(t,e)=>{let n=$ce.get(t);return n||(n=e(),$ce.set(t,n)),n};var ZS=ze(tn(),1);function TKe(t){let{items:e,children:n,style:r}=t,[l,a]=(0,ZS.useState)(0),o=(0,ZS.useMemo)(()=>e.slice(l),[e,l]);(0,ZS.useLayoutEffect)(()=>{a(e.length)},[e.length]);let s=o.map((c,d)=>n(c,l+d)),I=(0,ZS.useMemo)(()=>({position:"absolute",flexDirection:"column",...r}),[r]);return ZS.default.createElement("ink-box",{internal_static:!0,style:I},s)}var gcr=ze(tn(),1);var uba=ze(tn(),1);var mba=ze(tn(),1);var gJt=ze(tn(),1);import{Buffer as pba}from"node:buffer";var bba=/^(?:\x1b)([a-zA-Z0-9])$/,hba=/^(?:\x1b+)(O|N|\[|\[\[)(?:(\d+)(?:;(\d+))?([~^$])|(?:1;)?(\d+)?([a-zA-Z]))/,Acr={OP:"f1",OQ:"f2",OR:"f3",OS:"f4","[11~":"f1","[12~":"f2","[13~":"f3","[14~":"f4","[[A":"f1","[[B":"f2","[[C":"f3","[[D":"f4","[[E":"f5","[15~":"f5","[17~":"f6","[18~":"f7","[19~":"f8","[20~":"f9","[21~":"f10","[23~":"f11","[24~":"f12","[A":"up","[B":"down","[C":"right","[D":"left","[E":"clear","[F":"end","[H":"home",OA:"up",OB:"down",OC:"right",OD:"left",OE:"clear",OF:"end",OH:"home","[1~":"home","[2~":"insert","[3~":"delete","[4~":"end","[5~":"pageup","[6~":"pagedown","[[5~":"pageup","[[6~":"pagedown","[7~":"home","[8~":"end","[a":"up","[b":"down","[c":"right","[d":"left","[e":"clear","[2$":"insert","[3$":"delete","[5$":"pageup","[6$":"pagedown","[7$":"home","[8$":"end",Oa:"up",Ob:"down",Oc:"right",Od:"left",Oe:"clear","[2^":"insert","[3^":"delete","[5^":"pageup","[6^":"pagedown","[7^":"home","[8^":"end","[Z":"tab"},Zcr=[...Object.values(Acr),"backspace"],Gba=t=>["[a","[b","[c","[d","[e","[2$","[3$","[5$","[6$","[7$","[8$","[Z"].includes(t),gba=t=>["Oa","Ob","Oc","Od","Oe","[2^","[3^","[5^","[6^","[7^","[8^"].includes(t),Aba=(t="")=>{let e;pba.isBuffer(t)?t[0]>127&&t[1]===void 0?(t[0]-=128,t="\x1B"+String(t)):t=String(t):t!==void 0&&typeof t!="string"?t=String(t):t||(t="");let n={name:"",ctrl:!1,meta:!1,shift:!1,option:!1,sequence:t,raw:t};if(n.sequence=n.sequence||t||n.name,t==="\r")n.raw=void 0,n.name="return";else if(t===`
2956
- `)n.name="enter";else if(t===" ")n.name="tab";else if(t==="\b"||t==="\x1B\b")n.name="backspace",n.meta=t.charAt(0)==="\x1B";else if(t==="\x7F"||t==="\x1B\x7F")n.name="delete",n.meta=t.charAt(0)==="\x1B";else if(t==="\x1B"||t==="\x1B\x1B")n.name="escape",n.meta=t.length===2;else if(t===" "||t==="\x1B ")n.name="space",n.meta=t.length===2;else if(t.length===1&&t<="")n.name=String.fromCharCode(t.charCodeAt(0)+97-1),n.ctrl=!0;else if(t.length===1&&t>="0"&&t<="9")n.name="number";else if(t.length===1&&t>="a"&&t<="z")n.name=t;else if(t.length===1&&t>="A"&&t<="Z")n.name=t.toLowerCase(),n.shift=!0;else if(e=bba.exec(t))n.meta=!0,n.shift=/^[A-Z]$/.test(e[1]);else if(e=hba.exec(t)){let r=[...t];r[0]==="\x1B"&&r[1]==="\x1B"&&(n.option=!0);let l=[e[1],e[2],e[4],e[6]].filter(Boolean).join(""),a=(e[3]||e[5]||1)-1;n.ctrl=!!(a&4),n.meta=!!(a&10),n.shift=!!(a&1),n.code=l,n.name=Acr[l],n.shift=Gba(l)||n.shift,n.ctrl=gba(l)||n.ctrl}return n},Ncr=Aba;var ycr=ze(tn(),1);var Zba=()=>(0,ycr.useContext)(kKe),ede=Zba;var Nba=(t,e={})=>{let{stdin:n,setRawMode:r,internal_exitOnCtrlC:l,internal_eventEmitter:a}=ede();(0,gJt.useEffect)(()=>{if(e.isActive!==!1)return r(!0),()=>{r(!1)}},[e.isActive,r]),(0,gJt.useEffect)(()=>{if(e.isActive===!1)return;let o=s=>{let I=Ncr(s),c={upArrow:I.name==="up",downArrow:I.name==="down",leftArrow:I.name==="left",rightArrow:I.name==="right",pageDown:I.name==="pagedown",pageUp:I.name==="pageup",return:I.name==="return",escape:I.name==="escape",ctrl:I.ctrl,shift:I.shift,tab:I.name==="tab",backspace:I.name==="backspace",delete:I.name==="delete",meta:I.meta||I.name==="escape"||I.option},d=I.ctrl?I.name:I.sequence;Zcr.includes(I.name)&&(d=""),d.startsWith("\x1B")&&(d=d.slice(1)),d.length===1&&typeof d[0]=="string"&&/[A-Z]/.test(d[0])&&(c.shift=!0),(!(d==="c"&&c.ctrl)||!l)&&GS.batchedUpdates(()=>{t(d,c)})};return a?.on("input",o),()=>{a?.removeListener("input",o)}},[e.isActive,n,l,t])},y_=Nba;var yba=ze(tn(),1);var Wcr=ze(tn(),1);var Wba=()=>(0,Wcr.useContext)(xKe),hg=Wba;var Eba=ze(tn(),1);var AJt=ze(tn(),1);var fba=ze(tn(),1);var Ecr=ze(tn(),1);var Rba=()=>{let{isScreenReaderEnabled:t}=(0,Ecr.useContext)(gS);return t},NS=Rba;var wba=t=>({width:t.yogaNode?.getComputedWidth()??0,height:t.yogaNode?.getComputedHeight()??0}),tde=wba;var V_t=ze(tn(),1);import{spawn as VHa}from"child_process";var nt=ze(tn(),1);Nf();var fvr=ze(Mcr(),1);hIe();bIe();ML();ma();sT();Yv();$f();import{platform as CHa}from"os";import*as gm from"process";import{finished as Wvr}from"stream/promises";sxe();var OKe=ze(Sj(),1);uLe();TG();ma();import*as zcr from"node:fs/promises";import Dba from"node:os";import Dcr from"node:path";function oYe(){return process.execPath.endsWith("copilot")||process.execPath.endsWith("copilot.exe")}function zba(){try{let t=OKe.parse("0.0.378-2");return t!==null&&t.prerelease.length>0}catch{return!1}}function Pcr(t,e){return t||(e||zba()?"prerelease":"stable")}async function jcr(t,e="stable"){try{let n=await jba(e);if(!n)return;n.success?t.sendNotification(`Copilot CLI version ${n.version} downloaded. Restart to update.`):t.sendNotification(`Error auto updating: ${n.error}`)}catch(n){Qe.error(`Error auto updating: ${gt(n)}`)}}async function Pba(t){try{if(t==="prerelease"){let n=await r9("GET /repos/{owner}/{repo}/releases",{owner:"github",repo:"copilot-cli",per_page:1});if(n.data?.length===0){Qe.error("No releases found for auto-update");return}return n.data[0]}return(await r9("GET /repos/{owner}/{repo}/releases/latest",{owner:"github",repo:"copilot-cli"})).data}catch(e){Qe.error(`Failed to fetch latest release: ${gt(e)}`);return}}async function jba(t){if(!oYe())return;let e=await Pba(t);if(!e)return;if(OKe.lte(e.tag_name,"0.0.378-2")){Qe.info(`No update needed, current version is 0.0.378-2, fetched latest release is ${e.tag_name}`);return}let n=e.assets.find(I=>/github-copilot-[\d.]+(-[\w.]+)?\.tgz/.test(I.name));if(!n)return Qe.error(`No package asset found for auto-update to version ${e.tag_name}`),{success:!1,error:"No package asset found"};let r=await fetch(n.browser_download_url);if(!r.ok||!r.body)return Qe.error(`Failed to download package: ${r.status} ${r.statusText}`),{success:!1,error:`Failed to download package: ${r.status} ${r.statusText}`};let l=Buffer.from(await r.arrayBuffer()),a=Dcr.join(process.env.XDG_STATE_HOME||Dba.homedir(),".copilot","pkg","universal"),o=e.tag_name.startsWith("v")?e.tag_name.slice(1):e.tag_name,s=Dcr.join(a,`${o}`);try{return await zcr.mkdir(s,{recursive:!0}),await Kba(l,s),Qe.info(`Successfully downloaded package, restart to update to version ${o}`),{success:!0,version:o}}catch(I){return Qe.error(`Failed to download updated package: ${gt(I)}`),{success:!1,error:`Failed to download package: ${gt(I)}`}}}function Kba(t,e){let{resolve:n,reject:r,promise:l}=Promise.withResolvers(),a=A0e({cwd:e,strip:1});return a.write(t),a.end(),a.on("error",o=>r(o)),a.on("finish",()=>n()),l}TG();qB();TO();Lv();voe();au();P4();$V();qDe();Ps();Qre();var qba=_n({commandHistory:Dc(Gt())}),ZJt=G4e(qba.parse,"command-history");var $ba=50,NJt=class{commandHistory=[];historyIndex=-1;isNavigatingHistory=!1;unSubmittedCommand=null;async initialize(){try{let e=await ZJt.load();this.commandHistory=e?.commandHistory||[],this.resetNavigation()}catch{this.commandHistory=[]}}async addCommand(e){this.commandHistory=this.commandHistory.filter(n=>n!==e),this.commandHistory.unshift(e),this.commandHistory=this.commandHistory.slice(0,$ba),this.resetNavigation(),this.unSubmittedCommand=null,await this.saveHistory()}async updateCurrentCommand(e){this.historyIndex!==-1?(this.commandHistory[this.historyIndex]=e,await this.saveHistory()):this.unSubmittedCommand=e}navigateUp(e){if(this.commandHistory.length===0)return;let n=this.historyIndex+1;if(n<this.commandHistory.length){this.historyIndex=n,this.isNavigatingHistory=!0;let r=this.getCurrentHistoryItem();r&&e.setText(r)}}navigateDown(e){if(this.historyIndex===-1)return;if(this.historyIndex===0)this.resetNavigation();else{let r=this.historyIndex-1;this.historyIndex=r,this.isNavigatingHistory=!0}let n=this.getCurrentHistoryItem();n?(e.setText(n),e.setCursorPosition(0)):e.clear()}resetNavigation(){this.historyIndex=-1,this.isNavigatingHistory=!1}getHistoryIndex(){return this.historyIndex}getHistory(){return this.commandHistory}getCurrentHistoryItem(){return this.historyIndex===-1?this.unSubmittedCommand?this.unSubmittedCommand:void 0:this.commandHistory[this.historyIndex]}isNavigating(){return this.isNavigatingHistory}setNavigating(e){this.isNavigatingHistory=e}async saveHistory(){try{await ZJt.write({commandHistory:this.commandHistory})}catch{}}},C1=new NJt;JIe();var a5=ze(tn(),1);import{sep as SYe}from"path";function fJt(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var _8=fJt();function ndr(t){_8=t}var IYe={exec:()=>null};function nd(t,e=""){let n=typeof t=="string"?t:t.source,r={replace:(l,a)=>{let o=typeof a=="string"?a:a.source;return o=o.replace(yW.caret,"$1"),n=n.replace(l,o),r},getRegex:()=>new RegExp(n,e)};return r}var yW={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] /,listReplaceTask:/^\[[ xX]\] +/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:t=>new RegExp(`^( {0,3}${t})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}#`),htmlBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}<(?:[a-z].*>|!--)`,"i")},eha=/^(?:[ \t]*(?:\n|$))+/,tha=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,nha=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,cYe=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,rha=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,RJt=/(?:[*+-]|\d{1,9}[.)])/,rdr=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,ldr=nd(rdr).replace(/bull/g,RJt).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),lha=nd(rdr).replace(/bull/g,RJt).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),wJt=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,aha=/^[^\n]+/,YJt=/(?!\s*\])(?:\\.|[^\[\]\\])+/,oha=nd(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",YJt).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),sha=nd(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,RJt).getRegex(),PKe="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",vJt=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,iha=nd("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",vJt).replace("tag",PKe).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),adr=nd(wJt).replace("hr",cYe).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",PKe).getRegex(),Iha=nd(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",adr).getRegex(),VJt={blockquote:Iha,code:tha,def:oha,fences:nha,heading:rha,hr:cYe,html:iha,lheading:ldr,list:sha,newline:eha,paragraph:adr,table:IYe,text:aha},Kcr=nd("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",cYe).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",PKe).getRegex(),cha={...VJt,lheading:lha,table:Kcr,paragraph:nd(wJt).replace("hr",cYe).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Kcr).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",PKe).getRegex()},dha={...VJt,html:nd(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",vJt).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:IYe,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:nd(wJt).replace("hr",cYe).replace("heading",` *#{1,6} *[^
2952
+ `)n.name="enter";else if(t===" ")n.name="tab";else if(t==="\b"||t==="\x1B\b")n.name="backspace",n.meta=t.charAt(0)==="\x1B";else if(t==="\x7F"||t==="\x1B\x7F")n.name="delete",n.meta=t.charAt(0)==="\x1B";else if(t==="\x1B"||t==="\x1B\x1B")n.name="escape",n.meta=t.length===2;else if(t===" "||t==="\x1B ")n.name="space",n.meta=t.length===2;else if(t.length===1&&t<="")n.name=String.fromCharCode(t.charCodeAt(0)+97-1),n.ctrl=!0;else if(t.length===1&&t>="0"&&t<="9")n.name="number";else if(t.length===1&&t>="a"&&t<="z")n.name=t;else if(t.length===1&&t>="A"&&t<="Z")n.name=t.toLowerCase(),n.shift=!0;else if(e=bba.exec(t))n.meta=!0,n.shift=/^[A-Z]$/.test(e[1]);else if(e=hba.exec(t)){let r=[...t];r[0]==="\x1B"&&r[1]==="\x1B"&&(n.option=!0);let l=[e[1],e[2],e[4],e[6]].filter(Boolean).join(""),a=(e[3]||e[5]||1)-1;n.ctrl=!!(a&4),n.meta=!!(a&10),n.shift=!!(a&1),n.code=l,n.name=Acr[l],n.shift=Gba(l)||n.shift,n.ctrl=gba(l)||n.ctrl}return n},Ncr=Aba;var ycr=ze(tn(),1);var Zba=()=>(0,ycr.useContext)(kKe),ede=Zba;var Nba=(t,e={})=>{let{stdin:n,setRawMode:r,internal_exitOnCtrlC:l,internal_eventEmitter:a}=ede();(0,gJt.useEffect)(()=>{if(e.isActive!==!1)return r(!0),()=>{r(!1)}},[e.isActive,r]),(0,gJt.useEffect)(()=>{if(e.isActive===!1)return;let o=s=>{let I=Ncr(s),c={upArrow:I.name==="up",downArrow:I.name==="down",leftArrow:I.name==="left",rightArrow:I.name==="right",pageDown:I.name==="pagedown",pageUp:I.name==="pageup",return:I.name==="return",escape:I.name==="escape",ctrl:I.ctrl,shift:I.shift,tab:I.name==="tab",backspace:I.name==="backspace",delete:I.name==="delete",meta:I.meta||I.name==="escape"||I.option},d=I.ctrl?I.name:I.sequence;Zcr.includes(I.name)&&(d=""),d.startsWith("\x1B")&&(d=d.slice(1)),d.length===1&&typeof d[0]=="string"&&/[A-Z]/.test(d[0])&&(c.shift=!0),(!(d==="c"&&c.ctrl)||!l)&&GS.batchedUpdates(()=>{t(d,c)})};return a?.on("input",o),()=>{a?.removeListener("input",o)}},[e.isActive,n,l,t])},y_=Nba;var yba=ze(tn(),1);var Wcr=ze(tn(),1);var Wba=()=>(0,Wcr.useContext)(xKe),hg=Wba;var Eba=ze(tn(),1);var AJt=ze(tn(),1);var fba=ze(tn(),1);var Ecr=ze(tn(),1);var Rba=()=>{let{isScreenReaderEnabled:t}=(0,Ecr.useContext)(gS);return t},NS=Rba;var wba=t=>({width:t.yogaNode?.getComputedWidth()??0,height:t.yogaNode?.getComputedHeight()??0}),tde=wba;var V_t=ze(tn(),1);import{spawn as VHa}from"child_process";var nt=ze(tn(),1);Nf();var fvr=ze(Mcr(),1);hIe();bIe();ML();ma();sT();Yv();$f();import{platform as CHa}from"os";import*as gm from"process";import{finished as Wvr}from"stream/promises";sxe();var OKe=ze(Sj(),1);uLe();TG();ma();import*as zcr from"node:fs/promises";import Dba from"node:os";import Dcr from"node:path";function oYe(){return process.execPath.endsWith("copilot")||process.execPath.endsWith("copilot.exe")}function zba(){try{let t=OKe.parse("0.0.378");return t!==null&&t.prerelease.length>0}catch{return!1}}function Pcr(t,e){return t||(e||zba()?"prerelease":"stable")}async function jcr(t,e="stable"){try{let n=await jba(e);if(!n)return;n.success?t.sendNotification(`Copilot CLI version ${n.version} downloaded. Restart to update.`):t.sendNotification(`Error auto updating: ${n.error}`)}catch(n){Qe.error(`Error auto updating: ${gt(n)}`)}}async function Pba(t){try{if(t==="prerelease"){let n=await r9("GET /repos/{owner}/{repo}/releases",{owner:"github",repo:"copilot-cli",per_page:1});if(n.data?.length===0){Qe.error("No releases found for auto-update");return}return n.data[0]}return(await r9("GET /repos/{owner}/{repo}/releases/latest",{owner:"github",repo:"copilot-cli"})).data}catch(e){Qe.error(`Failed to fetch latest release: ${gt(e)}`);return}}async function jba(t){if(!oYe())return;let e=await Pba(t);if(!e)return;if(OKe.lte(e.tag_name,"0.0.378")){Qe.info(`No update needed, current version is 0.0.378, fetched latest release is ${e.tag_name}`);return}let n=e.assets.find(I=>/github-copilot-[\d.]+(-[\w.]+)?\.tgz/.test(I.name));if(!n)return Qe.error(`No package asset found for auto-update to version ${e.tag_name}`),{success:!1,error:"No package asset found"};let r=await fetch(n.browser_download_url);if(!r.ok||!r.body)return Qe.error(`Failed to download package: ${r.status} ${r.statusText}`),{success:!1,error:`Failed to download package: ${r.status} ${r.statusText}`};let l=Buffer.from(await r.arrayBuffer()),a=Dcr.join(process.env.XDG_STATE_HOME||Dba.homedir(),".copilot","pkg","universal"),o=e.tag_name.startsWith("v")?e.tag_name.slice(1):e.tag_name,s=Dcr.join(a,`${o}`);try{return await zcr.mkdir(s,{recursive:!0}),await Kba(l,s),Qe.info(`Successfully downloaded package, restart to update to version ${o}`),{success:!0,version:o}}catch(I){return Qe.error(`Failed to download updated package: ${gt(I)}`),{success:!1,error:`Failed to download package: ${gt(I)}`}}}function Kba(t,e){let{resolve:n,reject:r,promise:l}=Promise.withResolvers(),a=A0e({cwd:e,strip:1});return a.write(t),a.end(),a.on("error",o=>r(o)),a.on("finish",()=>n()),l}TG();qB();TO();Lv();voe();au();P4();$V();qDe();Ps();Qre();var qba=_n({commandHistory:Dc(Gt())}),ZJt=G4e(qba.parse,"command-history");var $ba=50,NJt=class{commandHistory=[];historyIndex=-1;isNavigatingHistory=!1;unSubmittedCommand=null;async initialize(){try{let e=await ZJt.load();this.commandHistory=e?.commandHistory||[],this.resetNavigation()}catch{this.commandHistory=[]}}async addCommand(e){this.commandHistory=this.commandHistory.filter(n=>n!==e),this.commandHistory.unshift(e),this.commandHistory=this.commandHistory.slice(0,$ba),this.resetNavigation(),this.unSubmittedCommand=null,await this.saveHistory()}async updateCurrentCommand(e){this.historyIndex!==-1?(this.commandHistory[this.historyIndex]=e,await this.saveHistory()):this.unSubmittedCommand=e}navigateUp(e){if(this.commandHistory.length===0)return;let n=this.historyIndex+1;if(n<this.commandHistory.length){this.historyIndex=n,this.isNavigatingHistory=!0;let r=this.getCurrentHistoryItem();r&&e.setText(r)}}navigateDown(e){if(this.historyIndex===-1)return;if(this.historyIndex===0)this.resetNavigation();else{let r=this.historyIndex-1;this.historyIndex=r,this.isNavigatingHistory=!0}let n=this.getCurrentHistoryItem();n?(e.setText(n),e.setCursorPosition(0)):e.clear()}resetNavigation(){this.historyIndex=-1,this.isNavigatingHistory=!1}getHistoryIndex(){return this.historyIndex}getHistory(){return this.commandHistory}getCurrentHistoryItem(){return this.historyIndex===-1?this.unSubmittedCommand?this.unSubmittedCommand:void 0:this.commandHistory[this.historyIndex]}isNavigating(){return this.isNavigatingHistory}setNavigating(e){this.isNavigatingHistory=e}async saveHistory(){try{await ZJt.write({commandHistory:this.commandHistory})}catch{}}},C1=new NJt;JIe();var a5=ze(tn(),1);import{sep as SYe}from"path";function fJt(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var _8=fJt();function ndr(t){_8=t}var IYe={exec:()=>null};function nd(t,e=""){let n=typeof t=="string"?t:t.source,r={replace:(l,a)=>{let o=typeof a=="string"?a:a.source;return o=o.replace(yW.caret,"$1"),n=n.replace(l,o),r},getRegex:()=>new RegExp(n,e)};return r}var yW={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] /,listReplaceTask:/^\[[ xX]\] +/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:t=>new RegExp(`^( {0,3}${t})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}#`),htmlBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}<(?:[a-z].*>|!--)`,"i")},eha=/^(?:[ \t]*(?:\n|$))+/,tha=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,nha=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,cYe=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,rha=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,RJt=/(?:[*+-]|\d{1,9}[.)])/,rdr=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,ldr=nd(rdr).replace(/bull/g,RJt).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),lha=nd(rdr).replace(/bull/g,RJt).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),wJt=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,aha=/^[^\n]+/,YJt=/(?!\s*\])(?:\\.|[^\[\]\\])+/,oha=nd(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",YJt).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),sha=nd(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,RJt).getRegex(),PKe="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",vJt=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,iha=nd("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",vJt).replace("tag",PKe).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),adr=nd(wJt).replace("hr",cYe).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",PKe).getRegex(),Iha=nd(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",adr).getRegex(),VJt={blockquote:Iha,code:tha,def:oha,fences:nha,heading:rha,hr:cYe,html:iha,lheading:ldr,list:sha,newline:eha,paragraph:adr,table:IYe,text:aha},Kcr=nd("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",cYe).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",PKe).getRegex(),cha={...VJt,lheading:lha,table:Kcr,paragraph:nd(wJt).replace("hr",cYe).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Kcr).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",PKe).getRegex()},dha={...VJt,html:nd(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",vJt).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:IYe,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:nd(wJt).replace("hr",cYe).replace("heading",` *#{1,6} *[^
2957
2953
  ]`).replace("lheading",ldr).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},uha=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,mha=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,odr=/^( {2,}|\\)\n(?!\s*$)/,pha=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,jKe=/[\p{P}\p{S}]/u,CJt=/[\s\p{P}\p{S}]/u,sdr=/[^\s\p{P}\p{S}]/u,bha=nd(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,CJt).getRegex(),idr=/(?!~)[\p{P}\p{S}]/u,hha=/(?!~)[\s\p{P}\p{S}]/u,Gha=/(?:[^\s\p{P}\p{S}]|~)/u,gha=/\[[^[\]]*?\]\((?:\\.|[^\\\(\)]|\((?:\\.|[^\\\(\)])*\))*\)|`[^`]*?`|<[^<>]*?>/g,Idr=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,Aha=nd(Idr,"u").replace(/punct/g,jKe).getRegex(),Zha=nd(Idr,"u").replace(/punct/g,idr).getRegex(),cdr="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Nha=nd(cdr,"gu").replace(/notPunctSpace/g,sdr).replace(/punctSpace/g,CJt).replace(/punct/g,jKe).getRegex(),yha=nd(cdr,"gu").replace(/notPunctSpace/g,Gha).replace(/punctSpace/g,hha).replace(/punct/g,idr).getRegex(),Wha=nd("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,sdr).replace(/punctSpace/g,CJt).replace(/punct/g,jKe).getRegex(),Eha=nd(/\\(punct)/,"gu").replace(/punct/g,jKe).getRegex(),fha=nd(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Rha=nd(vJt).replace("(?:-->|$)","-->").getRegex(),wha=nd("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",Rha).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),MKe=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,Yha=nd(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",MKe).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),ddr=nd(/^!?\[(label)\]\[(ref)\]/).replace("label",MKe).replace("ref",YJt).getRegex(),udr=nd(/^!?\[(ref)\](?:\[\])?/).replace("ref",YJt).getRegex(),vha=nd("reflink|nolink(?!\\()","g").replace("reflink",ddr).replace("nolink",udr).getRegex(),QJt={_backpedal:IYe,anyPunctuation:Eha,autolink:fha,blockSkip:gha,br:odr,code:mha,del:IYe,emStrongLDelim:Aha,emStrongRDelimAst:Nha,emStrongRDelimUnd:Wha,escape:uha,link:Yha,nolink:udr,punctuation:bha,reflink:ddr,reflinkSearch:vha,tag:wha,text:pha,url:IYe},Vha={...QJt,link:nd(/^!?\[(label)\]\((.*?)\)/).replace("label",MKe).getRegex(),reflink:nd(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",MKe).getRegex()},yJt={...QJt,emStrongRDelimAst:yha,emStrongLDelim:Zha,url:nd(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,"i").replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/},Cha={...yJt,br:nd(odr).replace("{2,}","*").getRegex(),text:nd(yJt.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},_Ke={normal:VJt,gfm:cha,pedantic:dha},sYe={normal:QJt,gfm:yJt,breaks:Cha,pedantic:Vha},Qha={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},qcr=t=>Qha[t];function $X(t,e){if(e){if(yW.escapeTest.test(t))return t.replace(yW.escapeReplace,qcr)}else if(yW.escapeTestNoEncode.test(t))return t.replace(yW.escapeReplaceNoEncode,qcr);return t}function $cr(t){try{t=encodeURI(t).replace(yW.percentDecode,"%")}catch{return null}return t}function edr(t,e){let n=t.replace(yW.findPipe,(a,o,s)=>{let I=!1,c=o;for(;--c>=0&&s[c]==="\\";)I=!I;return I?"|":" |"}),r=n.split(yW.splitPipe),l=0;if(r[0].trim()||r.shift(),r.length>0&&!r.at(-1)?.trim()&&r.pop(),e)if(r.length>e)r.splice(e);else for(;r.length<e;)r.push("");for(;l<r.length;l++)r[l]=r[l].trim().replace(yW.slashPipe,"|");return r}function iYe(t,e,n){let r=t.length;if(r===0)return"";let l=0;for(;l<r;){let a=t.charAt(r-l-1);if(a===e&&!n)l++;else if(a!==e&&n)l++;else break}return t.slice(0,r-l)}function Fha(t,e){if(t.indexOf(e[1])===-1)return-1;let n=0;for(let r=0;r<t.length;r++)if(t[r]==="\\")r++;else if(t[r]===e[0])n++;else if(t[r]===e[1]&&(n--,n<0))return r;return n>0?-2:-1}function tdr(t,e,n,r,l){let a=e.href,o=e.title||null,s=t[1].replace(l.other.outputLinkReplace,"$1");r.state.inLink=!0;let I={type:t[0].charAt(0)==="!"?"image":"link",raw:n,href:a,title:o,text:s,tokens:r.inlineTokens(s)};return r.state.inLink=!1,I}function Hha(t,e,n){let r=t.match(n.other.indentCodeCompensation);if(r===null)return e;let l=r[1];return e.split(`
2958
2954
  `).map(a=>{let o=a.match(n.other.beginningSpace);if(o===null)return a;let[s]=o;return s.length>=l.length?a.slice(l.length):a}).join(`
2959
2955
  `)}var DKe=class{options;rules;lexer;constructor(t){this.options=t||_8}space(t){let e=this.rules.block.newline.exec(t);if(e&&e[0].length>0)return{type:"space",raw:e[0]}}code(t){let e=this.rules.block.code.exec(t);if(e){let n=e[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:e[0],codeBlockStyle:"indented",text:this.options.pedantic?n:iYe(n,`
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.378-2",
4
+ "version": "0.0.378",
5
5
  "license": "SEE LICENSE IN LICENSE.md",
6
6
  "type": "module",
7
7
  "repository": {
@@ -42,14 +42,14 @@
42
42
  "definitions/**/*"
43
43
  ],
44
44
  "buildMetadata": {
45
- "gitCommit": "f66cd86"
45
+ "gitCommit": "30497b7"
46
46
  },
47
47
  "optionalDependencies": {
48
- "@github/copilot-linux-x64": "0.0.378-2",
49
- "@github/copilot-linux-arm64": "0.0.378-2",
50
- "@github/copilot-darwin-x64": "0.0.378-2",
51
- "@github/copilot-darwin-arm64": "0.0.378-2",
52
- "@github/copilot-win32-x64": "0.0.378-2",
53
- "@github/copilot-win32-arm64": "0.0.378-2"
48
+ "@github/copilot-linux-x64": "0.0.378",
49
+ "@github/copilot-linux-arm64": "0.0.378",
50
+ "@github/copilot-darwin-x64": "0.0.378",
51
+ "@github/copilot-darwin-arm64": "0.0.378",
52
+ "@github/copilot-win32-x64": "0.0.378",
53
+ "@github/copilot-win32-arm64": "0.0.378"
54
54
  }
55
55
  }
package/sdk/index.d.ts CHANGED
@@ -10172,8 +10172,6 @@ declare interface WorkspaceContextInfo {
10172
10172
  filesInWorkspace?: string[];
10173
10173
  /** List of checkpoints with their titles */
10174
10174
  checkpoints?: CheckpointInfo[];
10175
- /** Whether to show a plan update reminder */
10176
- showPlanReminder?: boolean;
10177
10175
  }
10178
10176
 
10179
10177
  /**
package/sdk/index.js CHANGED
@@ -1909,11 +1909,7 @@ Files (in files/):`;let o=10,c=l.slice(0,o);for(let i of c)a+=`
1909
1909
 
1910
1910
  For multi-step tasks, create plan.md to track progress.`),a+=`
1911
1911
 
1912
- files/ persists across checkpoints for artifacts that shouldn't be committed (e.g., architecture diagrams, task breakdowns, user preferences).`,t.showPlanReminder&&I&&(a+=`
1913
-
1914
- <reminder>
1915
- Consider updating plan.md to reflect current progress and next steps.
1916
- </reminder>`),a+=`
1912
+ files/ persists across checkpoints for artifacts that shouldn't be committed (e.g., architecture diagrams, task breakdowns, user preferences).`,a+=`
1917
1913
  </session_context>`,a}var _Kt=u(()=>{"use strict"});function TDe(t,e,I){return{kind:"telemetry",telemetry:{event:"workspace_checkpoint_read",properties:{sessionId:t,checkpointNumber:String(e)},restrictedProperties:{},metrics:{contentSizeBytes:I}}}}function jDe(t,e,I){return{kind:"telemetry",telemetry:{event:"workspace_plan_write",properties:{sessionId:t,operation:e},restrictedProperties:{},metrics:{contentSizeBytes:I}}}}function DDe(t,e){return{kind:"telemetry",telemetry:{event:"workspace_plan_read",properties:{sessionId:t},restrictedProperties:{},metrics:{contentSizeBytes:e}}}}function PDe(t,e,I,l){return{kind:"telemetry",telemetry:{event:"workspace_file_write",properties:{sessionId:t,relativePath:e,operation:I},restrictedProperties:{},metrics:{contentSizeBytes:l}}}}function KDe(t,e,I){return{kind:"telemetry",telemetry:{event:"workspace_file_read",properties:{sessionId:t,relativePath:e},restrictedProperties:{},metrics:{contentSizeBytes:I}}}}var qDe=u(()=>{"use strict"});var _De=u(()=>{"use strict";BDe();qKt();_Kt();qDe()});import{promises as Dpl}from"fs";import Ppl from"os";import{sep as Kpl}from"path";function nhl(t,e,I,l){let n=Ppl.type(),r=e===""?"":Fj(e);return Ihl.override({details:`You are working in the following environment. You do not need to make additional tool calls to verify this.
1918
1914
  * Current working directory: ${t}
1919
1915
  * Git repository root: ${r!==""?r:"Not a git repository"}
@@ -2090,11 +2086,12 @@ cwd: ${r.cwd}`);try{let s={...r,env:n};await this.registry.startLocalMcpClient(e
2090
2086
  CRITICAL: The following tools have been REMOVED and will FAIL if called: ${t.join(", ")}
2091
2087
 
2092
2088
  You MUST NOT attempt to call any of these tools. They no longer exist and any calls to them will result in an error. If you need functionality from these tools, explain to the user that the capability is no longer available.
2093
- </removed_tools_warning>`,yrI=({customAgentPrompt:t,problemStatement:e,capabilities:I,hasImages:l,handoffContext:n,removedTools:r})=>{let a=(I.vision&&l?dK(`
2089
+ </removed_tools_warning>`,yrI=({customAgentPrompt:t,problemStatement:e,capabilities:I,hasImages:l,handoffContext:n,removedTools:r,planReminder:s})=>{let c=[(I.vision&&l?dK(`
2094
2090
  The user mentioned images and they have been attached to this message in the order they were mentioned. You can view them with the ${zme}
2095
- `):"").trim()||void 0;return Gme.renderAs({repository_context:"raw",problem_statement:"raw"}).with({agent_instructions:t?`
2091
+ `):"").trim(),s?.trim()].filter(Boolean).join(`
2092
+ `)||void 0;return Gme.renderAs({repository_context:"raw",problem_statement:"raw"}).with({agent_instructions:t?`
2096
2093
  ${t}
2097
- `:"",problem_statement:e,repository_context:n,removed_tools_warning:r?.length?TAl(r):void 0,current_datetime:new Date().toISOString(),additional_instructions:a}).asXML().trim()},VrI=(t,e)=>Gme.with({problem_statement:"",agent_instructions:`
2094
+ `:"",problem_statement:e,repository_context:n,removed_tools_warning:r?.length?TAl(r):void 0,current_datetime:new Date().toISOString(),additional_instructions:c}).asXML().trim()},VrI=(t,e)=>Gme.with({problem_statement:"",agent_instructions:`
2098
2095
  ${t}
2099
2096
  `,current_datetime:new Date().toISOString(),additional_instructions:`In the <prompt> tag below, you will find the task you need to complete.
2100
2097
  When you have completed the task your response must include the following:
@@ -2220,18 +2217,9 @@ The summary should include the following parts:
2220
2217
  3. <work_done> - changes made, current state, and any issues encountered
2221
2218
  4. <technical_details> - key concepts, decisions, and quirks discovered
2222
2219
  5. <important_files> - files central to the work and why they matter
2223
- 6. <next_steps> - pending tasks and planned actions
2224
- ${t?`
2225
-
2226
- At the very end of your response, include a short descriptive title for this checkpoint:
2227
- CHECKPOINT_TITLE: [2-6 word description of the main work done in this segment]
2220
+ 6. <next_steps> - pending tasks and planned actions${t?`
2221
+ 7. <checkpoint_title> - 2-6 word description of the main work done`:""}
2228
2222
 
2229
- The title should be concise and descriptive, capturing the essence of what was accomplished in this specific work segment. Examples:
2230
- - "Implementing user authentication"
2231
- - "Fixing database connection bugs"
2232
- - "Refactoring payment module"
2233
- - "Adding unit tests for API"
2234
- `:""}
2235
2223
  ---
2236
2224
 
2237
2225
  ## Section Guidelines
@@ -2280,7 +2268,15 @@ List the files most central to the task, prioritizing those you've actively work
2280
2268
 
2281
2269
  If there's pending work, describe what you were actively working on when compaction occurred. List remaining tasks, outline your planned approach, and flag any blockers or open questions.
2282
2270
  If you've finished all requested work, you can simply note that no next steps are needed.
2271
+ ${t?`
2272
+ ### Checkpoint Title
2283
2273
 
2274
+ Provide a concise 2-6 word title capturing the essence of what was accomplished in this work segment. This title will be used to identify this checkpoint when reviewing session history. Examples:
2275
+ - "Implementing user authentication"
2276
+ - "Fixing database connection bugs"
2277
+ - "Refactoring payment module"
2278
+ - "Adding unit tests for API"
2279
+ `:""}
2284
2280
  ---
2285
2281
 
2286
2282
  ## Example
@@ -2340,7 +2336,7 @@ Immediate next steps:
2340
2336
 
2341
2337
  ---
2342
2338
 
2343
- Please write the summary now, following the structure and guidelines above. Be concise where possible, but don't sacrifice important context for brevity.${t?" Remember to include the <checkpoint_title> section at the very end.":""}`});function qAl(t,e,I=`
2339
+ Please write the summary now, following the structure and guidelines above. Be concise where possible, but don't sacrifice important context for brevity.`});function qAl(t,e,I=`
2344
2340
  ...<truncated>...
2345
2341
  `){if(t.length<=e)return t;let l=e-I.length;if(l<=0)return I;let n=Math.floor(l/2),r=l-n,s=t.slice(0,n),a=t.slice(t.length-r);return s+I+a}function _Al(t,e){if(t.length===0)return"";let l=`<user_message>
2346
2342
  ${t.join(`
@@ -2367,12 +2363,12 @@ Here is a summary of the prior context:
2367
2363
  <summary>
2368
2364
  ${e}
2369
2365
  </summary>
2370
- ${a}`},c=t.find(i=>i.role==="system");return c?[c,o]:[o]}function L2e(t,e){if(e.length===0||e[0].role!=="tool")return{adjustedCheckpoint:t,adjustedNew:e};let I=-1;for(let s=t.length-1;s>=0;s--){let a=t[s];if(a.role==="assistant"&&"tool_calls"in a&&a.tool_calls&&a.tool_calls.length>0){I=s;break}if(a.role!=="tool"&&a.role!=="assistant")break}if(I===-1)return{adjustedCheckpoint:t,adjustedNew:e};let l=t.slice(0,I),r=[...t.slice(I),...e];return{adjustedCheckpoint:l,adjustedNew:r}}function QrI(t,e){let I=See(t);return a0(I,e)}async function k2e(t,e,I,l,n){let r="",s=0,a=0,o=0,c=t.getCompletionWithTools(e,I,l,{stream:!1,processors:{preRequest:[new k2(n)]},...l.length>0?{toolChoice:"none"}:{}});for await(let i of c)i.kind==="response"&&i.response.content&&(r=typeof i.response.content=="string"?i.response.content:""),i.kind==="model_call_success"&&i.responseUsage&&(s=i.responseUsage.prompt_tokens||0,a=i.responseUsage.completion_tokens||0,o=i.responseUsage.prompt_tokens_details?.cached_tokens||0);if(!r)throw new Error("Compaction failed: received empty response from model");return{content:r,inputTokens:s,outputTokens:a,cachedInputTokens:o}}var KAl,X8e=u(()=>{"use strict";oB();v8e();eL();KAl=3e4});var x2e,vrI=u(()=>{"use strict";eL();X8e();L3e();x2e=class t{constructor(e,I){this.logger=e;this.backgroundThreshold=I.backgroundThreshold??aCt(),this.bufferExhaustionThreshold=I.bufferExhaustionThreshold??oCt(),this.minMessagesForCompaction=I.minMessagesForCompaction??t.DEFAULT_MIN_MESSAGES,this.getOriginalUserMessages=I.getOriginalUserMessages,this.getPlanContent=I.getPlanContent,this.getTodoContent=I.getTodoContent,this.shouldShowPlanReminder=I.shouldShowPlanReminder,this.onCompactionComplete=I.onCompactionComplete}static DEFAULT_BACKGROUND_THRESHOLD=.8;static DEFAULT_BUFFER_EXHAUSTION_THRESHOLD=.95;static DEFAULT_MIN_MESSAGES=6;static PLAN_REMINDER_THRESHOLD=.75;backgroundThreshold;bufferExhaustionThreshold;minMessagesForCompaction;getOriginalUserMessages;getPlanContent;getTodoContent;shouldShowPlanReminder;onCompactionComplete;pendingCompaction=null;lastCompactionStartTurn=null;planReminderShownAtTurn=null;toJSON(){return"CompactionProcessor"}async*preRequest(e){let{messages:I,modelInfo:l,toolDefinitions:n}=e,r=l.capabilities?.limits?.max_prompt_tokens||l.capabilities?.limits?.max_context_window_tokens||128e3,s=a0(I,l.name),a=ese(n,l.name),o=s+a,c=o/r;if(this.pendingCompaction){let i=this.checkCompactionCompleted();if(this.logger.debug(`CompactionProcessor: Checking pending compaction - completed: ${i}, has error: ${!!this.pendingCompaction.error}, has result: ${!!this.pendingCompaction.result}`),i){yield*this.applyCompactionResult(e);return}if(c>=this.bufferExhaustionThreshold){this.logger.info(`CompactionProcessor: Buffer exhausted at ${(c*100).toFixed(1)}% - waiting for compaction to complete...`),yield*this.waitForCompactionAndApply(e);return}this.logger.debug(`CompactionProcessor: Compaction in progress, utilization at ${(c*100).toFixed(1)}% - continuing with buffer space`);return}if(c<this.backgroundThreshold){this.logger.info(`CompactionProcessor: Utilization ${(c*100).toFixed(1)}% (${o}/${r} tokens) below threshold ${(this.backgroundThreshold*100).toFixed(0)}%`);return}if(this.lastCompactionStartTurn===e.turn){this.logger.debug("CompactionProcessor: Skipping - already started compaction this turn");return}if(I.length<this.minMessagesForCompaction){this.logger.info(`CompactionProcessor: Skipping - only ${I.length} messages (need at least ${this.minMessagesForCompaction}) at ${(c*100).toFixed(1)}% utilization`);return}this.logger.info(`CompactionProcessor: Context at ${(c*100).toFixed(1)}% utilization - starting background compaction...`),yield{kind:"compaction_started",turn:e.turn,performedBy:"CompactionProcessor"},this.startBackgroundCompaction(e,o),this.lastCompactionStartTurn=e.turn}checkCompactionCompleted(){return this.pendingCompaction?this.pendingCompaction.completed:!1}startBackgroundCompaction(e,I){let{messages:l,modelInfo:n}=e,r=[...l],s=this.getTodoContent?.()??null,a=l.find(m=>m.role==="system")?.content,o=typeof a=="string"?a:"";this.logger.debug(`CompactionProcessor: Sending ${l.length} messages for background compaction`);let c=!!this.getPlanContent,i=(async()=>{let m=See(l,c),b=await(this.getPlanContent?.()??Promise.resolve(null)),p=QrI(l,n.name);return{...await k2e(e.client,o,m,e.tools,this.logger),estimatedInputTokens:p,planContent:b}})(),G={promise:i.then(m=>({content:m.content,inputTokens:m.inputTokens,outputTokens:m.outputTokens,cachedInputTokens:m.cachedInputTokens})).catch(()=>new Promise(()=>{})),checkpointMessages:r,startTurn:e.turn,checkpointTokens:I,estimatedInputTokens:0,completed:!1,originalUserMessages:this.getOriginalUserMessages?.(),todoContent:s??void 0};i.then(m=>{this.logger.info("CompactionProcessor: Background compaction completed successfully"),G.completed=!0,G.result={content:m.content,inputTokens:m.inputTokens,outputTokens:m.outputTokens,cachedInputTokens:m.cachedInputTokens},G.estimatedInputTokens=m.estimatedInputTokens,G.planContent=m.planContent??void 0,this.onCompactionComplete({success:!0,startTurn:G.startTurn,summaryContent:m.content,checkpointMessagesLength:G.checkpointMessages.length,checkpointTokens:G.checkpointTokens,compactionTokensUsed:{input:m.inputTokens||m.estimatedInputTokens,output:m.outputTokens||0,cachedInput:m.cachedInputTokens||0}})}).catch(m=>{this.logger.error(`CompactionProcessor: Background compaction failed: ${m instanceof Error?m.message:String(m)}`),G.completed=!0,G.error=m,this.onCompactionComplete({success:!1,startTurn:G.startTurn,checkpointMessagesLength:G.checkpointMessages.length,checkpointTokens:G.checkpointTokens,error:m instanceof Error?m.message:String(m)})}),this.pendingCompaction=G}async*waitForCompactionAndApply(e){if(this.pendingCompaction){for(;!this.pendingCompaction.completed;)await new Promise(I=>setTimeout(I,50));yield*this.applyCompactionResult(e)}}async*applyCompactionResult(e){if(!this.pendingCompaction)return;let{messages:I,modelInfo:l}=e,n=this.pendingCompaction;if(n.error){this.handleCompactionFailure(e,n.error);return}let r=n.result;if(!r){this.handleCompactionFailure(e,new Error("Compaction completed but no result available"));return}let s=n.checkpointMessages.length,a=n.checkpointMessages,o=I.slice(s),c=L2e(a,o);a=c.adjustedCheckpoint,o=c.adjustedNew,this.logger.debug(`CompactionProcessor: Applying compaction - ${a.length} checkpoint messages (adjusted from ${s}), ${o.length} new messages`);let d=[...$B(a,r.content,n.originalUserMessages,{planContent:n.planContent,todoContent:n.todoContent}),...o],G=a0(d,l.name);I.splice(0,I.length,...d);let m=n.checkpointTokens-G;this.logger.info(`CompactionProcessor: Compaction complete - replaced ${n.checkpointMessages.length} messages with summary + ${o.length} new messages, saved ~${m} tokens`),this.pendingCompaction=null}handleCompactionFailure(e,I){this.logger.error(`CompactionProcessor: Compaction failed: ${I instanceof Error?I.message:String(I)}`);let l=I instanceof Error?I.cause:void 0;if(l&&typeof l=="object"){let n=l,r=n.ghRequestId||n.headers?.get?.("x-github-request-id")||n.requestID;this.logger.debug(`CompactionProcessor: API error details - status: ${n.status}, requestId: ${r}, message: ${n.message}`)}this.pendingCompaction=null}isCompacting(){return this.pendingCompaction!==null}getCompactionStartTurn(){return this.pendingCompaction?.startTurn??null}clearCompletedCompaction(){this.pendingCompaction?.completed&&(this.logger.debug("CompactionProcessor: Clearing completed compaction state at loop boundary"),this.pendingCompaction=null)}}});var S2e,XrI=u(()=>{"use strict";S2e=class{async exec(){return 0}async execReturn(){return{exitCode:0,stdout:"",stderr:""}}}});var asI=Y((Bee,ez)=>{var twl=200,zrI="__lodash_hash_undefined__",Iwl=800,lwl=16,UrI=9007199254740991,OrI="[object Arguments]",nwl="[object Array]",rwl="[object AsyncFunction]",swl="[object Boolean]",awl="[object Date]",owl="[object Error]",MrI="[object Function]",cwl="[object GeneratorFunction]",iwl="[object Map]",dwl="[object Number]",Gwl="[object Null]",TrI="[object Object]",mwl="[object Proxy]",uwl="[object RegExp]",bwl="[object Set]",pwl="[object String]",hwl="[object Undefined]",Zwl="[object WeakMap]",Wwl="[object ArrayBuffer]",Nwl="[object DataView]",gwl="[object Float32Array]",Ywl="[object Float64Array]",ywl="[object Int8Array]",Vwl="[object Int16Array]",Rwl="[object Int32Array]",Awl="[object Uint8Array]",wwl="[object Uint8ClampedArray]",Fwl="[object Uint16Array]",Ewl="[object Uint32Array]",Qwl=/[\\^$.*+?()[\]{}|]/g,vwl=/^\[object .+?Constructor\]$/,Xwl=/^(?:0|[1-9]\d*)$/,js={};js[gwl]=js[Ywl]=js[ywl]=js[Vwl]=js[Rwl]=js[Awl]=js[wwl]=js[Fwl]=js[Ewl]=!0;js[OrI]=js[nwl]=js[Wwl]=js[swl]=js[Nwl]=js[awl]=js[owl]=js[MrI]=js[iwl]=js[dwl]=js[TrI]=js[uwl]=js[bwl]=js[pwl]=js[Zwl]=!1;var jrI=typeof global=="object"&&global&&global.Object===Object&&global,Hwl=typeof self=="object"&&self&&self.Object===Object&&self,Oee=jrI||Hwl||Function("return this")(),DrI=typeof Bee=="object"&&Bee&&!Bee.nodeType&&Bee,zee=DrI&&typeof ez=="object"&&ez&&!ez.nodeType&&ez,PrI=zee&&zee.exports===DrI,H8e=PrI&&jrI.process,HrI=(function(){try{var t=zee&&zee.require&&zee.require("util").types;return t||H8e&&H8e.binding&&H8e.binding("util")}catch{}})(),CrI=HrI&&HrI.isTypedArray;function Cwl(t,e,I){switch(I.length){case 0:return t.call(e);case 1:return t.call(e,I[0]);case 2:return t.call(e,I[0],I[1]);case 3:return t.call(e,I[0],I[1],I[2])}return t.apply(e,I)}function fwl(t,e){for(var I=-1,l=Array(t);++I<t;)l[I]=e(I);return l}function Jwl(t){return function(e){return t(e)}}function Lwl(t,e){return t?.[e]}function kwl(t,e){return function(I){return t(e(I))}}var xwl=Array.prototype,Swl=Function.prototype,U2e=Object.prototype,C8e=Oee["__core-js_shared__"],O2e=Swl.toString,HV=U2e.hasOwnProperty,frI=(function(){var t=/[^.]+$/.exec(C8e&&C8e.keys&&C8e.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""})(),KrI=U2e.toString,Bwl=O2e.call(Object),zwl=RegExp("^"+O2e.call(HV).replace(Qwl,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),B2e=PrI?Oee.Buffer:void 0,JrI=Oee.Symbol,LrI=Oee.Uint8Array,krI=B2e?B2e.allocUnsafe:void 0,qrI=kwl(Object.getPrototypeOf,Object),xrI=Object.create,Uwl=U2e.propertyIsEnumerable,Owl=xwl.splice,Wf=JrI?JrI.toStringTag:void 0,z2e=(function(){try{var t=S8e(Object,"defineProperty");return t({},"",{}),t}catch{}})(),Mwl=B2e?B2e.isBuffer:void 0,SrI=Math.max,Twl=Date.now,_rI=S8e(Oee,"Map"),Uee=S8e(Object,"create"),jwl=(function(){function t(){}return function(e){if(!gf(e))return{};if(xrI)return xrI(e);t.prototype=e;var I=new t;return t.prototype=void 0,I}})();function Nf(t){var e=-1,I=t==null?0:t.length;for(this.clear();++e<I;){var l=t[e];this.set(l[0],l[1])}}function Dwl(){this.__data__=Uee?Uee(null):{},this.size=0}function Pwl(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}function Kwl(t){var e=this.__data__;if(Uee){var I=e[t];return I===zrI?void 0:I}return HV.call(e,t)?e[t]:void 0}function qwl(t){var e=this.__data__;return Uee?e[t]!==void 0:HV.call(e,t)}function _wl(t,e){var I=this.__data__;return this.size+=this.has(t)?0:1,I[t]=Uee&&e===void 0?zrI:e,this}Nf.prototype.clear=Dwl;Nf.prototype.delete=Pwl;Nf.prototype.get=Kwl;Nf.prototype.has=qwl;Nf.prototype.set=_wl;function CV(t){var e=-1,I=t==null?0:t.length;for(this.clear();++e<I;){var l=t[e];this.set(l[0],l[1])}}function $wl(){this.__data__=[],this.size=0}function eFl(t){var e=this.__data__,I=M2e(e,t);if(I<0)return!1;var l=e.length-1;return I==l?e.pop():Owl.call(e,I,1),--this.size,!0}function tFl(t){var e=this.__data__,I=M2e(e,t);return I<0?void 0:e[I][1]}function IFl(t){return M2e(this.__data__,t)>-1}function lFl(t,e){var I=this.__data__,l=M2e(I,t);return l<0?(++this.size,I.push([t,e])):I[l][1]=e,this}CV.prototype.clear=$wl;CV.prototype.delete=eFl;CV.prototype.get=tFl;CV.prototype.has=IFl;CV.prototype.set=lFl;function tz(t){var e=-1,I=t==null?0:t.length;for(this.clear();++e<I;){var l=t[e];this.set(l[0],l[1])}}function nFl(){this.size=0,this.__data__={hash:new Nf,map:new(_rI||CV),string:new Nf}}function rFl(t){var e=j2e(this,t).delete(t);return this.size-=e?1:0,e}function sFl(t){return j2e(this,t).get(t)}function aFl(t){return j2e(this,t).has(t)}function oFl(t,e){var I=j2e(this,t),l=I.size;return I.set(t,e),this.size+=I.size==l?0:1,this}tz.prototype.clear=nFl;tz.prototype.delete=rFl;tz.prototype.get=sFl;tz.prototype.has=aFl;tz.prototype.set=oFl;function Iz(t){var e=this.__data__=new CV(t);this.size=e.size}function cFl(){this.__data__=new CV,this.size=0}function iFl(t){var e=this.__data__,I=e.delete(t);return this.size=e.size,I}function dFl(t){return this.__data__.get(t)}function GFl(t){return this.__data__.has(t)}function mFl(t,e){var I=this.__data__;if(I instanceof CV){var l=I.__data__;if(!_rI||l.length<twl-1)return l.push([t,e]),this.size=++I.size,this;I=this.__data__=new tz(l)}return I.set(t,e),this.size=I.size,this}Iz.prototype.clear=cFl;Iz.prototype.delete=iFl;Iz.prototype.get=dFl;Iz.prototype.has=GFl;Iz.prototype.set=mFl;function uFl(t,e){var I=k8e(t),l=!I&&L8e(t),n=!I&&!l&&IsI(t),r=!I&&!l&&!n&&nsI(t),s=I||l||n||r,a=s?fwl(t.length,String):[],o=a.length;for(var c in t)(e||HV.call(t,c))&&!(s&&(c=="length"||n&&(c=="offset"||c=="parent")||r&&(c=="buffer"||c=="byteLength"||c=="byteOffset")||esI(c,o)))&&a.push(c);return a}function f8e(t,e,I){(I!==void 0&&!D2e(t[e],I)||I===void 0&&!(e in t))&&x8e(t,e,I)}function bFl(t,e,I){var l=t[e];(!(HV.call(t,e)&&D2e(l,I))||I===void 0&&!(e in t))&&x8e(t,e,I)}function M2e(t,e){for(var I=t.length;I--;)if(D2e(t[I][0],e))return I;return-1}function x8e(t,e,I){e=="__proto__"&&z2e?z2e(t,e,{configurable:!0,enumerable:!0,value:I,writable:!0}):t[e]=I}var pFl=EFl();function T2e(t){return t==null?t===void 0?hwl:Gwl:Wf&&Wf in Object(t)?QFl(t):JFl(t)}function BrI(t){return Mee(t)&&T2e(t)==OrI}function hFl(t){if(!gf(t)||CFl(t))return!1;var e=z8e(t)?zwl:vwl;return e.test(SFl(t))}function ZFl(t){return Mee(t)&&lsI(t.length)&&!!js[T2e(t)]}function WFl(t){if(!gf(t))return fFl(t);var e=tsI(t),I=[];for(var l in t)l=="constructor"&&(e||!HV.call(t,l))||I.push(l);return I}function $rI(t,e,I,l,n){t!==e&&pFl(e,function(r,s){if(n||(n=new Iz),gf(r))NFl(t,e,s,I,$rI,l,n);else{var a=l?l(J8e(t,s),r,s+"",t,e,n):void 0;a===void 0&&(a=r),f8e(t,s,a)}},rsI)}function NFl(t,e,I,l,n,r,s){var a=J8e(t,I),o=J8e(e,I),c=s.get(o);if(c){f8e(t,I,c);return}var i=r?r(a,o,I+"",t,e,s):void 0,d=i===void 0;if(d){var G=k8e(o),m=!G&&IsI(o),b=!G&&!m&&nsI(o);i=o,G||m||b?k8e(a)?i=a:BFl(a)?i=AFl(a):m?(d=!1,i=yFl(o,!0)):b?(d=!1,i=RFl(o,!0)):i=[]:zFl(o)||L8e(o)?(i=a,L8e(a)?i=UFl(a):(!gf(a)||z8e(a))&&(i=vFl(o))):d=!1}d&&(s.set(o,i),n(i,o,l,r,s),s.delete(o)),f8e(t,I,i)}function gFl(t,e){return kFl(LFl(t,e,ssI),t+"")}var YFl=z2e?function(t,e){return z2e(t,"toString",{configurable:!0,enumerable:!1,value:MFl(e),writable:!0})}:ssI;function yFl(t,e){if(e)return t.slice();var I=t.length,l=krI?krI(I):new t.constructor(I);return t.copy(l),l}function VFl(t){var e=new t.constructor(t.byteLength);return new LrI(e).set(new LrI(t)),e}function RFl(t,e){var I=e?VFl(t.buffer):t.buffer;return new t.constructor(I,t.byteOffset,t.length)}function AFl(t,e){var I=-1,l=t.length;for(e||(e=Array(l));++I<l;)e[I]=t[I];return e}function wFl(t,e,I,l){var n=!I;I||(I={});for(var r=-1,s=e.length;++r<s;){var a=e[r],o=l?l(I[a],t[a],a,I,t):void 0;o===void 0&&(o=t[a]),n?x8e(I,a,o):bFl(I,a,o)}return I}function FFl(t){return gFl(function(e,I){var l=-1,n=I.length,r=n>1?I[n-1]:void 0,s=n>2?I[2]:void 0;for(r=t.length>3&&typeof r=="function"?(n--,r):void 0,s&&XFl(I[0],I[1],s)&&(r=n<3?void 0:r,n=1),e=Object(e);++l<n;){var a=I[l];a&&t(e,a,l,r)}return e})}function EFl(t){return function(e,I,l){for(var n=-1,r=Object(e),s=l(e),a=s.length;a--;){var o=s[t?a:++n];if(I(r[o],o,r)===!1)break}return e}}function j2e(t,e){var I=t.__data__;return HFl(e)?I[typeof e=="string"?"string":"hash"]:I.map}function S8e(t,e){var I=Lwl(t,e);return hFl(I)?I:void 0}function QFl(t){var e=HV.call(t,Wf),I=t[Wf];try{t[Wf]=void 0;var l=!0}catch{}var n=KrI.call(t);return l&&(e?t[Wf]=I:delete t[Wf]),n}function vFl(t){return typeof t.constructor=="function"&&!tsI(t)?jwl(qrI(t)):{}}function esI(t,e){var I=typeof t;return e=e??UrI,!!e&&(I=="number"||I!="symbol"&&Xwl.test(t))&&t>-1&&t%1==0&&t<e}function XFl(t,e,I){if(!gf(I))return!1;var l=typeof e;return(l=="number"?B8e(I)&&esI(e,I.length):l=="string"&&e in I)?D2e(I[e],t):!1}function HFl(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}function CFl(t){return!!frI&&frI in t}function tsI(t){var e=t&&t.constructor,I=typeof e=="function"&&e.prototype||U2e;return t===I}function fFl(t){var e=[];if(t!=null)for(var I in Object(t))e.push(I);return e}function JFl(t){return KrI.call(t)}function LFl(t,e,I){return e=SrI(e===void 0?t.length-1:e,0),function(){for(var l=arguments,n=-1,r=SrI(l.length-e,0),s=Array(r);++n<r;)s[n]=l[e+n];n=-1;for(var a=Array(e+1);++n<e;)a[n]=l[n];return a[e]=I(s),Cwl(t,this,a)}}function J8e(t,e){if(!(e==="constructor"&&typeof t[e]=="function")&&e!="__proto__")return t[e]}var kFl=xFl(YFl);function xFl(t){var e=0,I=0;return function(){var l=Twl(),n=lwl-(l-I);if(I=l,n>0){if(++e>=Iwl)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}function SFl(t){if(t!=null){try{return O2e.call(t)}catch{}try{return t+""}catch{}}return""}function D2e(t,e){return t===e||t!==t&&e!==e}var L8e=BrI((function(){return arguments})())?BrI:function(t){return Mee(t)&&HV.call(t,"callee")&&!Uwl.call(t,"callee")},k8e=Array.isArray;function B8e(t){return t!=null&&lsI(t.length)&&!z8e(t)}function BFl(t){return Mee(t)&&B8e(t)}var IsI=Mwl||TFl;function z8e(t){if(!gf(t))return!1;var e=T2e(t);return e==MrI||e==cwl||e==rwl||e==mwl}function lsI(t){return typeof t=="number"&&t>-1&&t%1==0&&t<=UrI}function gf(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}function Mee(t){return t!=null&&typeof t=="object"}function zFl(t){if(!Mee(t)||T2e(t)!=TrI)return!1;var e=qrI(t);if(e===null)return!0;var I=HV.call(e,"constructor")&&e.constructor;return typeof I=="function"&&I instanceof I&&O2e.call(I)==Bwl}var nsI=CrI?Jwl(CrI):ZFl;function UFl(t){return wFl(t,rsI(t))}function rsI(t){return B8e(t)?uFl(t,!0):WFl(t)}var OFl=FFl(function(t,e,I){$rI(t,e,I)});function MFl(t){return function(){return t}}function ssI(t){return t}function TFl(){return!1}ez.exports=OFl});async function jFl(t={}){let e=await Itt();return jet((0,osI.default)({},e,t))}async function U8e(t={}){if(VIe())throw new Error("Settings have already been initialized");return jFl(t)}var osI,csI=u(()=>{"use strict";osI=dI(asI(),1);RIe();_z()});import{readdir as DFl,stat as PFl}from"fs/promises";async function KFl(t,e){try{let I=await PFl(t);if(I.isDirectory()){let l=await DFl(t);return{path:t,type:"directory",lines:l.length}}else{let l=I.size/1048576;if(I.size>isI){let r=(isI/1048576).toFixed(0);return e.debug(`File ${t} is too large (${l.toFixed(1)}MB). Maximum file size is ${r}MB. Skipping line count.`),{path:t,type:"file",sizeMB:l}}let{totalLineCount:n}=await rse(t,1,void 0);return{path:t,type:"file",lines:n}}}catch(I){return e.debug(`Error getting file info for ${t}: ${Ye(I)}`),{path:t,type:"file",error:Ye(I)}}}async function dsI(t,e){let I=t.filter(r=>!Bw(r.path));if(I.length===0)return"";let l=await Promise.all(I.map(r=>KFl(r.path,e))),n=["<tagged_files>"];for(let r of l)r.error?n.push(`* ${r.path} (error: ${r.error})`):r.sizeMB!==void 0?n.push(`* ${r.path} (large file: ${r.sizeMB.toFixed(1)}MB)`):r.type==="directory"?n.push(`* ${r.path} (${r.lines} entries)`):n.push(`* ${r.path} (${r.lines} lines)`);return n.push("</tagged_files>"),n.join(`
2366
+ ${a}`},c=t.find(i=>i.role==="system");return c?[c,o]:[o]}function L2e(t,e){if(e.length===0||e[0].role!=="tool")return{adjustedCheckpoint:t,adjustedNew:e};let I=-1;for(let s=t.length-1;s>=0;s--){let a=t[s];if(a.role==="assistant"&&"tool_calls"in a&&a.tool_calls&&a.tool_calls.length>0){I=s;break}if(a.role!=="tool"&&a.role!=="assistant")break}if(I===-1)return{adjustedCheckpoint:t,adjustedNew:e};let l=t.slice(0,I),r=[...t.slice(I),...e];return{adjustedCheckpoint:l,adjustedNew:r}}function QrI(t,e){let I=See(t);return a0(I,e)}async function k2e(t,e,I,l,n){let r="",s=0,a=0,o=0,c=t.getCompletionWithTools(e,I,l,{stream:!1,processors:{preRequest:[new k2(n)]},...l.length>0?{toolChoice:"none"}:{}});for await(let i of c)i.kind==="response"&&i.response.content&&(r=typeof i.response.content=="string"?i.response.content:""),i.kind==="model_call_success"&&i.responseUsage&&(s=i.responseUsage.prompt_tokens||0,a=i.responseUsage.completion_tokens||0,o=i.responseUsage.prompt_tokens_details?.cached_tokens||0);if(!r)throw new Error("Compaction failed: received empty response from model");return{content:r,inputTokens:s,outputTokens:a,cachedInputTokens:o}}var KAl,X8e=u(()=>{"use strict";oB();v8e();eL();KAl=3e4});var x2e,vrI=u(()=>{"use strict";eL();X8e();L3e();x2e=class t{constructor(e,I){this.logger=e;this.backgroundThreshold=I.backgroundThreshold??aCt(),this.bufferExhaustionThreshold=I.bufferExhaustionThreshold??oCt(),this.minMessagesForCompaction=I.minMessagesForCompaction??t.DEFAULT_MIN_MESSAGES,this.getOriginalUserMessages=I.getOriginalUserMessages,this.getPlanContent=I.getPlanContent,this.getTodoContent=I.getTodoContent,this.onCompactionComplete=I.onCompactionComplete}static DEFAULT_BACKGROUND_THRESHOLD=.8;static DEFAULT_BUFFER_EXHAUSTION_THRESHOLD=.95;static DEFAULT_MIN_MESSAGES=6;backgroundThreshold;bufferExhaustionThreshold;minMessagesForCompaction;getOriginalUserMessages;getPlanContent;getTodoContent;onCompactionComplete;pendingCompaction=null;lastCompactionStartTurn=null;toJSON(){return"CompactionProcessor"}async*preRequest(e){let{messages:I,modelInfo:l,toolDefinitions:n}=e,r=l.capabilities?.limits?.max_prompt_tokens||l.capabilities?.limits?.max_context_window_tokens||128e3,s=a0(I,l.name),a=ese(n,l.name),o=s+a,c=o/r;if(this.pendingCompaction){let i=this.checkCompactionCompleted();if(this.logger.debug(`CompactionProcessor: Checking pending compaction - completed: ${i}, has error: ${!!this.pendingCompaction.error}, has result: ${!!this.pendingCompaction.result}`),i){yield*this.applyCompactionResult(e);return}if(c>=this.bufferExhaustionThreshold){this.logger.info(`CompactionProcessor: Buffer exhausted at ${(c*100).toFixed(1)}% - waiting for compaction to complete...`),yield*this.waitForCompactionAndApply(e);return}this.logger.debug(`CompactionProcessor: Compaction in progress, utilization at ${(c*100).toFixed(1)}% - continuing with buffer space`);return}if(c<this.backgroundThreshold){this.logger.info(`CompactionProcessor: Utilization ${(c*100).toFixed(1)}% (${o}/${r} tokens) below threshold ${(this.backgroundThreshold*100).toFixed(0)}%`);return}if(this.lastCompactionStartTurn===e.turn){this.logger.debug("CompactionProcessor: Skipping - already started compaction this turn");return}if(I.length<this.minMessagesForCompaction){this.logger.info(`CompactionProcessor: Skipping - only ${I.length} messages (need at least ${this.minMessagesForCompaction}) at ${(c*100).toFixed(1)}% utilization`);return}this.logger.info(`CompactionProcessor: Context at ${(c*100).toFixed(1)}% utilization - starting background compaction...`),yield{kind:"compaction_started",turn:e.turn,performedBy:"CompactionProcessor"},this.startBackgroundCompaction(e,o),this.lastCompactionStartTurn=e.turn}checkCompactionCompleted(){return this.pendingCompaction?this.pendingCompaction.completed:!1}startBackgroundCompaction(e,I){let{messages:l,modelInfo:n}=e,r=[...l],s=this.getTodoContent?.()??null,a=l.find(m=>m.role==="system")?.content,o=typeof a=="string"?a:"";this.logger.debug(`CompactionProcessor: Sending ${l.length} messages for background compaction`);let c=!!this.getPlanContent,i=(async()=>{let m=See(l,c),b=await(this.getPlanContent?.()??Promise.resolve(null)),p=QrI(l,n.name);return{...await k2e(e.client,o,m,e.tools,this.logger),estimatedInputTokens:p,planContent:b}})(),G={promise:i.then(m=>({content:m.content,inputTokens:m.inputTokens,outputTokens:m.outputTokens,cachedInputTokens:m.cachedInputTokens})).catch(()=>new Promise(()=>{})),checkpointMessages:r,startTurn:e.turn,checkpointTokens:I,estimatedInputTokens:0,completed:!1,originalUserMessages:this.getOriginalUserMessages?.(),todoContent:s??void 0};i.then(m=>{this.logger.info("CompactionProcessor: Background compaction completed successfully"),G.completed=!0,G.result={content:m.content,inputTokens:m.inputTokens,outputTokens:m.outputTokens,cachedInputTokens:m.cachedInputTokens},G.estimatedInputTokens=m.estimatedInputTokens,G.planContent=m.planContent??void 0,this.onCompactionComplete({success:!0,startTurn:G.startTurn,summaryContent:m.content,checkpointMessagesLength:G.checkpointMessages.length,checkpointTokens:G.checkpointTokens,compactionTokensUsed:{input:m.inputTokens||m.estimatedInputTokens,output:m.outputTokens||0,cachedInput:m.cachedInputTokens||0}})}).catch(m=>{this.logger.error(`CompactionProcessor: Background compaction failed: ${m instanceof Error?m.message:String(m)}`),G.completed=!0,G.error=m,this.onCompactionComplete({success:!1,startTurn:G.startTurn,checkpointMessagesLength:G.checkpointMessages.length,checkpointTokens:G.checkpointTokens,error:m instanceof Error?m.message:String(m)})}),this.pendingCompaction=G}async*waitForCompactionAndApply(e){if(this.pendingCompaction){for(;!this.pendingCompaction.completed;)await new Promise(I=>setTimeout(I,50));yield*this.applyCompactionResult(e)}}async*applyCompactionResult(e){if(!this.pendingCompaction)return;let{messages:I,modelInfo:l}=e,n=this.pendingCompaction;if(n.error){this.handleCompactionFailure(e,n.error);return}let r=n.result;if(!r){this.handleCompactionFailure(e,new Error("Compaction completed but no result available"));return}let s=n.checkpointMessages.length,a=n.checkpointMessages,o=I.slice(s),c=L2e(a,o);a=c.adjustedCheckpoint,o=c.adjustedNew,this.logger.debug(`CompactionProcessor: Applying compaction - ${a.length} checkpoint messages (adjusted from ${s}), ${o.length} new messages`);let d=[...$B(a,r.content,n.originalUserMessages,{planContent:n.planContent,todoContent:n.todoContent}),...o],G=a0(d,l.name);I.splice(0,I.length,...d);let m=n.checkpointTokens-G;this.logger.info(`CompactionProcessor: Compaction complete - replaced ${n.checkpointMessages.length} messages with summary + ${o.length} new messages, saved ~${m} tokens`),this.pendingCompaction=null}handleCompactionFailure(e,I){this.logger.error(`CompactionProcessor: Compaction failed: ${I instanceof Error?I.message:String(I)}`);let l=I instanceof Error?I.cause:void 0;if(l&&typeof l=="object"){let n=l,r=n.ghRequestId||n.headers?.get?.("x-github-request-id")||n.requestID;this.logger.debug(`CompactionProcessor: API error details - status: ${n.status}, requestId: ${r}, message: ${n.message}`)}this.pendingCompaction=null}isCompacting(){return this.pendingCompaction!==null}getCompactionStartTurn(){return this.pendingCompaction?.startTurn??null}clearCompletedCompaction(){this.pendingCompaction?.completed&&(this.logger.debug("CompactionProcessor: Clearing completed compaction state at loop boundary"),this.pendingCompaction=null)}}});var S2e,XrI=u(()=>{"use strict";S2e=class{async exec(){return 0}async execReturn(){return{exitCode:0,stdout:"",stderr:""}}}});var asI=Y((Bee,ez)=>{var twl=200,zrI="__lodash_hash_undefined__",Iwl=800,lwl=16,UrI=9007199254740991,OrI="[object Arguments]",nwl="[object Array]",rwl="[object AsyncFunction]",swl="[object Boolean]",awl="[object Date]",owl="[object Error]",MrI="[object Function]",cwl="[object GeneratorFunction]",iwl="[object Map]",dwl="[object Number]",Gwl="[object Null]",TrI="[object Object]",mwl="[object Proxy]",uwl="[object RegExp]",bwl="[object Set]",pwl="[object String]",hwl="[object Undefined]",Zwl="[object WeakMap]",Wwl="[object ArrayBuffer]",Nwl="[object DataView]",gwl="[object Float32Array]",Ywl="[object Float64Array]",ywl="[object Int8Array]",Vwl="[object Int16Array]",Rwl="[object Int32Array]",Awl="[object Uint8Array]",wwl="[object Uint8ClampedArray]",Fwl="[object Uint16Array]",Ewl="[object Uint32Array]",Qwl=/[\\^$.*+?()[\]{}|]/g,vwl=/^\[object .+?Constructor\]$/,Xwl=/^(?:0|[1-9]\d*)$/,js={};js[gwl]=js[Ywl]=js[ywl]=js[Vwl]=js[Rwl]=js[Awl]=js[wwl]=js[Fwl]=js[Ewl]=!0;js[OrI]=js[nwl]=js[Wwl]=js[swl]=js[Nwl]=js[awl]=js[owl]=js[MrI]=js[iwl]=js[dwl]=js[TrI]=js[uwl]=js[bwl]=js[pwl]=js[Zwl]=!1;var jrI=typeof global=="object"&&global&&global.Object===Object&&global,Hwl=typeof self=="object"&&self&&self.Object===Object&&self,Oee=jrI||Hwl||Function("return this")(),DrI=typeof Bee=="object"&&Bee&&!Bee.nodeType&&Bee,zee=DrI&&typeof ez=="object"&&ez&&!ez.nodeType&&ez,PrI=zee&&zee.exports===DrI,H8e=PrI&&jrI.process,HrI=(function(){try{var t=zee&&zee.require&&zee.require("util").types;return t||H8e&&H8e.binding&&H8e.binding("util")}catch{}})(),CrI=HrI&&HrI.isTypedArray;function Cwl(t,e,I){switch(I.length){case 0:return t.call(e);case 1:return t.call(e,I[0]);case 2:return t.call(e,I[0],I[1]);case 3:return t.call(e,I[0],I[1],I[2])}return t.apply(e,I)}function fwl(t,e){for(var I=-1,l=Array(t);++I<t;)l[I]=e(I);return l}function Jwl(t){return function(e){return t(e)}}function Lwl(t,e){return t?.[e]}function kwl(t,e){return function(I){return t(e(I))}}var xwl=Array.prototype,Swl=Function.prototype,U2e=Object.prototype,C8e=Oee["__core-js_shared__"],O2e=Swl.toString,HV=U2e.hasOwnProperty,frI=(function(){var t=/[^.]+$/.exec(C8e&&C8e.keys&&C8e.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""})(),KrI=U2e.toString,Bwl=O2e.call(Object),zwl=RegExp("^"+O2e.call(HV).replace(Qwl,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),B2e=PrI?Oee.Buffer:void 0,JrI=Oee.Symbol,LrI=Oee.Uint8Array,krI=B2e?B2e.allocUnsafe:void 0,qrI=kwl(Object.getPrototypeOf,Object),xrI=Object.create,Uwl=U2e.propertyIsEnumerable,Owl=xwl.splice,Wf=JrI?JrI.toStringTag:void 0,z2e=(function(){try{var t=S8e(Object,"defineProperty");return t({},"",{}),t}catch{}})(),Mwl=B2e?B2e.isBuffer:void 0,SrI=Math.max,Twl=Date.now,_rI=S8e(Oee,"Map"),Uee=S8e(Object,"create"),jwl=(function(){function t(){}return function(e){if(!gf(e))return{};if(xrI)return xrI(e);t.prototype=e;var I=new t;return t.prototype=void 0,I}})();function Nf(t){var e=-1,I=t==null?0:t.length;for(this.clear();++e<I;){var l=t[e];this.set(l[0],l[1])}}function Dwl(){this.__data__=Uee?Uee(null):{},this.size=0}function Pwl(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}function Kwl(t){var e=this.__data__;if(Uee){var I=e[t];return I===zrI?void 0:I}return HV.call(e,t)?e[t]:void 0}function qwl(t){var e=this.__data__;return Uee?e[t]!==void 0:HV.call(e,t)}function _wl(t,e){var I=this.__data__;return this.size+=this.has(t)?0:1,I[t]=Uee&&e===void 0?zrI:e,this}Nf.prototype.clear=Dwl;Nf.prototype.delete=Pwl;Nf.prototype.get=Kwl;Nf.prototype.has=qwl;Nf.prototype.set=_wl;function CV(t){var e=-1,I=t==null?0:t.length;for(this.clear();++e<I;){var l=t[e];this.set(l[0],l[1])}}function $wl(){this.__data__=[],this.size=0}function eFl(t){var e=this.__data__,I=M2e(e,t);if(I<0)return!1;var l=e.length-1;return I==l?e.pop():Owl.call(e,I,1),--this.size,!0}function tFl(t){var e=this.__data__,I=M2e(e,t);return I<0?void 0:e[I][1]}function IFl(t){return M2e(this.__data__,t)>-1}function lFl(t,e){var I=this.__data__,l=M2e(I,t);return l<0?(++this.size,I.push([t,e])):I[l][1]=e,this}CV.prototype.clear=$wl;CV.prototype.delete=eFl;CV.prototype.get=tFl;CV.prototype.has=IFl;CV.prototype.set=lFl;function tz(t){var e=-1,I=t==null?0:t.length;for(this.clear();++e<I;){var l=t[e];this.set(l[0],l[1])}}function nFl(){this.size=0,this.__data__={hash:new Nf,map:new(_rI||CV),string:new Nf}}function rFl(t){var e=j2e(this,t).delete(t);return this.size-=e?1:0,e}function sFl(t){return j2e(this,t).get(t)}function aFl(t){return j2e(this,t).has(t)}function oFl(t,e){var I=j2e(this,t),l=I.size;return I.set(t,e),this.size+=I.size==l?0:1,this}tz.prototype.clear=nFl;tz.prototype.delete=rFl;tz.prototype.get=sFl;tz.prototype.has=aFl;tz.prototype.set=oFl;function Iz(t){var e=this.__data__=new CV(t);this.size=e.size}function cFl(){this.__data__=new CV,this.size=0}function iFl(t){var e=this.__data__,I=e.delete(t);return this.size=e.size,I}function dFl(t){return this.__data__.get(t)}function GFl(t){return this.__data__.has(t)}function mFl(t,e){var I=this.__data__;if(I instanceof CV){var l=I.__data__;if(!_rI||l.length<twl-1)return l.push([t,e]),this.size=++I.size,this;I=this.__data__=new tz(l)}return I.set(t,e),this.size=I.size,this}Iz.prototype.clear=cFl;Iz.prototype.delete=iFl;Iz.prototype.get=dFl;Iz.prototype.has=GFl;Iz.prototype.set=mFl;function uFl(t,e){var I=k8e(t),l=!I&&L8e(t),n=!I&&!l&&IsI(t),r=!I&&!l&&!n&&nsI(t),s=I||l||n||r,a=s?fwl(t.length,String):[],o=a.length;for(var c in t)(e||HV.call(t,c))&&!(s&&(c=="length"||n&&(c=="offset"||c=="parent")||r&&(c=="buffer"||c=="byteLength"||c=="byteOffset")||esI(c,o)))&&a.push(c);return a}function f8e(t,e,I){(I!==void 0&&!D2e(t[e],I)||I===void 0&&!(e in t))&&x8e(t,e,I)}function bFl(t,e,I){var l=t[e];(!(HV.call(t,e)&&D2e(l,I))||I===void 0&&!(e in t))&&x8e(t,e,I)}function M2e(t,e){for(var I=t.length;I--;)if(D2e(t[I][0],e))return I;return-1}function x8e(t,e,I){e=="__proto__"&&z2e?z2e(t,e,{configurable:!0,enumerable:!0,value:I,writable:!0}):t[e]=I}var pFl=EFl();function T2e(t){return t==null?t===void 0?hwl:Gwl:Wf&&Wf in Object(t)?QFl(t):JFl(t)}function BrI(t){return Mee(t)&&T2e(t)==OrI}function hFl(t){if(!gf(t)||CFl(t))return!1;var e=z8e(t)?zwl:vwl;return e.test(SFl(t))}function ZFl(t){return Mee(t)&&lsI(t.length)&&!!js[T2e(t)]}function WFl(t){if(!gf(t))return fFl(t);var e=tsI(t),I=[];for(var l in t)l=="constructor"&&(e||!HV.call(t,l))||I.push(l);return I}function $rI(t,e,I,l,n){t!==e&&pFl(e,function(r,s){if(n||(n=new Iz),gf(r))NFl(t,e,s,I,$rI,l,n);else{var a=l?l(J8e(t,s),r,s+"",t,e,n):void 0;a===void 0&&(a=r),f8e(t,s,a)}},rsI)}function NFl(t,e,I,l,n,r,s){var a=J8e(t,I),o=J8e(e,I),c=s.get(o);if(c){f8e(t,I,c);return}var i=r?r(a,o,I+"",t,e,s):void 0,d=i===void 0;if(d){var G=k8e(o),m=!G&&IsI(o),b=!G&&!m&&nsI(o);i=o,G||m||b?k8e(a)?i=a:BFl(a)?i=AFl(a):m?(d=!1,i=yFl(o,!0)):b?(d=!1,i=RFl(o,!0)):i=[]:zFl(o)||L8e(o)?(i=a,L8e(a)?i=UFl(a):(!gf(a)||z8e(a))&&(i=vFl(o))):d=!1}d&&(s.set(o,i),n(i,o,l,r,s),s.delete(o)),f8e(t,I,i)}function gFl(t,e){return kFl(LFl(t,e,ssI),t+"")}var YFl=z2e?function(t,e){return z2e(t,"toString",{configurable:!0,enumerable:!1,value:MFl(e),writable:!0})}:ssI;function yFl(t,e){if(e)return t.slice();var I=t.length,l=krI?krI(I):new t.constructor(I);return t.copy(l),l}function VFl(t){var e=new t.constructor(t.byteLength);return new LrI(e).set(new LrI(t)),e}function RFl(t,e){var I=e?VFl(t.buffer):t.buffer;return new t.constructor(I,t.byteOffset,t.length)}function AFl(t,e){var I=-1,l=t.length;for(e||(e=Array(l));++I<l;)e[I]=t[I];return e}function wFl(t,e,I,l){var n=!I;I||(I={});for(var r=-1,s=e.length;++r<s;){var a=e[r],o=l?l(I[a],t[a],a,I,t):void 0;o===void 0&&(o=t[a]),n?x8e(I,a,o):bFl(I,a,o)}return I}function FFl(t){return gFl(function(e,I){var l=-1,n=I.length,r=n>1?I[n-1]:void 0,s=n>2?I[2]:void 0;for(r=t.length>3&&typeof r=="function"?(n--,r):void 0,s&&XFl(I[0],I[1],s)&&(r=n<3?void 0:r,n=1),e=Object(e);++l<n;){var a=I[l];a&&t(e,a,l,r)}return e})}function EFl(t){return function(e,I,l){for(var n=-1,r=Object(e),s=l(e),a=s.length;a--;){var o=s[t?a:++n];if(I(r[o],o,r)===!1)break}return e}}function j2e(t,e){var I=t.__data__;return HFl(e)?I[typeof e=="string"?"string":"hash"]:I.map}function S8e(t,e){var I=Lwl(t,e);return hFl(I)?I:void 0}function QFl(t){var e=HV.call(t,Wf),I=t[Wf];try{t[Wf]=void 0;var l=!0}catch{}var n=KrI.call(t);return l&&(e?t[Wf]=I:delete t[Wf]),n}function vFl(t){return typeof t.constructor=="function"&&!tsI(t)?jwl(qrI(t)):{}}function esI(t,e){var I=typeof t;return e=e??UrI,!!e&&(I=="number"||I!="symbol"&&Xwl.test(t))&&t>-1&&t%1==0&&t<e}function XFl(t,e,I){if(!gf(I))return!1;var l=typeof e;return(l=="number"?B8e(I)&&esI(e,I.length):l=="string"&&e in I)?D2e(I[e],t):!1}function HFl(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}function CFl(t){return!!frI&&frI in t}function tsI(t){var e=t&&t.constructor,I=typeof e=="function"&&e.prototype||U2e;return t===I}function fFl(t){var e=[];if(t!=null)for(var I in Object(t))e.push(I);return e}function JFl(t){return KrI.call(t)}function LFl(t,e,I){return e=SrI(e===void 0?t.length-1:e,0),function(){for(var l=arguments,n=-1,r=SrI(l.length-e,0),s=Array(r);++n<r;)s[n]=l[e+n];n=-1;for(var a=Array(e+1);++n<e;)a[n]=l[n];return a[e]=I(s),Cwl(t,this,a)}}function J8e(t,e){if(!(e==="constructor"&&typeof t[e]=="function")&&e!="__proto__")return t[e]}var kFl=xFl(YFl);function xFl(t){var e=0,I=0;return function(){var l=Twl(),n=lwl-(l-I);if(I=l,n>0){if(++e>=Iwl)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}function SFl(t){if(t!=null){try{return O2e.call(t)}catch{}try{return t+""}catch{}}return""}function D2e(t,e){return t===e||t!==t&&e!==e}var L8e=BrI((function(){return arguments})())?BrI:function(t){return Mee(t)&&HV.call(t,"callee")&&!Uwl.call(t,"callee")},k8e=Array.isArray;function B8e(t){return t!=null&&lsI(t.length)&&!z8e(t)}function BFl(t){return Mee(t)&&B8e(t)}var IsI=Mwl||TFl;function z8e(t){if(!gf(t))return!1;var e=T2e(t);return e==MrI||e==cwl||e==rwl||e==mwl}function lsI(t){return typeof t=="number"&&t>-1&&t%1==0&&t<=UrI}function gf(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}function Mee(t){return t!=null&&typeof t=="object"}function zFl(t){if(!Mee(t)||T2e(t)!=TrI)return!1;var e=qrI(t);if(e===null)return!0;var I=HV.call(e,"constructor")&&e.constructor;return typeof I=="function"&&I instanceof I&&O2e.call(I)==Bwl}var nsI=CrI?Jwl(CrI):ZFl;function UFl(t){return wFl(t,rsI(t))}function rsI(t){return B8e(t)?uFl(t,!0):WFl(t)}var OFl=FFl(function(t,e,I){$rI(t,e,I)});function MFl(t){return function(){return t}}function ssI(t){return t}function TFl(){return!1}ez.exports=OFl});async function jFl(t={}){let e=await Itt();return jet((0,osI.default)({},e,t))}async function U8e(t={}){if(VIe())throw new Error("Settings have already been initialized");return jFl(t)}var osI,csI=u(()=>{"use strict";osI=dI(asI(),1);RIe();_z()});import{readdir as DFl,stat as PFl}from"fs/promises";async function KFl(t,e){try{let I=await PFl(t);if(I.isDirectory()){let l=await DFl(t);return{path:t,type:"directory",lines:l.length}}else{let l=I.size/1048576;if(I.size>isI){let r=(isI/1048576).toFixed(0);return e.debug(`File ${t} is too large (${l.toFixed(1)}MB). Maximum file size is ${r}MB. Skipping line count.`),{path:t,type:"file",sizeMB:l}}let{totalLineCount:n}=await rse(t,1,void 0);return{path:t,type:"file",lines:n}}}catch(I){return e.debug(`Error getting file info for ${t}: ${Ye(I)}`),{path:t,type:"file",error:Ye(I)}}}async function dsI(t,e){let I=t.filter(r=>!Bw(r.path));if(I.length===0)return"";let l=await Promise.all(I.map(r=>KFl(r.path,e))),n=["<tagged_files>"];for(let r of l)r.error?n.push(`* ${r.path} (error: ${r.error})`):r.sizeMB!==void 0?n.push(`* ${r.path} (large file: ${r.sizeMB.toFixed(1)}MB)`):r.type==="directory"?n.push(`* ${r.path} (${r.lines} entries)`):n.push(`* ${r.path} (${r.lines} lines)`);return n.push("</tagged_files>"),n.join(`
2371
2367
  `)}async function GsI(t,e){let I=t.filter(n=>n.type==="file"&&Bw(n.path));return(await Promise.all(I.map(async n=>{try{let r=await kme(n.path,e);return r?[{type:"text",text:`Image file at path ${n.path}`},{type:"image_url",image_url:{url:`data:${r.mimeType};base64,${r.base64Data}`}}]:void 0}catch(r){e.error(`Failed to process image ${n.path}: ${r instanceof Error?r.message:String(r)}`);return}}))).filter(n=>n!==void 0).flat()}var isI,msI=u(()=>{"use strict";zI();JZ();YK();isI=10*1024*1024});async function J1(t,e,I){if(!t||t.length===0)return;let l=!1,n={};for(let r of t)try{let s=await r(e);s&&(l=!0,n={...n,...s})}catch(s){I.error(`Hook execution failed: ${Ye(s)}`)}return l?n:void 0}var O8e=u(()=>{"use strict";zI()});function usI(t){return t.filter(e=>Jk(e.id)&&mW(e.id,t)).sort((e,I)=>z2.indexOf(e.id)-z2.indexOf(I.id))}async function gJr(t){return(await M8e(t,jf(),lz,Ra(),new Em)).models}async function M8e(t,e,I,l,n){if(GB())return{models:[],copilotUrl:e};if(t.type==="hmac"){if(cG&&t.type===cG.authInfo.type&&t.hmac===cG.authInfo.hmac)return{models:cG.models,copilotUrl:cG.copilotUrl};let d=e||jf(),m=await p1.createWithHmac(n,d,I,t.hmac,l).listModels();return cG={models:usI(m.models),authInfo:t,copilotUrl:m.copilotUrl},{models:cG.models,copilotUrl:m.copilotUrl}}let r=await Hb(t);if(!r)throw new Error("Failed to get token for auth info");if(cG&&cG.models.length>0&&cG.authInfo.type!=="hmac"&&r===await Hb(cG.authInfo))return{models:cG.models,copilotUrl:cG.copilotUrl};let a=await pE(t.host,r),c=await p1.createWithOAuthToken(n,a,I,r,l).listModels();return c.models.length===0?{models:[],copilotUrl:c.copilotUrl}:(cG={models:usI(c.models),authInfo:t,copilotUrl:c.copilotUrl},{models:cG.models,copilotUrl:c.copilotUrl})}async function YJr(t,e,I,l,n){if(l??=Ra(),I??=lz,n??=new Em,t.type==="hmac")return{success:!1,canBeEnabled:!1,error:"Model enablement is not available with HMAC authentication. Only Copilot for Individuals users can enable models."};let r=await Hb(t);if(!r)return{success:!1,error:"Failed to get authentication token"};let a=await pE(t.host,r),c=await p1.createWithOAuthToken(n,a,I,r,l).enableModelPolicy(e);return c.success&&(cG=null),c}var cG,T8e=u(()=>{"use strict";ig();hE();hX();Lk();Z$();ud();TNe();nz();cG=null});function bsI(t){return t?.trim().length??0}function psI(t,e){if(t&&e){let I=bsI(t),l=bsI(e);return I===l?e:I>l?t:e}return t??e??null}function P2e(t){let{streamingReasoningId:e,streamingReasoningContent:I,messageReasoningId:l,messageReasoningText:n,fallbackReasoningIdFactory:r=Ra}=t,s=psI(I,n),a=e??l??null;return!a&&s&&(a=r()),{reasoningId:a,reasoningContent:s}}var hsI=u(()=>{"use strict";ig()});var ZsI=u(()=>{"use strict";hsI()});function _Fl(t){if(!t)return"Unknown error occurred";try{let e=JSON.parse(t);if(typeof e=="object"&&e!==null){let I=e;if(typeof I.message=="string")return I.message;if(typeof I.error=="string")return I.error;if(typeof I.error=="object"&&I.error!==null){let l=I.error;if(typeof l.message=="string")return l.message}}}catch{}return t}function $Fl(t){return z2.filter(e=>mW(e,t)).map(e=>{let I=t.find(s=>s.id===e),l=I?.name??e,n=I?.billing?.multiplier??1,r=n<=.5?"fast/cheap":n>=2?"premium":"standard";return{id:e,label:l,description:r}})}function j8e(t){return t.map(e=>({name:e.name,namespacedName:e.namespacedName,description:e.description,title:e.title,input_schema:e.input_schema,instructions:e.instructions}))}function NsI(t){return t===void 0||t.type==="object"}function e1l(t){if(t.length===0)return t;let e=[],I=new Set,l=!1;for(let s=t.length-1;s>=0;s--){let a=t[s];if(a.role==="assistant"&&(l=!0),a.role==="assistant"&&"tool_calls"in a&&a.tool_calls&&a.tool_calls.length>0)for(let o of a.tool_calls)I.has(o.id)||e.push(o.id);else{if(l)break;a.role==="tool"&&a.tool_call_id&&I.add(a.tool_call_id)}}if(e.length===0)return t;let n="The execution of this tool, or a previous tool was interrupted.";Ke.info(`Completing ${e.length} orphaned tool calls.`);let r=e.map(s=>({role:"tool",tool_call_id:s,content:n}));return[...t,...r]}var qFl,lz,WsI,D8e,K2e,fV,q2e,nz=u(()=>{"use strict";E8t();ig();A$();N$();V$();oB();tU();v8t();k8t();H$();hE();hX();QGe();S8t();B8t();U8t();YrI();Lk();ePe();RrI();ArI();Hj();zI();Pz();YK();J7();NV();gNe();IR();E8e();X8e();vrI();Lme();x3e();cb();Lx();eL();UC();v8e();XrI();mg();RIe();ud();csI();mye();ua();Jue();_De();qDe();CPe();P8e();msI();O8e();T8e();ZsI();qFl="copilot-developer-cli",lz=process.env.GITHUB_COPILOT_INTEGRATION_ID||qFl,WsI=F8t(pE);D8e=class{constructor(e,I){this.premiumRequestProcessor=e;this.session=I}messageQueue=[];async*preRequest(e){if(this.messageQueue.length===0)return;Ke.debug("ImmediatePromptProcessor: Injecting immediate prompts"),this.premiumRequestProcessor.setForcePremiumRequest();let l=(await this.session.getChatMessages()).length;for(;this.messageQueue.length>0;){let s=this.messageQueue.shift();this.session.emitEphemeral("pending_messages.modified",{}),this.session.emit("user.message",{content:s.prompt,attachments:s.attachments})}let r=(await this.session.getChatMessages()).slice(l);for(let s of r)e.messages.push(s),yield{kind:"message",message:s,turn:e.turn,source:"immediate-prompt"}}addMessage(e){this.messageQueue.push(e)}getQueue(){return this.messageQueue}clearQueue(){this.messageQueue.length=0}popMessage(){return this.messageQueue.shift()}toJSON(){return"ImmediatePromptProcessor"}},K2e=class{sessionId;startTime;modifiedTime;summary;events=[];_chatMessages=[];_selectedModel;originalUserMessages=[];eventProcessingQueue=Promise.resolve();eventHandlers={};wildcardEventHandlers=[];integrationId;availableTools;excludedTools;executeToolsInParallel;shellConfig;requestPermission;mcpServers;mcpHost;hooks;customAgents;selectedCustomAgent;organizationCustomInstructions;skipCustomInstructions;systemMessageConfig;workingDir;featureFlags;skillDirectories;disabledSkills;trajectoryFile;eventsLogDirectory;authInfo;copilotUrl;provider;onToolsUpdate;enableStreaming=!1;handoffContext;externalToolDefinitions;externalToolDispatcher;clientName;largeOutputConfig;workspaceContext;currentSystemMessage;currentToolMetadata;currentTools;async initializeAndValidateTools(){}constructor(e={}){this.sessionId=e.sessionId||Ra(),this.startTime=e.startTime||new Date,this.modifiedTime=e.modifiedTime||this.startTime,this.summary=e.summary,this.integrationId=e.integrationId||lz,this.skipCustomInstructions=e.skipCustomInstructions??!1,this.workingDir=e.workingDirectory||process.cwd(),this.updateOptions(e)}static async fromEvents(e,I){if(e.length===0)throw new Error("Cannot create session from empty events array");let l=e[0];if(l.type!=="session.start")throw new Error("First event must be session.start");let n=new this({...I,sessionId:l.data.sessionId,startTime:new Date(l.data.startTime)});n._selectedModel=l.data.selectedModel,n.events.push(l);for(let r=1;r<e.length;r++){let s=e[r];n.events.push(s),await n.processEventForState(s)}return n}setAuthInfo(e){this.updateOptions({authInfo:e})}updateOptions(e){e.clientName!==void 0&&(this.clientName=e.clientName),e.model!==void 0&&(this._selectedModel=e.model),e.integrationId!==void 0&&(this.integrationId=e.integrationId),e.availableTools!==void 0&&(this.availableTools=e.availableTools),e.excludedTools!==void 0&&(this.excludedTools=e.excludedTools),e.executeToolsInParallel!==void 0&&(this.executeToolsInParallel=e.executeToolsInParallel),e.shellConfig!==void 0&&(this.shellConfig=e.shellConfig),e.requestPermission!==void 0&&(this.requestPermission=e.requestPermission),e.featureFlags!==void 0&&(this.featureFlags=e.featureFlags),e.skillDirectories!==void 0&&(this.skillDirectories=e.skillDirectories),e.disabledSkills!==void 0&&(this.disabledSkills=e.disabledSkills),e.mcpServers!==void 0&&(this.mcpServers=e.mcpServers),e.mcpHost!==void 0&&(this.mcpHost=e.mcpHost),e.customAgents!==void 0?this.customAgents=e.customAgents:this.loadCustomAgents().catch(I=>Ke.error(`Failed to load custom agents: ${Ye(I)}`)),"selectedCustomAgent"in e&&(this.selectedCustomAgent=e.selectedCustomAgent),e.organizationCustomInstructions!==void 0&&(this.organizationCustomInstructions=e.organizationCustomInstructions),e.skipCustomInstructions!==void 0&&(this.skipCustomInstructions=e.skipCustomInstructions),e.systemMessage!==void 0&&(this.systemMessageConfig=e.systemMessage),e.hooks!==void 0&&(this.hooks=e.hooks),e.externalToolDefinitions!==void 0&&(this.externalToolDefinitions=e.externalToolDefinitions),e.externalToolDispatcher!==void 0&&(this.externalToolDispatcher=e.externalToolDispatcher),e.trajectoryFile!==void 0&&(this.trajectoryFile=e.trajectoryFile),e.eventsLogDirectory!==void 0&&(this.eventsLogDirectory=e.eventsLogDirectory),e.workingDirectory!==void 0&&(this.workingDir=e.workingDirectory),e.authInfo!==void 0&&(this.authInfo=e.authInfo),e.copilotUrl!==void 0&&(this.copilotUrl=e.copilotUrl),e.provider!==void 0&&(this.provider=e.provider),e.enableStreaming!==void 0&&(this.enableStreaming=e.enableStreaming),e.largeOutput!==void 0&&(this.largeOutputConfig=e.largeOutput)}setOnToolsUpdate(e){this.onToolsUpdate=e}getAvailableCustomAgents(){return this.customAgents||[]}async selectCustomAgent(e){let I=this.customAgents?.find(l=>l.name===e);if(!I)throw new Error(`Custom agent '${e}' not found`);this.selectedCustomAgent=I,this.emit("custom_agent.selected",{agentName:I.name,agentDisplayName:I.displayName,tools:I.tools})}clearCustomAgent(){this.selectedCustomAgent=void 0}on(e,I){return e==="*"?(this.wildcardEventHandlers.push(I),()=>{let l=this.wildcardEventHandlers.indexOf(I);l!==-1&&this.wildcardEventHandlers.splice(l,1)}):(this.eventHandlers[e]||(this.eventHandlers[e]=[]),this.eventHandlers[e].push(I),()=>{let l=this.eventHandlers[e];if(l){let n=l.indexOf(I);n!==-1&&l.splice(n,1)}})}emitInternal(e,I,l=!1){let n=Ra(),r=new Date().toISOString(),s=this.getLastEventId(),a={type:e,data:I,id:n,timestamp:r,parentId:s,...l&&{ephemeral:l}};this.events.push(a),this.enqueueEventProcessing(()=>this.processEventForState(a)).catch(o=>{Ke.error(`Error emitting event: ${o instanceof Error?o.message:String(o)}`)}).catch(o=>{Ke.error(`Error emitting event ${o instanceof Error?o.message:String(o)}`)}),[...this.eventHandlers[a.type]||[],...this.wildcardEventHandlers].forEach(o=>{try{o(a)}catch(c){Ke.error(`Error in event handler for event type ${a.type}: ${c instanceof Error?c.message:String(c)}`)}})}emit(e,I){this.emitInternal(e,I)}emitEphemeral(e,I){this.emitInternal(e,I,!0)}getEvents(){return this.events}async getChatMessages(){return this.enqueueEventProcessing(()=>this._chatMessages)}async getChatContextMessages(){return(await this.getChatMessages()).filter(I=>I.role!=="system")}async getSystemContextMessages(){return(await this.getChatMessages()).filter(I=>I.role==="system")}getCurrentSystemMessage(){return this.currentSystemMessage}getCurrentToolMetadata(){return this.currentToolMetadata}async getSelectedModel(){return this.enqueueEventProcessing(()=>this._selectedModel)}getOrganizationCustomInstructions(){return this.organizationCustomInstructions}getSkipCustomInstructions(){return this.skipCustomInstructions}getSystemMessageConfig(){return this.systemMessageConfig}setWorkspaceContext(e){this.workspaceContext=e}getWorkspaceContext(){return this.workspaceContext}getWorkspace(){return null}isWorkspaceEnabled(){return!1}getWorkspacePath(){return null}getCheckpointCount(){return 0}async listCheckpointTitles(){return[]}hasPlan(){return!1}async ensureWorkspace(e,I){throw new Error("Workspace features are not available for this session type")}async setSelectedModel(e){let I=await this.getSelectedModel();this.emit("session.model_change",{previousModel:I,newModel:e})}getLastEventId(){return this.events.length===0?null:this.events[this.events.length-1].id}enqueueEventProcessing(e){let I=this.eventProcessingQueue.then(()=>e());return this.eventProcessingQueue=I,I}async processEventForState(e){switch(e.type){case"session.start":e.data.selectedModel&&(this._selectedModel=e.data.selectedModel);break;case"session.model_change":this._selectedModel=e.data.newModel;break;case"user.message":{this.originalUserMessages.push(e.data.content);let I=e.data.transformedContent??e.data.content,l=[];if(e.data.attachments&&e.data.attachments.length>0){let n=await GsI(e.data.attachments,Ke);if(l.push(...n),e.data.attachments&&e.data.attachments.length>0){let r=await dsI(e.data.attachments,Ke);r&&(I=`${I}
2372
2368
 
2373
- ${r}`)}}l.length>0?this._chatMessages.push({role:"user",content:[{type:"text",text:I},...l]}):this._chatMessages.push({role:"user",content:I});break}case"assistant.message":{if(e.ephemeral||e.data.parentToolCallId)break;let I={role:"assistant",content:e.data.content||null};e.data.toolRequests&&e.data.toolRequests.length>0&&(I.tool_calls=e.data.toolRequests.map(l=>l.toolCallId.startsWith("custom_")?{id:l.toolCallId,type:"custom",custom:{name:l.name,input:typeof l.arguments=="string"?l.arguments:JSON.stringify(l.arguments)}}:{id:l.toolCallId,type:"function",function:{name:l.name,arguments:typeof l.arguments=="string"?l.arguments:JSON.stringify(l.arguments)}})),this._chatMessages.push(I);break}case"tool.execution_complete":{if(e.data.parentToolCallId)break;e.data.isUserRequested||this._chatMessages.push({role:"tool",tool_call_id:e.data.toolCallId,content:e.data.success?e.data.result?.content||"":e.data.error?.message||"Tool execution failed"});break}case"system.message":this._chatMessages.push({role:e.data.role,content:e.data.content,...e.data.name&&{name:e.data.name}});break;case"session.import_legacy":this._chatMessages=[...e.data.legacySession.chatMessages],e.data.legacySession.selectedModel&&(this._selectedModel=e.data.legacySession.selectedModel);break;case"abort":case"session.resume":this._chatMessages=e1l(this._chatMessages);break;case"session.handoff":e.data.context&&(this.handoffContext=e.data.context);break;case"session.compaction_complete":{if(e.data.success&&e.data.summaryContent){let I=e.data.preCompactionMessagesLength??this._chatMessages.length;this.applyCompactionToMessages(I,e.data.summaryContent)}break}case"session.compaction_start":case"assistant.intent":case"assistant.message_delta":case"assistant.reasoning_delta":case"session.idle":case"session.error":case"session.info":case"session.truncation":case"assistant.turn_start":case"assistant.turn_end":case"assistant.usage":case"assistant.reasoning":case"tool.user_requested":case"tool.execution_start":case"tool.execution_partial_result":case"custom_agent.started":case"custom_agent.completed":case"custom_agent.failed":case"custom_agent.selected":case"hook.start":case"hook.end":case"pending_messages.modified":break;default:{let I=e;Ke.error(`Unknown event type: ${I.type}`);break}}}async loadCustomAgents(){if(this.provider){Ke.debug("Using custom provider, skipping custom agents load");return}if(!this.authInfo){Ke.debug("No auth info available, skipping custom agents load");return}this.customAgents=await gsI(this.authInfo,this.workingDir,this.integrationId,Ke)}applyCompactionToMessages(e,I){if(e<this._chatMessages.length){let l=this._chatMessages.slice(0,e),n=this._chatMessages.slice(e),r=L2e(l,n);l=r.adjustedCheckpoint,n=r.adjustedNew;let s=$B(l,I,this.originalUserMessages);for(;n.length>0&&n[0].role==="tool";)n.shift();return this._chatMessages=[...s,...n],{compacted:s,newMessages:n}}else{let l=$B(this._chatMessages,I,this.originalUserMessages);return this._chatMessages=l,{compacted:l,newMessages:[]}}}},fV=class t extends K2e{callback=new EIe;isProcessing=!1;messageQueue=[];premiumRequestProcessor;immediatePromptProcessor;compactionProcessor;abortController;activeCustomAgents=new Map;mcpHostCache;modelListCache=void 0;warnedUnknownTools=new Set;sessionWorkspace=null;workspaceEnabled=!1;lastTodoContent=null;lastPlanUpdateTurn=0;currentTurn=0;static PLAN_REMINDER_TURN_THRESHOLD=10;constructor(e={}){super(e),this.premiumRequestProcessor=new g$(Ke),this.immediatePromptProcessor=new D8e(this.premiumRequestProcessor,this),this.compactionProcessor=new x2e(Ke,{getOriginalUserMessages:()=>this.originalUserMessages,getPlanContent:this.workspaceEnabled?()=>this.getPlanContentForCompaction():void 0,getTodoContent:()=>this.lastTodoContent,onCompactionComplete:I=>{this.enqueueEventProcessing(()=>this.handleCompactionComplete(I))}}),this.mcpHostCache=new J2e(Ke),this.on("session.model_change",()=>{this.warnedUnknownTools.clear(),this.initializeAndValidateTools()}),e.featureFlags?.INFINITE_SESSIONS&&(this.workspaceEnabled=!0,this.initializeWorkspace(),this.on("session.compaction_complete",I=>{I.data.success&&I.data.summaryContent&&this.persistCompactionCheckpoint(I.data.summaryContent)}))}async initializeWorkspace(){let I=await S2().getOrCreateWorkspace(this.sessionId);this.sessionWorkspace=I,await this.updateWorkspaceContext(),Ke.debug(`Workspace initialized: ${this.sessionId} (checkpoints: ${I.summary_count})`)}async updateWorkspaceContext(){let e=this.getWorkspacePath();if(!e){this.setWorkspaceContext(void 0);return}let I=this.sessionWorkspace,l=I?I.name||`${I.owner||"_local"}/${I.repo||"workspace"}`:"_local/workspace",n=await this.listCheckpointTitles(),r=await S2().listFiles(this.sessionId);this.setWorkspaceContext({name:l,workspacePath:e,summaryCount:this.getCheckpointCount(),hasPlan:this.hasPlan(),checkpoints:n,filesInWorkspace:r,showPlanReminder:this.shouldShowPlanReminder()})}updateOptions(e){if(super.updateOptions(e),e.trajectoryFile!==void 0){let I=new KNe(Ke,e.trajectoryFile);this.callback.addCallback(I)}if(e.eventsLogDirectory!==void 0){let I=new jNe(Ke,e.eventsLogDirectory);this.callback.addCallback(I)}}getMetadata(){return{sessionId:this.sessionId,startTime:this.startTime,modifiedTime:this.modifiedTime,summary:this.summary,isRemote:!1}}getWorkspace(){return this.sessionWorkspace}isWorkspaceEnabled(){return this.workspaceEnabled}getWorkspacePath(){return this.workspaceEnabled?S2().getWorkspacePath(this.sessionId):null}getCheckpointCount(){return this.sessionWorkspace?.summary_count??0}async listCheckpointTitles(){return this.workspaceEnabled?(await S2().listCheckpoints(this.sessionId)).map(I=>({number:I.number,title:I.title,filename:I.filename})):[]}hasPlan(){return S2().planExists(this.sessionId)}async getPlanContentForCompaction(){return this.workspaceEnabled?S2().readPlan(this.sessionId):null}setLastTodoContent(e){this.lastTodoContent=e}getLastTodoContent(){return this.lastTodoContent}shouldShowPlanReminder(){return this.workspaceEnabled?this.currentTurn-this.lastPlanUpdateTurn>=t.PLAN_REMINDER_TURN_THRESHOLD&&this.hasPlan():!1}getPlanReminderMessage(){return this.shouldShowPlanReminder()?`<reminder>
2369
+ ${r}`)}}l.length>0?this._chatMessages.push({role:"user",content:[{type:"text",text:I},...l]}):this._chatMessages.push({role:"user",content:I});break}case"assistant.message":{if(e.ephemeral||e.data.parentToolCallId)break;let I={role:"assistant",content:e.data.content||null};e.data.toolRequests&&e.data.toolRequests.length>0&&(I.tool_calls=e.data.toolRequests.map(l=>l.toolCallId.startsWith("custom_")?{id:l.toolCallId,type:"custom",custom:{name:l.name,input:typeof l.arguments=="string"?l.arguments:JSON.stringify(l.arguments)}}:{id:l.toolCallId,type:"function",function:{name:l.name,arguments:typeof l.arguments=="string"?l.arguments:JSON.stringify(l.arguments)}})),this._chatMessages.push(I);break}case"tool.execution_complete":{if(e.data.parentToolCallId)break;e.data.isUserRequested||this._chatMessages.push({role:"tool",tool_call_id:e.data.toolCallId,content:e.data.success?e.data.result?.content||"":e.data.error?.message||"Tool execution failed"});break}case"system.message":this._chatMessages.push({role:e.data.role,content:e.data.content,...e.data.name&&{name:e.data.name}});break;case"session.import_legacy":this._chatMessages=[...e.data.legacySession.chatMessages],e.data.legacySession.selectedModel&&(this._selectedModel=e.data.legacySession.selectedModel);break;case"abort":case"session.resume":this._chatMessages=e1l(this._chatMessages);break;case"session.handoff":e.data.context&&(this.handoffContext=e.data.context);break;case"session.compaction_complete":{if(e.data.success&&e.data.summaryContent){let I=e.data.preCompactionMessagesLength??this._chatMessages.length;this.applyCompactionToMessages(I,e.data.summaryContent)}break}case"session.compaction_start":case"assistant.intent":case"assistant.message_delta":case"assistant.reasoning_delta":case"session.idle":case"session.error":case"session.info":case"session.truncation":case"assistant.turn_start":case"assistant.turn_end":case"assistant.usage":case"assistant.reasoning":case"tool.user_requested":case"tool.execution_start":case"tool.execution_partial_result":case"custom_agent.started":case"custom_agent.completed":case"custom_agent.failed":case"custom_agent.selected":case"hook.start":case"hook.end":case"pending_messages.modified":break;default:{let I=e;Ke.error(`Unknown event type: ${I.type}`);break}}}async loadCustomAgents(){if(this.provider){Ke.debug("Using custom provider, skipping custom agents load");return}if(!this.authInfo){Ke.debug("No auth info available, skipping custom agents load");return}this.customAgents=await gsI(this.authInfo,this.workingDir,this.integrationId,Ke)}applyCompactionToMessages(e,I){if(e<this._chatMessages.length){let l=this._chatMessages.slice(0,e),n=this._chatMessages.slice(e),r=L2e(l,n);l=r.adjustedCheckpoint,n=r.adjustedNew;let s=$B(l,I,this.originalUserMessages);for(;n.length>0&&n[0].role==="tool";)n.shift();return this._chatMessages=[...s,...n],{compacted:s,newMessages:n}}else{let l=$B(this._chatMessages,I,this.originalUserMessages);return this._chatMessages=l,{compacted:l,newMessages:[]}}}},fV=class t extends K2e{callback=new EIe;isProcessing=!1;messageQueue=[];premiumRequestProcessor;immediatePromptProcessor;compactionProcessor;abortController;activeCustomAgents=new Map;mcpHostCache;modelListCache=void 0;warnedUnknownTools=new Set;sessionWorkspace=null;workspaceEnabled=!1;lastTodoContent=null;lastPlanUpdateTurn=0;currentTurn=0;static PLAN_REMINDER_TURN_THRESHOLD=10;constructor(e={}){super(e),this.premiumRequestProcessor=new g$(Ke),this.immediatePromptProcessor=new D8e(this.premiumRequestProcessor,this),this.compactionProcessor=new x2e(Ke,{getOriginalUserMessages:()=>this.originalUserMessages,getPlanContent:this.workspaceEnabled?()=>this.getPlanContentForCompaction():void 0,getTodoContent:()=>this.lastTodoContent,onCompactionComplete:I=>{this.enqueueEventProcessing(()=>this.handleCompactionComplete(I))}}),this.mcpHostCache=new J2e(Ke),this.on("session.model_change",()=>{this.warnedUnknownTools.clear(),this.initializeAndValidateTools()}),e.featureFlags?.INFINITE_SESSIONS&&(this.workspaceEnabled=!0,this.initializeWorkspace(),this.on("session.compaction_complete",I=>{I.data.success&&I.data.summaryContent&&this.persistCompactionCheckpoint(I.data.summaryContent)}))}async initializeWorkspace(){let I=await S2().getOrCreateWorkspace(this.sessionId);this.sessionWorkspace=I,await this.updateWorkspaceContext(),Ke.debug(`Workspace initialized: ${this.sessionId} (checkpoints: ${I.summary_count})`)}async updateWorkspaceContext(){let e=this.getWorkspacePath();if(!e){this.setWorkspaceContext(void 0);return}let I=this.sessionWorkspace,l=I?I.name||`${I.owner||"_local"}/${I.repo||"workspace"}`:"_local/workspace",n=await this.listCheckpointTitles(),r=await S2().listFiles(this.sessionId);this.setWorkspaceContext({name:l,workspacePath:e,summaryCount:this.getCheckpointCount(),hasPlan:this.hasPlan(),checkpoints:n,filesInWorkspace:r})}updateOptions(e){if(super.updateOptions(e),e.trajectoryFile!==void 0){let I=new KNe(Ke,e.trajectoryFile);this.callback.addCallback(I)}if(e.eventsLogDirectory!==void 0){let I=new jNe(Ke,e.eventsLogDirectory);this.callback.addCallback(I)}}getMetadata(){return{sessionId:this.sessionId,startTime:this.startTime,modifiedTime:this.modifiedTime,summary:this.summary,isRemote:!1}}getWorkspace(){return this.sessionWorkspace}isWorkspaceEnabled(){return this.workspaceEnabled}getWorkspacePath(){return this.workspaceEnabled?S2().getWorkspacePath(this.sessionId):null}getCheckpointCount(){return this.sessionWorkspace?.summary_count??0}async listCheckpointTitles(){return this.workspaceEnabled?(await S2().listCheckpoints(this.sessionId)).map(I=>({number:I.number,title:I.title,filename:I.filename})):[]}hasPlan(){return S2().planExists(this.sessionId)}async getPlanContentForCompaction(){return this.workspaceEnabled?S2().readPlan(this.sessionId):null}setLastTodoContent(e){this.lastTodoContent=e}getLastTodoContent(){return this.lastTodoContent}shouldShowPlanReminder(){return!this.workspaceEnabled||!this.hasPlan()?!1:this.currentTurn-this.lastPlanUpdateTurn>=t.PLAN_REMINDER_TURN_THRESHOLD}getPlanReminderMessage(){return this.shouldShowPlanReminder()?`<reminder>
2374
2370
  Consider updating plan.md to reflect current progress and next steps.
2375
- </reminder>`:null}markPlanUpdated(){this.lastPlanUpdateTurn=this.currentTurn}emitWorkspaceFileTelemetry(e,I){let l=this.getWorkspacePath();if(!l)return;if(e.endsWith("/plan.md")||e.endsWith("\\plan.md")){this.invokeCallbacks(jDe(this.sessionId,I,0));return}let n=`${l}/files/`,r=`${l}\\files\\`;if(e.startsWith(n)||e.startsWith(r)){let s=e.startsWith(n)?e.slice(n.length):e.slice(r.length);this.invokeCallbacks(PDe(this.sessionId,s,I,0))}}emitWorkspaceFileReadTelemetry(e){let I=this.getWorkspacePath();if(!I)return;if(e.endsWith("/plan.md")||e.endsWith("\\plan.md")){this.invokeCallbacks(DDe(this.sessionId,0));return}let l=`${I}/checkpoints/`,n=`${I}\\checkpoints\\`;if(e.startsWith(l)||e.startsWith(n)){let o=(e.split(/[/\\]/).pop()||"").match(/^(\d+)-/),c=o?parseInt(o[1],10):0;this.invokeCallbacks(TDe(this.sessionId,c,0));return}let r=`${I}/files/`,s=`${I}\\files\\`;if(e.startsWith(r)||e.startsWith(s)){let a=e.startsWith(r)?e.slice(r.length):e.slice(s.length);this.invokeCallbacks(KDe(this.sessionId,a,0))}}async ensureWorkspace(e,I){if(!this.workspaceEnabled)throw new Error("Workspace features are not enabled for this session");let n=await S2().getOrCreateWorkspace(this.sessionId,e,I);return this.sessionWorkspace=n,n}async persistCompactionCheckpoint(e){if(!this.sessionWorkspace){Ke.debug("No workspace loaded, skipping checkpoint persistence");return}try{let I=S2(),l=UDe(e,this.sessionId),n=ODe(e),r=await I.addSummary(this.sessionId,n,l);Ke.info(`Persisted checkpoint #${r}: ${l}`);let s=await I.loadWorkspace(this.sessionId);s&&(this.sessionWorkspace=s,await this.updateWorkspaceContext())}catch(I){let l=I instanceof Error?I.message:String(I);Ke.error(`Failed to persist checkpoint: ${l}`)}}async send(e){if(e.mode==="immediate"&&this.isProcessing){this.immediatePromptProcessor.addMessage(e),this.emitEphemeral("pending_messages.modified",{});return}if(this.messageQueue.push(e),this.emitEphemeral("pending_messages.modified",{}),!this.isProcessing){for(this.isProcessing=!0,await this.initializeMcpHost();this.messageQueue.length>0;){let I=this.messageQueue.shift();this.emitEphemeral("pending_messages.modified",{}),this.abortController=I.abortController||new AbortController,await this.runAgenticLoop(I.prompt,I.attachments);let l=this.immediatePromptProcessor.popMessage();l&&(this.emitEphemeral("pending_messages.modified",{}),this.messageQueue.unshift(l))}this.isProcessing=!1,this.emitEphemeral("session.idle",{})}}async abort(){this.abortController?.abort()}getPendingSteeringMessages(){return this.immediatePromptProcessor.getQueue().map(e=>e.prompt)}getPendingQueuedMessages(){return this.messageQueue.map(e=>e.prompt)}clearPendingMessages(){this.immediatePromptProcessor.clearQueue(),this.messageQueue.length=0,this.emitEphemeral("pending_messages.modified",{})}async compactHistory(){this.emit("session.compaction_start",{});let e=await this.getChatMessages();if(e.length<2)throw new Error("Nothing to compact.");if(!this.authInfo)throw new Error("Authentication required for compaction. Please log in first.");if(this.currentSystemMessage===void 0)throw new Error("Cannot compact: no active agent context. Send a message first.");let{client:I,settings:l}=await this.getClient(),n=B2(l.service?.agent?.model).model,r=a0(e,n),s=e.length,o=See(e,this.workspaceEnabled).filter(p=>p.role!=="system"),c=await k2e(I,this.currentSystemMessage,o,this.currentTools??[],Ke);if(!c.content)throw new Error("Compaction failed: No response from model");let i=this.workspaceEnabled?await this.getPlanContentForCompaction():null,d=$B(e,c.content,this.originalUserMessages,{isManualCompaction:!0,planContent:i??void 0,todoContent:this.lastTodoContent??void 0}),G=a0(d,n),m=r-G,b=s-d.length;return this._chatMessages=d,this.emit("session.compaction_complete",{success:!0,preCompactionTokens:r,postCompactionTokens:G,preCompactionMessagesLength:s,messagesRemoved:b,tokensRemoved:m,summaryContent:c.content,compactionTokensUsed:{input:c.inputTokens,output:c.outputTokens,cachedInput:c.cachedInputTokens}}),Ke.info(`Compacted ${b} messages, saved ~${m} tokens`),{success:!0,tokensRemoved:m,messagesRemoved:b,summaryContent:c.content}}handleCompactionComplete(e){if(e.success&&e.summaryContent){let I={success:!0,preCompactionTokens:e.checkpointTokens,preCompactionMessagesLength:e.checkpointMessagesLength,summaryContent:e.summaryContent,compactionTokensUsed:e.compactionTokensUsed};this.emit("session.compaction_complete",I);let l={kind:"compaction_completed",turn:e.startTurn,performedBy:"CompactionProcessor",success:!0,compactionResult:{tokenLimit:0,preCompactionTokens:e.checkpointTokens,preCompactionMessagesLength:e.checkpointMessagesLength,summaryContent:e.summaryContent}};this.invokeCallbacks(l)}else{this.emit("session.compaction_complete",{success:!1,error:e.error});let I={kind:"compaction_completed",turn:e.startTurn,performedBy:"CompactionProcessor",success:!1,error:e.error};this.invokeCallbacks(I)}}async initializeMcpHost(){if(!this.mcpHost&&this.mcpServers&&Object.keys(this.mcpServers).length>0)try{this.mcpHost=new _B(Ke,{mcpServers:this.mcpServers},this.excludedTools),await this.mcpHost.startServers()}catch(e){Ke.error(`Failed to initialize MCP host: ${Ye(e)}`)}}async initializeAndValidateTools(){try{let e=await this.buildSettingsAndTools();if(!e){Ke.debug("Could not initialize tools: buildSettingsAndTools returned undefined");return}let{settings:I,builtInTools:l,mcpTools:n,config:r,toolConfig:s}=e,a=[];for(let W of this.externalToolDefinitions??[])NsI(W.parameters)&&a.push({name:W.name,description:W.description,input_schema:W.parameters??{type:"object",properties:{}}});let o=new Set([...l.map(W=>W.name),...n.map(W=>W.name),...a.map(W=>W.name)]);this.validateToolFilters(o);let c=l.filter(W=>this.isToolEnabled(W.name)),i=n.filter(W=>this.isToolEnabled(W.name)),d=a.filter(W=>this.isToolEnabled(W.name)),G=await jC(this.workingDir),m={...r.supports,reasoning:!0},b,p=[...j8e(c),...j8e(i),...d];if(this.customAgents&&this.customAgents.length>0&&!dg(I)){let g=(this.selectedCustomAgent?[this.selectedCustomAgent]:this.customAgents).filter(R=>R.infer!==!1).map(kqt),y=[...p,...g];b=this.filterToolsForSelectedAgent(y)}else b=p,b=this.filterToolsForSelectedAgent(b);let h=await iB({location:G.found?G.gitRoot:"",version:WNe(),currentWorkingDirectory:this.workingDir,parts:r.cli?.systemMessage||{},capabilities:m,tools:b,organizationCustomInstructions:this.organizationCustomInstructions,skipCustomInstructions:this.skipCustomInstructions,systemMessage:this.systemMessageConfig,toolConfigOverrides:s,workspaceContext:this.workspaceContext});this.currentSystemMessage=h,this.currentToolMetadata=b}catch(e){Ke.debug(`Failed to initialize tools for validation: ${Ye(e)}`)}}async buildSettingsAndTools(e){if(!this.authInfo&&!this.provider)return;await this.initializeMcpHost();let I,l;if(!this.provider){if(!this.authInfo)return;I=await Hb(this.authInfo),l=this.copilotUrl,!l&&I&&this.authInfo.type!=="hmac"&&(l=await WsI(this.authInfo.host,I||""))}let n=!!this.provider,r=n?[]:await this.getModelList(),s=await APe(this._selectedModel,this,r,Ke,n);if(!s)throw new Error("No model available. Check policy enablement under GitHub Settings > Copilot");let a=n?`capi:${s}`:await RPe(s),c=new ZE().setProblemStatement(e??"").setAgentModel(a).setGithubRepoName("copilot-sdk-session").setGithubRepoCommit("copilot-sdk-commit").setGithubRepoReadWrite(!1).setCopilotIntegrationId(this.integrationId).setCopilotUrl(l).setCopilotHmacKey(this.authInfo?.type==="hmac"?this.authInfo.hmac:void 0).setGithubToken(I).setCopilotToken(I).setTrajectoryOutputFile(this.trajectoryFile).setEventsLogDirectory(this.eventsLogDirectory).setFeatureFlags(this.featureFlags).setClientName(this.clientName).build();iye();let i=await U8e(c),d=i.service?.agent?.model,G=B2(d),m=OC(G.agent,G.model),b=$Fl(r),p={location:this.workingDir,timeout:3e4,availableModels:b,toolPartialResultCallback:(g,y)=>{this.emitEphemeral("tool.execution_partial_result",{toolCallId:g,partialOutput:y})},createSubAgentCallback:g=>({progress:async y=>{if(await this.invokeCallbacks(y),uB(y))switch(y.kind){case"message":if(Yh(y)){let R=Jx(y)?y.message.tool_calls.map(v=>({toolCallId:v.id,name:fZ(v),arguments:wre(v,iV)})):[];this.emit("assistant.message",{parentToolCallId:g,messageId:Ra(),content:typeof y.message.content=="string"?y.message.content:"",toolRequests:R});for(let v of R)this.emit("tool.execution_start",{parentToolCallId:g,toolCallId:v.toolCallId,toolName:v.name,arguments:v.arguments})}break;case"tool_execution":this.emit("tool.execution_complete",{parentToolCallId:g,toolCallId:y.toolCallId,success:y.toolResult.resultType==="success",result:y.toolResult.resultType==="success"?{content:y.toolResult.textResultForLlm||y.toolResult.sessionLog||""}:void 0,error:y.toolResult.resultType!=="success"?{message:(y.toolResult.resultType==="failure"?y.toolResult.error:void 0)||y.toolResult.textResultForLlm||y.toolResult.sessionLog||"Tool execution failed",code:y.toolResult.resultType}:void 0});break;default:break}},partialResult:async()=>{},commentReply:async()=>{},result:async()=>{},error:async()=>{}}),permissions:this.requestPermission?{requestRequired:!0,request:this.requestPermission}:{requestRequired:!1},shellConfig:this.shellConfig??(process.platform==="win32"?Zy.powerShell:Zy.bash).withScriptSafetyAssessor(async function(g){return{result:"completed",commands:[{identifier:g,readOnly:!1}],possiblePaths:[],possibleUrls:[],hasWriteFileRedirection:!1,canOfferSessionApproval:!1}}),skillDirectories:this.skillDirectories,disabledSkills:this.disabledSkills,customAgents:this.customAgents,...m.toolConfigOverrides},h=[];if(this.mcpHost){try{h=await this.mcpHost.getTools(i,Ke,p.permissions)}catch(g){Ke.error(`Failed to get MCP tools: ${Ye(g)}`)}vxe(m.supports,h)}p.mcpTools=h,p.getMcpServerProviderForAgent=this.mcpHost?async g=>{let y=await this.mcpHostCache.getOrCreateHost(g,{});if(y)return new Q$(y,i,p.permissions)}:void 0;let N=await(m.cli?.toolInit??Xr.cli.toolInit)(p,i,Ke,new S2e,this.callback,void 0);return{settings:i,builtInTools:N,mcpTools:h,config:m,toolConfig:p}}isToolEnabled(e){return this.availableTools?this.availableTools.includes(e):this.excludedTools?!this.excludedTools.includes(e):!0}validateToolFilters(e){let I=Array.from(e).filter(l=>!this.isToolEnabled(l));if(I.length>0&&!this.warnedUnknownTools.has("__disabled_tools_info__")){this.warnedUnknownTools.add("__disabled_tools_info__");let l=I.sort();this.emitEphemeral("session.info",{infoType:"configuration",message:`Disabled tools: ${l.join(", ")}`})}if(this.availableTools)for(let l of this.availableTools)!e.has(l)&&!this.warnedUnknownTools.has(l)&&(this.warnedUnknownTools.add(l),this.emitEphemeral("session.info",{infoType:"configuration",message:`Unknown tool name in the tool allowlist: "${l}"`}));if(this.excludedTools)for(let l of this.excludedTools)!e.has(l)&&!this.warnedUnknownTools.has(l)&&(this.warnedUnknownTools.add(l),this.emitEphemeral("session.info",{infoType:"configuration",message:`Unknown tool name in the tool denylist: "${l}"`}))}async buildCustomAgentTools(e,I,l,n,r,s,a){let o=async d=>await iB({location:r,version:WNe(),currentWorkingDirectory:this.workingDir,parts:{},capabilities:{...s,customAgents:!1},tools:d,organizationCustomInstructions:this.organizationCustomInstructions,toolConfigOverrides:a}),i=(this.selectedCustomAgent?[this.selectedCustomAgent]:e).filter(d=>d.infer!==!1);return await Promise.all(i.map(async d=>{let G;if(d.mcpServers&&Object.keys(d.mcpServers).length>0){let m=await this.mcpHostCache.getOrCreateHost(d.name,d.mcpServers);m&&(G=new Q$(m,I,a.permissions))}return Lqt(o,VrI,d,this.workingDir,n,l,G)}))}filterToolsForSelectedAgent(e){return this.selectedCustomAgent?R$(e,this.selectedCustomAgent,"top-level"):e}async invokeCallbacks(e){if(uB(e))try{await this.callback.progress(e)}catch(I){Ke.error(`Error in callback: ${Ye(I)}`)}}async getModelList(){if(this.provider)return[];if(!this.authInfo)return Promise.reject(new Error("Session was not created with authentication info or custom provider"));let e=await M8e(this.authInfo,this.copilotUrl||jf(),this.integrationId,this.sessionId,Ke);return e.copilotUrl&&(this.copilotUrl=e.copilotUrl),e.models}async getClient(){if(!this.authInfo&&!this.provider)throw new Error("Session was not created with authentication info or custom provider");let e,I;if(!this.provider){if(!this.authInfo)throw new Error("Session was not created with authentication info");e=await Hb(this.authInfo),I=this.copilotUrl,!I&&e&&this.authInfo.type!=="hmac"&&(I=await WsI(this.authInfo.host,e||""))}let l=!!this.provider,n=l?[]:await this.getModelList(),r=await APe(this._selectedModel,this,n,Ke,l);if(!r)throw new Error("No model available. Check policy enablement under GitHub Settings > Copilot");let s=l?`capi:${r}`:await RPe(r),o=new ZE().setProblemStatement("").setAgentModel(s).setGithubRepoName("copilot-sdk-session").setGithubRepoCommit("copilot-sdk-commit").setGithubRepoReadWrite(!1).setCopilotIntegrationId(this.integrationId).setCopilotUrl(I).setCopilotHmacKey(this.authInfo?.type==="hmac"?this.authInfo.hmac:void 0).setGithubToken(e).setCopilotToken(e).setTrajectoryOutputFile(this.trajectoryFile).setEventsLogDirectory(this.eventsLogDirectory).build();iye();let c=await U8e(o);this.largeOutputConfig&&(c.tools={...c.tools,largeOutput:this.largeOutputConfig});let i=c.service?.agent?.model,d=B2(i),G=OC(d.agent,d.model);return{client:W1(c,Ke,d.agent,{...G.clientOptions,...d.clientOptions,model:d.model},this.provider),settings:c}}async getContextSummary(){let e=await this.getChatMessages();if(e.length===0)return"";let{client:I}=await this.getClient(),l=wrI(),n=2e4,r={role:"user",content:FrI()},s=new vX(r,Ke);try{let a="";for await(let o of I.getCompletionWithTools(l,[...e,r],[],{failIfInitialInputsTooLong:!1,processors:{preRequest:[s],onRequestError:[s]}}))o.kind==="message"&&o.message.role==="assistant"&&(a=typeof o.message.content=="string"?o.message.content:"");return a.length>n?a.slice(0,n):a}catch(a){return Ke.error(`Failed to summarize context: ${Ye(a)}`),""}}async runAgenticLoop(e,I=[]){if(!this.authInfo&&!this.provider)throw new Error("Session was not created with authentication info or custom provider");this.compactionProcessor.clearCompletedCompaction();let l=new Map,n=new Map,r=[],s=!1;try{let o=(await J1(this.hooks?.userPromptSubmitted,{timestamp:Date.now(),cwd:this.workingDir,prompt:e},Ke))?.modifiedPrompt??e,c=await this.buildSettingsAndTools(o);if(!c)throw new Error("No model available. Check policy enablement under GitHub Settings > Copilot");let{settings:i,builtInTools:d,mcpTools:G,config:m,toolConfig:b}=c,p=i.service?.agent?.model,h=B2(p),W=W1(i,Ke,h.agent,{...m.clientOptions,...h.clientOptions,model:h.model},this.provider),N=[];if(this.externalToolDefinitions?.length){let T=this.externalToolDispatcher;if(!T)Ke.warning("External tool definitions provided without a dispatcher; ignoring");else for(let At of this.externalToolDefinitions){if(!NsI(At.parameters)){Ke.warning(`External tool "${At.name}" has invalid parameters schema (expected type object), ignoring tool`);continue}N.push({name:At.name,description:At.description,input_schema:At.parameters??{type:"object",properties:{}},callback:async(oI,Gt)=>{if(!Gt?.toolCallId)throw new Error("External tool invocation missing toolCallId");return await T({sessionId:this.sessionId,toolCallId:Gt.toolCallId,toolName:At.name,arguments:oI,abortSignal:Gt.abortSignal})}})}}let g=new Set([...d,...G,...N].map(T=>T.name));this.validateToolFilters(g);let y=[...d,...G,...N].filter(T=>this.isToolEnabled(T.name)),R=await jC(this.workingDir),v={...m.supports,reasoning:!0},E,Q={progress:async T=>{if(T.kind==="message"&&T.turn===0){if(!T.callId)throw new Error("message on turn 0 event missing callId");E=T.callId}if(await this.invokeCallbacks(T),T.kind==="custom_agent_session_boundary"){let At=T.agentId;if(At)if(T.sessionBoundaryType==="start"){let oI=this.customAgents?.find(ir=>ir.name===T.agentName),Gt=oI?.displayName||T.agentDisplayName||T.agentName,fl=oI?.description||T.agentDescription||"";this.activeCustomAgents.set(At,{name:T.agentName,displayName:Gt}),this.emit("custom_agent.started",{toolCallId:At,agentName:T.agentName,agentDisplayName:Gt,agentDescription:fl})}else{let oI=this.activeCustomAgents.get(At);oI&&this.emit("custom_agent.completed",{toolCallId:At,agentName:oI.name}),this.activeCustomAgents.delete(At)}return}if(uB(T)){if(!E)throw new Error("Custom agent event received without parentToolCallId");switch(T.kind){case"message":if(Yh(T)){let{messageId:At,reasoningId:oI,reasoningContent:Gt}=ct.endCurrentStreamingMessage(),fl=Jx(T)?T.message.tool_calls.map(il=>({toolCallId:il.id,name:fZ(il),arguments:wre(il,iV)})):[],ir=At??Ra(),Rs=typeof T.message.reasoning_text=="string"?T.message.reasoning_text:void 0,fr=typeof T.message.reasoning_opaque=="string"?T.message.reasoning_opaque:null,{reasoningId:_a,reasoningContent:tr}=P2e({streamingReasoningId:oI,streamingReasoningContent:Gt,messageReasoningId:fr,messageReasoningText:Rs});this.emit("assistant.message",{parentToolCallId:E,messageId:ir,content:typeof T.message.content=="string"?T.message.content:"",toolRequests:fl}),_a&&tr&&this.emit("assistant.reasoning",{reasoningId:_a,content:tr});for(let il of fl)this.emit("tool.execution_start",{parentToolCallId:E,toolCallId:il.toolCallId,toolName:il.name,arguments:il.arguments})}break;case"tool_execution":this.emit("tool.execution_complete",{parentToolCallId:E,toolCallId:T.toolCallId,success:T.toolResult.resultType==="success",result:T.toolResult.resultType==="success"?{content:T.toolResult.textResultForLlm||T.toolResult.sessionLog||""}:void 0,error:T.toolResult.resultType!=="success"?{message:(T.toolResult.resultType==="failure"?T.toolResult.error:void 0)||T.toolResult.textResultForLlm||T.toolResult.sessionLog||"Tool execution failed",code:T.toolResult.resultType}:void 0,toolTelemetry:T.toolResult.toolTelemetry});break;case"model_call_failure":case"model_call_success":case"image_processing":case"images_removed":case"response":case"history_truncated":case"compaction_started":case"compaction_completed":case"turn_started":case"turn_ended":case"turn_failed":case"turn_retry":break;default:QA(T,`Unknown event kind: ${JSON.stringify(T)}`)}}},partialResult:async()=>{},commentReply:async()=>{},result:async()=>{},error:async()=>{}},H={client:W,settings:i,logger:Ke,exec:new dG(Ke),customAgents:this.customAgents||[],organizationCustomInstructions:this.organizationCustomInstructions,callback:Q},J=y;if(this.customAgents&&this.customAgents.length>0&&!dg(i)){let T=await this.buildCustomAgentTools(this.customAgents,i,y,H,R.found?R.gitRoot:"",v,b);J=[...y,...T]}r=this.filterToolsForSelectedAgent(J),this.onToolsUpdate&&this.onToolsUpdate(r);let X=await iB({location:R.found?R.gitRoot:"",version:WNe(),currentWorkingDirectory:this.workingDir,parts:m.cli?.systemMessage||{},capabilities:v,tools:r,organizationCustomInstructions:this.organizationCustomInstructions,skipCustomInstructions:this.skipCustomInstructions,systemMessage:this.systemMessageConfig,toolConfigOverrides:b,workspaceContext:this.workspaceContext});this.currentSystemMessage=X;let M=nCt(this.currentTools??[],r);this.currentTools=r,this.currentToolMetadata=j8e(r);let be=I?.some(T=>T.type==="file"&&Bw(T.path))??!1,f=await this.selectedCustomAgent?.prompt(),le=yrI({customAgentPrompt:f,problemStatement:o,capabilities:v,hasImages:be,handoffContext:this.handoffContext,removedTools:M});this.emit("user.message",{content:o,transformedContent:le,attachments:I});let Je=await this.getChatMessages(),Ae=Je.findLastIndex(T=>T.role==="user"),ge=Je[Ae];this.handoffContext=void 0;let Pe=Je.map((T,At)=>At===Ae?ge:T);await J1(this.hooks?.sessionStart,{timestamp:Date.now(),cwd:this.workingDir,source:"new",initialPrompt:e},Ke);let ct=new qNe(this,()=>{},!1,Ke),ke=new _Ne(T=>{this.emitEphemeral("assistant.intent",{intent:T})}),Et=new vX(ge,Ke),it=Jme(Ke,i,J.find(T=>T.name==="github-mcp-server-get_file_contents")),me=W.getCompletionWithTools(X,Pe,r,{failIfInitialInputsTooLong:!1,processors:{preRequest:[this.compactionProcessor,Et,this.immediatePromptProcessor,this.premiumRequestProcessor,it],postToolExecution:[it],onRequestError:[it,Et],onStreamingChunk:[ct,ke]},executeToolsInParallel:this.executeToolsInParallel??!0,abortSignal:this.abortController?.signal,stream:this.enableStreaming});for await(let T of me){if(this.abortController?.signal.aborted){this.emit("abort",{reason:"user initiated"}),this.emitEphemeral("session.info",{infoType:"cancellation",message:"Operation cancelled by user"});break}switch(await this.invokeCallbacks(T),T.kind){case"message":{if(Yh(T)){let{messageId:At,reasoningId:oI,reasoningContent:Gt}=ct.endCurrentStreamingMessage(),fl=At??Ra(),ir=Jx(T)?await Promise.all(T.message.tool_calls.map(async il=>{let Vr=fZ(il),rc=wre(il,iV);l.set(il.id,Vr),n.set(il.id,rc);let uI=await J1(this.hooks?.preToolUse,{timestamp:Date.now(),cwd:this.workingDir,toolName:Vr,toolArgs:rc},Ke);return{toolCallId:il.id,name:Vr,arguments:uI?.modifiedArgs??rc}})):[],Rs=typeof T.message.reasoning_text=="string"?T.message.reasoning_text:void 0,fr=typeof T.message.reasoning_opaque=="string"?T.message.reasoning_opaque:null,{reasoningId:_a,reasoningContent:tr}=P2e({streamingReasoningId:oI,streamingReasoningContent:Gt,messageReasoningId:fr,messageReasoningText:Rs});this.emit("assistant.message",{parentToolCallId:void 0,messageId:fl,content:typeof T.message.content=="string"?T.message.content:"",toolRequests:ir}),_a&&tr&&this.emit("assistant.reasoning",{reasoningId:_a,content:tr});for(let il of ir)this.emit("tool.execution_start",{toolCallId:il.toolCallId,toolName:il.name,arguments:il.arguments})}else(T.message.role==="system"||T.message.role==="developer")&&this.emit("system.message",{role:T.message.role,content:typeof T.message.content=="string"?T.message.content:JSON.stringify(T.message.content),name:"name"in T.message?T.message.name:void 0});break}case"model_call_failure":{let At=new Error(T.modelCall?.error||"Model call failed");if(await J1(this.hooks?.errorOccurred,{timestamp:Date.now(),cwd:this.workingDir,error:At,errorContext:"model_call",recoverable:!0},Ke),Q8e(T.modelCall?.error||""))return;let Gt=_Fl(T.modelCall?.error);T.modelCall.request_id&&(Gt+=` (Request ID: ${T.modelCall.request_id})`),this.emit("session.error",{errorType:"model_call",message:`Model call failed: ${Gt}`,stack:At.stack});break}case"tool_execution":{let At=l.get(T.toolCallId)||"unknown",oI=n.get(T.toolCallId)||{},fl=(await J1(this.hooks?.postToolUse,{timestamp:Date.now(),cwd:this.workingDir,toolName:At,toolArgs:oI,toolResult:T.toolResult},Ke))?.modifiedResult??T.toolResult;fl.resultType==="rejected"&&(s=!0);let ir=(fl.resultType==="failure"?fl.error:void 0)||fl.textResultForLlm||fl.sessionLog||"";if(At===VK&&fl.resultType==="success"&&typeof oI=="object"&&oI!==null&&"todos"in oI&&this.setLastTodoContent(oI.todos),this.workspaceEnabled&&(At==="edit"||At==="create")&&fl.resultType==="success"&&typeof oI=="object"&&oI!==null&&"path"in oI){let Rs=oI.path;(Rs.endsWith("/plan.md")||Rs.endsWith("\\plan.md"))&&(this.lastPlanUpdateTurn=this.currentTurn,this.emitWorkspaceFileTelemetry(Rs,At==="create"?"create":"update"))}if(this.workspaceEnabled&&At==="view"&&fl.resultType==="success"&&typeof oI=="object"&&oI!==null&&"path"in oI){let Rs=oI.path;this.emitWorkspaceFileReadTelemetry(Rs)}this.emit("tool.execution_complete",{parentToolCallId:void 0,toolCallId:T.toolCallId,success:fl.resultType==="success",result:fl.resultType==="success"?{content:ir}:void 0,error:fl.resultType!=="success"?{message:ir,code:fl.resultType}:void 0,toolTelemetry:fl.toolTelemetry});break}case"turn_started":{this.currentTurn=T.turn,this.emit("assistant.turn_start",{turnId:`${T.turn}`});break}case"turn_ended":{this.emit("assistant.turn_end",{turnId:`${T.turn}`});break}case"model_call_success":{let At=T.modelCall.model||await this.getSelectedModel(),oI=T.modelCallDurationMs||0,Gt=T.responseUsage,fl=await this.getModelList(),ir=At?VPe(At,fl):1;this.emitEphemeral("assistant.usage",{model:At||"unknown",inputTokens:Gt?.prompt_tokens||0,outputTokens:Gt?.completion_tokens||0,cacheReadTokens:Gt?.prompt_tokens_details?.cached_tokens||0,cacheWriteTokens:0,cost:ir,duration:oI,initiator:T.modelCall?.initiator,apiCallId:T.modelCall?.api_id,providerCallId:T.modelCall?.request_id,quotaSnapshots:T.quotaSnapshots});break}case"history_truncated":{this.emit("session.truncation",{...T.truncateResult,performedBy:T.performedBy});break}case"compaction_started":{this.emit("session.compaction_start",{});break}case"compaction_completed":{T.success&&T.compactionResult?this.emit("session.compaction_complete",{success:!0,preCompactionTokens:T.compactionResult.preCompactionTokens,postCompactionTokens:T.compactionResult.postCompactionTokens,preCompactionMessagesLength:T.compactionResult.preCompactionMessagesLength,messagesRemoved:T.compactionResult.messagesRemoved,tokensRemoved:T.compactionResult.tokensRemoved,summaryContent:T.compactionResult.summaryContent,compactionTokensUsed:T.compactionResult.compactionTokensUsed}):this.emit("session.compaction_complete",{success:!1,error:T.error});break}case"response":case"images_removed":case"image_processing":case"turn_failed":case"turn_retry":Ke.debug(`Ignoring event of kind: ${T.kind}`);break;default:QA(T,"Unhandled event type")}}}catch(a){if(await J1(this.hooks?.sessionEnd,{timestamp:Date.now(),cwd:this.workingDir,reason:"error",error:a instanceof Error?a:new Error(String(a))},Ke),a&&typeof a=="object"&&"status"in a&&(a.status===401||a.status===403)){if("message"in a&&typeof a.message=="string"){let c=Q8e(a.message);c&&this.emit("session.error",{errorType:"authentication",message:c.message})}this.emit("session.error",{errorType:"authorization",message:"Authorization error, you may need to run /login"})}a&&typeof a=="object"&&"status"in a&&a.status===402&&this.emit("session.error",{errorType:"quota",message:"Quota exceeded. Upgrade to increase your limit: https://github.com/features/copilot/plans"});let o=`Execution failed: ${Ye(a)}`;this.emit("session.error",{errorType:"query",message:o,stack:a instanceof Error?a.stack:void 0})}finally{await J1(this.hooks?.sessionEnd,{timestamp:Date.now(),cwd:this.workingDir,reason:"complete"},Ke),s&&this.clearPendingMessages();try{for(let a of r)a.shutdown&&await a.shutdown()}catch(a){Ke.error(`Error during session shutdown: ${Ye(a)}`)}}}},q2e=class extends K2e{repository;remoteSessionIds;pullRequestNumber;constructor(e){super(e),this.repository=e.repository,this.remoteSessionIds=e.remoteSessionIds,this.pullRequestNumber=e.pullRequestNumber}async send(e){let{prompt:I}=e;if(!this.pullRequestNumber)throw new Error("Cannot send message: Pull request number is not available");if(!this.authInfo)throw new Error("Cannot send message: Authentication info is not available");let{owner:l,name:n}=this.repository,r=this.pullRequestNumber,s=`@copilot ${I}`;Ke.debug(`Posting user message to PR ${l}/${n}#${r}`);let a=MFt(this.authInfo),o=new URL(`/repos/${l}/${n}/issues/${r}/comments`,tR(a)),c=await z8t(o,this.authInfo,Ke,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({body:s})});if(!c.ok){let i=await c.text();throw new Error(`Failed to post comment to PR ${l}/${n}#${r}: ${c.status} ${c.statusText}
2371
+ </reminder>`:null}markPlanUpdated(){this.lastPlanUpdateTurn=this.currentTurn}emitWorkspaceFileTelemetry(e,I){let l=this.getWorkspacePath();if(!l)return;if(e.endsWith("/plan.md")||e.endsWith("\\plan.md")){this.invokeCallbacks(jDe(this.sessionId,I,0));return}let n=`${l}/files/`,r=`${l}\\files\\`;if(e.startsWith(n)||e.startsWith(r)){let s=e.startsWith(n)?e.slice(n.length):e.slice(r.length);this.invokeCallbacks(PDe(this.sessionId,s,I,0))}}emitWorkspaceFileReadTelemetry(e){let I=this.getWorkspacePath();if(!I)return;if(e.endsWith("/plan.md")||e.endsWith("\\plan.md")){this.invokeCallbacks(DDe(this.sessionId,0));return}let l=`${I}/checkpoints/`,n=`${I}\\checkpoints\\`;if(e.startsWith(l)||e.startsWith(n)){let o=(e.split(/[/\\]/).pop()||"").match(/^(\d+)-/),c=o?parseInt(o[1],10):0;this.invokeCallbacks(TDe(this.sessionId,c,0));return}let r=`${I}/files/`,s=`${I}\\files\\`;if(e.startsWith(r)||e.startsWith(s)){let a=e.startsWith(r)?e.slice(r.length):e.slice(s.length);this.invokeCallbacks(KDe(this.sessionId,a,0))}}async ensureWorkspace(e,I){if(!this.workspaceEnabled)throw new Error("Workspace features are not enabled for this session");let n=await S2().getOrCreateWorkspace(this.sessionId,e,I);return this.sessionWorkspace=n,n}async persistCompactionCheckpoint(e){if(!this.sessionWorkspace){Ke.debug("No workspace loaded, skipping checkpoint persistence");return}try{let I=S2(),l=UDe(e,this.sessionId),n=ODe(e),r=await I.addSummary(this.sessionId,n,l);Ke.info(`Persisted checkpoint #${r}: ${l}`);let s=await I.loadWorkspace(this.sessionId);s&&(this.sessionWorkspace=s,await this.updateWorkspaceContext())}catch(I){let l=I instanceof Error?I.message:String(I);Ke.error(`Failed to persist checkpoint: ${l}`)}}async send(e){if(e.mode==="immediate"&&this.isProcessing){this.immediatePromptProcessor.addMessage(e),this.emitEphemeral("pending_messages.modified",{});return}if(this.messageQueue.push(e),this.emitEphemeral("pending_messages.modified",{}),!this.isProcessing){for(this.isProcessing=!0,await this.initializeMcpHost();this.messageQueue.length>0;){let I=this.messageQueue.shift();this.emitEphemeral("pending_messages.modified",{}),this.abortController=I.abortController||new AbortController,await this.runAgenticLoop(I.prompt,I.attachments);let l=this.immediatePromptProcessor.popMessage();l&&(this.emitEphemeral("pending_messages.modified",{}),this.messageQueue.unshift(l))}this.isProcessing=!1,this.emitEphemeral("session.idle",{})}}async abort(){this.abortController?.abort()}getPendingSteeringMessages(){return this.immediatePromptProcessor.getQueue().map(e=>e.prompt)}getPendingQueuedMessages(){return this.messageQueue.map(e=>e.prompt)}clearPendingMessages(){this.immediatePromptProcessor.clearQueue(),this.messageQueue.length=0,this.emitEphemeral("pending_messages.modified",{})}async compactHistory(){this.emit("session.compaction_start",{});let e=await this.getChatMessages();if(e.length<2)throw new Error("Nothing to compact.");if(!this.authInfo)throw new Error("Authentication required for compaction. Please log in first.");if(this.currentSystemMessage===void 0)throw new Error("Cannot compact: no active agent context. Send a message first.");let{client:I,settings:l}=await this.getClient(),n=B2(l.service?.agent?.model).model,r=a0(e,n),s=e.length,o=See(e,this.workspaceEnabled).filter(p=>p.role!=="system"),c=await k2e(I,this.currentSystemMessage,o,this.currentTools??[],Ke);if(!c.content)throw new Error("Compaction failed: No response from model");let i=this.workspaceEnabled?await this.getPlanContentForCompaction():null,d=$B(e,c.content,this.originalUserMessages,{isManualCompaction:!0,planContent:i??void 0,todoContent:this.lastTodoContent??void 0}),G=a0(d,n),m=r-G,b=s-d.length;return this._chatMessages=d,this.emit("session.compaction_complete",{success:!0,preCompactionTokens:r,postCompactionTokens:G,preCompactionMessagesLength:s,messagesRemoved:b,tokensRemoved:m,summaryContent:c.content,compactionTokensUsed:{input:c.inputTokens,output:c.outputTokens,cachedInput:c.cachedInputTokens}}),Ke.info(`Compacted ${b} messages, saved ~${m} tokens`),{success:!0,tokensRemoved:m,messagesRemoved:b,summaryContent:c.content}}handleCompactionComplete(e){if(e.success&&e.summaryContent){let I={success:!0,preCompactionTokens:e.checkpointTokens,preCompactionMessagesLength:e.checkpointMessagesLength,summaryContent:e.summaryContent,compactionTokensUsed:e.compactionTokensUsed};this.emit("session.compaction_complete",I);let l={kind:"compaction_completed",turn:e.startTurn,performedBy:"CompactionProcessor",success:!0,compactionResult:{tokenLimit:0,preCompactionTokens:e.checkpointTokens,preCompactionMessagesLength:e.checkpointMessagesLength,summaryContent:e.summaryContent}};this.invokeCallbacks(l)}else{this.emit("session.compaction_complete",{success:!1,error:e.error});let I={kind:"compaction_completed",turn:e.startTurn,performedBy:"CompactionProcessor",success:!1,error:e.error};this.invokeCallbacks(I)}}async initializeMcpHost(){if(!this.mcpHost&&this.mcpServers&&Object.keys(this.mcpServers).length>0)try{this.mcpHost=new _B(Ke,{mcpServers:this.mcpServers},this.excludedTools),await this.mcpHost.startServers()}catch(e){Ke.error(`Failed to initialize MCP host: ${Ye(e)}`)}}async initializeAndValidateTools(){try{let e=await this.buildSettingsAndTools();if(!e){Ke.debug("Could not initialize tools: buildSettingsAndTools returned undefined");return}let{settings:I,builtInTools:l,mcpTools:n,config:r,toolConfig:s}=e,a=[];for(let W of this.externalToolDefinitions??[])NsI(W.parameters)&&a.push({name:W.name,description:W.description,input_schema:W.parameters??{type:"object",properties:{}}});let o=new Set([...l.map(W=>W.name),...n.map(W=>W.name),...a.map(W=>W.name)]);this.validateToolFilters(o);let c=l.filter(W=>this.isToolEnabled(W.name)),i=n.filter(W=>this.isToolEnabled(W.name)),d=a.filter(W=>this.isToolEnabled(W.name)),G=await jC(this.workingDir),m={...r.supports,reasoning:!0},b,p=[...j8e(c),...j8e(i),...d];if(this.customAgents&&this.customAgents.length>0&&!dg(I)){let g=(this.selectedCustomAgent?[this.selectedCustomAgent]:this.customAgents).filter(R=>R.infer!==!1).map(kqt),y=[...p,...g];b=this.filterToolsForSelectedAgent(y)}else b=p,b=this.filterToolsForSelectedAgent(b);let h=await iB({location:G.found?G.gitRoot:"",version:WNe(),currentWorkingDirectory:this.workingDir,parts:r.cli?.systemMessage||{},capabilities:m,tools:b,organizationCustomInstructions:this.organizationCustomInstructions,skipCustomInstructions:this.skipCustomInstructions,systemMessage:this.systemMessageConfig,toolConfigOverrides:s,workspaceContext:this.workspaceContext});this.currentSystemMessage=h,this.currentToolMetadata=b}catch(e){Ke.debug(`Failed to initialize tools for validation: ${Ye(e)}`)}}async buildSettingsAndTools(e){if(!this.authInfo&&!this.provider)return;await this.initializeMcpHost();let I,l;if(!this.provider){if(!this.authInfo)return;I=await Hb(this.authInfo),l=this.copilotUrl,!l&&I&&this.authInfo.type!=="hmac"&&(l=await WsI(this.authInfo.host,I||""))}let n=!!this.provider,r=n?[]:await this.getModelList(),s=await APe(this._selectedModel,this,r,Ke,n);if(!s)throw new Error("No model available. Check policy enablement under GitHub Settings > Copilot");let a=n?`capi:${s}`:await RPe(s),c=new ZE().setProblemStatement(e??"").setAgentModel(a).setGithubRepoName("copilot-sdk-session").setGithubRepoCommit("copilot-sdk-commit").setGithubRepoReadWrite(!1).setCopilotIntegrationId(this.integrationId).setCopilotUrl(l).setCopilotHmacKey(this.authInfo?.type==="hmac"?this.authInfo.hmac:void 0).setGithubToken(I).setCopilotToken(I).setTrajectoryOutputFile(this.trajectoryFile).setEventsLogDirectory(this.eventsLogDirectory).setFeatureFlags(this.featureFlags).setClientName(this.clientName).build();iye();let i=await U8e(c),d=i.service?.agent?.model,G=B2(d),m=OC(G.agent,G.model),b=$Fl(r),p={location:this.workingDir,timeout:3e4,availableModels:b,toolPartialResultCallback:(g,y)=>{this.emitEphemeral("tool.execution_partial_result",{toolCallId:g,partialOutput:y})},createSubAgentCallback:g=>({progress:async y=>{if(await this.invokeCallbacks(y),uB(y))switch(y.kind){case"message":if(Yh(y)){let R=Jx(y)?y.message.tool_calls.map(v=>({toolCallId:v.id,name:fZ(v),arguments:wre(v,iV)})):[];this.emit("assistant.message",{parentToolCallId:g,messageId:Ra(),content:typeof y.message.content=="string"?y.message.content:"",toolRequests:R});for(let v of R)this.emit("tool.execution_start",{parentToolCallId:g,toolCallId:v.toolCallId,toolName:v.name,arguments:v.arguments})}break;case"tool_execution":this.emit("tool.execution_complete",{parentToolCallId:g,toolCallId:y.toolCallId,success:y.toolResult.resultType==="success",result:y.toolResult.resultType==="success"?{content:y.toolResult.textResultForLlm||y.toolResult.sessionLog||""}:void 0,error:y.toolResult.resultType!=="success"?{message:(y.toolResult.resultType==="failure"?y.toolResult.error:void 0)||y.toolResult.textResultForLlm||y.toolResult.sessionLog||"Tool execution failed",code:y.toolResult.resultType}:void 0});break;default:break}},partialResult:async()=>{},commentReply:async()=>{},result:async()=>{},error:async()=>{}}),permissions:this.requestPermission?{requestRequired:!0,request:this.requestPermission}:{requestRequired:!1},shellConfig:this.shellConfig??(process.platform==="win32"?Zy.powerShell:Zy.bash).withScriptSafetyAssessor(async function(g){return{result:"completed",commands:[{identifier:g,readOnly:!1}],possiblePaths:[],possibleUrls:[],hasWriteFileRedirection:!1,canOfferSessionApproval:!1}}),skillDirectories:this.skillDirectories,disabledSkills:this.disabledSkills,customAgents:this.customAgents,...m.toolConfigOverrides},h=[];if(this.mcpHost){try{h=await this.mcpHost.getTools(i,Ke,p.permissions)}catch(g){Ke.error(`Failed to get MCP tools: ${Ye(g)}`)}vxe(m.supports,h)}p.mcpTools=h,p.getMcpServerProviderForAgent=this.mcpHost?async g=>{let y=await this.mcpHostCache.getOrCreateHost(g,{});if(y)return new Q$(y,i,p.permissions)}:void 0;let N=await(m.cli?.toolInit??Xr.cli.toolInit)(p,i,Ke,new S2e,this.callback,void 0);return{settings:i,builtInTools:N,mcpTools:h,config:m,toolConfig:p}}isToolEnabled(e){return this.availableTools?this.availableTools.includes(e):this.excludedTools?!this.excludedTools.includes(e):!0}validateToolFilters(e){let I=Array.from(e).filter(l=>!this.isToolEnabled(l));if(I.length>0&&!this.warnedUnknownTools.has("__disabled_tools_info__")){this.warnedUnknownTools.add("__disabled_tools_info__");let l=I.sort();this.emitEphemeral("session.info",{infoType:"configuration",message:`Disabled tools: ${l.join(", ")}`})}if(this.availableTools)for(let l of this.availableTools)!e.has(l)&&!this.warnedUnknownTools.has(l)&&(this.warnedUnknownTools.add(l),this.emitEphemeral("session.info",{infoType:"configuration",message:`Unknown tool name in the tool allowlist: "${l}"`}));if(this.excludedTools)for(let l of this.excludedTools)!e.has(l)&&!this.warnedUnknownTools.has(l)&&(this.warnedUnknownTools.add(l),this.emitEphemeral("session.info",{infoType:"configuration",message:`Unknown tool name in the tool denylist: "${l}"`}))}async buildCustomAgentTools(e,I,l,n,r,s,a){let o=async d=>await iB({location:r,version:WNe(),currentWorkingDirectory:this.workingDir,parts:{},capabilities:{...s,customAgents:!1},tools:d,organizationCustomInstructions:this.organizationCustomInstructions,toolConfigOverrides:a}),i=(this.selectedCustomAgent?[this.selectedCustomAgent]:e).filter(d=>d.infer!==!1);return await Promise.all(i.map(async d=>{let G;if(d.mcpServers&&Object.keys(d.mcpServers).length>0){let m=await this.mcpHostCache.getOrCreateHost(d.name,d.mcpServers);m&&(G=new Q$(m,I,a.permissions))}return Lqt(o,VrI,d,this.workingDir,n,l,G)}))}filterToolsForSelectedAgent(e){return this.selectedCustomAgent?R$(e,this.selectedCustomAgent,"top-level"):e}async invokeCallbacks(e){if(uB(e))try{await this.callback.progress(e)}catch(I){Ke.error(`Error in callback: ${Ye(I)}`)}}async getModelList(){if(this.provider)return[];if(!this.authInfo)return Promise.reject(new Error("Session was not created with authentication info or custom provider"));let e=await M8e(this.authInfo,this.copilotUrl||jf(),this.integrationId,this.sessionId,Ke);return e.copilotUrl&&(this.copilotUrl=e.copilotUrl),e.models}async getClient(){if(!this.authInfo&&!this.provider)throw new Error("Session was not created with authentication info or custom provider");let e,I;if(!this.provider){if(!this.authInfo)throw new Error("Session was not created with authentication info");e=await Hb(this.authInfo),I=this.copilotUrl,!I&&e&&this.authInfo.type!=="hmac"&&(I=await WsI(this.authInfo.host,e||""))}let l=!!this.provider,n=l?[]:await this.getModelList(),r=await APe(this._selectedModel,this,n,Ke,l);if(!r)throw new Error("No model available. Check policy enablement under GitHub Settings > Copilot");let s=l?`capi:${r}`:await RPe(r),o=new ZE().setProblemStatement("").setAgentModel(s).setGithubRepoName("copilot-sdk-session").setGithubRepoCommit("copilot-sdk-commit").setGithubRepoReadWrite(!1).setCopilotIntegrationId(this.integrationId).setCopilotUrl(I).setCopilotHmacKey(this.authInfo?.type==="hmac"?this.authInfo.hmac:void 0).setGithubToken(e).setCopilotToken(e).setTrajectoryOutputFile(this.trajectoryFile).setEventsLogDirectory(this.eventsLogDirectory).build();iye();let c=await U8e(o);this.largeOutputConfig&&(c.tools={...c.tools,largeOutput:this.largeOutputConfig});let i=c.service?.agent?.model,d=B2(i),G=OC(d.agent,d.model);return{client:W1(c,Ke,d.agent,{...G.clientOptions,...d.clientOptions,model:d.model},this.provider),settings:c}}async getContextSummary(){let e=await this.getChatMessages();if(e.length===0)return"";let{client:I}=await this.getClient(),l=wrI(),n=2e4,r={role:"user",content:FrI()},s=new vX(r,Ke);try{let a="";for await(let o of I.getCompletionWithTools(l,[...e,r],[],{failIfInitialInputsTooLong:!1,processors:{preRequest:[s],onRequestError:[s]}}))o.kind==="message"&&o.message.role==="assistant"&&(a=typeof o.message.content=="string"?o.message.content:"");return a.length>n?a.slice(0,n):a}catch(a){return Ke.error(`Failed to summarize context: ${Ye(a)}`),""}}async runAgenticLoop(e,I=[]){if(!this.authInfo&&!this.provider)throw new Error("Session was not created with authentication info or custom provider");this.compactionProcessor.clearCompletedCompaction();let l=new Map,n=new Map,r=[],s=!1;try{let o=(await J1(this.hooks?.userPromptSubmitted,{timestamp:Date.now(),cwd:this.workingDir,prompt:e},Ke))?.modifiedPrompt??e,c=await this.buildSettingsAndTools(o);if(!c)throw new Error("No model available. Check policy enablement under GitHub Settings > Copilot");let{settings:i,builtInTools:d,mcpTools:G,config:m,toolConfig:b}=c,p=i.service?.agent?.model,h=B2(p),W=W1(i,Ke,h.agent,{...m.clientOptions,...h.clientOptions,model:h.model},this.provider),N=[];if(this.externalToolDefinitions?.length){let T=this.externalToolDispatcher;if(!T)Ke.warning("External tool definitions provided without a dispatcher; ignoring");else for(let At of this.externalToolDefinitions){if(!NsI(At.parameters)){Ke.warning(`External tool "${At.name}" has invalid parameters schema (expected type object), ignoring tool`);continue}N.push({name:At.name,description:At.description,input_schema:At.parameters??{type:"object",properties:{}},callback:async(oI,Gt)=>{if(!Gt?.toolCallId)throw new Error("External tool invocation missing toolCallId");return await T({sessionId:this.sessionId,toolCallId:Gt.toolCallId,toolName:At.name,arguments:oI,abortSignal:Gt.abortSignal})}})}}let g=new Set([...d,...G,...N].map(T=>T.name));this.validateToolFilters(g);let y=[...d,...G,...N].filter(T=>this.isToolEnabled(T.name)),R=await jC(this.workingDir),v={...m.supports,reasoning:!0},E,Q={progress:async T=>{if(T.kind==="message"&&T.turn===0){if(!T.callId)throw new Error("message on turn 0 event missing callId");E=T.callId}if(await this.invokeCallbacks(T),T.kind==="custom_agent_session_boundary"){let At=T.agentId;if(At)if(T.sessionBoundaryType==="start"){let oI=this.customAgents?.find(ir=>ir.name===T.agentName),Gt=oI?.displayName||T.agentDisplayName||T.agentName,fl=oI?.description||T.agentDescription||"";this.activeCustomAgents.set(At,{name:T.agentName,displayName:Gt}),this.emit("custom_agent.started",{toolCallId:At,agentName:T.agentName,agentDisplayName:Gt,agentDescription:fl})}else{let oI=this.activeCustomAgents.get(At);oI&&this.emit("custom_agent.completed",{toolCallId:At,agentName:oI.name}),this.activeCustomAgents.delete(At)}return}if(uB(T)){if(!E)throw new Error("Custom agent event received without parentToolCallId");switch(T.kind){case"message":if(Yh(T)){let{messageId:At,reasoningId:oI,reasoningContent:Gt}=ct.endCurrentStreamingMessage(),fl=Jx(T)?T.message.tool_calls.map(il=>({toolCallId:il.id,name:fZ(il),arguments:wre(il,iV)})):[],ir=At??Ra(),Rs=typeof T.message.reasoning_text=="string"?T.message.reasoning_text:void 0,fr=typeof T.message.reasoning_opaque=="string"?T.message.reasoning_opaque:null,{reasoningId:_a,reasoningContent:tr}=P2e({streamingReasoningId:oI,streamingReasoningContent:Gt,messageReasoningId:fr,messageReasoningText:Rs});this.emit("assistant.message",{parentToolCallId:E,messageId:ir,content:typeof T.message.content=="string"?T.message.content:"",toolRequests:fl}),_a&&tr&&this.emit("assistant.reasoning",{reasoningId:_a,content:tr});for(let il of fl)this.emit("tool.execution_start",{parentToolCallId:E,toolCallId:il.toolCallId,toolName:il.name,arguments:il.arguments})}break;case"tool_execution":this.emit("tool.execution_complete",{parentToolCallId:E,toolCallId:T.toolCallId,success:T.toolResult.resultType==="success",result:T.toolResult.resultType==="success"?{content:T.toolResult.textResultForLlm||T.toolResult.sessionLog||""}:void 0,error:T.toolResult.resultType!=="success"?{message:(T.toolResult.resultType==="failure"?T.toolResult.error:void 0)||T.toolResult.textResultForLlm||T.toolResult.sessionLog||"Tool execution failed",code:T.toolResult.resultType}:void 0,toolTelemetry:T.toolResult.toolTelemetry});break;case"model_call_failure":case"model_call_success":case"image_processing":case"images_removed":case"response":case"history_truncated":case"compaction_started":case"compaction_completed":case"turn_started":case"turn_ended":case"turn_failed":case"turn_retry":break;default:QA(T,`Unknown event kind: ${JSON.stringify(T)}`)}}},partialResult:async()=>{},commentReply:async()=>{},result:async()=>{},error:async()=>{}},H={client:W,settings:i,logger:Ke,exec:new dG(Ke),customAgents:this.customAgents||[],organizationCustomInstructions:this.organizationCustomInstructions,callback:Q},J=y;if(this.customAgents&&this.customAgents.length>0&&!dg(i)){let T=await this.buildCustomAgentTools(this.customAgents,i,y,H,R.found?R.gitRoot:"",v,b);J=[...y,...T]}r=this.filterToolsForSelectedAgent(J),this.onToolsUpdate&&this.onToolsUpdate(r);let X=await iB({location:R.found?R.gitRoot:"",version:WNe(),currentWorkingDirectory:this.workingDir,parts:m.cli?.systemMessage||{},capabilities:v,tools:r,organizationCustomInstructions:this.organizationCustomInstructions,skipCustomInstructions:this.skipCustomInstructions,systemMessage:this.systemMessageConfig,toolConfigOverrides:b,workspaceContext:this.workspaceContext});this.currentSystemMessage=X;let M=nCt(this.currentTools??[],r);this.currentTools=r,this.currentToolMetadata=j8e(r);let be=I?.some(T=>T.type==="file"&&Bw(T.path))??!1,f=await this.selectedCustomAgent?.prompt(),le=yrI({customAgentPrompt:f,problemStatement:o,capabilities:v,hasImages:be,handoffContext:this.handoffContext,removedTools:M,planReminder:this.getPlanReminderMessage()??void 0});this.emit("user.message",{content:o,transformedContent:le,attachments:I});let Je=await this.getChatMessages(),Ae=Je.findLastIndex(T=>T.role==="user"),ge=Je[Ae];this.handoffContext=void 0;let Pe=Je.map((T,At)=>At===Ae?ge:T);await J1(this.hooks?.sessionStart,{timestamp:Date.now(),cwd:this.workingDir,source:"new",initialPrompt:e},Ke);let ct=new qNe(this,()=>{},!1,Ke),ke=new _Ne(T=>{this.emitEphemeral("assistant.intent",{intent:T})}),Et=new vX(ge,Ke),it=Jme(Ke,i,J.find(T=>T.name==="github-mcp-server-get_file_contents")),me=W.getCompletionWithTools(X,Pe,r,{failIfInitialInputsTooLong:!1,processors:{preRequest:[this.compactionProcessor,Et,this.immediatePromptProcessor,this.premiumRequestProcessor,it],postToolExecution:[it],onRequestError:[it,Et],onStreamingChunk:[ct,ke]},executeToolsInParallel:this.executeToolsInParallel??!0,abortSignal:this.abortController?.signal,stream:this.enableStreaming});for await(let T of me){if(this.abortController?.signal.aborted){this.emit("abort",{reason:"user initiated"}),this.emitEphemeral("session.info",{infoType:"cancellation",message:"Operation cancelled by user"});break}switch(await this.invokeCallbacks(T),T.kind){case"message":{if(Yh(T)){let{messageId:At,reasoningId:oI,reasoningContent:Gt}=ct.endCurrentStreamingMessage(),fl=At??Ra(),ir=Jx(T)?await Promise.all(T.message.tool_calls.map(async il=>{let Vr=fZ(il),rc=wre(il,iV);l.set(il.id,Vr),n.set(il.id,rc);let uI=await J1(this.hooks?.preToolUse,{timestamp:Date.now(),cwd:this.workingDir,toolName:Vr,toolArgs:rc},Ke);return{toolCallId:il.id,name:Vr,arguments:uI?.modifiedArgs??rc}})):[],Rs=typeof T.message.reasoning_text=="string"?T.message.reasoning_text:void 0,fr=typeof T.message.reasoning_opaque=="string"?T.message.reasoning_opaque:null,{reasoningId:_a,reasoningContent:tr}=P2e({streamingReasoningId:oI,streamingReasoningContent:Gt,messageReasoningId:fr,messageReasoningText:Rs});this.emit("assistant.message",{parentToolCallId:void 0,messageId:fl,content:typeof T.message.content=="string"?T.message.content:"",toolRequests:ir}),_a&&tr&&this.emit("assistant.reasoning",{reasoningId:_a,content:tr});for(let il of ir)this.emit("tool.execution_start",{toolCallId:il.toolCallId,toolName:il.name,arguments:il.arguments})}else(T.message.role==="system"||T.message.role==="developer")&&this.emit("system.message",{role:T.message.role,content:typeof T.message.content=="string"?T.message.content:JSON.stringify(T.message.content),name:"name"in T.message?T.message.name:void 0});break}case"model_call_failure":{let At=new Error(T.modelCall?.error||"Model call failed");if(await J1(this.hooks?.errorOccurred,{timestamp:Date.now(),cwd:this.workingDir,error:At,errorContext:"model_call",recoverable:!0},Ke),Q8e(T.modelCall?.error||""))return;let Gt=_Fl(T.modelCall?.error);T.modelCall.request_id&&(Gt+=` (Request ID: ${T.modelCall.request_id})`),this.emit("session.error",{errorType:"model_call",message:`Model call failed: ${Gt}`,stack:At.stack});break}case"tool_execution":{let At=l.get(T.toolCallId)||"unknown",oI=n.get(T.toolCallId)||{},fl=(await J1(this.hooks?.postToolUse,{timestamp:Date.now(),cwd:this.workingDir,toolName:At,toolArgs:oI,toolResult:T.toolResult},Ke))?.modifiedResult??T.toolResult;fl.resultType==="rejected"&&(s=!0);let ir=(fl.resultType==="failure"?fl.error:void 0)||fl.textResultForLlm||fl.sessionLog||"";if(At===VK&&fl.resultType==="success"&&typeof oI=="object"&&oI!==null&&"todos"in oI&&this.setLastTodoContent(oI.todos),this.workspaceEnabled&&(At==="edit"||At==="create")&&fl.resultType==="success"&&typeof oI=="object"&&oI!==null&&"path"in oI){let Rs=oI.path;(Rs.endsWith("/plan.md")||Rs.endsWith("\\plan.md"))&&(this.lastPlanUpdateTurn=this.currentTurn,this.emitWorkspaceFileTelemetry(Rs,At==="create"?"create":"update"))}if(this.workspaceEnabled&&At==="view"&&fl.resultType==="success"&&typeof oI=="object"&&oI!==null&&"path"in oI){let Rs=oI.path;this.emitWorkspaceFileReadTelemetry(Rs)}this.emit("tool.execution_complete",{parentToolCallId:void 0,toolCallId:T.toolCallId,success:fl.resultType==="success",result:fl.resultType==="success"?{content:ir}:void 0,error:fl.resultType!=="success"?{message:ir,code:fl.resultType}:void 0,toolTelemetry:fl.toolTelemetry});break}case"turn_started":{this.currentTurn=T.turn,this.emit("assistant.turn_start",{turnId:`${T.turn}`});break}case"turn_ended":{this.emit("assistant.turn_end",{turnId:`${T.turn}`});break}case"model_call_success":{let At=T.modelCall.model||await this.getSelectedModel(),oI=T.modelCallDurationMs||0,Gt=T.responseUsage,fl=await this.getModelList(),ir=At?VPe(At,fl):1;this.emitEphemeral("assistant.usage",{model:At||"unknown",inputTokens:Gt?.prompt_tokens||0,outputTokens:Gt?.completion_tokens||0,cacheReadTokens:Gt?.prompt_tokens_details?.cached_tokens||0,cacheWriteTokens:0,cost:ir,duration:oI,initiator:T.modelCall?.initiator,apiCallId:T.modelCall?.api_id,providerCallId:T.modelCall?.request_id,quotaSnapshots:T.quotaSnapshots});break}case"history_truncated":{this.emit("session.truncation",{...T.truncateResult,performedBy:T.performedBy});break}case"compaction_started":{this.emit("session.compaction_start",{});break}case"compaction_completed":{T.success&&T.compactionResult?this.emit("session.compaction_complete",{success:!0,preCompactionTokens:T.compactionResult.preCompactionTokens,postCompactionTokens:T.compactionResult.postCompactionTokens,preCompactionMessagesLength:T.compactionResult.preCompactionMessagesLength,messagesRemoved:T.compactionResult.messagesRemoved,tokensRemoved:T.compactionResult.tokensRemoved,summaryContent:T.compactionResult.summaryContent,compactionTokensUsed:T.compactionResult.compactionTokensUsed}):this.emit("session.compaction_complete",{success:!1,error:T.error});break}case"response":case"images_removed":case"image_processing":case"turn_failed":case"turn_retry":Ke.debug(`Ignoring event of kind: ${T.kind}`);break;default:QA(T,"Unhandled event type")}}}catch(a){if(await J1(this.hooks?.sessionEnd,{timestamp:Date.now(),cwd:this.workingDir,reason:"error",error:a instanceof Error?a:new Error(String(a))},Ke),a&&typeof a=="object"&&"status"in a&&(a.status===401||a.status===403)){if("message"in a&&typeof a.message=="string"){let c=Q8e(a.message);c&&this.emit("session.error",{errorType:"authentication",message:c.message})}this.emit("session.error",{errorType:"authorization",message:"Authorization error, you may need to run /login"})}a&&typeof a=="object"&&"status"in a&&a.status===402&&this.emit("session.error",{errorType:"quota",message:"Quota exceeded. Upgrade to increase your limit: https://github.com/features/copilot/plans"});let o=`Execution failed: ${Ye(a)}`;this.emit("session.error",{errorType:"query",message:o,stack:a instanceof Error?a.stack:void 0})}finally{await J1(this.hooks?.sessionEnd,{timestamp:Date.now(),cwd:this.workingDir,reason:"complete"},Ke),s&&this.clearPendingMessages();try{for(let a of r)a.shutdown&&await a.shutdown()}catch(a){Ke.error(`Error during session shutdown: ${Ye(a)}`)}}}},q2e=class extends K2e{repository;remoteSessionIds;pullRequestNumber;constructor(e){super(e),this.repository=e.repository,this.remoteSessionIds=e.remoteSessionIds,this.pullRequestNumber=e.pullRequestNumber}async send(e){let{prompt:I}=e;if(!this.pullRequestNumber)throw new Error("Cannot send message: Pull request number is not available");if(!this.authInfo)throw new Error("Cannot send message: Authentication info is not available");let{owner:l,name:n}=this.repository,r=this.pullRequestNumber,s=`@copilot ${I}`;Ke.debug(`Posting user message to PR ${l}/${n}#${r}`);let a=MFt(this.authInfo),o=new URL(`/repos/${l}/${n}/issues/${r}/comments`,tR(a)),c=await z8t(o,this.authInfo,Ke,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({body:s})});if(!c.ok){let i=await c.text();throw new Error(`Failed to post comment to PR ${l}/${n}#${r}: ${c.status} ${c.statusText}
2376
2372
  ${i}
2377
2373
  ${o.toString()}`)}Ke.info(`Successfully posted user message to PR ${l}/${n}#${r}`),this.emit("user.message",{content:I})}async abort(){throw new Error("RemoteSession.abort() is not implemented yet.")}async compactHistory(){throw new Error("RemoteSession.compactHistory() is not implemented yet.")}getMetadata(){return{sessionId:this.sessionId,startTime:this.startTime,modifiedTime:this.modifiedTime,summary:this.summary,isRemote:!0,repository:this.repository,remoteSessionIds:this.remoteSessionIds,pullRequestNumber:this.pullRequestNumber}}}});import t1l from"node:path";async function gsI(t,e,I,l){I??=lz,l??=new Em;let n=await m8t(e),{agents:r}=await N8t(l,I,t,t1l.join(UJ(),"agents"),n,!1);return r.map(s=>({name:s.id,displayName:s.displayName,description:s.description,tools:s.tools,prompt:s.prompt,mcpServers:s.mcpServers||{},infer:s.infer}))}var P8e=u(()=>{"use strict";V8t();vPe();zQ();TNe();nz()});var Tee,l1l,n1l,r1l,s1l,a1l,o1l,c1l,i1l,d1l,G1l,m1l,u1l,b1l,p1l,h1l,Z1l,W1l,N1l,g1l,Y1l,y1l,V1l,R1l,A1l,w1l,F1l,E1l,K8e,L1,q8e=u(()=>{"use strict";cn();Lk();kJe();Xj();Tee=xe({type:dt("text"),text:_()}),l1l=xe({type:dt("refusal"),refusal:_()}),n1l=xe({type:dt("image_url"),image_url:xe({url:_(),detail:md(["auto","low","high"]).optional()})}),r1l=xe({type:dt("input_audio"),input_audio:xe({data:_(),format:dt("wav").or(dt("mp3"))})}),s1l=xe({type:dt("file"),file:xe({file_date:_().optional(),file_id:_().optional(),filename:_().optional()})}),a1l=Gd([Tee,n1l,r1l,s1l]),o1l=xe({name:_(),arguments:_()}),c1l=xe({name:_(),input:_()}),i1l=xe({id:_(),type:dt("function"),function:o1l}),d1l=xe({id:_(),type:dt("custom"),custom:c1l}),G1l=Gd([i1l,d1l]),m1l=xe({name:_(),arguments:_()}),u1l=xe({id:_()}),b1l=xe({content:Gd([_(),Jr(Tee)]),role:dt("developer"),name:_().optional()}),p1l=xe({content:Gd([_(),Jr(Tee)]),role:dt("system"),name:_().optional()}),h1l=xe({content:Gd([_(),Jr(a1l)]),role:dt("user"),name:_().optional()}),Z1l=xe({content:Gd([_(),Jr(Gd([Tee,l1l]))]).nullable().optional(),role:dt("assistant"),name:_().optional(),refusal:_().nullable().optional(),audio:u1l.nullable().optional(),function_call:m1l.nullable().optional(),tool_calls:Jr(G1l).optional()}),W1l=xe({content:Gd([_(),Jr(Tee)]),role:dt("tool"),tool_call_id:_()}),N1l=xe({content:_().nullable(),role:dt("function"),name:_()}),g1l=Gd([b1l,p1l,h1l,Z1l,W1l,N1l]),Y1l=xe({type:dt("copilot"),text:_(),isStreaming:sl().optional()}),y1l=xe({type:dt("error"),text:_()}),V1l=xe({type:dt("info"),text:_()}),R1l=xe({type:dt("user"),text:_()}),A1l=xe({type:dt("tool_call_requested"),callId:_(),name:_(),toolTitle:_().optional(),intentionSummary:_().nullable(),arguments:LJe,partialOutput:_().optional(),isHidden:sl().optional(),isAlwaysExpanded:sl().optional(),showNoContent:sl().optional()}),w1l=xe({type:dt("tool_call_completed"),callId:_(),name:_(),toolTitle:_().optional(),intentionSummary:_().nullable(),result:Gd([xe({type:dt("success"),log:_(),markdown:sl().optional()}),xe({type:dt("failure"),log:_(),markdown:sl().optional()}),xe({type:dt("rejected"),markdown:sl().optional()}),xe({type:dt("denied"),log:_(),markdown:sl().optional()})]),arguments:LJe,isHidden:sl().optional(),isAlwaysExpanded:sl().optional(),showNoContent:sl().optional()}),F1l=Gd([Y1l,y1l,V1l,R1l,A1l,w1l]),E1l=F1l.and(xe({id:_(),timestamp:ZIe.date()})),K8e=xe({sessionId:_(),startTime:ZIe.date(),chatMessages:Jr(g1l),timeline:Jr(E1l),selectedModel:md(z2).optional()}),L1=Xct(K8e.parse,"history-session")});var jn,_2e,Q1l,v1l,X1l,H1l,C1l,f1l,J1l,L1l,k1l,x1l,S1l,B1l,z1l,U1l,O1l,M1l,T1l,j1l,D1l,P1l,K1l,q1l,_1l,$1l,eEl,tEl,IEl,lEl,nEl,rEl,sEl,aEl,oEl,cEl,YsI,_8e=u(()=>{"use strict";cn();q8e();jn=xe({id:_().uuid(),timestamp:_().datetime(),parentId:_().uuid().nullable(),ephemeral:sl().optional()}),_2e=xe({parentToolCallId:_().optional()}),Q1l=jn.extend({type:dt("session.start"),data:xe({sessionId:_(),version:HI(),producer:_(),copilotVersion:_(),startTime:_().datetime(),selectedModel:_().optional()})}),v1l=jn.extend({type:dt("session.resume"),data:xe({resumeTime:_().datetime(),eventCount:HI()})}),X1l=jn.extend({type:dt("session.error"),data:xe({errorType:_(),message:_(),stack:_().optional()})}),H1l=jn.extend({type:dt("session.info"),data:xe({infoType:_(),message:_()})}),C1l=jn.extend({type:dt("session.model_change"),data:xe({previousModel:_().optional(),newModel:_()})}),f1l=jn.extend({type:dt("session.import_legacy"),data:xe({legacySession:K8e,importTime:_().datetime(),sourceFile:_()})}),J1l=jn.extend({type:dt("session.handoff"),data:xe({handoffTime:_().datetime(),sourceType:md(["remote","local"]),repository:xe({owner:_(),name:_(),branch:_().optional()}).optional(),context:_().optional(),summary:_().optional(),remoteSessionId:_().optional()})}),L1l=jn.extend({type:dt("session.idle"),ephemeral:dt(!0),data:xe({})}),k1l=jn.extend({type:dt("session.truncation"),data:xe({tokenLimit:HI(),preTruncationTokensInMessages:HI(),preTruncationMessagesLength:HI(),postTruncationTokensInMessages:HI(),postTruncationMessagesLength:HI(),tokensRemovedDuringTruncation:HI(),messagesRemovedDuringTruncation:HI(),performedBy:_()})}),x1l=jn.extend({type:dt("session.compaction_start"),data:xe({})}),S1l=jn.extend({type:dt("session.compaction_complete"),data:xe({success:sl(),error:_().optional(),preCompactionTokens:HI().optional(),postCompactionTokens:HI().optional(),preCompactionMessagesLength:HI().optional(),messagesRemoved:HI().optional(),tokensRemoved:HI().optional(),summaryContent:_().optional(),compactionTokensUsed:xe({input:HI(),output:HI(),cachedInput:HI()}).optional()})}),B1l=xe({type:md(["file","directory"]),path:_(),displayName:_()}),z1l=jn.extend({type:dt("user.message"),data:xe({content:_(),transformedContent:_().optional(),attachments:Jr(B1l).optional(),source:_().optional()})}),U1l=jn.extend({type:dt("pending_messages.modified"),ephemeral:dt(!0),data:xe({})}),O1l=jn.extend({type:dt("assistant.turn_start"),data:xe({turnId:_()})}),M1l=jn.extend({type:dt("assistant.message"),data:xe({messageId:_(),content:_(),toolRequests:Jr(xe({toolCallId:_(),name:_(),arguments:IZ()})).optional()}).merge(_2e)}),T1l=jn.extend({type:dt("assistant.message_delta"),ephemeral:dt(!0),data:xe({messageId:_(),deltaContent:_(),totalResponseSizeBytes:HI().optional()}).merge(_2e)}),j1l=jn.extend({type:dt("assistant.intent"),ephemeral:dt(!0),data:xe({intent:_()})}),D1l=jn.extend({type:dt("assistant.reasoning"),data:xe({reasoningId:_(),content:_()})}),P1l=jn.extend({type:dt("assistant.reasoning_delta"),ephemeral:dt(!0),data:xe({reasoningId:_(),deltaContent:_()})}),K1l=jn.extend({type:dt("assistant.turn_end"),data:xe({turnId:_()})}),q1l=jn.extend({type:dt("assistant.usage"),ephemeral:dt(!0),data:xe({model:_().optional(),inputTokens:HI().optional(),outputTokens:HI().optional(),cacheReadTokens:HI().optional(),cacheWriteTokens:HI().optional(),cost:HI().optional(),duration:HI().optional(),initiator:_().optional(),apiCallId:_().optional(),providerCallId:_().optional(),quotaSnapshots:ju(_(),xe({isUnlimitedEntitlement:sl(),entitlementRequests:HI(),usedRequests:HI(),usageAllowedWithExhaustedQuota:sl(),overage:HI(),overageAllowedWithExhaustedQuota:sl(),remainingPercentage:HI(),resetDate:nye().optional()})).optional()})}),_1l=jn.extend({type:dt("abort"),data:xe({reason:_()})}),$1l=jn.extend({type:dt("tool.user_requested"),data:xe({toolCallId:_(),toolName:_(),arguments:IZ()})}),eEl=jn.extend({type:dt("tool.execution_start"),data:xe({toolCallId:_(),toolName:_(),arguments:IZ()}).merge(_2e)}),tEl=jn.extend({type:dt("tool.execution_partial_result"),ephemeral:dt(!0),data:xe({toolCallId:_(),partialOutput:_()})}),IEl=jn.extend({type:dt("tool.execution_complete"),data:xe({toolCallId:_(),success:sl(),isUserRequested:sl().optional(),result:xe({content:_()}).optional(),error:xe({message:_(),code:_().optional()}).optional(),toolTelemetry:ju(IZ()).optional()}).merge(_2e)}),lEl=jn.extend({type:dt("custom_agent.started"),data:xe({toolCallId:_(),agentName:_(),agentDisplayName:_(),agentDescription:_()})}),nEl=jn.extend({type:dt("custom_agent.completed"),data:xe({toolCallId:_(),agentName:_()})}),rEl=jn.extend({type:dt("custom_agent.failed"),data:xe({toolCallId:_(),agentName:_(),error:_()})}),sEl=jn.extend({type:dt("custom_agent.selected"),data:xe({agentName:_(),agentDisplayName:_(),tools:Jr(_()).nullable()})}),aEl=jn.extend({type:dt("hook.start"),data:xe({hookInvocationId:_(),hookType:_(),input:IZ()})}),oEl=jn.extend({type:dt("hook.end"),data:xe({hookInvocationId:_(),hookType:_(),output:IZ(),success:sl(),error:xe({message:_(),stack:_().optional()}).optional()})}),cEl=jn.extend({type:dt("system.message"),data:xe({content:_(),role:md(["system","developer"]),name:_().optional(),metadata:xe({promptVersion:_().optional(),variables:ju(IZ()).optional()}).optional()})}),YsI=Tz("type",[Q1l,v1l,X1l,L1l,H1l,C1l,f1l,J1l,k1l,x1l,S1l,z1l,U1l,O1l,j1l,D1l,P1l,M1l,T1l,K1l,q1l,_1l,$1l,eEl,tEl,IEl,lEl,nEl,rEl,sEl,aEl,oEl,cEl])});var k1,ysI=u(()=>{"use strict";_8e();Xj();k1=Hct(YsI.parse,"session")});var VsI,$8e,RsI,AsI,wsI,FsI,EsI=u(()=>{VsI=t=>{t=1831565813+(t|=0)|0;let e=Math.imul(t^t>>>15,1|t);return e=e+Math.imul(e^e>>>7,61|e)^e,((e^e>>>14)>>>0)/4294967296},$8e=class{constructor(e){this.dictionaries=void 0,this.length=void 0,this.separator=void 0,this.style=void 0,this.seed=void 0;let{length:I,separator:l,dictionaries:n,style:r,seed:s}=e;this.dictionaries=n,this.separator=l,this.length=I,this.style=r,this.seed=s}generate(){if(!this.dictionaries)throw new Error('Cannot find any dictionary. Please provide at least one, or leave the "dictionary" field empty in the config object');if(this.length<=0)throw new Error("Invalid length provided");if(this.length>this.dictionaries.length)throw new Error(`The length cannot be bigger than the number of dictionaries.
2378
2374
  Length provided: ${this.length}. Number of dictionaries provided: ${this.dictionaries.length}`);let e=this.seed;return this.dictionaries.slice(0,this.length).reduce((I,l)=>{let n;e?(n=(s=>{if(typeof s=="string"){let a=s.split("").map(c=>c.charCodeAt(0)).reduce((c,i)=>c+i,1),o=Math.floor(Number(a));return VsI(o)}return VsI(s)})(e),e=4294967296*n):n=Math.random();let r=l[Math.floor(n*l.length)]||"";if(this.style==="lowerCase")r=r.toLowerCase();else if(this.style==="capital"){let[s,...a]=r.split("");r=s.toUpperCase()+a.join("")}else this.style==="upperCase"&&(r=r.toUpperCase());return I?`${I}${this.separator}${r}`:`${r}`},"")}},RsI={separator:"_",dictionaries:[]},AsI=t=>{let e=[...t&&t.dictionaries||RsI.dictionaries],I={...RsI,...t,length:t&&t.length||e.length,dictionaries:e};if(!t||!t.dictionaries||!t.dictionaries.length)throw new Error('A "dictionaries" array must be provided. This is a breaking change introduced starting from Unique Name Generator v4. Read more about the breaking change here: https://github.com/andreasonny83/unique-names-generator#migration-guide');return new $8e(I).generate()},wsI=["able","above","absent","absolute","abstract","abundant","academic","acceptable","accepted","accessible","accurate","accused","active","actual","acute","added","additional","adequate","adjacent","administrative","adorable","advanced","adverse","advisory","aesthetic","afraid","aggregate","aggressive","agreeable","agreed","agricultural","alert","alive","alleged","allied","alone","alright","alternative","amateur","amazing","ambitious","amused","ancient","angry","annoyed","annual","anonymous","anxious","appalling","apparent","applicable","appropriate","arbitrary","architectural","armed","arrogant","artificial","artistic","ashamed","asleep","assistant","associated","atomic","attractive","automatic","autonomous","available","average","awake","aware","awful","awkward","back","bad","balanced","bare","basic","beautiful","beneficial","better","bewildered","big","binding","biological","bitter","bizarre","blank","blonde","blushing","boiling","bold","bored","boring","bottom","brainy","brave","breakable","breezy","brief","bright","brilliant","broad","broken","bumpy","burning","busy","calm","capable","careful","casual","causal","cautious","central","certain","changing","characteristic","charming","cheap","cheerful","chemical","chief","chilly","chosen","chronic","chubby","circular","civic","civil","classic","classical","clean","clear","clever","clinical","close","closed","cloudy","clumsy","coastal","cognitive","coherent","cold","collective","colorful","colossal","coloured","colourful","combined","comfortable","commercial","common","compact","comparable","comparative","compatible","competent","competitive","complete","complex","complicated","comprehensive","compulsory","conceptual","concerned","concrete","condemned","confident","confidential","confused","conscious","conservation","considerable","consistent","constant","constitutional","contemporary","content","continental","continued","continuing","continuous","controlled","controversial","convenient","conventional","convinced","convincing","cooing","cool","cooperative","corporate","correct","corresponding","costly","courageous","creative","creepy","criminal","critical","crooked","crowded","crucial","crude","cruel","cuddly","cultural","curious","curly","current","curved","cute","daily","damaged","damp","dangerous","dark","dead","deafening","dear","decent","decisive","deep","defeated","defensive","defiant","definite","deliberate","delicate","delicious","delighted","delightful","democratic","dependent","depressed","desirable","desperate","detailed","determined","developed","developing","devoted","different","difficult","digital","diplomatic","direct","dirty","disappointed","disastrous","disciplinary","disgusted","distant","distinct","distinctive","distinguished","disturbed","disturbing","diverse","divine","dizzy","domestic","dominant","double","doubtful","drab","dramatic","dreadful","driving","dry","dual","due","dull","dusty","dutch","dying","dynamic","eager","early","eastern","easy","economic","educational","eerie","effective","efficient","elaborate","elated","elderly","eldest","electoral","electric","electrical","electronic","elegant","eligible","embarrassed","embarrassing","emotional","empirical","empty","enchanting","encouraging","endless","energetic","enormous","enthusiastic","entire","entitled","envious","environmental","equal","equivalent","essential","established","estimated","ethical","eventual","everyday","evident","evil","evolutionary","exact","excellent","exceptional","excess","excessive","excited","exciting","exclusive","existing","exotic","expected","expensive","experienced","experimental","explicit","extended","extensive","external","extra","extraordinary","extreme","exuberant","faint","fair","faithful","familiar","famous","fancy","fantastic","far","fascinating","fashionable","fast","fatal","favourable","favourite","federal","fellow","few","fierce","final","financial","fine","firm","fiscal","fit","fixed","flaky","flat","flexible","fluffy","fluttering","flying","following","fond","foolish","foreign","formal","formidable","forthcoming","fortunate","forward","fragile","frail","frantic","free","frequent","fresh","friendly","frightened","front","frozen","full","fun","functional","fundamental","funny","furious","future","fuzzy","gastric","general","generous","genetic","gentle","genuine","geographical","giant","gigantic","given","glad","glamorous","gleaming","global","glorious","golden","good","gorgeous","gothic","governing","graceful","gradual","grand","grateful","greasy","great","grieving","grim","gross","grotesque","growing","grubby","grumpy","guilty","handsome","happy","hard","harsh","head","healthy","heavy","helpful","helpless","hidden","high","hilarious","hissing","historic","historical","hollow","holy","homely","hon","honest","horizontal","horrible","hostile","hot","huge","human","hungry","hurt","hushed","husky","icy","ideal","identical","ideological","ill","illegal","imaginative","immediate","immense","implicit","important","impossible","impressed","impressive","improved","inadequate","inc","inclined","increased","increasing","incredible","independent","indirect","individual","industrial","inevitable","influential","informal","inherent","initial","injured","inland","inner","innocent","innovative","inquisitive","instant","institutional","insufficient","intact","integral","integrated","intellectual","intelligent","intense","intensive","interested","interesting","interim","interior","intermediate","internal","international","invisible","involved","irrelevant","isolated","itchy","jealous","jittery","joint","jolly","joyous","judicial","juicy","junior","just","keen","key","kind","known","labour","large","late","latin","lazy","leading","left","legal","legislative","legitimate","lengthy","lesser","level","lexical","liable","light","like","likely","limited","linear","linguistic","liquid","literary","little","live","lively","living","local","logical","lonely","long","loose","lost","loud","lovely","low","loyal","ltd","lucky","mad","magic","magnetic","magnificent","main","major","mammoth","managerial","managing","manual","many","marginal","marine","marked","married","marvellous","mass","massive","mathematical","mature","maximum","mean","meaningful","mechanical","medical","medieval","melodic","melted","mental","mere","metropolitan","mid","middle","mighty","mild","military","miniature","minimal","minimum","ministerial","minor","miserable","misleading","missing","misty","mixed","moaning","mobile","moderate","modern","modest","molecular","monetary","monthly","moral","motionless","muddy","multiple","mushy","musical","mutual","mysterious","naked","narrow","nasty","national","natural","naughty","naval","near","nearby","neat","necessary","negative","neighbouring","nervous","net","neutral","new","nice","noble","noisy","normal","northern","nosy","notable","novel","nuclear","numerous","nursing","nutritious","nutty","obedient","objective","obliged","obnoxious","obvious","occasional","occupational","odd","official","ok","okay","old","only","open","operational","opposite","optimistic","ordinary","organic","organisational","original","orthodox","other","outdoor","outer","outrageous","outside","outstanding","overall","overseas","overwhelming","painful","pale","panicky","parallel","parental","parliamentary","partial","particular","passing","passive","past","patient","payable","peaceful","peculiar","perfect","permanent","persistent","personal","petite","philosophical","physical","plain","planned","plastic","pleasant","pleased","poised","polite","poor","popular","positive","possible","potential","powerful","practical","precious","precise","preferred","pregnant","preliminary","premier","prepared","present","presidential","pretty","previous","prickly","primary","prime","principal","printed","prior","private","probable","productive","professional","profitable","profound","progressive","prominent","promising","proper","proposed","prospective","protective","proud","provincial","psychiatric","psychological","public","puny","pure","purring","puzzled","quaint","qualified","quarrelsome","querulous","quick","quickest","quiet","quintessential","quixotic","racial","radical","rainy","random","rapid","rare","raspy","rational","ratty","raw","ready","real","realistic","rear","reasonable","recent","reduced","redundant","regional","registered","regular","regulatory","related","relative","relaxed","relevant","reliable","relieved","religious","reluctant","remaining","remarkable","remote","renewed","representative","repulsive","required","resident","residential","resonant","respectable","respective","responsible","resulting","retail","retired","revolutionary","rich","ridiculous","right","rigid","ripe","rising","rival","roasted","robust","rolling","romantic","rotten","rough","round","royal","rubber","rude","ruling","running","rural","sacred","sad","safe","salty","satisfactory","satisfied","scared","scary","scattered","scientific","scornful","scrawny","screeching","secondary","secret","secure","select","selected","selective","selfish","semantic","senior","sensible","sensitive","separate","serious","severe","shaggy","shaky","shallow","shared","sharp","sheer","shiny","shivering","shocked","short","shrill","shy","sick","significant","silent","silky","silly","similar","simple","single","skilled","skinny","sleepy","slight","slim","slimy","slippery","slow","small","smart","smiling","smoggy","smooth","social","soft","solar","sole","solid","sophisticated","sore","sorry","sound","sour","southern","spare","sparkling","spatial","special","specific","specified","spectacular","spicy","spiritual","splendid","spontaneous","sporting","spotless","spotty","square","squealing","stable","stale","standard","static","statistical","statutory","steady","steep","sticky","stiff","still","stingy","stormy","straight","straightforward","strange","strategic","strict","striking","striped","strong","structural","stuck","subjective","subsequent","substantial","subtle","successful","successive","sudden","sufficient","suitable","sunny","super","superb","superior","supporting","supposed","supreme","sure","surprised","surprising","surrounding","surviving","suspicious","sweet","swift","symbolic","sympathetic","systematic","tall","tame","tart","tasteless","tasty","technical","technological","teenage","temporary","tender","tense","terrible","territorial","testy","then","theoretical","thick","thin","thorough","thoughtful","thoughtless","thundering","tight","tiny","tired","top","total","tough","toxic","traditional","tragic","tremendous","tricky","tropical","troubled","typical","ugliest","ugly","ultimate","unable","unacceptable","unaware","uncertain","unchanged","uncomfortable","unconscious","underground","underlying","unemployed","uneven","unexpected","unfair","unfortunate","unhappy","uniform","uninterested","unique","united","universal","unknown","unlikely","unnecessary","unpleasant","unsightly","unusual","unwilling","upper","upset","uptight","urban","urgent","used","useful","useless","usual","vague","valid","valuable","variable","varied","various","varying","vast","verbal","vertical","very","vicarious","vicious","victorious","violent","visible","visiting","visual","vital","vitreous","vivacious","vivid","vocal","vocational","voiceless","voluminous","voluntary","vulnerable","wandering","warm","wasteful","watery","weak","wealthy","weary","wee","weekly","weird","welcome","well","western","wet","whispering","whole","wicked","wide","widespread","wild","wilful","willing","willowy","wily","wise","wispy","wittering","witty","wonderful","wooden","working","worldwide","worried","worrying","worthwhile","worthy","written","wrong","xenacious","xenial","xenogeneic","xeric","xerothermic","yabbering","yammering","yappiest","yappy","yawning","yearling","yearning","yeasty","yelling","yelping","yielding","yodelling","young","youngest","youthful","ytterbic","yucky","yummy","zany","zealous","zeroth","zestful","zesty","zippy","zonal","zoophagous","zygomorphic","zygotic"],FsI=["aardvark","aardwolf","albatross","alligator","alpaca","amphibian","anaconda","angelfish","anglerfish","ant","anteater","antelope","antlion","ape","aphid","armadillo","asp","baboon","badger","bandicoot","barnacle","barracuda","basilisk","bass","bat","bear","beaver","bedbug","bee","beetle","bird","bison","blackbird","boa","boar","bobcat","bobolink","bonobo","bovid","bug","butterfly","buzzard","camel","canid","canidae","capybara","cardinal","caribou","carp","cat","caterpillar","catfish","catshark","cattle","centipede","cephalopod","chameleon","cheetah","chickadee","chicken","chimpanzee","chinchilla","chipmunk","cicada","clam","clownfish","cobra","cockroach","cod","condor","constrictor","coral","cougar","cow","coyote","crab","crane","crawdad","crayfish","cricket","crocodile","crow","cuckoo","damselfly","deer","dingo","dinosaur","dog","dolphin","donkey","dormouse","dove","dragon","dragonfly","duck","eagle","earthworm","earwig","echidna","eel","egret","elephant","elk","emu","ermine","falcon","felidae","ferret","finch","firefly","fish","flamingo","flea","fly","flyingfish","fowl","fox","frog","galliform","gamefowl","gayal","gazelle","gecko","gerbil","gibbon","giraffe","goat","goldfish","goose","gopher","gorilla","grasshopper","grouse","guan","guanaco","guineafowl","gull","guppy","haddock","halibut","hamster","hare","harrier","hawk","hedgehog","heron","herring","hippopotamus","hookworm","hornet","horse","hoverfly","hummingbird","hyena","iguana","impala","jackal","jaguar","jay","jellyfish","junglefowl","kangaroo","kingfisher","kite","kiwi","koala","koi","krill","ladybug","lamprey","landfowl","lark","leech","lemming","lemur","leopard","leopon","limpet","lion","lizard","llama","lobster","locust","loon","louse","lungfish","lynx","macaw","mackerel","magpie","mammal","manatee","mandrill","marlin","marmoset","marmot","marsupial","marten","mastodon","meadowlark","meerkat","mink","minnow","mite","mockingbird","mole","mollusk","mongoose","monkey","moose","mosquito","moth","mouse","mule","muskox","narwhal","newt","nightingale","ocelot","octopus","opossum","orangutan","orca","ostrich","otter","owl","ox","panda","panther","parakeet","parrot","parrotfish","partridge","peacock","peafowl","pelican","penguin","perch","pheasant","pig","pigeon","pike","pinniped","piranha","planarian","platypus","pony","porcupine","porpoise","possum","prawn","primate","ptarmigan","puffin","puma","python","quail","quelea","quokka","rabbit","raccoon","rat","rattlesnake","raven","reindeer","reptile","rhinoceros","roadrunner","rodent","rook","rooster","roundworm","sailfish","salamander","salmon","sawfish","scallop","scorpion","seahorse","shark","sheep","shrew","shrimp","silkworm","silverfish","skink","skunk","sloth","slug","smelt","snail","snake","snipe","sole","sparrow","spider","spoonbill","squid","squirrel","starfish","stingray","stoat","stork","sturgeon","swallow","swan","swift","swordfish","swordtail","tahr","takin","tapir","tarantula","tarsier","termite","tern","thrush","tick","tiger","tiglon","toad","tortoise","toucan","trout","tuna","turkey","turtle","tyrannosaurus","unicorn","urial","vicuna","viper","vole","vulture","wallaby","walrus","warbler","wasp","weasel","whale","whippet","whitefish","wildcat","wildebeest","wildfowl","wolf","wolverine","wombat","woodpecker","worm","wren","xerinae","yak","zebra"]});import{execFile as iEl}from"node:child_process";import{promisify as dEl}from"node:util";async function QsI(t){try{let{stdout:e}=await JV("git",["status","--porcelain","--ignore-submodules"],{cwd:t,encoding:"utf8",timeout:5e3,maxBuffer:1048576}),I=e.split(`